blob: b5c21a53d71b0593cab3e2e94f0a8b9a15189e16 [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"
Weze976b732018-10-20 03:37:3111#include "base/stl_util.h"
avi9b6f42932015-12-26 22:15:1412#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5013
[email protected]b16ef312008-08-19 18:36:2314#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5015#include <io.h>
alex-accc1bde62017-04-19 08:33:5516#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2817typedef HANDLE FileHandle;
18typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5019// Windows warns on using write(). It prefers _write().
20#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
21// Windows doesn't define STDERR_FILENO. Define it here.
22#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3423
[email protected]052f1b52008-11-06 21:43:0724#elif defined(OS_MACOSX)
Eric Noyaufce100702017-10-16 09:46:3425// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
26// in favor of OS_LOG (Unified Logging).
27#include <AvailabilityMacros.h>
28#if defined(OS_IOS)
29#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
30#define USE_ASL
31#endif
32#else // !defined(OS_IOS)
33#if !defined(MAC_OS_X_VERSION_10_12) || \
34 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
35#define USE_ASL
36#endif
37#endif // defined(OS_IOS)
38
39#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4240#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3441#else
42#include <os/log.h>
43#endif
44
mark4c7449c2015-11-10 19:53:4245#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2846#include <mach/mach.h>
47#include <mach/mach_time.h>
48#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3449
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3950#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]19ea84ca2010-11-12 08:37:0851#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2752#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0853#endif
[email protected]052f1b52008-11-06 21:43:0754#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5955#endif
56
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3957#if defined(OS_FUCHSIA)
58#include <zircon/process.h>
59#include <zircon/syscalls.h>
60#endif
61
62#if defined(OS_ANDROID)
63#include <android/log.h>
64#endif
65
66#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2067#include <errno.h>
mark4c7449c2015-11-10 19:53:4268#include <paths.h>
[email protected]166326c62010-08-05 15:50:2369#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2870#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0071#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2872#include <string.h>
mark4c7449c2015-11-10 19:53:4273#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2874#include <unistd.h>
75#define MAX_PATH PATH_MAX
76typedef FILE* FileHandle;
77typedef pthread_mutex_t* MutexHandle;
78#endif
79
[email protected]1f88b5162011-04-01 00:02:2980#include <algorithm>
81#include <cstring>
initial.commitd7cae122008-07-26 21:49:3882#include <ctime>
83#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2984#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0185#include <string>
alex-accc1bde62017-04-19 08:33:5586#include <utility>
[email protected]b16ef312008-08-19 18:36:2387
initial.commitd7cae122008-07-26 21:49:3888#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5589#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3890#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2891#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5592#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0593#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5094#include "base/debug/debugger.h"
95#include "base/debug/stack_trace.h"
alex-accc1bde62017-04-19 08:33:5596#include "base/lazy_instance.h"
[email protected]2025d002012-11-14 20:54:3597#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0098#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:1399#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01100#include "base/strings/string_util.h"
101#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42102#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07103#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:20104#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:09105#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36106#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39107
108#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24109#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04110#endif
[email protected]52a261f2009-03-03 15:01:12111
initial.commitd7cae122008-07-26 21:49:38112namespace logging {
113
[email protected]064aa162011-12-03 00:30:08114namespace {
115
thestig3e4787d2015-05-19 19:31:52116VlogInfo* g_vlog_info = nullptr;
117VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38118
weza245bd072017-06-18 23:26:34119const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
120static_assert(LOG_NUM_SEVERITIES == arraysize(log_severity_names),
121 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38122
thestig75f87352014-12-03 21:42:27123const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19124 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
125 return log_severity_names[severity];
126 return "UNKNOWN";
127}
128
thestig3e4787d2015-05-19 19:31:52129int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32130
thestig3e4787d2015-05-19 19:31:52131LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38132
[email protected]a33c9892008-08-25 20:10:31133// For LOG_ERROR and above, always print to stderr.
134const int kAlwaysPrintErrorLevel = LOG_ERROR;
135
[email protected]614e9fa2008-08-11 22:52:59136// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38137// will be lazily initialized to the default value when it is
138// first needed.
[email protected]f6abeba2008-08-08 13:27:28139#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59140typedef std::wstring PathString;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39141#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59142typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28143#endif
thestig3e4787d2015-05-19 19:31:52144PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38145
thestig3e4787d2015-05-19 19:31:52146// This file is lazily opened and the handle may be nullptr
147FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38148
thestig3e4787d2015-05-19 19:31:52149// What should be prepended to each message?
150bool g_log_process_id = false;
151bool g_log_thread_id = false;
152bool g_log_timestamp = true;
153bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31154const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38155
[email protected]81e0a852010-08-17 00:38:12156// Should we pop up fatal debug messages in a dialog?
157bool show_error_dialogs = false;
158
initial.commitd7cae122008-07-26 21:49:38159// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55160// the debug message dialog and process termination. Assert handlers are stored
161// in stack to allow overriding and restoring.
Brett Wilson1f07f20e2017-10-02 18:55:28162base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
alex-accc1bde62017-04-19 08:33:55163 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
164
[email protected]2b07b8412009-11-25 15:26:34165// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52166LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38167
[email protected]f6abeba2008-08-08 13:27:28168// Helper functions to wrap platform differences.
169
avi9b6f42932015-12-26 22:15:14170int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24171#if defined(OS_WIN)
172 return GetCurrentProcessId();
Wezb0501302018-03-09 05:18:45173#elif defined(OS_FUCHSIA)
174 zx_info_handle_basic_t basic = {};
175 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
176 sizeof(basic), nullptr, nullptr);
177 return basic.koid;
[email protected]f8588472008-11-05 23:17:24178#elif defined(OS_POSIX)
179 return getpid();
180#endif
181}
182
avi9b6f42932015-12-26 22:15:14183uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24184#if defined(OS_WIN)
185 return GetTickCount();
Wezb0501302018-03-09 05:18:45186#elif defined(OS_FUCHSIA)
187 return zx_clock_get(ZX_CLOCK_MONOTONIC) /
188 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39189#elif defined(OS_MACOSX)
190 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08191#elif defined(OS_NACL)
192 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
193 // So we have to use clock() for now.
194 return clock();
[email protected]e43eddf12009-12-29 00:32:52195#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07196 struct timespec ts;
197 clock_gettime(CLOCK_MONOTONIC, &ts);
198
avi9b6f42932015-12-26 22:15:14199 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
200 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07201
202 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24203#endif
204}
205
[email protected]614e9fa2008-08-11 22:52:59206void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28207#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59208 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27209#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45210 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39211#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59212 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39213#else
214#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28215#endif
216}
initial.commitd7cae122008-07-26 21:49:38217
[email protected]5f95d532010-10-01 17:16:58218PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55219#if defined(OS_WIN)
220 // On Windows we use the same path as the exe.
221 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52222 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58223
scottmgfc5b7072015-01-27 21:46:28224 PathString log_name = module_name;
225 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58226 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28227 log_name.erase(last_backslash + 1);
228 log_name += L"debug.log";
229 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39230#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55231 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58232 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55233#endif
234}
235
ananta61762fb2015-09-18 01:00:09236// We don't need locks on Windows for atomically appending to files. The OS
237// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39238#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55239// This class acts as a wrapper for locking the logging files.
240// LoggingLock::Init() should be called from the main thread before any logging
241// is done. Then whenever logging, be sure to have a local LoggingLock
242// instance on the stack. This will ensure that the lock is unlocked upon
243// exiting the frame.
244// LoggingLocks can not be nested.
245class LoggingLock {
246 public:
247 LoggingLock() {
248 LockLogging();
249 }
250
251 ~LoggingLock() {
252 UnlockLogging();
253 }
254
255 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
256 if (initialized)
257 return;
258 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58259
ananta61762fb2015-09-18 01:00:09260 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20261 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09262
[email protected]5b84fe32010-09-14 22:24:55263 initialized = true;
264 }
265
266 private:
267 static void LockLogging() {
268 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55269 pthread_mutex_lock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55270 } else {
271 // use the lock
272 log_lock->Lock();
273 }
274 }
275
276 static void UnlockLogging() {
277 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55278 pthread_mutex_unlock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55279 } else {
280 log_lock->Unlock();
281 }
282 }
283
284 // The lock is used if log file locking is false. It helps us avoid problems
285 // with multiple threads writing to the log file at the same time. Use
286 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20287 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55288
289 // When we don't use a lock, we are using a global mutex. We need to do this
290 // because LockFileEx is not thread safe.
[email protected]5b84fe32010-09-14 22:24:55291 static pthread_mutex_t log_mutex;
[email protected]5b84fe32010-09-14 22:24:55292
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
[email protected]5b84fe32010-09-14 22:24:55304pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
[email protected]5b84fe32010-09-14 22:24:55305
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39306#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09307
thestig3e4787d2015-05-19 19:31:52308// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38309// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52310// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38311bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52312 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38313 return true;
314
thestig3e4787d2015-05-19 19:31:52315 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59316 // Nobody has called InitLogging to specify a debug log file, so here we
317 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52318 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38319 }
320
thestig3e4787d2015-05-19 19:31:52321 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59322#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09323 // The FILE_APPEND_DATA access mask ensures that the file is atomically
324 // appended to across accesses from multiple threads.
325 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
326 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
327 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52328 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
329 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
330 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02331 // We are intentionally not using FilePath or FileUtil here to reduce the
332 // dependencies of the logging implementation. For e.g. FilePath and
333 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
334 // some consumers of base logging like chrome_elf, etc.
335 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32336 // try the current directory
anantaf2651872016-06-16 22:21:02337 wchar_t system_buffer[MAX_PATH];
338 system_buffer[0] = 0;
339 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
340 system_buffer);
341 if (len == 0 || len > arraysize(system_buffer))
ananta61762fb2015-09-18 01:00:09342 return false;
343
anantaf2651872016-06-16 22:21:02344 *g_log_file_name = system_buffer;
345 // Append a trailing backslash if needed.
346 if (g_log_file_name->back() != L'\\')
347 *g_log_file_name += L"\\";
348 *g_log_file_name += L"debug.log";
ananta61762fb2015-09-18 01:00:09349
350 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52351 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
352 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
353 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
354 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32355 return false;
356 }
initial.commitd7cae122008-07-26 21:49:38357 }
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39358#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52359 g_log_file = fopen(g_log_file_name->c_str(), "a");
360 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11361 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39362#else
363#error Unsupported platform
[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);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39373#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09374 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39375#else
376#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09377#endif
378}
379
380void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52381 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09382 return;
383
thestig3e4787d2015-05-19 19:31:52384 CloseFile(g_log_file);
385 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09386}
387
[email protected]064aa162011-12-03 00:30:08388} // namespace
389
Weza6ca5b92018-03-23 19:03:07390#if DCHECK_IS_CONFIGURABLE
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51391// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30392// determined at run-time. We default it to INFO, to avoid it triggering
393// crashes before the run-time has explicitly chosen the behaviour.
394BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Weza6ca5b92018-03-23 19:03:07395#endif // DCHECK_IS_CONFIGURABLE
Wez289477f2017-08-24 20:51:30396
scottmg3c957a52016-12-10 20:57:59397// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
398// an object of the correct type on the LHS of the unused part of the ternary
399// operator.
400std::ostream* g_swallow_stream;
401
[email protected]5e3f7c22013-06-21 21:15:33402LoggingSettings::LoggingSettings()
403 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52404 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33405 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38406 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08407
[email protected]5e3f7c22013-06-21 21:15:33408bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45409#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33410 // Can log only to the system debug log.
411 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45412#endif
pgal.u-szeged421dddb2014-11-25 12:55:02413 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52414 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36415 // vlog switches.
416 if (command_line->HasSwitch(switches::kV) ||
417 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52418 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08419 // by another thread. Don't delete the old VLogInfo, just create a second
420 // one. We keep track of both to avoid memory leak warnings.
421 CHECK(!g_vlog_info_prev);
422 g_vlog_info_prev = g_vlog_info;
423
[email protected]99b7c57f2010-09-29 19:26:36424 g_vlog_info =
425 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49426 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52427 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36428 }
429
thestig3e4787d2015-05-19 19:31:52430 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38431
[email protected]5e3f7c22013-06-21 21:15:33432 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52433 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21434 return true;
initial.commitd7cae122008-07-26 21:49:38435
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39436#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09437 LoggingLock::Init(settings.lock_log, settings.log_file);
438 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09439#endif
[email protected]17dcf752013-07-15 21:47:09440
441 // Calling InitLogging twice or after some log call has already opened the
442 // default log file will re-initialize to the new options.
443 CloseLogFileUnlocked();
444
thestig3e4787d2015-05-19 19:31:52445 if (!g_log_file_name)
446 g_log_file_name = new PathString();
447 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33448 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52449 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38450
[email protected]c7d5da992010-10-28 00:20:21451 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38452}
453
454void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52455 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38456}
457
458int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52459 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38460}
461
skobesc78c0ad72015-12-07 20:21:23462bool ShouldCreateLogMessage(int severity) {
463 if (severity < g_min_log_level)
464 return false;
465
466 // Return true here unless we know ~LogMessage won't do anything. Note that
467 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
468 // when g_logging_destination is LOG_NONE.
469 return g_logging_destination != LOG_NONE || log_message_handler ||
470 severity >= kAlwaysPrintErrorLevel;
471}
472
[email protected]162ac0f2010-11-04 15:50:49473int GetVlogVerbosity() {
474 return std::max(-1, LOG_INFO - GetMinLogLevel());
475}
476
[email protected]99b7c57f2010-09-29 19:26:36477int GetVlogLevelHelper(const char* file, size_t N) {
478 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52479 // Note: |g_vlog_info| may change on a different thread during startup
480 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08481 VlogInfo* vlog_info = g_vlog_info;
482 return vlog_info ?
483 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49484 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36485}
486
initial.commitd7cae122008-07-26 21:49:38487void SetLogItems(bool enable_process_id, bool enable_thread_id,
488 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52489 g_log_process_id = enable_process_id;
490 g_log_thread_id = enable_thread_id;
491 g_log_timestamp = enable_timestamp;
492 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38493}
494
James Cooka0536c32018-08-01 20:13:31495void SetLogPrefix(const char* prefix) {
496 DCHECK(!prefix ||
497 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
498 g_log_prefix = prefix;
499}
500
[email protected]81e0a852010-08-17 00:38:12501void SetShowErrorDialogs(bool enable_dialogs) {
502 show_error_dialogs = enable_dialogs;
503}
504
alex-accc1bde62017-04-19 08:33:55505ScopedLogAssertHandler::ScopedLogAssertHandler(
506 LogAssertHandlerFunction handler) {
507 log_assert_handler_stack.Get().push(std::move(handler));
508}
509
510ScopedLogAssertHandler::~ScopedLogAssertHandler() {
511 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38512}
513
[email protected]2b07b8412009-11-25 15:26:34514void SetLogMessageHandler(LogMessageHandlerFunction handler) {
515 log_message_handler = handler;
516}
517
[email protected]64e5cc02010-11-03 19:20:27518LogMessageHandlerFunction GetLogMessageHandler() {
519 return log_message_handler;
520}
521
[email protected]6d445d32010-09-30 19:10:03522// Explicit instantiations for commonly used comparisons.
523template std::string* MakeCheckOpString<int, int>(
524 const int&, const int&, const char* names);
525template std::string* MakeCheckOpString<unsigned long, unsigned long>(
526 const unsigned long&, const unsigned long&, const char* names);
527template std::string* MakeCheckOpString<unsigned long, unsigned int>(
528 const unsigned long&, const unsigned int&, const char* names);
529template std::string* MakeCheckOpString<unsigned int, unsigned long>(
530 const unsigned int&, const unsigned long&, const char* names);
531template std::string* MakeCheckOpString<std::string, std::string>(
532 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34533
jbroman6bcfec422016-05-26 00:28:46534void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16535 (*os) << "nullptr";
536}
537
[email protected]f2c05492014-06-17 12:04:23538#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22539// Displays a message box to the user with the error message in it.
540// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25541// This is for developers only; we don't use this in circumstances
542// (like release builds) where users could see it, since users don't
543// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22544void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38545 if (str.empty())
546 return;
547
[email protected]81e0a852010-08-17 00:38:12548 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44549 return;
550
[email protected]f6abeba2008-08-08 13:27:28551#if defined(OS_WIN)
[email protected]561513f2010-12-16 23:29:25552 // We intentionally don't implement a dialog on other platforms.
553 // You can just look at stderr.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39554 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
555 MB_OK | MB_ICONHAND | MB_TOPMOST);
thestig3e4787d2015-05-19 19:31:52556#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38557}
[email protected]f2c05492014-06-17 12:04:23558#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38559
[email protected]eae9c062011-01-11 00:50:59560LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
561 : severity_(severity), file_(file), line_(line) {
562 Init(file, line);
563}
564
tnagel4a045d3f2015-07-12 14:19:28565LogMessage::LogMessage(const char* file, int line, const char* condition)
566 : severity_(LOG_FATAL), file_(file), line_(line) {
567 Init(file, line);
568 stream_ << "Check failed: " << condition << ". ";
569}
570
[email protected]9c7132e2011-02-08 07:39:08571LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49572 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38573 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08574 stream_ << "Check failed: " << *result;
575 delete result;
initial.commitd7cae122008-07-26 21:49:38576}
577
[email protected]fb62a532009-02-12 01:19:05578LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08579 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49580 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05581 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08582 stream_ << "Check failed: " << *result;
583 delete result;
[email protected]fb62a532009-02-12 01:19:05584}
585
initial.commitd7cae122008-07-26 21:49:38586LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55587 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08588#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
589 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42590 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
591 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50592 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24593 stream_ << std::endl; // Newline to separate from log message.
594 trace.OutputToStream(&stream_);
595 }
[email protected]1d8c2702008-08-19 23:39:32596#endif
[email protected]d1ccc35a2010-03-24 05:03:24597 stream_ << std::endl;
598 std::string str_newline(stream_.str());
599
[email protected]2b07b8412009-11-25 15:26:34600 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33601 if (log_message_handler &&
602 log_message_handler(severity_, file_, line_,
603 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49604 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34605 return;
[email protected]162ac0f2010-11-04 15:50:49606 }
initial.commitd7cae122008-07-26 21:49:38607
thestig3e4787d2015-05-19 19:31:52608 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28609#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38610 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42611#elif defined(OS_MACOSX)
612 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34613 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
614 // its successor OS_LOG. If there's something weird about stderr, assume
615 // that log messages are going nowhere and log via ASL/OS_LOG too.
616 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42617 //
618 // Programs started by launchd, as UI applications normally are, have had
619 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
620 // a pipe to launchd, which logged what it received (see log_redirect_fd in
621 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
622 //
623 // Another alternative would be to determine whether stderr is a pipe to
624 // launchd and avoid logging via ASL only in that case. See 10.7.5
625 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34626 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
627 // to the system log at all.
mark4c7449c2015-11-10 19:53:42628 //
629 // Note that the ASL client by default discards messages whose levels are
630 // below ASL_LEVEL_NOTICE. It's possible to change that with
631 // asl_set_filter(), but this is pointless because syslogd normally applies
632 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34633 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42634 struct stat stderr_stat;
635 if (fstat(fileno(stderr), &stderr_stat) == -1) {
636 return true;
637 }
638 if (!S_ISCHR(stderr_stat.st_mode)) {
639 return false;
640 }
641
642 struct stat dev_null_stat;
643 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
644 return true;
645 }
646
647 return !S_ISCHR(dev_null_stat.st_mode) ||
648 stderr_stat.st_rdev == dev_null_stat.st_rdev;
649 }();
650
Eric Noyaufce100702017-10-16 09:46:34651 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42652 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
653 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42654 CFBundleRef main_bundle = CFBundleGetMainBundle();
655 CFStringRef main_bundle_id_cf =
656 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34657 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42658 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34659 : std::string("");
660#if defined(USE_ASL)
661 // The facility is set to the main bundle ID if available. Otherwise,
662 // "com.apple.console" is used.
663 const class ASLClient {
mark4c7449c2015-11-10 19:53:42664 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59665 explicit ASLClient(const std::string& facility)
666 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42667 ~ASLClient() { asl_close(client_); }
668
669 aslclient get() const { return client_; }
670
671 private:
672 aslclient client_;
673 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34674 } asl_client(main_bundle_id.empty() ? main_bundle_id
675 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42676
Eric Noyaufce100702017-10-16 09:46:34677 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42678 public:
679 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
680 ~ASLMessage() { asl_free(message_); }
681
682 aslmsg get() const { return message_; }
683
684 private:
685 aslmsg message_;
686 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
687 } asl_message;
688
689 // By default, messages are only readable by the admin group. Explicitly
690 // make them readable by the user generating the messages.
691 char euid_string[12];
692 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
693 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
694
695 // Map Chrome log severities to ASL log levels.
696 const char* const asl_level_string = [](LogSeverity severity) {
697 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
698 // non-obvious two-step macro trick achieves what's needed.
699 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
700#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
701#define ASL_LEVEL_STR_X(level) #level
702 switch (severity) {
703 case LOG_INFO:
704 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
705 case LOG_WARNING:
706 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
707 case LOG_ERROR:
708 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
709 case LOG_FATAL:
710 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
711 default:
712 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
713 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
714 }
715#undef ASL_LEVEL_STR
716#undef ASL_LEVEL_STR_X
717 }(severity_);
718 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
719
720 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
721
722 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34723#else // !defined(USE_ASL)
724 const class OSLog {
725 public:
726 explicit OSLog(const char* subsystem)
727 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
728 : OS_LOG_DEFAULT) {}
729 ~OSLog() {
730 if (os_log_ != OS_LOG_DEFAULT) {
731 os_release(os_log_);
732 }
733 }
734 os_log_t get() const { return os_log_; }
735
736 private:
737 os_log_t os_log_;
738 DISALLOW_COPY_AND_ASSIGN(OSLog);
739 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
740 const os_log_type_t os_log_type = [](LogSeverity severity) {
741 switch (severity) {
742 case LOG_INFO:
743 return OS_LOG_TYPE_INFO;
744 case LOG_WARNING:
745 return OS_LOG_TYPE_DEFAULT;
746 case LOG_ERROR:
747 return OS_LOG_TYPE_ERROR;
748 case LOG_FATAL:
749 return OS_LOG_TYPE_FAULT;
750 default:
751 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
752 }
753 }(severity_);
754 os_log_with_type(log.get(), os_log_type, "%{public}s",
755 str_newline.c_str());
756#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42757 }
[email protected]3132e35c2011-07-07 20:46:50758#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25759 android_LogPriority priority =
760 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50761 switch (severity_) {
762 case LOG_INFO:
763 priority = ANDROID_LOG_INFO;
764 break;
765 case LOG_WARNING:
766 priority = ANDROID_LOG_WARN;
767 break;
768 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50769 priority = ANDROID_LOG_ERROR;
770 break;
771 case LOG_FATAL:
772 priority = ANDROID_LOG_FATAL;
773 break;
774 }
Xianzhu Wangae8d96a32018-10-16 20:41:13775#if DCHECK_IS_ON()
776 // Split the output by new lines to prevent the Android system from
777 // truncating the log.
778 for (const auto& line : base::SplitString(
779 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL))
780 __android_log_write(priority, "chromium", line.c_str());
781#else
782 // The Android system may truncate the string if it's too long.
[email protected]3132e35c2011-07-07 20:46:50783 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18784#endif
Xianzhu Wangae8d96a32018-10-16 20:41:13785#endif // OS_ANDROID
[email protected]51105382014-03-14 17:02:15786 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06787 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31788 } else if (severity_ >= kAlwaysPrintErrorLevel) {
789 // When we're only outputting to a log file, above a certain log level, we
790 // should still output to stderr so that we can better detect and diagnose
791 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15792 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02793 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28794 }
[email protected]52a261f2009-03-03 15:01:12795
initial.commitd7cae122008-07-26 21:49:38796 // write to log file
thestig3e4787d2015-05-19 19:31:52797 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09798 // We can have multiple threads and/or processes, so try to prevent them
799 // from clobbering each other's writes.
800 // If the client app did not call InitLogging, and the lock has not
801 // been created do it now. We do this on demand, but if two threads try
802 // to do this at the same time, there will be a race condition to create
803 // the lock. This is why InitLogging should be called from the main
804 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39805#if defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52806 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55807 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09808#endif
[email protected]5b84fe32010-09-14 22:24:55809 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28810#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55811 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52812 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55813 static_cast<const void*>(str_newline.c_str()),
814 static_cast<DWORD>(str_newline.length()),
815 &num_written,
thestig3e4787d2015-05-19 19:31:52816 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39817#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15818 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52819 str_newline.data(), str_newline.size(), 1, g_log_file));
820 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39821#else
822#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55823#endif
initial.commitd7cae122008-07-26 21:49:38824 }
825 }
826
827 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40828 // Write the log message to the global activity tracker, if running.
829 base::debug::GlobalActivityTracker* tracker =
830 base::debug::GlobalActivityTracker::Get();
831 if (tracker)
832 tracker->RecordLogMessage(str_newline);
833
[email protected]eb4c4d032012-04-03 18:45:05834 // Ensure the first characters of the string are on the stack so they
Weze976b732018-10-20 03:37:31835 // are contained in minidumps for diagnostic purposes. We place start
836 // and end marker values at either end, so we can scan captured stacks
837 // for the data easily.
838 struct {
839 uint32_t start_marker = 0xbedead01;
840 char data[1024];
841 uint32_t end_marker = 0x5050dead;
842 } str_stack;
843 base::strlcpy(str_stack.data, str_newline.data(),
844 base::size(str_stack.data));
845 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05846
Lukasz Anforowiczd3e19132017-12-06 19:44:27847 if (log_assert_handler_stack.IsCreated() &&
alex-accc1bde62017-04-19 08:33:55848 !log_assert_handler_stack.Get().empty()) {
849 LogAssertHandlerFunction log_assert_handler =
850 log_assert_handler_stack.Get().top();
851
852 if (log_assert_handler) {
853 log_assert_handler.Run(
854 file_, line_,
855 base::StringPiece(str_newline.c_str() + message_start_,
856 stack_start - message_start_),
857 base::StringPiece(str_newline.c_str() + stack_start));
858 }
[email protected]1ffe08c12008-08-13 11:15:11859 } else {
[email protected]82d89ab2014-02-28 18:25:34860 // Don't use the string with the newline, get a fresh version to send to
861 // the debug message process. We also don't display assertions to the
862 // user in release mode. The enduser can't do anything with this
863 // information, and displaying message boxes when the application is
864 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50865#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42866 if (!base::debug::BeingDebugged()) {
867 // Displaying a dialog is unnecessary when debugging and can complicate
868 // debugging.
869 DisplayDebugMessageInDialog(stream_.str());
870 }
[email protected]4d5901272008-11-06 00:33:50871#endif
[email protected]82d89ab2014-02-28 18:25:34872 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52873#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
874 IMMEDIATE_CRASH();
875#else
[email protected]82d89ab2014-02-28 18:25:34876 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52877#endif
initial.commitd7cae122008-07-26 21:49:38878 }
879 }
880}
881
[email protected]eae9c062011-01-11 00:50:59882// writes the common header info to the stream
883void LogMessage::Init(const char* file, int line) {
884 base::StringPiece filename(file);
885 size_t last_slash_pos = filename.find_last_of("\\/");
886 if (last_slash_pos != base::StringPiece::npos)
887 filename.remove_prefix(last_slash_pos + 1);
888
889 // TODO(darin): It might be nice if the columns were fixed width.
890
891 stream_ << '[';
James Cooka0536c32018-08-01 20:13:31892 if (g_log_prefix)
893 stream_ << g_log_prefix << ':';
thestig3e4787d2015-05-19 19:31:52894 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59895 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52896 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09897 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52898 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39899#if defined(OS_WIN)
900 SYSTEMTIME local_time;
901 GetLocalTime(&local_time);
902 stream_ << std::setfill('0')
903 << std::setw(2) << local_time.wMonth
904 << std::setw(2) << local_time.wDay
905 << '/'
906 << std::setw(2) << local_time.wHour
907 << std::setw(2) << local_time.wMinute
908 << std::setw(2) << local_time.wSecond
909 << '.'
910 << std::setw(3)
911 << local_time.wMilliseconds
912 << ':';
913#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
djkurtz543a3be2016-11-30 14:17:34914 timeval tv;
915 gettimeofday(&tv, nullptr);
916 time_t t = tv.tv_sec;
917 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59918 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59919 struct tm* tm_time = &local_time;
920 stream_ << std::setfill('0')
921 << std::setw(2) << 1 + tm_time->tm_mon
922 << std::setw(2) << tm_time->tm_mday
923 << '/'
924 << std::setw(2) << tm_time->tm_hour
925 << std::setw(2) << tm_time->tm_min
926 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34927 << '.'
928 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59929 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39930#else
931#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34932#endif
[email protected]eae9c062011-01-11 00:50:59933 }
thestig3e4787d2015-05-19 19:31:52934 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59935 stream_ << TickCount() << ':';
936 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19937 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59938 else
939 stream_ << "VERBOSE" << -severity_;
940
941 stream_ << ":" << filename << "(" << line << ")] ";
942
pkasting9cf9b94a2014-10-01 22:18:43943 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59944}
945
[email protected]d8617a62009-10-09 23:52:20946#if defined(OS_WIN)
947// This has already been defined in the header, but defining it again as DWORD
948// ensures that the type used in the header is equivalent to DWORD. If not,
949// the redefinition is a compile error.
950typedef DWORD SystemErrorCode;
951#endif
952
953SystemErrorCode GetLastSystemErrorCode() {
954#if defined(OS_WIN)
955 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39956#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20957 return errno;
[email protected]d8617a62009-10-09 23:52:20958#endif
959}
960
[email protected]c914d8a2014-04-23 01:11:01961BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39962#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:27963 const int kErrorMessageBufferSize = 256;
964 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01965 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52966 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
967 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01968 if (len) {
969 // Messages returned by system end with line breaks.
970 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:45971 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:01972 }
Bruce Dawson19175842017-08-02 17:00:45973 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:01974 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39975#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:14976 return base::safe_strerror(error_code) +
977 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:52978#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39979}
[email protected]d8617a62009-10-09 23:52:20980
[email protected]c914d8a2014-04-23 01:11:01981
982#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20983Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
984 int line,
985 LogSeverity severity,
986 SystemErrorCode err)
987 : err_(err),
[email protected]d8617a62009-10-09 23:52:20988 log_message_(file, line, severity) {
989}
990
991Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01992 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06993 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
994 // field) and use Alias in hopes that it makes it into crash dumps.
995 DWORD last_error = err_;
996 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20997}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39998#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20999ErrnoLogMessage::ErrnoLogMessage(const char* file,
1000 int line,
1001 LogSeverity severity,
1002 SystemErrorCode err)
1003 : err_(err),
1004 log_message_(file, line, severity) {
1005}
1006
1007ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011008 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141009 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1010 // field) and use Alias in hopes that it makes it into crash dumps.
1011 int last_error = err_;
1012 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201013}
thestig3e4787d2015-05-19 19:31:521014#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201015
initial.commitd7cae122008-07-26 21:49:381016void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391017#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:551018 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:091019#endif
[email protected]17dcf752013-07-15 21:47:091020 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381021}
1022
[email protected]e36ddc82009-12-08 04:22:501023void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491024 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501025 size_t bytes_written = 0;
1026 const size_t message_len = strlen(message);
1027 int rv;
1028 while (bytes_written < message_len) {
1029 rv = HANDLE_EINTR(
1030 write(STDERR_FILENO, message + bytes_written,
1031 message_len - bytes_written));
1032 if (rv < 0) {
1033 // Give up, nothing we can do now.
1034 break;
1035 }
1036 bytes_written += rv;
1037 }
1038
1039 if (message_len > 0 && message[message_len - 1] != '\n') {
1040 do {
1041 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1042 if (rv < 0) {
1043 // Give up, nothing we can do now.
1044 break;
1045 }
1046 } while (rv != 1);
1047 }
1048 }
1049
1050 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501051 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501052}
1053
[email protected]34a907732012-01-20 06:33:271054// This was defined at the beginning of this file.
1055#undef write
1056
[email protected]f01b88a2013-02-27 22:04:001057#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091058bool IsLoggingToFileEnabled() {
1059 return g_logging_destination & LOG_TO_FILE;
1060}
1061
[email protected]f01b88a2013-02-27 22:04:001062std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521063 if (g_log_file_name)
1064 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:001065 return std::wstring();
1066}
1067#endif
1068
tnagel80388e682015-05-26 13:27:561069BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:141070 LogMessage(file, line, LOG_ERROR).stream()
1071 << "NOTREACHED() hit.";
1072}
1073
[email protected]96fd0032009-04-24 00:13:081074} // namespace logging
initial.commitd7cae122008-07-26 21:49:381075
[email protected]81411c62014-07-08 23:03:061076std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491077 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381078}