blob: 2da71c73819b34a45911131e2cc8bff861178789 [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
Hans Wennborg12aea3e2020-04-14 15:29:007// logging.h is a widely included header and its size has significant impact on
8// build time. Try not to raise this limit unless absolutely necessary. See
9// https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md
10#ifndef NACL_TC_REV
Hans Wennborg944479f2020-06-25 21:39:2511#pragma clang max_tokens_here 350000
Hans Wennborg12aea3e2020-04-14 15:29:0012#endif // NACL_TC_REV
13
Hans Wennborg944479f2020-06-25 21:39:2514#ifdef BASE_CHECK_H_
15#error "logging.h should not include check.h"
16#endif
17
avi51ba3e692015-12-26 17:30:5018#include <limits.h>
avi9b6f42932015-12-26 22:15:1419#include <stdint.h>
20
Chris Hamilton306740d2019-04-25 18:48:3621#include "base/pending_task.h"
Weze976b732018-10-20 03:37:3122#include "base/stl_util.h"
Chris Hamilton306740d2019-04-25 18:48:3623#include "base/task/common/task_annotator.h"
Eric Secklerf6c544f2020-06-02 10:49:2124#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1425#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5026
[email protected]b16ef312008-08-19 18:36:2327#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5028#include <io.h>
alex-accc1bde62017-04-19 08:33:5529#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2830typedef HANDLE FileHandle;
31typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5032// Windows warns on using write(). It prefers _write().
33#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
34// Windows doesn't define STDERR_FILENO. Define it here.
35#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3436
[email protected]052f1b52008-11-06 21:43:0737#elif defined(OS_MACOSX)
Eric Noyaufce100702017-10-16 09:46:3438// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
39// in favor of OS_LOG (Unified Logging).
40#include <AvailabilityMacros.h>
41#if defined(OS_IOS)
42#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
43#define USE_ASL
44#endif
45#else // !defined(OS_IOS)
46#if !defined(MAC_OS_X_VERSION_10_12) || \
47 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
48#define USE_ASL
49#endif
50#endif // defined(OS_IOS)
51
52#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4253#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3454#else
55#include <os/log.h>
56#endif
57
mark4c7449c2015-11-10 19:53:4258#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2859#include <mach/mach.h>
60#include <mach/mach_time.h>
61#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3462
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3963#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]19ea84ca2010-11-12 08:37:0864#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2765#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0866#endif
[email protected]052f1b52008-11-06 21:43:0767#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5968#endif
69
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3970#if defined(OS_FUCHSIA)
Sharon Yanga4b908de2019-05-07 22:19:0371#include <lib/syslog/global.h>
72#include <lib/syslog/logger.h>
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3973#include <zircon/process.h>
74#include <zircon/syscalls.h>
75#endif
76
77#if defined(OS_ANDROID)
78#include <android/log.h>
79#endif
80
81#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2082#include <errno.h>
mark4c7449c2015-11-10 19:53:4283#include <paths.h>
[email protected]166326c62010-08-05 15:50:2384#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2885#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0086#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2887#include <string.h>
mark4c7449c2015-11-10 19:53:4288#include <sys/stat.h>
Chris Findeisen2a373a2d2019-08-15 19:44:3089#include "base/process/process_handle.h"
[email protected]f6abeba2008-08-08 13:27:2890#define MAX_PATH PATH_MAX
91typedef FILE* FileHandle;
92typedef pthread_mutex_t* MutexHandle;
93#endif
94
[email protected]1f88b5162011-04-01 00:02:2995#include <algorithm>
96#include <cstring>
initial.commitd7cae122008-07-26 21:49:3897#include <ctime>
98#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2999#include <ostream>
[email protected]c914d8a2014-04-23 01:11:01100#include <string>
alex-accc1bde62017-04-19 08:33:55101#include <utility>
[email protected]b16ef312008-08-19 18:36:23102
initial.commitd7cae122008-07-26 21:49:38103#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:55104#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:38105#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:28106#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:55107#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:05108#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:50109#include "base/debug/debugger.h"
110#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:16111#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45112#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:03113#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35114#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00115#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13116#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01117#include "base/strings/string_util.h"
118#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42119#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07120#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:20121#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:09122#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36123#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39124
Cliff Smolinskyc5c52102019-05-03 20:51:54125#if defined(OS_WIN)
126#include "base/win/win_util.h"
127#endif
128
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39129#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24130#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04131#endif
[email protected]52a261f2009-03-03 15:01:12132
Robbie McElrath8bf49842019-08-20 22:22:53133#if defined(OS_CHROMEOS)
134#include "base/files/scoped_file.h"
135#endif
136
initial.commitd7cae122008-07-26 21:49:38137namespace logging {
138
[email protected]064aa162011-12-03 00:30:08139namespace {
140
thestig3e4787d2015-05-19 19:31:52141VlogInfo* g_vlog_info = nullptr;
142VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38143
weza245bd072017-06-18 23:26:34144const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Avi Drissmane3b70bf2019-01-04 19:50:22145static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
weza245bd072017-06-18 23:26:34146 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38147
thestig75f87352014-12-03 21:42:27148const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19149 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
150 return log_severity_names[severity];
151 return "UNKNOWN";
152}
153
thestig3e4787d2015-05-19 19:31:52154int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32155
Sharon Yang7cb919a2019-05-20 20:27:15156// Specifies the process' logging sink(s), represented as a combination of
157// LoggingDestination values joined by bitwise OR.
158int g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38159
[email protected]a33c9892008-08-25 20:10:31160// For LOG_ERROR and above, always print to stderr.
161const int kAlwaysPrintErrorLevel = LOG_ERROR;
162
[email protected]614e9fa2008-08-11 22:52:59163// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38164// will be lazily initialized to the default value when it is
165// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33166using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52167PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38168
thestig3e4787d2015-05-19 19:31:52169// This file is lazily opened and the handle may be nullptr
170FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38171
thestig3e4787d2015-05-19 19:31:52172// What should be prepended to each message?
173bool g_log_process_id = false;
174bool g_log_thread_id = false;
175bool g_log_timestamp = true;
176bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31177const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38178
[email protected]81e0a852010-08-17 00:38:12179// Should we pop up fatal debug messages in a dialog?
180bool show_error_dialogs = false;
181
initial.commitd7cae122008-07-26 21:49:38182// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55183// the debug message dialog and process termination. Assert handlers are stored
184// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45185base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
186 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
187 return *instance;
188}
alex-accc1bde62017-04-19 08:33:55189
[email protected]2b07b8412009-11-25 15:26:34190// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52191LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38192
avi9b6f42932015-12-26 22:15:14193uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24194#if defined(OS_WIN)
195 return GetTickCount();
Wezb0501302018-03-09 05:18:45196#elif defined(OS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35197 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45198 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39199#elif defined(OS_MACOSX)
200 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08201#elif defined(OS_NACL)
202 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
203 // So we have to use clock() for now.
204 return clock();
[email protected]e43eddf12009-12-29 00:32:52205#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07206 struct timespec ts;
207 clock_gettime(CLOCK_MONOTONIC, &ts);
208
avi9b6f42932015-12-26 22:15:14209 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
210 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07211
212 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24213#endif
214}
215
[email protected]614e9fa2008-08-11 22:52:59216void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28217#if defined(OS_WIN)
Jan Wilken Dörrieb630aca2019-12-04 10:59:11218 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27219#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45220 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39221#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59222 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39223#else
224#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28225#endif
226}
initial.commitd7cae122008-07-26 21:49:38227
[email protected]5f95d532010-10-01 17:16:58228PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55229#if defined(OS_WIN)
230 // On Windows we use the same path as the exe.
Jan Wilken Dörrieb630aca2019-12-04 10:59:11231 wchar_t module_name[MAX_PATH];
232 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58233
scottmgfc5b7072015-01-27 21:46:28234 PathString log_name = module_name;
235 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58236 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28237 log_name.erase(last_backslash + 1);
Jan Wilken Dörrieb630aca2019-12-04 10:59:11238 log_name += FILE_PATH_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28239 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39240#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55241 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58242 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55243#endif
244}
245
ananta61762fb2015-09-18 01:00:09246// We don't need locks on Windows for atomically appending to files. The OS
247// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39248#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55249// This class acts as a wrapper for locking the logging files.
250// LoggingLock::Init() should be called from the main thread before any logging
251// is done. Then whenever logging, be sure to have a local LoggingLock
252// instance on the stack. This will ensure that the lock is unlocked upon
253// exiting the frame.
254// LoggingLocks can not be nested.
255class LoggingLock {
256 public:
257 LoggingLock() {
258 LockLogging();
259 }
260
261 ~LoggingLock() {
262 UnlockLogging();
263 }
264
265 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
266 if (initialized)
267 return;
268 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58269
ananta61762fb2015-09-18 01:00:09270 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20271 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09272
[email protected]5b84fe32010-09-14 22:24:55273 initialized = true;
274 }
275
276 private:
277 static void LockLogging() {
278 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55279 pthread_mutex_lock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55280 } else {
281 // use the lock
282 log_lock->Lock();
283 }
284 }
285
286 static void UnlockLogging() {
287 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55288 pthread_mutex_unlock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55289 } else {
290 log_lock->Unlock();
291 }
292 }
293
294 // The lock is used if log file locking is false. It helps us avoid problems
295 // with multiple threads writing to the log file at the same time. Use
296 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20297 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55298
299 // When we don't use a lock, we are using a global mutex. We need to do this
300 // because LockFileEx is not thread safe.
[email protected]5b84fe32010-09-14 22:24:55301 static pthread_mutex_t log_mutex;
[email protected]5b84fe32010-09-14 22:24:55302
303 static bool initialized;
304 static LogLockingState lock_log_file;
305};
306
307// static
308bool LoggingLock::initialized = false;
309// static
thestig3e4787d2015-05-19 19:31:52310base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55311// static
312LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
313
[email protected]5b84fe32010-09-14 22:24:55314pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
[email protected]5b84fe32010-09-14 22:24:55315
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39316#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09317
thestig3e4787d2015-05-19 19:31:52318// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38319// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52320// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38321bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52322 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38323 return true;
324
thestig3e4787d2015-05-19 19:31:52325 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59326 // Nobody has called InitLogging to specify a debug log file, so here we
327 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52328 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38329 }
330
Robbie McElrath8bf49842019-08-20 22:22:53331 if ((g_logging_destination & LOG_TO_FILE) == 0)
332 return true;
333
[email protected]614e9fa2008-08-11 22:52:59334#if defined(OS_WIN)
Robbie McElrath8bf49842019-08-20 22:22:53335 // The FILE_APPEND_DATA access mask ensures that the file is atomically
336 // appended to across accesses from multiple threads.
337 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
338 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
Jan Wilken Dörrieb630aca2019-12-04 10:59:11339 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
Robbie McElrath8bf49842019-08-20 22:22:53340 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
341 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
342 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
343 // We are intentionally not using FilePath or FileUtil here to reduce the
344 // dependencies of the logging implementation. For e.g. FilePath and
345 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
346 // some consumers of base logging like chrome_elf, etc.
347 // Please don't change the code below to use FilePath.
348 // try the current directory
Jan Wilken Dörrieb630aca2019-12-04 10:59:11349 wchar_t system_buffer[MAX_PATH];
Robbie McElrath8bf49842019-08-20 22:22:53350 system_buffer[0] = 0;
Jan Wilken Dörrieb630aca2019-12-04 10:59:11351 DWORD len = ::GetCurrentDirectory(base::size(system_buffer), system_buffer);
Robbie McElrath8bf49842019-08-20 22:22:53352 if (len == 0 || len > base::size(system_buffer))
353 return false;
354
355 *g_log_file_name = system_buffer;
356 // Append a trailing backslash if needed.
357 if (g_log_file_name->back() != L'\\')
Jan Wilken Dörrieb630aca2019-12-04 10:59:11358 *g_log_file_name += FILE_PATH_LITERAL("\\");
359 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
Robbie McElrath8bf49842019-08-20 22:22:53360
Jan Wilken Dörrieb630aca2019-12-04 10:59:11361 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52362 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
363 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
364 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
Robbie McElrath8bf49842019-08-20 22:22:53365 g_log_file = nullptr;
[email protected]78c6dd62009-06-08 23:29:11366 return false;
Robbie McElrath8bf49842019-08-20 22:22:53367 }
368 }
369#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
370 g_log_file = fopen(g_log_file_name->c_str(), "a");
371 if (g_log_file == nullptr)
372 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39373#else
374#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28375#endif
[email protected]1d8c2702008-08-19 23:39:32376
initial.commitd7cae122008-07-26 21:49:38377 return true;
378}
379
[email protected]17dcf752013-07-15 21:47:09380void CloseFile(FileHandle log) {
381#if defined(OS_WIN)
382 CloseHandle(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39383#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09384 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39385#else
386#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09387#endif
388}
389
390void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52391 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09392 return;
393
thestig3e4787d2015-05-19 19:31:52394 CloseFile(g_log_file);
395 g_log_file = nullptr;
Robbie McElrath8bf49842019-08-20 22:22:53396
397 // If we initialized logging via an externally-provided file descriptor, we
398 // won't have a log path set and shouldn't try to reopen the log file.
399 if (!g_log_file_name)
400 g_logging_destination &= ~LOG_TO_FILE;
[email protected]17dcf752013-07-15 21:47:09401}
402
[email protected]064aa162011-12-03 00:30:08403} // namespace
404
Tomas Popelaafffa972018-11-13 20:42:05405#if defined(DCHECK_IS_CONFIGURABLE)
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51406// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30407// determined at run-time. We default it to INFO, to avoid it triggering
408// crashes before the run-time has explicitly chosen the behaviour.
409BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Tomas Popelaafffa972018-11-13 20:42:05410#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30411
scottmg3c957a52016-12-10 20:57:59412// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
413// an object of the correct type on the LHS of the unused part of the ternary
414// operator.
415std::ostream* g_swallow_stream;
416
[email protected]5e3f7c22013-06-21 21:15:33417bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45418#if defined(OS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15419 // Can log only to the system debug log and stderr.
420 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
421 0u);
[email protected]ac07ec52013-04-22 17:32:45422#endif
Robbie McElrath8bf49842019-08-20 22:22:53423
pgal.u-szeged421dddb2014-11-25 12:55:02424 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52425 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36426 // vlog switches.
427 if (command_line->HasSwitch(switches::kV) ||
428 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52429 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08430 // by another thread. Don't delete the old VLogInfo, just create a second
431 // one. We keep track of both to avoid memory leak warnings.
432 CHECK(!g_vlog_info_prev);
433 g_vlog_info_prev = g_vlog_info;
434
[email protected]99b7c57f2010-09-29 19:26:36435 g_vlog_info =
436 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49437 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52438 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36439 }
440
thestig3e4787d2015-05-19 19:31:52441 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38442
Wez224c0bf62019-05-24 19:26:13443#if defined(OS_FUCHSIA)
444 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
445 fx_logger_config_t config;
446 config.min_severity = FX_LOG_INFO;
447 config.console_fd = -1;
448 config.log_service_channel = ZX_HANDLE_INVALID;
449 std::string log_tag = command_line->GetProgram().BaseName().AsUTF8Unsafe();
450 const char* log_tag_data = log_tag.data();
451 config.tags = &log_tag_data;
452 config.num_tags = 1;
Wez0e6cefc2020-04-21 18:04:47453 fx_log_reconfigure(&config);
Wez224c0bf62019-05-24 19:26:13454 }
455#endif
456
[email protected]5e3f7c22013-06-21 21:15:33457 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52458 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21459 return true;
initial.commitd7cae122008-07-26 21:49:38460
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39461#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Robbie McElrath8bf49842019-08-20 22:22:53462 LoggingLock::Init(settings.lock_log, settings.log_file_path);
[email protected]17dcf752013-07-15 21:47:09463 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09464#endif
[email protected]17dcf752013-07-15 21:47:09465
466 // Calling InitLogging twice or after some log call has already opened the
467 // default log file will re-initialize to the new options.
468 CloseLogFileUnlocked();
469
Robbie McElrath8bf49842019-08-20 22:22:53470#if defined(OS_CHROMEOS)
471 if (settings.log_file) {
472 DCHECK(!settings.log_file_path);
473 g_log_file = settings.log_file;
474 return true;
475 }
476#endif
477
thestig3e4787d2015-05-19 19:31:52478 if (!g_log_file_name)
479 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53480 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33481 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52482 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38483
[email protected]c7d5da992010-10-28 00:20:21484 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38485}
486
487void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52488 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38489}
490
491int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52492 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38493}
494
skobesc78c0ad72015-12-07 20:21:23495bool ShouldCreateLogMessage(int severity) {
496 if (severity < g_min_log_level)
497 return false;
498
Wez6c8acb82019-07-18 00:32:59499 // Return true here unless we know ~LogMessage won't do anything.
skobesc78c0ad72015-12-07 20:21:23500 return g_logging_destination != LOG_NONE || log_message_handler ||
501 severity >= kAlwaysPrintErrorLevel;
502}
503
Wez6c8acb82019-07-18 00:32:59504// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
505// If |severity| is high then true will be returned when no log destinations are
506// set, or only LOG_TO_FILE is set, since that is useful for local development
507// and debugging.
508bool ShouldLogToStderr(int severity) {
509 if (g_logging_destination & LOG_TO_STDERR)
510 return true;
511 if (severity >= kAlwaysPrintErrorLevel)
512 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
513 return false;
514}
515
[email protected]162ac0f2010-11-04 15:50:49516int GetVlogVerbosity() {
517 return std::max(-1, LOG_INFO - GetMinLogLevel());
518}
519
[email protected]99b7c57f2010-09-29 19:26:36520int GetVlogLevelHelper(const char* file, size_t N) {
521 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52522 // Note: |g_vlog_info| may change on a different thread during startup
523 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08524 VlogInfo* vlog_info = g_vlog_info;
525 return vlog_info ?
526 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49527 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36528}
529
initial.commitd7cae122008-07-26 21:49:38530void SetLogItems(bool enable_process_id, bool enable_thread_id,
531 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52532 g_log_process_id = enable_process_id;
533 g_log_thread_id = enable_thread_id;
534 g_log_timestamp = enable_timestamp;
535 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38536}
537
James Cooka0536c32018-08-01 20:13:31538void SetLogPrefix(const char* prefix) {
539 DCHECK(!prefix ||
540 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
541 g_log_prefix = prefix;
542}
543
[email protected]81e0a852010-08-17 00:38:12544void SetShowErrorDialogs(bool enable_dialogs) {
545 show_error_dialogs = enable_dialogs;
546}
547
alex-accc1bde62017-04-19 08:33:55548ScopedLogAssertHandler::ScopedLogAssertHandler(
549 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45550 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55551}
552
553ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45554 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38555}
556
[email protected]2b07b8412009-11-25 15:26:34557void SetLogMessageHandler(LogMessageHandlerFunction handler) {
558 log_message_handler = handler;
559}
560
[email protected]64e5cc02010-11-03 19:20:27561LogMessageHandlerFunction GetLogMessageHandler() {
562 return log_message_handler;
563}
564
[email protected]f2c05492014-06-17 12:04:23565#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22566// Displays a message box to the user with the error message in it.
567// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25568// This is for developers only; we don't use this in circumstances
569// (like release builds) where users could see it, since users don't
570// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22571void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38572 if (str.empty())
573 return;
574
[email protected]81e0a852010-08-17 00:38:12575 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44576 return;
577
[email protected]f6abeba2008-08-08 13:27:28578#if defined(OS_WIN)
[email protected]561513f2010-12-16 23:29:25579 // We intentionally don't implement a dialog on other platforms.
580 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54581 if (base::win::IsUser32AndGdi32Available()) {
582 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
583 MB_OK | MB_ICONHAND | MB_TOPMOST);
584 } else {
585 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
586 }
thestig3e4787d2015-05-19 19:31:52587#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38588}
[email protected]f2c05492014-06-17 12:04:23589#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38590
[email protected]eae9c062011-01-11 00:50:59591LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
592 : severity_(severity), file_(file), line_(line) {
593 Init(file, line);
594}
595
tnagel4a045d3f2015-07-12 14:19:28596LogMessage::LogMessage(const char* file, int line, const char* condition)
597 : severity_(LOG_FATAL), file_(file), line_(line) {
598 Init(file, line);
599 stream_ << "Check failed: " << condition << ". ";
600}
601
initial.commitd7cae122008-07-26 21:49:38602LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55603 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08604#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
605 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42606 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
607 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16608 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24609 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16610 stack_trace.OutputToStream(&stream_);
611 base::debug::TaskTrace task_trace;
612 if (!task_trace.empty())
613 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36614
Chris Hamilton888085312019-05-30 00:53:30615 // Include the IPC context, if any.
616 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36617 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30618 if (task && task->ipc_hash) {
619 stream_ << "IPC message handler context: "
620 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36621 }
[email protected]d1ccc35a2010-03-24 05:03:24622 }
[email protected]1d8c2702008-08-19 23:39:32623#endif
[email protected]d1ccc35a2010-03-24 05:03:24624 stream_ << std::endl;
625 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44626 TRACE_LOG_MESSAGE(
627 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24628
[email protected]2b07b8412009-11-25 15:26:34629 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33630 if (log_message_handler &&
631 log_message_handler(severity_, file_, line_,
632 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49633 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34634 return;
[email protected]162ac0f2010-11-04 15:50:49635 }
initial.commitd7cae122008-07-26 21:49:38636
thestig3e4787d2015-05-19 19:31:52637 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28638#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38639 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42640#elif defined(OS_MACOSX)
641 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34642 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
643 // its successor OS_LOG. If there's something weird about stderr, assume
644 // that log messages are going nowhere and log via ASL/OS_LOG too.
645 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42646 //
647 // Programs started by launchd, as UI applications normally are, have had
648 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
649 // a pipe to launchd, which logged what it received (see log_redirect_fd in
650 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
651 //
652 // Another alternative would be to determine whether stderr is a pipe to
653 // launchd and avoid logging via ASL only in that case. See 10.7.5
654 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34655 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
656 // to the system log at all.
mark4c7449c2015-11-10 19:53:42657 //
658 // Note that the ASL client by default discards messages whose levels are
659 // below ASL_LEVEL_NOTICE. It's possible to change that with
660 // asl_set_filter(), but this is pointless because syslogd normally applies
661 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34662 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42663 struct stat stderr_stat;
664 if (fstat(fileno(stderr), &stderr_stat) == -1) {
665 return true;
666 }
667 if (!S_ISCHR(stderr_stat.st_mode)) {
668 return false;
669 }
670
671 struct stat dev_null_stat;
672 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
673 return true;
674 }
675
676 return !S_ISCHR(dev_null_stat.st_mode) ||
677 stderr_stat.st_rdev == dev_null_stat.st_rdev;
678 }();
679
Eric Noyaufce100702017-10-16 09:46:34680 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42681 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
682 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42683 CFBundleRef main_bundle = CFBundleGetMainBundle();
684 CFStringRef main_bundle_id_cf =
685 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34686 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42687 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34688 : std::string("");
689#if defined(USE_ASL)
690 // The facility is set to the main bundle ID if available. Otherwise,
691 // "com.apple.console" is used.
692 const class ASLClient {
mark4c7449c2015-11-10 19:53:42693 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59694 explicit ASLClient(const std::string& facility)
695 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42696 ~ASLClient() { asl_close(client_); }
697
698 aslclient get() const { return client_; }
699
700 private:
701 aslclient client_;
702 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34703 } asl_client(main_bundle_id.empty() ? main_bundle_id
704 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42705
Eric Noyaufce100702017-10-16 09:46:34706 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42707 public:
708 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
709 ~ASLMessage() { asl_free(message_); }
710
711 aslmsg get() const { return message_; }
712
713 private:
714 aslmsg message_;
715 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
716 } asl_message;
717
718 // By default, messages are only readable by the admin group. Explicitly
719 // make them readable by the user generating the messages.
720 char euid_string[12];
Avi Drissmane3b70bf2019-01-04 19:50:22721 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42722 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
723
724 // Map Chrome log severities to ASL log levels.
725 const char* const asl_level_string = [](LogSeverity severity) {
726 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
727 // non-obvious two-step macro trick achieves what's needed.
728 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
729#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
730#define ASL_LEVEL_STR_X(level) #level
731 switch (severity) {
732 case LOG_INFO:
733 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
734 case LOG_WARNING:
735 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
736 case LOG_ERROR:
737 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
738 case LOG_FATAL:
739 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
740 default:
741 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
742 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
743 }
744#undef ASL_LEVEL_STR
745#undef ASL_LEVEL_STR_X
746 }(severity_);
747 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
748
749 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
750
751 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34752#else // !defined(USE_ASL)
753 const class OSLog {
754 public:
755 explicit OSLog(const char* subsystem)
756 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
757 : OS_LOG_DEFAULT) {}
758 ~OSLog() {
759 if (os_log_ != OS_LOG_DEFAULT) {
760 os_release(os_log_);
761 }
762 }
763 os_log_t get() const { return os_log_; }
764
765 private:
766 os_log_t os_log_;
767 DISALLOW_COPY_AND_ASSIGN(OSLog);
768 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
769 const os_log_type_t os_log_type = [](LogSeverity severity) {
770 switch (severity) {
771 case LOG_INFO:
772 return OS_LOG_TYPE_INFO;
773 case LOG_WARNING:
774 return OS_LOG_TYPE_DEFAULT;
775 case LOG_ERROR:
776 return OS_LOG_TYPE_ERROR;
777 case LOG_FATAL:
778 return OS_LOG_TYPE_FAULT;
779 default:
780 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
781 }
782 }(severity_);
783 os_log_with_type(log.get(), os_log_type, "%{public}s",
784 str_newline.c_str());
785#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42786 }
[email protected]3132e35c2011-07-07 20:46:50787#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25788 android_LogPriority priority =
789 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50790 switch (severity_) {
791 case LOG_INFO:
792 priority = ANDROID_LOG_INFO;
793 break;
794 case LOG_WARNING:
795 priority = ANDROID_LOG_WARN;
796 break;
797 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50798 priority = ANDROID_LOG_ERROR;
799 break;
800 case LOG_FATAL:
801 priority = ANDROID_LOG_FATAL;
802 break;
803 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03804 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13805#if DCHECK_IS_ON()
806 // Split the output by new lines to prevent the Android system from
807 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03808 std::vector<std::string> lines = base::SplitString(
809 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
810 // str_newline has an extra newline appended to it (at the top of this
811 // function), so skip the last split element to avoid needlessly
812 // logging an empty string.
813 lines.pop_back();
814 for (const auto& line : lines)
815 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13816#else
817 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03818 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18819#endif
Sharon Yanga4b908de2019-05-07 22:19:03820#elif defined(OS_FUCHSIA)
821 fx_log_severity_t severity = FX_LOG_INFO;
Wez224c0bf62019-05-24 19:26:13822 switch (severity_) {
Sharon Yanga4b908de2019-05-07 22:19:03823 case LOG_INFO:
824 severity = FX_LOG_INFO;
825 break;
826 case LOG_WARNING:
827 severity = FX_LOG_WARNING;
828 break;
829 case LOG_ERROR:
830 severity = FX_LOG_ERROR;
831 break;
832 case LOG_FATAL:
Wez224c0bf62019-05-24 19:26:13833 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
834 severity = FX_LOG_ERROR;
Sharon Yanga4b908de2019-05-07 22:19:03835 break;
836 }
837
838 fx_logger_t* logger = fx_log_get_logger();
839 if (logger) {
Kevin Marshall9873826d2019-10-14 20:09:35840 // Temporarily remove the trailing newline from |str_newline|'s C-string
841 // representation, since fx_logger will add a newline of its own.
Wez224c0bf62019-05-24 19:26:13842 str_newline.pop_back();
Kevin Marshall9873826d2019-10-14 20:09:35843 std::string message =
844 base::StringPrintf("%s(%d) %s", file_basename_, line_,
845 str_newline.c_str() + message_start_);
846 fx_logger_log(logger, severity, nullptr, message.data());
Wez224c0bf62019-05-24 19:26:13847 str_newline.push_back('\n');
Sharon Yanga4b908de2019-05-07 22:19:03848 }
849#endif // OS_FUCHSIA
Sharon Yang7cb919a2019-05-20 20:27:15850 }
851
Wez6c8acb82019-07-18 00:32:59852 if (ShouldLogToStderr(severity_)) {
[email protected]51105382014-03-14 17:02:15853 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02854 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28855 }
[email protected]52a261f2009-03-03 15:01:12856
thestig3e4787d2015-05-19 19:31:52857 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09858 // We can have multiple threads and/or processes, so try to prevent them
859 // from clobbering each other's writes.
860 // If the client app did not call InitLogging, and the lock has not
861 // been created do it now. We do this on demand, but if two threads try
862 // to do this at the same time, there will be a race condition to create
863 // the lock. This is why InitLogging should be called from the main
864 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39865#if defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52866 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55867 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09868#endif
[email protected]5b84fe32010-09-14 22:24:55869 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28870#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55871 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52872 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55873 static_cast<const void*>(str_newline.c_str()),
874 static_cast<DWORD>(str_newline.length()),
875 &num_written,
thestig3e4787d2015-05-19 19:31:52876 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39877#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15878 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52879 str_newline.data(), str_newline.size(), 1, g_log_file));
880 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39881#else
882#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55883#endif
initial.commitd7cae122008-07-26 21:49:38884 }
885 }
886
887 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40888 // Write the log message to the global activity tracker, if running.
889 base::debug::GlobalActivityTracker* tracker =
890 base::debug::GlobalActivityTracker::Get();
891 if (tracker)
892 tracker->RecordLogMessage(str_newline);
893
[email protected]eb4c4d032012-04-03 18:45:05894 // Ensure the first characters of the string are on the stack so they
Weze976b732018-10-20 03:37:31895 // are contained in minidumps for diagnostic purposes. We place start
896 // and end marker values at either end, so we can scan captured stacks
897 // for the data easily.
898 struct {
899 uint32_t start_marker = 0xbedead01;
900 char data[1024];
901 uint32_t end_marker = 0x5050dead;
902 } str_stack;
903 base::strlcpy(str_stack.data, str_newline.data(),
904 base::size(str_stack.data));
905 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05906
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45907 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55908 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45909 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55910
911 if (log_assert_handler) {
912 log_assert_handler.Run(
913 file_, line_,
914 base::StringPiece(str_newline.c_str() + message_start_,
915 stack_start - message_start_),
916 base::StringPiece(str_newline.c_str() + stack_start));
917 }
[email protected]1ffe08c12008-08-13 11:15:11918 } else {
[email protected]82d89ab2014-02-28 18:25:34919 // Don't use the string with the newline, get a fresh version to send to
920 // the debug message process. We also don't display assertions to the
921 // user in release mode. The enduser can't do anything with this
922 // information, and displaying message boxes when the application is
923 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50924#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42925 if (!base::debug::BeingDebugged()) {
926 // Displaying a dialog is unnecessary when debugging and can complicate
927 // debugging.
928 DisplayDebugMessageInDialog(stream_.str());
929 }
[email protected]4d5901272008-11-06 00:33:50930#endif
[email protected]82d89ab2014-02-28 18:25:34931 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52932#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
933 IMMEDIATE_CRASH();
934#else
[email protected]82d89ab2014-02-28 18:25:34935 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52936#endif
initial.commitd7cae122008-07-26 21:49:38937 }
938 }
939}
940
[email protected]eae9c062011-01-11 00:50:59941// writes the common header info to the stream
942void LogMessage::Init(const char* file, int line) {
943 base::StringPiece filename(file);
944 size_t last_slash_pos = filename.find_last_of("\\/");
945 if (last_slash_pos != base::StringPiece::npos)
946 filename.remove_prefix(last_slash_pos + 1);
947
Kevin Marshall9873826d2019-10-14 20:09:35948 // Stores the base name as the null-terminated suffix substring of |filename|.
949 file_basename_ = filename.data();
950
[email protected]eae9c062011-01-11 00:50:59951 // TODO(darin): It might be nice if the columns were fixed width.
952
953 stream_ << '[';
James Cooka0536c32018-08-01 20:13:31954 if (g_log_prefix)
955 stream_ << g_log_prefix << ':';
thestig3e4787d2015-05-19 19:31:52956 if (g_log_process_id)
Chris Findeisen2a373a2d2019-08-15 19:44:30957 stream_ << base::GetUniqueIdForProcess() << ':';
thestig3e4787d2015-05-19 19:31:52958 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09959 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52960 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39961#if defined(OS_WIN)
962 SYSTEMTIME local_time;
963 GetLocalTime(&local_time);
964 stream_ << std::setfill('0')
965 << std::setw(2) << local_time.wMonth
966 << std::setw(2) << local_time.wDay
967 << '/'
968 << std::setw(2) << local_time.wHour
969 << std::setw(2) << local_time.wMinute
970 << std::setw(2) << local_time.wSecond
971 << '.'
972 << std::setw(3)
973 << local_time.wMilliseconds
974 << ':';
975#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
djkurtz543a3be2016-11-30 14:17:34976 timeval tv;
977 gettimeofday(&tv, nullptr);
978 time_t t = tv.tv_sec;
979 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59980 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59981 struct tm* tm_time = &local_time;
982 stream_ << std::setfill('0')
983 << std::setw(2) << 1 + tm_time->tm_mon
984 << std::setw(2) << tm_time->tm_mday
985 << '/'
986 << std::setw(2) << tm_time->tm_hour
987 << std::setw(2) << tm_time->tm_min
988 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34989 << '.'
990 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59991 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39992#else
993#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34994#endif
[email protected]eae9c062011-01-11 00:50:59995 }
thestig3e4787d2015-05-19 19:31:52996 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59997 stream_ << TickCount() << ':';
998 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19999 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:591000 else
1001 stream_ << "VERBOSE" << -severity_;
1002
1003 stream_ << ":" << filename << "(" << line << ")] ";
1004
pkasting9cf9b94a2014-10-01 22:18:431005 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:591006}
1007
[email protected]d8617a62009-10-09 23:52:201008#if defined(OS_WIN)
1009// This has already been defined in the header, but defining it again as DWORD
1010// ensures that the type used in the header is equivalent to DWORD. If not,
1011// the redefinition is a compile error.
1012typedef DWORD SystemErrorCode;
1013#endif
1014
1015SystemErrorCode GetLastSystemErrorCode() {
1016#if defined(OS_WIN)
1017 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391018#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201019 return errno;
[email protected]d8617a62009-10-09 23:52:201020#endif
1021}
1022
[email protected]c914d8a2014-04-23 01:11:011023BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391024#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:271025 const int kErrorMessageBufferSize = 256;
1026 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011027 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521028 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Avi Drissmane3b70bf2019-01-04 19:50:221029 base::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011030 if (len) {
1031 // Messages returned by system end with line breaks.
1032 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451033 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011034 }
Bruce Dawson19175842017-08-02 17:00:451035 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011036 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391037#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141038 return base::safe_strerror(error_code) +
1039 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:521040#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391041}
[email protected]d8617a62009-10-09 23:52:201042
[email protected]c914d8a2014-04-23 01:11:011043
1044#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201045Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1046 int line,
1047 LogSeverity severity,
1048 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001049 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201050
1051Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011052 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061053 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1054 // field) and use Alias in hopes that it makes it into crash dumps.
1055 DWORD last_error = err_;
1056 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201057}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391058#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201059ErrnoLogMessage::ErrnoLogMessage(const char* file,
1060 int line,
1061 LogSeverity severity,
1062 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001063 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201064
1065ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011066 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141067 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1068 // field) and use Alias in hopes that it makes it into crash dumps.
1069 int last_error = err_;
1070 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201071}
thestig3e4787d2015-05-19 19:31:521072#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201073
initial.commitd7cae122008-07-26 21:49:381074void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391075#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:551076 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:091077#endif
[email protected]17dcf752013-07-15 21:47:091078 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381079}
1080
Robbie McElrath8bf49842019-08-20 22:22:531081#if defined(OS_CHROMEOS)
1082FILE* DuplicateLogFILE() {
1083 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1084 return nullptr;
1085
1086 int log_fd = fileno(g_log_file);
1087 if (log_fd == -1)
1088 return nullptr;
1089 base::ScopedFD dup_fd(dup(log_fd));
1090 if (dup_fd == -1)
1091 return nullptr;
1092 FILE* duplicate = fdopen(dup_fd.get(), "a");
1093 if (!duplicate)
1094 return nullptr;
1095 ignore_result(dup_fd.release());
1096 return duplicate;
1097}
1098#endif
1099
[email protected]e36ddc82009-12-08 04:22:501100void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491101 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501102 size_t bytes_written = 0;
1103 const size_t message_len = strlen(message);
1104 int rv;
1105 while (bytes_written < message_len) {
1106 rv = HANDLE_EINTR(
1107 write(STDERR_FILENO, message + bytes_written,
1108 message_len - bytes_written));
1109 if (rv < 0) {
1110 // Give up, nothing we can do now.
1111 break;
1112 }
1113 bytes_written += rv;
1114 }
1115
1116 if (message_len > 0 && message[message_len - 1] != '\n') {
1117 do {
1118 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1119 if (rv < 0) {
1120 // Give up, nothing we can do now.
1121 break;
1122 }
1123 } while (rv != 1);
1124 }
1125 }
1126
1127 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501128 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501129}
1130
[email protected]34a907732012-01-20 06:33:271131// This was defined at the beginning of this file.
1132#undef write
1133
[email protected]f01b88a2013-02-27 22:04:001134#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091135bool IsLoggingToFileEnabled() {
1136 return g_logging_destination & LOG_TO_FILE;
1137}
1138
Jan Wilken Dörrieb630aca2019-12-04 10:59:111139std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521140 if (g_log_file_name)
1141 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111142 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001143}
1144#endif
1145
[email protected]96fd0032009-04-24 00:13:081146} // namespace logging
initial.commitd7cae122008-07-26 21:49:381147
[email protected]81411c62014-07-08 23:03:061148std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491149 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381150}