blob: 971c2a8c9fdc10002e3691b8964c70813f2b8d56 [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
Weze976b732018-10-20 03:37:3110#include "base/stl_util.h"
avi9b6f42932015-12-26 22:15:1411#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
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3949#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[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
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3956#if defined(OS_FUCHSIA)
57#include <zircon/process.h>
58#include <zircon/syscalls.h>
59#endif
60
61#if defined(OS_ANDROID)
62#include <android/log.h>
63#endif
64
65#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2066#include <errno.h>
mark4c7449c2015-11-10 19:53:4267#include <paths.h>
[email protected]166326c62010-08-05 15:50:2368#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2869#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0070#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2871#include <string.h>
mark4c7449c2015-11-10 19:53:4272#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2873#include <unistd.h>
74#define MAX_PATH PATH_MAX
75typedef FILE* FileHandle;
76typedef pthread_mutex_t* MutexHandle;
77#endif
78
[email protected]1f88b5162011-04-01 00:02:2979#include <algorithm>
80#include <cstring>
initial.commitd7cae122008-07-26 21:49:3881#include <ctime>
82#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2983#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0184#include <string>
alex-accc1bde62017-04-19 08:33:5585#include <utility>
[email protected]b16ef312008-08-19 18:36:2386
initial.commitd7cae122008-07-26 21:49:3887#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5588#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3889#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2890#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5591#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0592#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5093#include "base/debug/debugger.h"
94#include "base/debug/stack_trace.h"
alex-accc1bde62017-04-19 08:33:5595#include "base/lazy_instance.h"
[email protected]2025d002012-11-14 20:54:3596#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0097#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:1398#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:0199#include "base/strings/string_util.h"
100#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42101#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07102#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:20103#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:09104#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36105#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39106
107#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24108#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04109#endif
[email protected]52a261f2009-03-03 15:01:12110
initial.commitd7cae122008-07-26 21:49:38111namespace logging {
112
[email protected]064aa162011-12-03 00:30:08113namespace {
114
thestig3e4787d2015-05-19 19:31:52115VlogInfo* g_vlog_info = nullptr;
116VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38117
weza245bd072017-06-18 23:26:34118const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Avi Drissmane3b70bf2019-01-04 19:50:22119static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
weza245bd072017-06-18 23:26:34120 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38121
thestig75f87352014-12-03 21:42:27122const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19123 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
124 return log_severity_names[severity];
125 return "UNKNOWN";
126}
127
thestig3e4787d2015-05-19 19:31:52128int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32129
thestig3e4787d2015-05-19 19:31:52130LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38131
[email protected]a33c9892008-08-25 20:10:31132// For LOG_ERROR and above, always print to stderr.
133const int kAlwaysPrintErrorLevel = LOG_ERROR;
134
[email protected]614e9fa2008-08-11 22:52:59135// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38136// will be lazily initialized to the default value when it is
137// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33138using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52139PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38140
thestig3e4787d2015-05-19 19:31:52141// This file is lazily opened and the handle may be nullptr
142FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38143
thestig3e4787d2015-05-19 19:31:52144// What should be prepended to each message?
145bool g_log_process_id = false;
146bool g_log_thread_id = false;
147bool g_log_timestamp = true;
148bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31149const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38150
[email protected]81e0a852010-08-17 00:38:12151// Should we pop up fatal debug messages in a dialog?
152bool show_error_dialogs = false;
153
initial.commitd7cae122008-07-26 21:49:38154// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55155// the debug message dialog and process termination. Assert handlers are stored
156// in stack to allow overriding and restoring.
Brett Wilson1f07f20e2017-10-02 18:55:28157base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
alex-accc1bde62017-04-19 08:33:55158 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
159
[email protected]2b07b8412009-11-25 15:26:34160// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52161LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38162
[email protected]f6abeba2008-08-08 13:27:28163// Helper functions to wrap platform differences.
164
avi9b6f42932015-12-26 22:15:14165int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24166#if defined(OS_WIN)
167 return GetCurrentProcessId();
Wezb0501302018-03-09 05:18:45168#elif defined(OS_FUCHSIA)
169 zx_info_handle_basic_t basic = {};
170 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
171 sizeof(basic), nullptr, nullptr);
172 return basic.koid;
[email protected]f8588472008-11-05 23:17:24173#elif defined(OS_POSIX)
174 return getpid();
175#endif
176}
177
avi9b6f42932015-12-26 22:15:14178uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24179#if defined(OS_WIN)
180 return GetTickCount();
Wezb0501302018-03-09 05:18:45181#elif defined(OS_FUCHSIA)
182 return zx_clock_get(ZX_CLOCK_MONOTONIC) /
183 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39184#elif defined(OS_MACOSX)
185 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08186#elif defined(OS_NACL)
187 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
188 // So we have to use clock() for now.
189 return clock();
[email protected]e43eddf12009-12-29 00:32:52190#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07191 struct timespec ts;
192 clock_gettime(CLOCK_MONOTONIC, &ts);
193
avi9b6f42932015-12-26 22:15:14194 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
195 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07196
197 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24198#endif
199}
200
[email protected]614e9fa2008-08-11 22:52:59201void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28202#if defined(OS_WIN)
jdoerrie5c4dc4e2019-02-01 18:02:33203 DeleteFile(base::wdata(log_name));
thestig75f87352014-12-03 21:42:27204#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45205 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39206#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59207 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39208#else
209#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28210#endif
211}
initial.commitd7cae122008-07-26 21:49:38212
[email protected]5f95d532010-10-01 17:16:58213PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55214#if defined(OS_WIN)
215 // On Windows we use the same path as the exe.
jdoerrie5c4dc4e2019-02-01 18:02:33216 base::char16 module_name[MAX_PATH];
217 GetModuleFileName(nullptr, base::wdata(module_name), MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58218
scottmgfc5b7072015-01-27 21:46:28219 PathString log_name = module_name;
220 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58221 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28222 log_name.erase(last_backslash + 1);
jdoerrie5c4dc4e2019-02-01 18:02:33223 log_name += STRING16_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28224 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39225#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55226 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58227 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55228#endif
229}
230
ananta61762fb2015-09-18 01:00:09231// We don't need locks on Windows for atomically appending to files. The OS
232// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39233#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55234// This class acts as a wrapper for locking the logging files.
235// LoggingLock::Init() should be called from the main thread before any logging
236// is done. Then whenever logging, be sure to have a local LoggingLock
237// instance on the stack. This will ensure that the lock is unlocked upon
238// exiting the frame.
239// LoggingLocks can not be nested.
240class LoggingLock {
241 public:
242 LoggingLock() {
243 LockLogging();
244 }
245
246 ~LoggingLock() {
247 UnlockLogging();
248 }
249
250 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
251 if (initialized)
252 return;
253 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58254
ananta61762fb2015-09-18 01:00:09255 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20256 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09257
[email protected]5b84fe32010-09-14 22:24:55258 initialized = true;
259 }
260
261 private:
262 static void LockLogging() {
263 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55264 pthread_mutex_lock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55265 } else {
266 // use the lock
267 log_lock->Lock();
268 }
269 }
270
271 static void UnlockLogging() {
272 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55273 pthread_mutex_unlock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55274 } else {
275 log_lock->Unlock();
276 }
277 }
278
279 // The lock is used if log file locking is false. It helps us avoid problems
280 // with multiple threads writing to the log file at the same time. Use
281 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20282 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55283
284 // When we don't use a lock, we are using a global mutex. We need to do this
285 // because LockFileEx is not thread safe.
[email protected]5b84fe32010-09-14 22:24:55286 static pthread_mutex_t log_mutex;
[email protected]5b84fe32010-09-14 22:24:55287
288 static bool initialized;
289 static LogLockingState lock_log_file;
290};
291
292// static
293bool LoggingLock::initialized = false;
294// static
thestig3e4787d2015-05-19 19:31:52295base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55296// static
297LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
298
[email protected]5b84fe32010-09-14 22:24:55299pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
[email protected]5b84fe32010-09-14 22:24:55300
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39301#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09302
thestig3e4787d2015-05-19 19:31:52303// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38304// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52305// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38306bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52307 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38308 return true;
309
thestig3e4787d2015-05-19 19:31:52310 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59311 // Nobody has called InitLogging to specify a debug log file, so here we
312 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52313 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38314 }
315
thestig3e4787d2015-05-19 19:31:52316 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59317#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09318 // The FILE_APPEND_DATA access mask ensures that the file is atomically
319 // appended to across accesses from multiple threads.
320 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
321 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
jdoerrie5c4dc4e2019-02-01 18:02:33322 g_log_file = CreateFile(base::wdata(*g_log_file_name), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52323 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
324 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
325 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02326 // We are intentionally not using FilePath or FileUtil here to reduce the
327 // dependencies of the logging implementation. For e.g. FilePath and
328 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
329 // some consumers of base logging like chrome_elf, etc.
330 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32331 // try the current directory
jdoerrie5c4dc4e2019-02-01 18:02:33332 base::char16 system_buffer[MAX_PATH];
anantaf2651872016-06-16 22:21:02333 system_buffer[0] = 0;
jdoerrie5c4dc4e2019-02-01 18:02:33334 DWORD len = ::GetCurrentDirectory(base::size(system_buffer),
335 base::wdata(system_buffer));
Avi Drissmane3b70bf2019-01-04 19:50:22336 if (len == 0 || len > base::size(system_buffer))
ananta61762fb2015-09-18 01:00:09337 return false;
338
anantaf2651872016-06-16 22:21:02339 *g_log_file_name = system_buffer;
340 // Append a trailing backslash if needed.
341 if (g_log_file_name->back() != L'\\')
jdoerrie5c4dc4e2019-02-01 18:02:33342 *g_log_file_name += STRING16_LITERAL("\\");
343 *g_log_file_name += STRING16_LITERAL("debug.log");
ananta61762fb2015-09-18 01:00:09344
jdoerrie5c4dc4e2019-02-01 18:02:33345 g_log_file = CreateFile(base::wdata(*g_log_file_name), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52346 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
347 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
348 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
349 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32350 return false;
351 }
initial.commitd7cae122008-07-26 21:49:38352 }
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39353#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52354 g_log_file = fopen(g_log_file_name->c_str(), "a");
355 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11356 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39357#else
358#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28359#endif
[email protected]1d8c2702008-08-19 23:39:32360 }
361
initial.commitd7cae122008-07-26 21:49:38362 return true;
363}
364
[email protected]17dcf752013-07-15 21:47:09365void CloseFile(FileHandle log) {
366#if defined(OS_WIN)
367 CloseHandle(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39368#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09369 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39370#else
371#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09372#endif
373}
374
375void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52376 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09377 return;
378
thestig3e4787d2015-05-19 19:31:52379 CloseFile(g_log_file);
380 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09381}
382
[email protected]064aa162011-12-03 00:30:08383} // namespace
384
Tomas Popelaafffa972018-11-13 20:42:05385#if defined(DCHECK_IS_CONFIGURABLE)
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51386// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30387// determined at run-time. We default it to INFO, to avoid it triggering
388// crashes before the run-time has explicitly chosen the behaviour.
389BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Tomas Popelaafffa972018-11-13 20:42:05390#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30391
scottmg3c957a52016-12-10 20:57:59392// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
393// an object of the correct type on the LHS of the unused part of the ternary
394// operator.
395std::ostream* g_swallow_stream;
396
[email protected]5e3f7c22013-06-21 21:15:33397LoggingSettings::LoggingSettings()
398 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52399 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33400 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38401 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08402
[email protected]5e3f7c22013-06-21 21:15:33403bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45404#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33405 // Can log only to the system debug log.
406 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45407#endif
pgal.u-szeged421dddb2014-11-25 12:55:02408 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52409 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36410 // vlog switches.
411 if (command_line->HasSwitch(switches::kV) ||
412 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52413 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08414 // by another thread. Don't delete the old VLogInfo, just create a second
415 // one. We keep track of both to avoid memory leak warnings.
416 CHECK(!g_vlog_info_prev);
417 g_vlog_info_prev = g_vlog_info;
418
[email protected]99b7c57f2010-09-29 19:26:36419 g_vlog_info =
420 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49421 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52422 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36423 }
424
thestig3e4787d2015-05-19 19:31:52425 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38426
[email protected]5e3f7c22013-06-21 21:15:33427 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52428 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21429 return true;
initial.commitd7cae122008-07-26 21:49:38430
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39431#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09432 LoggingLock::Init(settings.lock_log, settings.log_file);
433 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09434#endif
[email protected]17dcf752013-07-15 21:47:09435
436 // Calling InitLogging twice or after some log call has already opened the
437 // default log file will re-initialize to the new options.
438 CloseLogFileUnlocked();
439
thestig3e4787d2015-05-19 19:31:52440 if (!g_log_file_name)
441 g_log_file_name = new PathString();
442 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33443 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52444 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38445
[email protected]c7d5da992010-10-28 00:20:21446 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38447}
448
449void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52450 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38451}
452
453int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52454 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38455}
456
skobesc78c0ad72015-12-07 20:21:23457bool ShouldCreateLogMessage(int severity) {
458 if (severity < g_min_log_level)
459 return false;
460
461 // Return true here unless we know ~LogMessage won't do anything. Note that
462 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
463 // when g_logging_destination is LOG_NONE.
464 return g_logging_destination != LOG_NONE || log_message_handler ||
465 severity >= kAlwaysPrintErrorLevel;
466}
467
[email protected]162ac0f2010-11-04 15:50:49468int GetVlogVerbosity() {
469 return std::max(-1, LOG_INFO - GetMinLogLevel());
470}
471
[email protected]99b7c57f2010-09-29 19:26:36472int GetVlogLevelHelper(const char* file, size_t N) {
473 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52474 // Note: |g_vlog_info| may change on a different thread during startup
475 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08476 VlogInfo* vlog_info = g_vlog_info;
477 return vlog_info ?
478 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49479 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36480}
481
initial.commitd7cae122008-07-26 21:49:38482void SetLogItems(bool enable_process_id, bool enable_thread_id,
483 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52484 g_log_process_id = enable_process_id;
485 g_log_thread_id = enable_thread_id;
486 g_log_timestamp = enable_timestamp;
487 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38488}
489
James Cooka0536c32018-08-01 20:13:31490void SetLogPrefix(const char* prefix) {
491 DCHECK(!prefix ||
492 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
493 g_log_prefix = prefix;
494}
495
[email protected]81e0a852010-08-17 00:38:12496void SetShowErrorDialogs(bool enable_dialogs) {
497 show_error_dialogs = enable_dialogs;
498}
499
alex-accc1bde62017-04-19 08:33:55500ScopedLogAssertHandler::ScopedLogAssertHandler(
501 LogAssertHandlerFunction handler) {
502 log_assert_handler_stack.Get().push(std::move(handler));
503}
504
505ScopedLogAssertHandler::~ScopedLogAssertHandler() {
506 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38507}
508
[email protected]2b07b8412009-11-25 15:26:34509void SetLogMessageHandler(LogMessageHandlerFunction handler) {
510 log_message_handler = handler;
511}
512
[email protected]64e5cc02010-11-03 19:20:27513LogMessageHandlerFunction GetLogMessageHandler() {
514 return log_message_handler;
515}
516
[email protected]6d445d32010-09-30 19:10:03517// Explicit instantiations for commonly used comparisons.
518template std::string* MakeCheckOpString<int, int>(
519 const int&, const int&, const char* names);
520template std::string* MakeCheckOpString<unsigned long, unsigned long>(
521 const unsigned long&, const unsigned long&, const char* names);
522template std::string* MakeCheckOpString<unsigned long, unsigned int>(
523 const unsigned long&, const unsigned int&, const char* names);
524template std::string* MakeCheckOpString<unsigned int, unsigned long>(
525 const unsigned int&, const unsigned long&, const char* names);
526template std::string* MakeCheckOpString<std::string, std::string>(
527 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34528
jbroman6bcfec422016-05-26 00:28:46529void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16530 (*os) << "nullptr";
531}
532
[email protected]f2c05492014-06-17 12:04:23533#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22534// Displays a message box to the user with the error message in it.
535// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25536// This is for developers only; we don't use this in circumstances
537// (like release builds) where users could see it, since users don't
538// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22539void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38540 if (str.empty())
541 return;
542
[email protected]81e0a852010-08-17 00:38:12543 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44544 return;
545
[email protected]f6abeba2008-08-08 13:27:28546#if defined(OS_WIN)
[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.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39549 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
550 MB_OK | MB_ICONHAND | MB_TOPMOST);
thestig3e4787d2015-05-19 19:31:52551#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38552}
[email protected]f2c05492014-06-17 12:04:23553#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38554
[email protected]eae9c062011-01-11 00:50:59555LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
556 : severity_(severity), file_(file), line_(line) {
557 Init(file, line);
558}
559
tnagel4a045d3f2015-07-12 14:19:28560LogMessage::LogMessage(const char* file, int line, const char* condition)
561 : severity_(LOG_FATAL), file_(file), line_(line) {
562 Init(file, line);
563 stream_ << "Check failed: " << condition << ". ";
564}
565
[email protected]9c7132e2011-02-08 07:39:08566LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49567 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38568 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08569 stream_ << "Check failed: " << *result;
570 delete result;
initial.commitd7cae122008-07-26 21:49:38571}
572
[email protected]fb62a532009-02-12 01:19:05573LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08574 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49575 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05576 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08577 stream_ << "Check failed: " << *result;
578 delete result;
[email protected]fb62a532009-02-12 01:19:05579}
580
initial.commitd7cae122008-07-26 21:49:38581LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55582 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08583#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
584 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42585 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
586 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50587 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24588 stream_ << std::endl; // Newline to separate from log message.
589 trace.OutputToStream(&stream_);
590 }
[email protected]1d8c2702008-08-19 23:39:32591#endif
[email protected]d1ccc35a2010-03-24 05:03:24592 stream_ << std::endl;
593 std::string str_newline(stream_.str());
594
[email protected]2b07b8412009-11-25 15:26:34595 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33596 if (log_message_handler &&
597 log_message_handler(severity_, file_, line_,
598 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49599 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34600 return;
[email protected]162ac0f2010-11-04 15:50:49601 }
initial.commitd7cae122008-07-26 21:49:38602
thestig3e4787d2015-05-19 19:31:52603 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28604#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38605 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42606#elif defined(OS_MACOSX)
607 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34608 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
609 // its successor OS_LOG. If there's something weird about stderr, assume
610 // that log messages are going nowhere and log via ASL/OS_LOG too.
611 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42612 //
613 // Programs started by launchd, as UI applications normally are, have had
614 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
615 // a pipe to launchd, which logged what it received (see log_redirect_fd in
616 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
617 //
618 // Another alternative would be to determine whether stderr is a pipe to
619 // launchd and avoid logging via ASL only in that case. See 10.7.5
620 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34621 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
622 // to the system log at all.
mark4c7449c2015-11-10 19:53:42623 //
624 // Note that the ASL client by default discards messages whose levels are
625 // below ASL_LEVEL_NOTICE. It's possible to change that with
626 // asl_set_filter(), but this is pointless because syslogd normally applies
627 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34628 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42629 struct stat stderr_stat;
630 if (fstat(fileno(stderr), &stderr_stat) == -1) {
631 return true;
632 }
633 if (!S_ISCHR(stderr_stat.st_mode)) {
634 return false;
635 }
636
637 struct stat dev_null_stat;
638 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
639 return true;
640 }
641
642 return !S_ISCHR(dev_null_stat.st_mode) ||
643 stderr_stat.st_rdev == dev_null_stat.st_rdev;
644 }();
645
Eric Noyaufce100702017-10-16 09:46:34646 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42647 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
648 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42649 CFBundleRef main_bundle = CFBundleGetMainBundle();
650 CFStringRef main_bundle_id_cf =
651 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34652 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42653 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34654 : std::string("");
655#if defined(USE_ASL)
656 // The facility is set to the main bundle ID if available. Otherwise,
657 // "com.apple.console" is used.
658 const class ASLClient {
mark4c7449c2015-11-10 19:53:42659 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59660 explicit ASLClient(const std::string& facility)
661 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42662 ~ASLClient() { asl_close(client_); }
663
664 aslclient get() const { return client_; }
665
666 private:
667 aslclient client_;
668 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34669 } asl_client(main_bundle_id.empty() ? main_bundle_id
670 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42671
Eric Noyaufce100702017-10-16 09:46:34672 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42673 public:
674 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
675 ~ASLMessage() { asl_free(message_); }
676
677 aslmsg get() const { return message_; }
678
679 private:
680 aslmsg message_;
681 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
682 } asl_message;
683
684 // By default, messages are only readable by the admin group. Explicitly
685 // make them readable by the user generating the messages.
686 char euid_string[12];
Avi Drissmane3b70bf2019-01-04 19:50:22687 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42688 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
689
690 // Map Chrome log severities to ASL log levels.
691 const char* const asl_level_string = [](LogSeverity severity) {
692 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
693 // non-obvious two-step macro trick achieves what's needed.
694 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
695#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
696#define ASL_LEVEL_STR_X(level) #level
697 switch (severity) {
698 case LOG_INFO:
699 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
700 case LOG_WARNING:
701 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
702 case LOG_ERROR:
703 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
704 case LOG_FATAL:
705 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
706 default:
707 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
708 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
709 }
710#undef ASL_LEVEL_STR
711#undef ASL_LEVEL_STR_X
712 }(severity_);
713 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
714
715 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
716
717 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34718#else // !defined(USE_ASL)
719 const class OSLog {
720 public:
721 explicit OSLog(const char* subsystem)
722 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
723 : OS_LOG_DEFAULT) {}
724 ~OSLog() {
725 if (os_log_ != OS_LOG_DEFAULT) {
726 os_release(os_log_);
727 }
728 }
729 os_log_t get() const { return os_log_; }
730
731 private:
732 os_log_t os_log_;
733 DISALLOW_COPY_AND_ASSIGN(OSLog);
734 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
735 const os_log_type_t os_log_type = [](LogSeverity severity) {
736 switch (severity) {
737 case LOG_INFO:
738 return OS_LOG_TYPE_INFO;
739 case LOG_WARNING:
740 return OS_LOG_TYPE_DEFAULT;
741 case LOG_ERROR:
742 return OS_LOG_TYPE_ERROR;
743 case LOG_FATAL:
744 return OS_LOG_TYPE_FAULT;
745 default:
746 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
747 }
748 }(severity_);
749 os_log_with_type(log.get(), os_log_type, "%{public}s",
750 str_newline.c_str());
751#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42752 }
[email protected]3132e35c2011-07-07 20:46:50753#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25754 android_LogPriority priority =
755 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50756 switch (severity_) {
757 case LOG_INFO:
758 priority = ANDROID_LOG_INFO;
759 break;
760 case LOG_WARNING:
761 priority = ANDROID_LOG_WARN;
762 break;
763 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50764 priority = ANDROID_LOG_ERROR;
765 break;
766 case LOG_FATAL:
767 priority = ANDROID_LOG_FATAL;
768 break;
769 }
Xianzhu Wangae8d96a32018-10-16 20:41:13770#if DCHECK_IS_ON()
771 // Split the output by new lines to prevent the Android system from
772 // truncating the log.
773 for (const auto& line : base::SplitString(
774 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL))
775 __android_log_write(priority, "chromium", line.c_str());
776#else
777 // The Android system may truncate the string if it's too long.
[email protected]3132e35c2011-07-07 20:46:50778 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18779#endif
Xianzhu Wangae8d96a32018-10-16 20:41:13780#endif // OS_ANDROID
[email protected]51105382014-03-14 17:02:15781 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06782 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31783 } else if (severity_ >= kAlwaysPrintErrorLevel) {
784 // When we're only outputting to a log file, above a certain log level, we
785 // should still output to stderr so that we can better detect and diagnose
786 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15787 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02788 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28789 }
[email protected]52a261f2009-03-03 15:01:12790
initial.commitd7cae122008-07-26 21:49:38791 // write to log file
thestig3e4787d2015-05-19 19:31:52792 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09793 // We can have multiple threads and/or processes, so try to prevent them
794 // from clobbering each other's writes.
795 // If the client app did not call InitLogging, and the lock has not
796 // been created do it now. We do this on demand, but if two threads try
797 // to do this at the same time, there will be a race condition to create
798 // the lock. This is why InitLogging should be called from the main
799 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39800#if defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52801 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55802 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09803#endif
[email protected]5b84fe32010-09-14 22:24:55804 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28805#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55806 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52807 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55808 static_cast<const void*>(str_newline.c_str()),
809 static_cast<DWORD>(str_newline.length()),
810 &num_written,
thestig3e4787d2015-05-19 19:31:52811 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39812#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15813 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52814 str_newline.data(), str_newline.size(), 1, g_log_file));
815 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39816#else
817#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55818#endif
initial.commitd7cae122008-07-26 21:49:38819 }
820 }
821
822 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40823 // Write the log message to the global activity tracker, if running.
824 base::debug::GlobalActivityTracker* tracker =
825 base::debug::GlobalActivityTracker::Get();
826 if (tracker)
827 tracker->RecordLogMessage(str_newline);
828
[email protected]eb4c4d032012-04-03 18:45:05829 // Ensure the first characters of the string are on the stack so they
Weze976b732018-10-20 03:37:31830 // are contained in minidumps for diagnostic purposes. We place start
831 // and end marker values at either end, so we can scan captured stacks
832 // for the data easily.
833 struct {
834 uint32_t start_marker = 0xbedead01;
835 char data[1024];
836 uint32_t end_marker = 0x5050dead;
837 } str_stack;
838 base::strlcpy(str_stack.data, str_newline.data(),
839 base::size(str_stack.data));
840 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05841
Lukasz Anforowiczd3e19132017-12-06 19:44:27842 if (log_assert_handler_stack.IsCreated() &&
alex-accc1bde62017-04-19 08:33:55843 !log_assert_handler_stack.Get().empty()) {
844 LogAssertHandlerFunction log_assert_handler =
845 log_assert_handler_stack.Get().top();
846
847 if (log_assert_handler) {
848 log_assert_handler.Run(
849 file_, line_,
850 base::StringPiece(str_newline.c_str() + message_start_,
851 stack_start - message_start_),
852 base::StringPiece(str_newline.c_str() + stack_start));
853 }
[email protected]1ffe08c12008-08-13 11:15:11854 } else {
[email protected]82d89ab2014-02-28 18:25:34855 // Don't use the string with the newline, get a fresh version to send to
856 // the debug message process. We also don't display assertions to the
857 // user in release mode. The enduser can't do anything with this
858 // information, and displaying message boxes when the application is
859 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50860#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42861 if (!base::debug::BeingDebugged()) {
862 // Displaying a dialog is unnecessary when debugging and can complicate
863 // debugging.
864 DisplayDebugMessageInDialog(stream_.str());
865 }
[email protected]4d5901272008-11-06 00:33:50866#endif
[email protected]82d89ab2014-02-28 18:25:34867 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52868#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
869 IMMEDIATE_CRASH();
870#else
[email protected]82d89ab2014-02-28 18:25:34871 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52872#endif
initial.commitd7cae122008-07-26 21:49:38873 }
874 }
875}
876
[email protected]eae9c062011-01-11 00:50:59877// writes the common header info to the stream
878void LogMessage::Init(const char* file, int line) {
879 base::StringPiece filename(file);
880 size_t last_slash_pos = filename.find_last_of("\\/");
881 if (last_slash_pos != base::StringPiece::npos)
882 filename.remove_prefix(last_slash_pos + 1);
883
884 // TODO(darin): It might be nice if the columns were fixed width.
885
886 stream_ << '[';
James Cooka0536c32018-08-01 20:13:31887 if (g_log_prefix)
888 stream_ << g_log_prefix << ':';
thestig3e4787d2015-05-19 19:31:52889 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59890 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52891 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09892 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52893 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39894#if defined(OS_WIN)
895 SYSTEMTIME local_time;
896 GetLocalTime(&local_time);
897 stream_ << std::setfill('0')
898 << std::setw(2) << local_time.wMonth
899 << std::setw(2) << local_time.wDay
900 << '/'
901 << std::setw(2) << local_time.wHour
902 << std::setw(2) << local_time.wMinute
903 << std::setw(2) << local_time.wSecond
904 << '.'
905 << std::setw(3)
906 << local_time.wMilliseconds
907 << ':';
908#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
djkurtz543a3be2016-11-30 14:17:34909 timeval tv;
910 gettimeofday(&tv, nullptr);
911 time_t t = tv.tv_sec;
912 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59913 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59914 struct tm* tm_time = &local_time;
915 stream_ << std::setfill('0')
916 << std::setw(2) << 1 + tm_time->tm_mon
917 << std::setw(2) << tm_time->tm_mday
918 << '/'
919 << std::setw(2) << tm_time->tm_hour
920 << std::setw(2) << tm_time->tm_min
921 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34922 << '.'
923 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59924 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39925#else
926#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34927#endif
[email protected]eae9c062011-01-11 00:50:59928 }
thestig3e4787d2015-05-19 19:31:52929 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59930 stream_ << TickCount() << ':';
931 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19932 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59933 else
934 stream_ << "VERBOSE" << -severity_;
935
936 stream_ << ":" << filename << "(" << line << ")] ";
937
pkasting9cf9b94a2014-10-01 22:18:43938 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59939}
940
[email protected]d8617a62009-10-09 23:52:20941#if defined(OS_WIN)
942// This has already been defined in the header, but defining it again as DWORD
943// ensures that the type used in the header is equivalent to DWORD. If not,
944// the redefinition is a compile error.
945typedef DWORD SystemErrorCode;
946#endif
947
948SystemErrorCode GetLastSystemErrorCode() {
949#if defined(OS_WIN)
950 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39951#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20952 return errno;
[email protected]d8617a62009-10-09 23:52:20953#endif
954}
955
[email protected]c914d8a2014-04-23 01:11:01956BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39957#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:27958 const int kErrorMessageBufferSize = 256;
959 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01960 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52961 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Avi Drissmane3b70bf2019-01-04 19:50:22962 base::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01963 if (len) {
964 // Messages returned by system end with line breaks.
965 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:45966 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:01967 }
Bruce Dawson19175842017-08-02 17:00:45968 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:01969 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39970#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:14971 return base::safe_strerror(error_code) +
972 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:52973#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39974}
[email protected]d8617a62009-10-09 23:52:20975
[email protected]c914d8a2014-04-23 01:11:01976
977#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20978Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
979 int line,
980 LogSeverity severity,
981 SystemErrorCode err)
982 : err_(err),
[email protected]d8617a62009-10-09 23:52:20983 log_message_(file, line, severity) {
984}
985
986Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01987 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06988 // 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 DWORD last_error = err_;
991 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20992}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39993#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20994ErrnoLogMessage::ErrnoLogMessage(const char* file,
995 int line,
996 LogSeverity severity,
997 SystemErrorCode err)
998 : err_(err),
999 log_message_(file, line, severity) {
1000}
1001
1002ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011003 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141004 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1005 // field) and use Alias in hopes that it makes it into crash dumps.
1006 int last_error = err_;
1007 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201008}
thestig3e4787d2015-05-19 19:31:521009#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201010
initial.commitd7cae122008-07-26 21:49:381011void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391012#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:551013 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:091014#endif
[email protected]17dcf752013-07-15 21:47:091015 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381016}
1017
[email protected]e36ddc82009-12-08 04:22:501018void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491019 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501020 size_t bytes_written = 0;
1021 const size_t message_len = strlen(message);
1022 int rv;
1023 while (bytes_written < message_len) {
1024 rv = HANDLE_EINTR(
1025 write(STDERR_FILENO, message + bytes_written,
1026 message_len - bytes_written));
1027 if (rv < 0) {
1028 // Give up, nothing we can do now.
1029 break;
1030 }
1031 bytes_written += rv;
1032 }
1033
1034 if (message_len > 0 && message[message_len - 1] != '\n') {
1035 do {
1036 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1037 if (rv < 0) {
1038 // Give up, nothing we can do now.
1039 break;
1040 }
1041 } while (rv != 1);
1042 }
1043 }
1044
1045 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501046 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501047}
1048
[email protected]34a907732012-01-20 06:33:271049// This was defined at the beginning of this file.
1050#undef write
1051
[email protected]f01b88a2013-02-27 22:04:001052#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091053bool IsLoggingToFileEnabled() {
1054 return g_logging_destination & LOG_TO_FILE;
1055}
1056
jdoerrie5c4dc4e2019-02-01 18:02:331057base::string16 GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521058 if (g_log_file_name)
1059 return *g_log_file_name;
jdoerrie5c4dc4e2019-02-01 18:02:331060 return base::string16();
[email protected]f01b88a2013-02-27 22:04:001061}
1062#endif
1063
tnagel80388e682015-05-26 13:27:561064BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:141065 LogMessage(file, line, LOG_ERROR).stream()
1066 << "NOTREACHED() hit.";
1067}
1068
[email protected]96fd0032009-04-24 00:13:081069} // namespace logging
initial.commitd7cae122008-07-26 21:49:381070
[email protected]81411c62014-07-08 23:03:061071std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491072 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381073}