blob: 20550a7b42fa6851e4d392ef00f127456104edd4 [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
avi51ba3e692015-12-26 17:30:507#include <limits.h>
avi9b6f42932015-12-26 22:15:148#include <stdint.h>
9
10#include "base/macros.h"
11#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5012
[email protected]b16ef312008-08-19 18:36:2313#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5014#include <io.h>
alex-accc1bde62017-04-19 08:33:5515#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2816typedef HANDLE FileHandle;
17typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5018// Windows warns on using write(). It prefers _write().
19#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
20// Windows doesn't define STDERR_FILENO. Define it here.
21#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3422
[email protected]052f1b52008-11-06 21:43:0723#elif defined(OS_MACOSX)
Eric Noyaufce100702017-10-16 09:46:3424// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
25// in favor of OS_LOG (Unified Logging).
26#include <AvailabilityMacros.h>
27#if defined(OS_IOS)
28#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
29#define USE_ASL
30#endif
31#else // !defined(OS_IOS)
32#if !defined(MAC_OS_X_VERSION_10_12) || \
33 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
34#define USE_ASL
35#endif
36#endif // defined(OS_IOS)
37
38#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4239#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3440#else
41#include <os/log.h>
42#endif
43
mark4c7449c2015-11-10 19:53:4244#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2845#include <mach/mach.h>
46#include <mach/mach_time.h>
47#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3448
[email protected]e43eddf12009-12-29 00:32:5249#elif defined(OS_POSIX)
[email protected]19ea84ca2010-11-12 08:37:0850#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2751#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0852#endif
[email protected]052f1b52008-11-06 21:43:0753#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5954#endif
55
56#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2057#include <errno.h>
mark4c7449c2015-11-10 19:53:4258#include <paths.h>
[email protected]166326c62010-08-05 15:50:2359#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2860#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0061#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2862#include <string.h>
mark4c7449c2015-11-10 19:53:4263#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2864#include <unistd.h>
65#define MAX_PATH PATH_MAX
66typedef FILE* FileHandle;
67typedef pthread_mutex_t* MutexHandle;
68#endif
69
[email protected]1f88b5162011-04-01 00:02:2970#include <algorithm>
71#include <cstring>
initial.commitd7cae122008-07-26 21:49:3872#include <ctime>
73#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2974#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0175#include <string>
alex-accc1bde62017-04-19 08:33:5576#include <utility>
[email protected]b16ef312008-08-19 18:36:2377
initial.commitd7cae122008-07-26 21:49:3878#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5579#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3880#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2881#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5582#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0583#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5084#include "base/debug/debugger.h"
85#include "base/debug/stack_trace.h"
alex-accc1bde62017-04-19 08:33:5586#include "base/lazy_instance.h"
[email protected]2025d002012-11-14 20:54:3587#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0088#include "base/strings/string_piece.h"
[email protected]c914d8a2014-04-23 01:11:0189#include "base/strings/string_util.h"
90#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:4291#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:0792#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2093#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0994#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3695#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0496#if defined(OS_POSIX)
brettw6ee6fd62015-06-09 18:05:2497#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:0498#endif
[email protected]52a261f2009-03-03 15:01:1299
[email protected]3132e35c2011-07-07 20:46:50100#if defined(OS_ANDROID)
101#include <android/log.h>
102#endif
103
Wezb0501302018-03-09 05:18:45104#if defined(OS_FUCHSIA)
105#include <zircon/process.h>
106#include <zircon/syscalls.h>
107#endif
108
initial.commitd7cae122008-07-26 21:49:38109namespace logging {
110
[email protected]064aa162011-12-03 00:30:08111namespace {
112
thestig3e4787d2015-05-19 19:31:52113VlogInfo* g_vlog_info = nullptr;
114VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38115
weza245bd072017-06-18 23:26:34116const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
117static_assert(LOG_NUM_SEVERITIES == arraysize(log_severity_names),
118 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38119
thestig75f87352014-12-03 21:42:27120const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19121 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
122 return log_severity_names[severity];
123 return "UNKNOWN";
124}
125
thestig3e4787d2015-05-19 19:31:52126int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32127
thestig3e4787d2015-05-19 19:31:52128LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38129
[email protected]a33c9892008-08-25 20:10:31130// For LOG_ERROR and above, always print to stderr.
131const int kAlwaysPrintErrorLevel = LOG_ERROR;
132
[email protected]614e9fa2008-08-11 22:52:59133// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38134// will be lazily initialized to the default value when it is
135// first needed.
[email protected]f6abeba2008-08-08 13:27:28136#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59137typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:28138#else
[email protected]614e9fa2008-08-11 22:52:59139typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28140#endif
thestig3e4787d2015-05-19 19:31:52141PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38142
thestig3e4787d2015-05-19 19:31:52143// This file is lazily opened and the handle may be nullptr
144FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38145
thestig3e4787d2015-05-19 19:31:52146// What should be prepended to each message?
147bool g_log_process_id = false;
148bool g_log_thread_id = false;
149bool g_log_timestamp = true;
150bool g_log_tickcount = false;
initial.commitd7cae122008-07-26 21:49:38151
[email protected]81e0a852010-08-17 00:38:12152// Should we pop up fatal debug messages in a dialog?
153bool show_error_dialogs = false;
154
initial.commitd7cae122008-07-26 21:49:38155// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55156// the debug message dialog and process termination. Assert handlers are stored
157// in stack to allow overriding and restoring.
Brett Wilson1f07f20e2017-10-02 18:55:28158base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
alex-accc1bde62017-04-19 08:33:55159 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
160
[email protected]2b07b8412009-11-25 15:26:34161// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52162LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38163
[email protected]f6abeba2008-08-08 13:27:28164// Helper functions to wrap platform differences.
165
avi9b6f42932015-12-26 22:15:14166int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24167#if defined(OS_WIN)
168 return GetCurrentProcessId();
Wezb0501302018-03-09 05:18:45169#elif defined(OS_FUCHSIA)
170 zx_info_handle_basic_t basic = {};
171 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
172 sizeof(basic), nullptr, nullptr);
173 return basic.koid;
[email protected]f8588472008-11-05 23:17:24174#elif defined(OS_POSIX)
175 return getpid();
176#endif
177}
178
avi9b6f42932015-12-26 22:15:14179uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24180#if defined(OS_WIN)
181 return GetTickCount();
182#elif defined(OS_MACOSX)
183 return mach_absolute_time();
Wezb0501302018-03-09 05:18:45184#elif defined(OS_FUCHSIA)
185 return zx_clock_get(ZX_CLOCK_MONOTONIC) /
186 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
[email protected]19ea84ca2010-11-12 08:37:08187#elif defined(OS_NACL)
188 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
189 // So we have to use clock() for now.
190 return clock();
[email protected]e43eddf12009-12-29 00:32:52191#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07192 struct timespec ts;
193 clock_gettime(CLOCK_MONOTONIC, &ts);
194
avi9b6f42932015-12-26 22:15:14195 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
196 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07197
198 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24199#endif
200}
201
[email protected]614e9fa2008-08-11 22:52:59202void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28203#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59204 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27205#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45206 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28207#else
[email protected]614e9fa2008-08-11 22:52:59208 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28209#endif
210}
initial.commitd7cae122008-07-26 21:49:38211
[email protected]5f95d532010-10-01 17:16:58212PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55213#if defined(OS_WIN)
214 // On Windows we use the same path as the exe.
215 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52216 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58217
scottmgfc5b7072015-01-27 21:46:28218 PathString log_name = module_name;
219 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58220 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28221 log_name.erase(last_backslash + 1);
222 log_name += L"debug.log";
223 return log_name;
[email protected]5b84fe32010-09-14 22:24:55224#elif defined(OS_POSIX)
225 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58226 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55227#endif
228}
229
ananta61762fb2015-09-18 01:00:09230// We don't need locks on Windows for atomically appending to files. The OS
231// provides this functionality.
232#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55233// This class acts as a wrapper for locking the logging files.
234// LoggingLock::Init() should be called from the main thread before any logging
235// is done. Then whenever logging, be sure to have a local LoggingLock
236// instance on the stack. This will ensure that the lock is unlocked upon
237// exiting the frame.
238// LoggingLocks can not be nested.
239class LoggingLock {
240 public:
241 LoggingLock() {
242 LockLogging();
243 }
244
245 ~LoggingLock() {
246 UnlockLogging();
247 }
248
249 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
250 if (initialized)
251 return;
252 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58253
ananta61762fb2015-09-18 01:00:09254 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20255 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09256
[email protected]5b84fe32010-09-14 22:24:55257 initialized = true;
258 }
259
260 private:
261 static void LockLogging() {
262 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09263#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55264 pthread_mutex_lock(&log_mutex);
265#endif
266 } else {
267 // use the lock
268 log_lock->Lock();
269 }
270 }
271
272 static void UnlockLogging() {
273 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09274#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55275 pthread_mutex_unlock(&log_mutex);
276#endif
277 } else {
278 log_lock->Unlock();
279 }
280 }
281
282 // The lock is used if log file locking is false. It helps us avoid problems
283 // with multiple threads writing to the log file at the same time. Use
284 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20285 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55286
287 // When we don't use a lock, we are using a global mutex. We need to do this
288 // because LockFileEx is not thread safe.
ananta61762fb2015-09-18 01:00:09289#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55290 static pthread_mutex_t log_mutex;
291#endif
292
293 static bool initialized;
294 static LogLockingState lock_log_file;
295};
296
297// static
298bool LoggingLock::initialized = false;
299// static
thestig3e4787d2015-05-19 19:31:52300base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55301// static
302LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
303
ananta61762fb2015-09-18 01:00:09304#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55305pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
306#endif
307
ananta61762fb2015-09-18 01:00:09308#endif // OS_WIN
309
thestig3e4787d2015-05-19 19:31:52310// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38311// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52312// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38313bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52314 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38315 return true;
316
thestig3e4787d2015-05-19 19:31:52317 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59318 // Nobody has called InitLogging to specify a debug log file, so here we
319 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52320 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38321 }
322
thestig3e4787d2015-05-19 19:31:52323 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59324#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09325 // The FILE_APPEND_DATA access mask ensures that the file is atomically
326 // appended to across accesses from multiple threads.
327 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
328 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
329 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52330 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
331 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
332 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02333 // We are intentionally not using FilePath or FileUtil here to reduce the
334 // dependencies of the logging implementation. For e.g. FilePath and
335 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
336 // some consumers of base logging like chrome_elf, etc.
337 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32338 // try the current directory
anantaf2651872016-06-16 22:21:02339 wchar_t system_buffer[MAX_PATH];
340 system_buffer[0] = 0;
341 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
342 system_buffer);
343 if (len == 0 || len > arraysize(system_buffer))
ananta61762fb2015-09-18 01:00:09344 return false;
345
anantaf2651872016-06-16 22:21:02346 *g_log_file_name = system_buffer;
347 // Append a trailing backslash if needed.
348 if (g_log_file_name->back() != L'\\')
349 *g_log_file_name += L"\\";
350 *g_log_file_name += L"debug.log";
ananta61762fb2015-09-18 01:00:09351
352 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52353 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
354 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
355 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
356 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32357 return false;
358 }
initial.commitd7cae122008-07-26 21:49:38359 }
[email protected]78c6dd62009-06-08 23:29:11360#elif defined(OS_POSIX)
thestig3e4787d2015-05-19 19:31:52361 g_log_file = fopen(g_log_file_name->c_str(), "a");
362 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11363 return false;
[email protected]f6abeba2008-08-08 13:27:28364#endif
[email protected]1d8c2702008-08-19 23:39:32365 }
366
initial.commitd7cae122008-07-26 21:49:38367 return true;
368}
369
[email protected]17dcf752013-07-15 21:47:09370void CloseFile(FileHandle log) {
371#if defined(OS_WIN)
372 CloseHandle(log);
373#else
374 fclose(log);
375#endif
376}
377
378void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52379 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09380 return;
381
thestig3e4787d2015-05-19 19:31:52382 CloseFile(g_log_file);
383 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09384}
385
[email protected]064aa162011-12-03 00:30:08386} // namespace
387
Wez289477f2017-08-24 20:51:30388#if DCHECK_IS_ON() && defined(SYZYASAN)
389// In DCHECK-enabled SyzyASAN builds, allow the meaning of LOG_DCHECK to be
390// determined at run-time. We default it to INFO, to avoid it triggering
391// crashes before the run-time has explicitly chosen the behaviour.
392BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
393#endif
394
scottmg3c957a52016-12-10 20:57:59395// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
396// an object of the correct type on the LHS of the unused part of the ternary
397// operator.
398std::ostream* g_swallow_stream;
399
[email protected]5e3f7c22013-06-21 21:15:33400LoggingSettings::LoggingSettings()
401 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52402 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33403 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38404 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08405
[email protected]5e3f7c22013-06-21 21:15:33406bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45407#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33408 // Can log only to the system debug log.
409 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45410#endif
pgal.u-szeged421dddb2014-11-25 12:55:02411 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52412 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36413 // vlog switches.
414 if (command_line->HasSwitch(switches::kV) ||
415 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52416 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08417 // by another thread. Don't delete the old VLogInfo, just create a second
418 // one. We keep track of both to avoid memory leak warnings.
419 CHECK(!g_vlog_info_prev);
420 g_vlog_info_prev = g_vlog_info;
421
[email protected]99b7c57f2010-09-29 19:26:36422 g_vlog_info =
423 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49424 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52425 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36426 }
427
thestig3e4787d2015-05-19 19:31:52428 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38429
[email protected]5e3f7c22013-06-21 21:15:33430 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52431 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21432 return true;
initial.commitd7cae122008-07-26 21:49:38433
ananta61762fb2015-09-18 01:00:09434#if !defined(OS_WIN)
[email protected]17dcf752013-07-15 21:47:09435 LoggingLock::Init(settings.lock_log, settings.log_file);
436 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09437#endif
[email protected]17dcf752013-07-15 21:47:09438
439 // Calling InitLogging twice or after some log call has already opened the
440 // default log file will re-initialize to the new options.
441 CloseLogFileUnlocked();
442
thestig3e4787d2015-05-19 19:31:52443 if (!g_log_file_name)
444 g_log_file_name = new PathString();
445 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33446 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52447 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38448
[email protected]c7d5da992010-10-28 00:20:21449 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38450}
451
452void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52453 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38454}
455
456int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52457 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38458}
459
skobesc78c0ad72015-12-07 20:21:23460bool ShouldCreateLogMessage(int severity) {
461 if (severity < g_min_log_level)
462 return false;
463
464 // Return true here unless we know ~LogMessage won't do anything. Note that
465 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
466 // when g_logging_destination is LOG_NONE.
467 return g_logging_destination != LOG_NONE || log_message_handler ||
468 severity >= kAlwaysPrintErrorLevel;
469}
470
[email protected]162ac0f2010-11-04 15:50:49471int GetVlogVerbosity() {
472 return std::max(-1, LOG_INFO - GetMinLogLevel());
473}
474
[email protected]99b7c57f2010-09-29 19:26:36475int GetVlogLevelHelper(const char* file, size_t N) {
476 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52477 // Note: |g_vlog_info| may change on a different thread during startup
478 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08479 VlogInfo* vlog_info = g_vlog_info;
480 return vlog_info ?
481 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49482 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36483}
484
initial.commitd7cae122008-07-26 21:49:38485void SetLogItems(bool enable_process_id, bool enable_thread_id,
486 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52487 g_log_process_id = enable_process_id;
488 g_log_thread_id = enable_thread_id;
489 g_log_timestamp = enable_timestamp;
490 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38491}
492
[email protected]81e0a852010-08-17 00:38:12493void SetShowErrorDialogs(bool enable_dialogs) {
494 show_error_dialogs = enable_dialogs;
495}
496
alex-accc1bde62017-04-19 08:33:55497ScopedLogAssertHandler::ScopedLogAssertHandler(
498 LogAssertHandlerFunction handler) {
499 log_assert_handler_stack.Get().push(std::move(handler));
500}
501
502ScopedLogAssertHandler::~ScopedLogAssertHandler() {
503 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38504}
505
[email protected]2b07b8412009-11-25 15:26:34506void SetLogMessageHandler(LogMessageHandlerFunction handler) {
507 log_message_handler = handler;
508}
509
[email protected]64e5cc02010-11-03 19:20:27510LogMessageHandlerFunction GetLogMessageHandler() {
511 return log_message_handler;
512}
513
[email protected]6d445d32010-09-30 19:10:03514// Explicit instantiations for commonly used comparisons.
515template std::string* MakeCheckOpString<int, int>(
516 const int&, const int&, const char* names);
517template std::string* MakeCheckOpString<unsigned long, unsigned long>(
518 const unsigned long&, const unsigned long&, const char* names);
519template std::string* MakeCheckOpString<unsigned long, unsigned int>(
520 const unsigned long&, const unsigned int&, const char* names);
521template std::string* MakeCheckOpString<unsigned int, unsigned long>(
522 const unsigned int&, const unsigned long&, const char* names);
523template std::string* MakeCheckOpString<std::string, std::string>(
524 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34525
jbroman6bcfec422016-05-26 00:28:46526void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16527 (*os) << "nullptr";
528}
529
[email protected]f2c05492014-06-17 12:04:23530#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22531// Displays a message box to the user with the error message in it.
532// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25533// This is for developers only; we don't use this in circumstances
534// (like release builds) where users could see it, since users don't
535// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22536void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38537 if (str.empty())
538 return;
539
[email protected]81e0a852010-08-17 00:38:12540 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44541 return;
542
[email protected]f6abeba2008-08-08 13:27:28543#if defined(OS_WIN)
brettwe33526852015-10-03 00:46:01544 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
545 MB_OK | MB_ICONHAND | MB_TOPMOST);
[email protected]f6abeba2008-08-08 13:27:28546#else
[email protected]561513f2010-12-16 23:29:25547 // We intentionally don't implement a dialog on other platforms.
548 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52549#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38550}
[email protected]f2c05492014-06-17 12:04:23551#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38552
[email protected]3f85caa2009-04-14 16:52:11553#if defined(OS_WIN)
554LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
555}
556
557LogMessage::SaveLastError::~SaveLastError() {
558 ::SetLastError(last_error_);
559}
560#endif // defined(OS_WIN)
561
[email protected]eae9c062011-01-11 00:50:59562LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
563 : severity_(severity), file_(file), line_(line) {
564 Init(file, line);
565}
566
tnagel4a045d3f2015-07-12 14:19:28567LogMessage::LogMessage(const char* file, int line, const char* condition)
568 : severity_(LOG_FATAL), file_(file), line_(line) {
569 Init(file, line);
570 stream_ << "Check failed: " << condition << ". ";
571}
572
[email protected]9c7132e2011-02-08 07:39:08573LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49574 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38575 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08576 stream_ << "Check failed: " << *result;
577 delete result;
initial.commitd7cae122008-07-26 21:49:38578}
579
[email protected]fb62a532009-02-12 01:19:05580LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08581 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49582 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05583 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08584 stream_ << "Check failed: " << *result;
585 delete result;
[email protected]fb62a532009-02-12 01:19:05586}
587
initial.commitd7cae122008-07-26 21:49:38588LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55589 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08590#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
591 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42592 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
593 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50594 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24595 stream_ << std::endl; // Newline to separate from log message.
596 trace.OutputToStream(&stream_);
597 }
[email protected]1d8c2702008-08-19 23:39:32598#endif
[email protected]d1ccc35a2010-03-24 05:03:24599 stream_ << std::endl;
600 std::string str_newline(stream_.str());
601
[email protected]2b07b8412009-11-25 15:26:34602 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33603 if (log_message_handler &&
604 log_message_handler(severity_, file_, line_,
605 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49606 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34607 return;
[email protected]162ac0f2010-11-04 15:50:49608 }
initial.commitd7cae122008-07-26 21:49:38609
thestig3e4787d2015-05-19 19:31:52610 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28611#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38612 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42613#elif defined(OS_MACOSX)
614 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34615 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
616 // its successor OS_LOG. If there's something weird about stderr, assume
617 // that log messages are going nowhere and log via ASL/OS_LOG too.
618 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42619 //
620 // Programs started by launchd, as UI applications normally are, have had
621 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
622 // a pipe to launchd, which logged what it received (see log_redirect_fd in
623 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
624 //
625 // Another alternative would be to determine whether stderr is a pipe to
626 // launchd and avoid logging via ASL only in that case. See 10.7.5
627 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34628 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
629 // to the system log at all.
mark4c7449c2015-11-10 19:53:42630 //
631 // Note that the ASL client by default discards messages whose levels are
632 // below ASL_LEVEL_NOTICE. It's possible to change that with
633 // asl_set_filter(), but this is pointless because syslogd normally applies
634 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34635 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42636 struct stat stderr_stat;
637 if (fstat(fileno(stderr), &stderr_stat) == -1) {
638 return true;
639 }
640 if (!S_ISCHR(stderr_stat.st_mode)) {
641 return false;
642 }
643
644 struct stat dev_null_stat;
645 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
646 return true;
647 }
648
649 return !S_ISCHR(dev_null_stat.st_mode) ||
650 stderr_stat.st_rdev == dev_null_stat.st_rdev;
651 }();
652
Eric Noyaufce100702017-10-16 09:46:34653 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42654 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
655 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42656 CFBundleRef main_bundle = CFBundleGetMainBundle();
657 CFStringRef main_bundle_id_cf =
658 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34659 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42660 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34661 : std::string("");
662#if defined(USE_ASL)
663 // The facility is set to the main bundle ID if available. Otherwise,
664 // "com.apple.console" is used.
665 const class ASLClient {
mark4c7449c2015-11-10 19:53:42666 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59667 explicit ASLClient(const std::string& facility)
668 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42669 ~ASLClient() { asl_close(client_); }
670
671 aslclient get() const { return client_; }
672
673 private:
674 aslclient client_;
675 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34676 } asl_client(main_bundle_id.empty() ? main_bundle_id
677 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42678
Eric Noyaufce100702017-10-16 09:46:34679 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42680 public:
681 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
682 ~ASLMessage() { asl_free(message_); }
683
684 aslmsg get() const { return message_; }
685
686 private:
687 aslmsg message_;
688 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
689 } asl_message;
690
691 // By default, messages are only readable by the admin group. Explicitly
692 // make them readable by the user generating the messages.
693 char euid_string[12];
694 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
695 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
696
697 // Map Chrome log severities to ASL log levels.
698 const char* const asl_level_string = [](LogSeverity severity) {
699 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
700 // non-obvious two-step macro trick achieves what's needed.
701 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
702#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
703#define ASL_LEVEL_STR_X(level) #level
704 switch (severity) {
705 case LOG_INFO:
706 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
707 case LOG_WARNING:
708 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
709 case LOG_ERROR:
710 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
711 case LOG_FATAL:
712 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
713 default:
714 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
715 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
716 }
717#undef ASL_LEVEL_STR
718#undef ASL_LEVEL_STR_X
719 }(severity_);
720 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
721
722 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
723
724 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34725#else // !defined(USE_ASL)
726 const class OSLog {
727 public:
728 explicit OSLog(const char* subsystem)
729 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
730 : OS_LOG_DEFAULT) {}
731 ~OSLog() {
732 if (os_log_ != OS_LOG_DEFAULT) {
733 os_release(os_log_);
734 }
735 }
736 os_log_t get() const { return os_log_; }
737
738 private:
739 os_log_t os_log_;
740 DISALLOW_COPY_AND_ASSIGN(OSLog);
741 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
742 const os_log_type_t os_log_type = [](LogSeverity severity) {
743 switch (severity) {
744 case LOG_INFO:
745 return OS_LOG_TYPE_INFO;
746 case LOG_WARNING:
747 return OS_LOG_TYPE_DEFAULT;
748 case LOG_ERROR:
749 return OS_LOG_TYPE_ERROR;
750 case LOG_FATAL:
751 return OS_LOG_TYPE_FAULT;
752 default:
753 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
754 }
755 }(severity_);
756 os_log_with_type(log.get(), os_log_type, "%{public}s",
757 str_newline.c_str());
758#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42759 }
[email protected]3132e35c2011-07-07 20:46:50760#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25761 android_LogPriority priority =
762 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50763 switch (severity_) {
764 case LOG_INFO:
765 priority = ANDROID_LOG_INFO;
766 break;
767 case LOG_WARNING:
768 priority = ANDROID_LOG_WARN;
769 break;
770 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50771 priority = ANDROID_LOG_ERROR;
772 break;
773 case LOG_FATAL:
774 priority = ANDROID_LOG_FATAL;
775 break;
776 }
777 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18778#endif
[email protected]51105382014-03-14 17:02:15779 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06780 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31781 } else if (severity_ >= kAlwaysPrintErrorLevel) {
782 // When we're only outputting to a log file, above a certain log level, we
783 // should still output to stderr so that we can better detect and diagnose
784 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15785 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02786 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28787 }
[email protected]52a261f2009-03-03 15:01:12788
initial.commitd7cae122008-07-26 21:49:38789 // write to log file
thestig3e4787d2015-05-19 19:31:52790 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09791 // We can have multiple threads and/or processes, so try to prevent them
792 // from clobbering each other's writes.
793 // If the client app did not call InitLogging, and the lock has not
794 // been created do it now. We do this on demand, but if two threads try
795 // to do this at the same time, there will be a race condition to create
796 // the lock. This is why InitLogging should be called from the main
797 // thread at the beginning of execution.
ananta61762fb2015-09-18 01:00:09798#if !defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52799 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55800 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09801#endif
[email protected]5b84fe32010-09-14 22:24:55802 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28803#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55804 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52805 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55806 static_cast<const void*>(str_newline.c_str()),
807 static_cast<DWORD>(str_newline.length()),
808 &num_written,
thestig3e4787d2015-05-19 19:31:52809 nullptr);
[email protected]cba21962010-08-31 22:35:55810#else
[email protected]51105382014-03-14 17:02:15811 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52812 str_newline.data(), str_newline.size(), 1, g_log_file));
813 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55814#endif
initial.commitd7cae122008-07-26 21:49:38815 }
816 }
817
818 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40819 // Write the log message to the global activity tracker, if running.
820 base::debug::GlobalActivityTracker* tracker =
821 base::debug::GlobalActivityTracker::Get();
822 if (tracker)
823 tracker->RecordLogMessage(str_newline);
824
[email protected]eb4c4d032012-04-03 18:45:05825 // Ensure the first characters of the string are on the stack so they
826 // are contained in minidumps for diagnostic purposes.
Lukasz Anforowicz68c21772018-01-13 03:42:44827 DEBUG_ALIAS_FOR_CSTR(str_stack, str_newline.c_str(), 1024);
[email protected]eb4c4d032012-04-03 18:45:05828
Lukasz Anforowiczd3e19132017-12-06 19:44:27829 if (log_assert_handler_stack.IsCreated() &&
alex-accc1bde62017-04-19 08:33:55830 !log_assert_handler_stack.Get().empty()) {
831 LogAssertHandlerFunction log_assert_handler =
832 log_assert_handler_stack.Get().top();
833
834 if (log_assert_handler) {
835 log_assert_handler.Run(
836 file_, line_,
837 base::StringPiece(str_newline.c_str() + message_start_,
838 stack_start - message_start_),
839 base::StringPiece(str_newline.c_str() + stack_start));
840 }
[email protected]1ffe08c12008-08-13 11:15:11841 } else {
[email protected]82d89ab2014-02-28 18:25:34842 // Don't use the string with the newline, get a fresh version to send to
843 // the debug message process. We also don't display assertions to the
844 // user in release mode. The enduser can't do anything with this
845 // information, and displaying message boxes when the application is
846 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50847#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42848 if (!base::debug::BeingDebugged()) {
849 // Displaying a dialog is unnecessary when debugging and can complicate
850 // debugging.
851 DisplayDebugMessageInDialog(stream_.str());
852 }
[email protected]4d5901272008-11-06 00:33:50853#endif
[email protected]82d89ab2014-02-28 18:25:34854 // Crash the process to generate a dump.
855 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38856 }
857 }
858}
859
[email protected]eae9c062011-01-11 00:50:59860// writes the common header info to the stream
861void LogMessage::Init(const char* file, int line) {
862 base::StringPiece filename(file);
863 size_t last_slash_pos = filename.find_last_of("\\/");
864 if (last_slash_pos != base::StringPiece::npos)
865 filename.remove_prefix(last_slash_pos + 1);
866
867 // TODO(darin): It might be nice if the columns were fixed width.
868
869 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52870 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59871 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52872 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09873 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52874 if (g_log_timestamp) {
djkurtz543a3be2016-11-30 14:17:34875#if defined(OS_POSIX)
876 timeval tv;
877 gettimeofday(&tv, nullptr);
878 time_t t = tv.tv_sec;
879 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59880 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59881 struct tm* tm_time = &local_time;
882 stream_ << std::setfill('0')
883 << std::setw(2) << 1 + tm_time->tm_mon
884 << std::setw(2) << tm_time->tm_mday
885 << '/'
886 << std::setw(2) << tm_time->tm_hour
887 << std::setw(2) << tm_time->tm_min
888 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34889 << '.'
890 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59891 << ':';
djkurtz543a3be2016-11-30 14:17:34892#elif defined(OS_WIN)
893 SYSTEMTIME local_time;
894 GetLocalTime(&local_time);
895 stream_ << std::setfill('0')
896 << std::setw(2) << local_time.wMonth
897 << std::setw(2) << local_time.wDay
898 << '/'
899 << std::setw(2) << local_time.wHour
900 << std::setw(2) << local_time.wMinute
901 << std::setw(2) << local_time.wSecond
902 << '.'
903 << std::setw(3) << local_time.wMilliseconds
904 << ':';
905#endif
[email protected]eae9c062011-01-11 00:50:59906 }
thestig3e4787d2015-05-19 19:31:52907 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59908 stream_ << TickCount() << ':';
909 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19910 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59911 else
912 stream_ << "VERBOSE" << -severity_;
913
914 stream_ << ":" << filename << "(" << line << ")] ";
915
pkasting9cf9b94a2014-10-01 22:18:43916 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59917}
918
[email protected]d8617a62009-10-09 23:52:20919#if defined(OS_WIN)
920// This has already been defined in the header, but defining it again as DWORD
921// ensures that the type used in the header is equivalent to DWORD. If not,
922// the redefinition is a compile error.
923typedef DWORD SystemErrorCode;
924#endif
925
926SystemErrorCode GetLastSystemErrorCode() {
927#if defined(OS_WIN)
928 return ::GetLastError();
929#elif defined(OS_POSIX)
930 return errno;
931#else
932#error Not implemented
933#endif
934}
935
936#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01937BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27938 const int kErrorMessageBufferSize = 256;
939 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01940 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52941 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
942 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01943 if (len) {
944 // Messages returned by system end with line breaks.
945 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:45946 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:01947 }
Bruce Dawson19175842017-08-02 17:00:45948 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:01949 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20950}
[email protected]c914d8a2014-04-23 01:11:01951#elif defined(OS_POSIX)
952BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Robert Sesekd2f495f2017-07-25 22:03:14953 return base::safe_strerror(error_code) +
954 base::StringPrintf(" (%d)", error_code);
[email protected]c914d8a2014-04-23 01:11:01955}
956#else
957#error Not implemented
thestig3e4787d2015-05-19 19:31:52958#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20959
[email protected]c914d8a2014-04-23 01:11:01960
961#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20962Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
963 int line,
964 LogSeverity severity,
965 SystemErrorCode err)
966 : err_(err),
[email protected]d8617a62009-10-09 23:52:20967 log_message_(file, line, severity) {
968}
969
970Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01971 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06972 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
973 // field) and use Alias in hopes that it makes it into crash dumps.
974 DWORD last_error = err_;
975 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20976}
977#elif defined(OS_POSIX)
978ErrnoLogMessage::ErrnoLogMessage(const char* file,
979 int line,
980 LogSeverity severity,
981 SystemErrorCode err)
982 : err_(err),
983 log_message_(file, line, severity) {
984}
985
986ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01987 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:14988 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
989 // field) and use Alias in hopes that it makes it into crash dumps.
990 int last_error = err_;
991 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20992}
thestig3e4787d2015-05-19 19:31:52993#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20994
initial.commitd7cae122008-07-26 21:49:38995void CloseLogFile() {
ananta61762fb2015-09-18 01:00:09996#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55997 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09998#endif
[email protected]17dcf752013-07-15 21:47:09999 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381000}
1001
[email protected]e36ddc82009-12-08 04:22:501002void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491003 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501004 size_t bytes_written = 0;
1005 const size_t message_len = strlen(message);
1006 int rv;
1007 while (bytes_written < message_len) {
1008 rv = HANDLE_EINTR(
1009 write(STDERR_FILENO, message + bytes_written,
1010 message_len - bytes_written));
1011 if (rv < 0) {
1012 // Give up, nothing we can do now.
1013 break;
1014 }
1015 bytes_written += rv;
1016 }
1017
1018 if (message_len > 0 && message[message_len - 1] != '\n') {
1019 do {
1020 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1021 if (rv < 0) {
1022 // Give up, nothing we can do now.
1023 break;
1024 }
1025 } while (rv != 1);
1026 }
1027 }
1028
1029 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501030 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501031}
1032
[email protected]34a907732012-01-20 06:33:271033// This was defined at the beginning of this file.
1034#undef write
1035
[email protected]f01b88a2013-02-27 22:04:001036#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091037bool IsLoggingToFileEnabled() {
1038 return g_logging_destination & LOG_TO_FILE;
1039}
1040
[email protected]f01b88a2013-02-27 22:04:001041std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521042 if (g_log_file_name)
1043 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:001044 return std::wstring();
1045}
1046#endif
1047
tnagel80388e682015-05-26 13:27:561048BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:141049 LogMessage(file, line, LOG_ERROR).stream()
1050 << "NOTREACHED() hit.";
1051}
1052
[email protected]96fd0032009-04-24 00:13:081053} // namespace logging
initial.commitd7cae122008-07-26 21:49:381054
[email protected]81411c62014-07-08 23:03:061055std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491056 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381057}