blob: 010b8e9be370bd84d8ec008ca472ca9c6e6412d6 [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
Chris Hamilton306740d2019-04-25 18:48:3610#include "base/pending_task.h"
Weze976b732018-10-20 03:37:3111#include "base/stl_util.h"
Chris Hamilton306740d2019-04-25 18:48:3612#include "base/task/common/task_annotator.h"
avi9b6f42932015-12-26 22:15:1413#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5014
[email protected]b16ef312008-08-19 18:36:2315#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5016#include <io.h>
alex-accc1bde62017-04-19 08:33:5517#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2818typedef HANDLE FileHandle;
19typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5020// Windows warns on using write(). It prefers _write().
21#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
22// Windows doesn't define STDERR_FILENO. Define it here.
23#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3424
[email protected]052f1b52008-11-06 21:43:0725#elif defined(OS_MACOSX)
Eric Noyaufce100702017-10-16 09:46:3426// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
27// in favor of OS_LOG (Unified Logging).
28#include <AvailabilityMacros.h>
29#if defined(OS_IOS)
30#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
31#define USE_ASL
32#endif
33#else // !defined(OS_IOS)
34#if !defined(MAC_OS_X_VERSION_10_12) || \
35 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
36#define USE_ASL
37#endif
38#endif // defined(OS_IOS)
39
40#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4241#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3442#else
43#include <os/log.h>
44#endif
45
mark4c7449c2015-11-10 19:53:4246#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2847#include <mach/mach.h>
48#include <mach/mach_time.h>
49#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3450
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3951#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]19ea84ca2010-11-12 08:37:0852#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2753#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0854#endif
[email protected]052f1b52008-11-06 21:43:0755#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5956#endif
57
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3958#if defined(OS_FUCHSIA)
Sharon Yanga4b908de2019-05-07 22:19:0359#include <lib/syslog/global.h>
60#include <lib/syslog/logger.h>
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3961#include <zircon/process.h>
62#include <zircon/syscalls.h>
63#endif
64
65#if defined(OS_ANDROID)
66#include <android/log.h>
67#endif
68
69#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2070#include <errno.h>
mark4c7449c2015-11-10 19:53:4271#include <paths.h>
[email protected]166326c62010-08-05 15:50:2372#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2873#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0074#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2875#include <string.h>
mark4c7449c2015-11-10 19:53:4276#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2877#include <unistd.h>
78#define MAX_PATH PATH_MAX
79typedef FILE* FileHandle;
80typedef pthread_mutex_t* MutexHandle;
81#endif
82
[email protected]1f88b5162011-04-01 00:02:2983#include <algorithm>
84#include <cstring>
initial.commitd7cae122008-07-26 21:49:3885#include <ctime>
86#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2987#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0188#include <string>
alex-accc1bde62017-04-19 08:33:5589#include <utility>
[email protected]b16ef312008-08-19 18:36:2390
initial.commitd7cae122008-07-26 21:49:3891#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5592#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3893#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2894#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5595#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0596#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5097#include "base/debug/debugger.h"
98#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:1699#include "base/debug/task_trace.h"
alex-accc1bde62017-04-19 08:33:55100#include "base/lazy_instance.h"
Sharon Yanga4b908de2019-05-07 22:19:03101#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35102#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00103#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13104#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01105#include "base/strings/string_util.h"
106#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42107#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07108#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:20109#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:09110#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36111#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39112
Cliff Smolinskyc5c52102019-05-03 20:51:54113#if defined(OS_WIN)
114#include "base/win/win_util.h"
115#endif
116
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39117#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24118#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04119#endif
[email protected]52a261f2009-03-03 15:01:12120
initial.commitd7cae122008-07-26 21:49:38121namespace logging {
122
[email protected]064aa162011-12-03 00:30:08123namespace {
124
thestig3e4787d2015-05-19 19:31:52125VlogInfo* g_vlog_info = nullptr;
126VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38127
weza245bd072017-06-18 23:26:34128const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Avi Drissmane3b70bf2019-01-04 19:50:22129static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
weza245bd072017-06-18 23:26:34130 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38131
thestig75f87352014-12-03 21:42:27132const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19133 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
134 return log_severity_names[severity];
135 return "UNKNOWN";
136}
137
thestig3e4787d2015-05-19 19:31:52138int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32139
thestig3e4787d2015-05-19 19:31:52140LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38141
[email protected]a33c9892008-08-25 20:10:31142// For LOG_ERROR and above, always print to stderr.
143const int kAlwaysPrintErrorLevel = LOG_ERROR;
144
[email protected]614e9fa2008-08-11 22:52:59145// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38146// will be lazily initialized to the default value when it is
147// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33148using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52149PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38150
thestig3e4787d2015-05-19 19:31:52151// This file is lazily opened and the handle may be nullptr
152FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38153
thestig3e4787d2015-05-19 19:31:52154// What should be prepended to each message?
155bool g_log_process_id = false;
156bool g_log_thread_id = false;
157bool g_log_timestamp = true;
158bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31159const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38160
[email protected]81e0a852010-08-17 00:38:12161// Should we pop up fatal debug messages in a dialog?
162bool show_error_dialogs = false;
163
initial.commitd7cae122008-07-26 21:49:38164// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55165// the debug message dialog and process termination. Assert handlers are stored
166// in stack to allow overriding and restoring.
Brett Wilson1f07f20e2017-10-02 18:55:28167base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
alex-accc1bde62017-04-19 08:33:55168 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
169
[email protected]2b07b8412009-11-25 15:26:34170// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52171LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38172
[email protected]f6abeba2008-08-08 13:27:28173// Helper functions to wrap platform differences.
174
avi9b6f42932015-12-26 22:15:14175int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24176#if defined(OS_WIN)
177 return GetCurrentProcessId();
Wezb0501302018-03-09 05:18:45178#elif defined(OS_FUCHSIA)
179 zx_info_handle_basic_t basic = {};
180 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
181 sizeof(basic), nullptr, nullptr);
182 return basic.koid;
[email protected]f8588472008-11-05 23:17:24183#elif defined(OS_POSIX)
184 return getpid();
185#endif
186}
187
avi9b6f42932015-12-26 22:15:14188uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24189#if defined(OS_WIN)
190 return GetTickCount();
Wezb0501302018-03-09 05:18:45191#elif defined(OS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35192 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45193 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39194#elif defined(OS_MACOSX)
195 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08196#elif defined(OS_NACL)
197 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
198 // So we have to use clock() for now.
199 return clock();
[email protected]e43eddf12009-12-29 00:32:52200#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07201 struct timespec ts;
202 clock_gettime(CLOCK_MONOTONIC, &ts);
203
avi9b6f42932015-12-26 22:15:14204 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
205 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07206
207 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24208#endif
209}
210
[email protected]614e9fa2008-08-11 22:52:59211void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28212#if defined(OS_WIN)
jdoerriebacc1962019-02-07 13:39:22213 DeleteFile(base::as_wcstr(log_name));
thestig75f87352014-12-03 21:42:27214#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45215 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39216#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59217 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39218#else
219#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28220#endif
221}
initial.commitd7cae122008-07-26 21:49:38222
[email protected]5f95d532010-10-01 17:16:58223PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55224#if defined(OS_WIN)
225 // On Windows we use the same path as the exe.
jdoerrie5c4dc4e2019-02-01 18:02:33226 base::char16 module_name[MAX_PATH];
jdoerriebacc1962019-02-07 13:39:22227 GetModuleFileName(nullptr, base::as_writable_wcstr(module_name), MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58228
scottmgfc5b7072015-01-27 21:46:28229 PathString log_name = module_name;
230 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58231 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28232 log_name.erase(last_backslash + 1);
jdoerrie5c4dc4e2019-02-01 18:02:33233 log_name += STRING16_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28234 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39235#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55236 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58237 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55238#endif
239}
240
ananta61762fb2015-09-18 01:00:09241// We don't need locks on Windows for atomically appending to files. The OS
242// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39243#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55244// This class acts as a wrapper for locking the logging files.
245// LoggingLock::Init() should be called from the main thread before any logging
246// is done. Then whenever logging, be sure to have a local LoggingLock
247// instance on the stack. This will ensure that the lock is unlocked upon
248// exiting the frame.
249// LoggingLocks can not be nested.
250class LoggingLock {
251 public:
252 LoggingLock() {
253 LockLogging();
254 }
255
256 ~LoggingLock() {
257 UnlockLogging();
258 }
259
260 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
261 if (initialized)
262 return;
263 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58264
ananta61762fb2015-09-18 01:00:09265 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20266 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09267
[email protected]5b84fe32010-09-14 22:24:55268 initialized = true;
269 }
270
271 private:
272 static void LockLogging() {
273 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55274 pthread_mutex_lock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55275 } else {
276 // use the lock
277 log_lock->Lock();
278 }
279 }
280
281 static void UnlockLogging() {
282 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55283 pthread_mutex_unlock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55284 } else {
285 log_lock->Unlock();
286 }
287 }
288
289 // The lock is used if log file locking is false. It helps us avoid problems
290 // with multiple threads writing to the log file at the same time. Use
291 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20292 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55293
294 // When we don't use a lock, we are using a global mutex. We need to do this
295 // because LockFileEx is not thread safe.
[email protected]5b84fe32010-09-14 22:24:55296 static pthread_mutex_t log_mutex;
[email protected]5b84fe32010-09-14 22:24:55297
298 static bool initialized;
299 static LogLockingState lock_log_file;
300};
301
302// static
303bool LoggingLock::initialized = false;
304// static
thestig3e4787d2015-05-19 19:31:52305base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55306// static
307LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
308
[email protected]5b84fe32010-09-14 22:24:55309pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
[email protected]5b84fe32010-09-14 22:24:55310
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39311#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09312
thestig3e4787d2015-05-19 19:31:52313// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38314// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52315// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38316bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52317 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38318 return true;
319
thestig3e4787d2015-05-19 19:31:52320 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59321 // Nobody has called InitLogging to specify a debug log file, so here we
322 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52323 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38324 }
325
thestig3e4787d2015-05-19 19:31:52326 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59327#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09328 // The FILE_APPEND_DATA access mask ensures that the file is atomically
329 // appended to across accesses from multiple threads.
330 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
331 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
jdoerriebacc1962019-02-07 13:39:22332 g_log_file = CreateFile(base::as_wcstr(*g_log_file_name), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52333 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
334 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
335 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02336 // We are intentionally not using FilePath or FileUtil here to reduce the
337 // dependencies of the logging implementation. For e.g. FilePath and
338 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
339 // some consumers of base logging like chrome_elf, etc.
340 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32341 // try the current directory
jdoerrie5c4dc4e2019-02-01 18:02:33342 base::char16 system_buffer[MAX_PATH];
anantaf2651872016-06-16 22:21:02343 system_buffer[0] = 0;
jdoerrie5c4dc4e2019-02-01 18:02:33344 DWORD len = ::GetCurrentDirectory(base::size(system_buffer),
jdoerriebacc1962019-02-07 13:39:22345 base::as_writable_wcstr(system_buffer));
Avi Drissmane3b70bf2019-01-04 19:50:22346 if (len == 0 || len > base::size(system_buffer))
ananta61762fb2015-09-18 01:00:09347 return false;
348
anantaf2651872016-06-16 22:21:02349 *g_log_file_name = system_buffer;
350 // Append a trailing backslash if needed.
351 if (g_log_file_name->back() != L'\\')
jdoerrie5c4dc4e2019-02-01 18:02:33352 *g_log_file_name += STRING16_LITERAL("\\");
353 *g_log_file_name += STRING16_LITERAL("debug.log");
ananta61762fb2015-09-18 01:00:09354
jdoerriebacc1962019-02-07 13:39:22355 g_log_file =
356 CreateFile(base::as_wcstr(*g_log_file_name), FILE_APPEND_DATA,
357 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS,
358 FILE_ATTRIBUTE_NORMAL, nullptr);
thestig3e4787d2015-05-19 19:31:52359 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
360 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32361 return false;
362 }
initial.commitd7cae122008-07-26 21:49:38363 }
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39364#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52365 g_log_file = fopen(g_log_file_name->c_str(), "a");
366 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11367 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39368#else
369#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28370#endif
[email protected]1d8c2702008-08-19 23:39:32371 }
372
initial.commitd7cae122008-07-26 21:49:38373 return true;
374}
375
[email protected]17dcf752013-07-15 21:47:09376void CloseFile(FileHandle log) {
377#if defined(OS_WIN)
378 CloseHandle(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39379#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09380 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39381#else
382#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09383#endif
384}
385
386void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52387 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09388 return;
389
thestig3e4787d2015-05-19 19:31:52390 CloseFile(g_log_file);
391 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09392}
393
[email protected]064aa162011-12-03 00:30:08394} // namespace
395
Tomas Popelaafffa972018-11-13 20:42:05396#if defined(DCHECK_IS_CONFIGURABLE)
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51397// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30398// determined at run-time. We default it to INFO, to avoid it triggering
399// crashes before the run-time has explicitly chosen the behaviour.
400BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Tomas Popelaafffa972018-11-13 20:42:05401#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30402
scottmg3c957a52016-12-10 20:57:59403// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
404// an object of the correct type on the LHS of the unused part of the ternary
405// operator.
406std::ostream* g_swallow_stream;
407
[email protected]5e3f7c22013-06-21 21:15:33408LoggingSettings::LoggingSettings()
409 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52410 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33411 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38412 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08413
[email protected]5e3f7c22013-06-21 21:15:33414bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45415#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33416 // Can log only to the system debug log.
417 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45418#endif
pgal.u-szeged421dddb2014-11-25 12:55:02419 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52420 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36421 // vlog switches.
422 if (command_line->HasSwitch(switches::kV) ||
423 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52424 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08425 // by another thread. Don't delete the old VLogInfo, just create a second
426 // one. We keep track of both to avoid memory leak warnings.
427 CHECK(!g_vlog_info_prev);
428 g_vlog_info_prev = g_vlog_info;
429
[email protected]99b7c57f2010-09-29 19:26:36430 g_vlog_info =
431 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49432 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52433 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36434 }
435
thestig3e4787d2015-05-19 19:31:52436 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38437
[email protected]5e3f7c22013-06-21 21:15:33438 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52439 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21440 return true;
initial.commitd7cae122008-07-26 21:49:38441
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39442#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09443 LoggingLock::Init(settings.lock_log, settings.log_file);
444 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09445#endif
Sharon Yanga4b908de2019-05-07 22:19:03446#if defined(OS_FUCHSIA)
447 fx_log_init();
448#endif
[email protected]17dcf752013-07-15 21:47:09449
450 // Calling InitLogging twice or after some log call has already opened the
451 // default log file will re-initialize to the new options.
452 CloseLogFileUnlocked();
453
thestig3e4787d2015-05-19 19:31:52454 if (!g_log_file_name)
455 g_log_file_name = new PathString();
456 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33457 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52458 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38459
[email protected]c7d5da992010-10-28 00:20:21460 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38461}
462
463void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52464 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38465}
466
467int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52468 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38469}
470
skobesc78c0ad72015-12-07 20:21:23471bool ShouldCreateLogMessage(int severity) {
472 if (severity < g_min_log_level)
473 return false;
474
475 // Return true here unless we know ~LogMessage won't do anything. Note that
476 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
477 // when g_logging_destination is LOG_NONE.
478 return g_logging_destination != LOG_NONE || log_message_handler ||
479 severity >= kAlwaysPrintErrorLevel;
480}
481
[email protected]162ac0f2010-11-04 15:50:49482int GetVlogVerbosity() {
483 return std::max(-1, LOG_INFO - GetMinLogLevel());
484}
485
[email protected]99b7c57f2010-09-29 19:26:36486int GetVlogLevelHelper(const char* file, size_t N) {
487 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52488 // Note: |g_vlog_info| may change on a different thread during startup
489 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08490 VlogInfo* vlog_info = g_vlog_info;
491 return vlog_info ?
492 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49493 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36494}
495
initial.commitd7cae122008-07-26 21:49:38496void SetLogItems(bool enable_process_id, bool enable_thread_id,
497 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52498 g_log_process_id = enable_process_id;
499 g_log_thread_id = enable_thread_id;
500 g_log_timestamp = enable_timestamp;
501 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38502}
503
James Cooka0536c32018-08-01 20:13:31504void SetLogPrefix(const char* prefix) {
505 DCHECK(!prefix ||
506 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
507 g_log_prefix = prefix;
508}
509
[email protected]81e0a852010-08-17 00:38:12510void SetShowErrorDialogs(bool enable_dialogs) {
511 show_error_dialogs = enable_dialogs;
512}
513
alex-accc1bde62017-04-19 08:33:55514ScopedLogAssertHandler::ScopedLogAssertHandler(
515 LogAssertHandlerFunction handler) {
516 log_assert_handler_stack.Get().push(std::move(handler));
517}
518
519ScopedLogAssertHandler::~ScopedLogAssertHandler() {
520 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38521}
522
[email protected]2b07b8412009-11-25 15:26:34523void SetLogMessageHandler(LogMessageHandlerFunction handler) {
524 log_message_handler = handler;
525}
526
[email protected]64e5cc02010-11-03 19:20:27527LogMessageHandlerFunction GetLogMessageHandler() {
528 return log_message_handler;
529}
530
[email protected]6d445d32010-09-30 19:10:03531// Explicit instantiations for commonly used comparisons.
532template std::string* MakeCheckOpString<int, int>(
533 const int&, const int&, const char* names);
534template std::string* MakeCheckOpString<unsigned long, unsigned long>(
535 const unsigned long&, const unsigned long&, const char* names);
536template std::string* MakeCheckOpString<unsigned long, unsigned int>(
537 const unsigned long&, const unsigned int&, const char* names);
538template std::string* MakeCheckOpString<unsigned int, unsigned long>(
539 const unsigned int&, const unsigned long&, const char* names);
540template std::string* MakeCheckOpString<std::string, std::string>(
541 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34542
jbroman6bcfec422016-05-26 00:28:46543void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16544 (*os) << "nullptr";
545}
546
[email protected]f2c05492014-06-17 12:04:23547#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22548// Displays a message box to the user with the error message in it.
549// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25550// This is for developers only; we don't use this in circumstances
551// (like release builds) where users could see it, since users don't
552// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22553void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38554 if (str.empty())
555 return;
556
[email protected]81e0a852010-08-17 00:38:12557 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44558 return;
559
[email protected]f6abeba2008-08-08 13:27:28560#if defined(OS_WIN)
[email protected]561513f2010-12-16 23:29:25561 // We intentionally don't implement a dialog on other platforms.
562 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54563 if (base::win::IsUser32AndGdi32Available()) {
564 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
565 MB_OK | MB_ICONHAND | MB_TOPMOST);
566 } else {
567 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
568 }
thestig3e4787d2015-05-19 19:31:52569#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38570}
[email protected]f2c05492014-06-17 12:04:23571#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38572
[email protected]eae9c062011-01-11 00:50:59573LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
574 : severity_(severity), file_(file), line_(line) {
575 Init(file, line);
576}
577
tnagel4a045d3f2015-07-12 14:19:28578LogMessage::LogMessage(const char* file, int line, const char* condition)
579 : severity_(LOG_FATAL), file_(file), line_(line) {
580 Init(file, line);
581 stream_ << "Check failed: " << condition << ". ";
582}
583
[email protected]9c7132e2011-02-08 07:39:08584LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49585 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38586 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08587 stream_ << "Check failed: " << *result;
588 delete result;
initial.commitd7cae122008-07-26 21:49:38589}
590
[email protected]fb62a532009-02-12 01:19:05591LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08592 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49593 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05594 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08595 stream_ << "Check failed: " << *result;
596 delete result;
[email protected]fb62a532009-02-12 01:19:05597}
598
initial.commitd7cae122008-07-26 21:49:38599LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55600 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08601#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
602 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42603 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
604 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16605 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24606 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16607 stack_trace.OutputToStream(&stream_);
608 base::debug::TaskTrace task_trace;
609 if (!task_trace.empty())
610 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36611
612 // Include the IPC context, if any. This is output as a stack trace with a
613 // single frame.
614 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
615 if (task && task->ipc_program_counter) {
616 stream_ << "IPC message handler context:" << std::endl;
617 base::debug::StackTrace ipc_trace(&task->ipc_program_counter, 1);
618 ipc_trace.OutputToStream(&stream_);
619 }
[email protected]d1ccc35a2010-03-24 05:03:24620 }
[email protected]1d8c2702008-08-19 23:39:32621#endif
[email protected]d1ccc35a2010-03-24 05:03:24622 stream_ << std::endl;
623 std::string str_newline(stream_.str());
624
[email protected]2b07b8412009-11-25 15:26:34625 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33626 if (log_message_handler &&
627 log_message_handler(severity_, file_, line_,
628 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49629 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34630 return;
[email protected]162ac0f2010-11-04 15:50:49631 }
initial.commitd7cae122008-07-26 21:49:38632
thestig3e4787d2015-05-19 19:31:52633 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28634#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38635 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42636#elif defined(OS_MACOSX)
637 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34638 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
639 // its successor OS_LOG. If there's something weird about stderr, assume
640 // that log messages are going nowhere and log via ASL/OS_LOG too.
641 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42642 //
643 // Programs started by launchd, as UI applications normally are, have had
644 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
645 // a pipe to launchd, which logged what it received (see log_redirect_fd in
646 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
647 //
648 // Another alternative would be to determine whether stderr is a pipe to
649 // launchd and avoid logging via ASL only in that case. See 10.7.5
650 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34651 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
652 // to the system log at all.
mark4c7449c2015-11-10 19:53:42653 //
654 // Note that the ASL client by default discards messages whose levels are
655 // below ASL_LEVEL_NOTICE. It's possible to change that with
656 // asl_set_filter(), but this is pointless because syslogd normally applies
657 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34658 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42659 struct stat stderr_stat;
660 if (fstat(fileno(stderr), &stderr_stat) == -1) {
661 return true;
662 }
663 if (!S_ISCHR(stderr_stat.st_mode)) {
664 return false;
665 }
666
667 struct stat dev_null_stat;
668 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
669 return true;
670 }
671
672 return !S_ISCHR(dev_null_stat.st_mode) ||
673 stderr_stat.st_rdev == dev_null_stat.st_rdev;
674 }();
675
Eric Noyaufce100702017-10-16 09:46:34676 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42677 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
678 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42679 CFBundleRef main_bundle = CFBundleGetMainBundle();
680 CFStringRef main_bundle_id_cf =
681 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34682 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42683 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34684 : std::string("");
685#if defined(USE_ASL)
686 // The facility is set to the main bundle ID if available. Otherwise,
687 // "com.apple.console" is used.
688 const class ASLClient {
mark4c7449c2015-11-10 19:53:42689 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59690 explicit ASLClient(const std::string& facility)
691 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42692 ~ASLClient() { asl_close(client_); }
693
694 aslclient get() const { return client_; }
695
696 private:
697 aslclient client_;
698 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34699 } asl_client(main_bundle_id.empty() ? main_bundle_id
700 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42701
Eric Noyaufce100702017-10-16 09:46:34702 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42703 public:
704 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
705 ~ASLMessage() { asl_free(message_); }
706
707 aslmsg get() const { return message_; }
708
709 private:
710 aslmsg message_;
711 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
712 } asl_message;
713
714 // By default, messages are only readable by the admin group. Explicitly
715 // make them readable by the user generating the messages.
716 char euid_string[12];
Avi Drissmane3b70bf2019-01-04 19:50:22717 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42718 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
719
720 // Map Chrome log severities to ASL log levels.
721 const char* const asl_level_string = [](LogSeverity severity) {
722 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
723 // non-obvious two-step macro trick achieves what's needed.
724 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
725#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
726#define ASL_LEVEL_STR_X(level) #level
727 switch (severity) {
728 case LOG_INFO:
729 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
730 case LOG_WARNING:
731 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
732 case LOG_ERROR:
733 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
734 case LOG_FATAL:
735 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
736 default:
737 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
738 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
739 }
740#undef ASL_LEVEL_STR
741#undef ASL_LEVEL_STR_X
742 }(severity_);
743 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
744
745 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
746
747 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34748#else // !defined(USE_ASL)
749 const class OSLog {
750 public:
751 explicit OSLog(const char* subsystem)
752 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
753 : OS_LOG_DEFAULT) {}
754 ~OSLog() {
755 if (os_log_ != OS_LOG_DEFAULT) {
756 os_release(os_log_);
757 }
758 }
759 os_log_t get() const { return os_log_; }
760
761 private:
762 os_log_t os_log_;
763 DISALLOW_COPY_AND_ASSIGN(OSLog);
764 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
765 const os_log_type_t os_log_type = [](LogSeverity severity) {
766 switch (severity) {
767 case LOG_INFO:
768 return OS_LOG_TYPE_INFO;
769 case LOG_WARNING:
770 return OS_LOG_TYPE_DEFAULT;
771 case LOG_ERROR:
772 return OS_LOG_TYPE_ERROR;
773 case LOG_FATAL:
774 return OS_LOG_TYPE_FAULT;
775 default:
776 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
777 }
778 }(severity_);
779 os_log_with_type(log.get(), os_log_type, "%{public}s",
780 str_newline.c_str());
781#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42782 }
[email protected]3132e35c2011-07-07 20:46:50783#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25784 android_LogPriority priority =
785 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50786 switch (severity_) {
787 case LOG_INFO:
788 priority = ANDROID_LOG_INFO;
789 break;
790 case LOG_WARNING:
791 priority = ANDROID_LOG_WARN;
792 break;
793 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50794 priority = ANDROID_LOG_ERROR;
795 break;
796 case LOG_FATAL:
797 priority = ANDROID_LOG_FATAL;
798 break;
799 }
Tomasz Åšniatowski23dd15af2019-02-15 08:32:03800 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13801#if DCHECK_IS_ON()
802 // Split the output by new lines to prevent the Android system from
803 // truncating the log.
Tomasz Åšniatowski23dd15af2019-02-15 08:32:03804 std::vector<std::string> lines = base::SplitString(
805 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
806 // str_newline has an extra newline appended to it (at the top of this
807 // function), so skip the last split element to avoid needlessly
808 // logging an empty string.
809 lines.pop_back();
810 for (const auto& line : lines)
811 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13812#else
813 // The Android system may truncate the string if it's too long.
Tomasz Åšniatowski23dd15af2019-02-15 08:32:03814 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18815#endif
Sharon Yanga4b908de2019-05-07 22:19:03816#elif defined(OS_FUCHSIA)
817 fx_log_severity_t severity = FX_LOG_INFO;
818 switch (severity) {
819 case LOG_INFO:
820 severity = FX_LOG_INFO;
821 break;
822 case LOG_WARNING:
823 severity = FX_LOG_WARNING;
824 break;
825 case LOG_ERROR:
826 severity = FX_LOG_ERROR;
827 break;
828 case LOG_FATAL:
829 severity = FX_LOG_FATAL;
830 break;
831 }
832
833 fx_logger_t* logger = fx_log_get_logger();
834 if (logger) {
835 base::FilePath path;
836 base::PathService::Get(base::FILE_EXE, &path);
837 fx_logger_log(logger, severity, path.BaseName().value().c_str(),
838 str_newline.c_str());
839 }
840#endif // OS_FUCHSIA
[email protected]51105382014-03-14 17:02:15841 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06842 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31843 } else if (severity_ >= kAlwaysPrintErrorLevel) {
844 // When we're only outputting to a log file, above a certain log level, we
845 // should still output to stderr so that we can better detect and diagnose
846 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15847 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02848 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28849 }
[email protected]52a261f2009-03-03 15:01:12850
initial.commitd7cae122008-07-26 21:49:38851 // write to log file
thestig3e4787d2015-05-19 19:31:52852 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09853 // We can have multiple threads and/or processes, so try to prevent them
854 // from clobbering each other's writes.
855 // If the client app did not call InitLogging, and the lock has not
856 // been created do it now. We do this on demand, but if two threads try
857 // to do this at the same time, there will be a race condition to create
858 // the lock. This is why InitLogging should be called from the main
859 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39860#if defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52861 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55862 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09863#endif
[email protected]5b84fe32010-09-14 22:24:55864 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28865#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55866 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52867 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55868 static_cast<const void*>(str_newline.c_str()),
869 static_cast<DWORD>(str_newline.length()),
870 &num_written,
thestig3e4787d2015-05-19 19:31:52871 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39872#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15873 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52874 str_newline.data(), str_newline.size(), 1, g_log_file));
875 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39876#else
877#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55878#endif
initial.commitd7cae122008-07-26 21:49:38879 }
880 }
881
882 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40883 // Write the log message to the global activity tracker, if running.
884 base::debug::GlobalActivityTracker* tracker =
885 base::debug::GlobalActivityTracker::Get();
886 if (tracker)
887 tracker->RecordLogMessage(str_newline);
888
[email protected]eb4c4d032012-04-03 18:45:05889 // Ensure the first characters of the string are on the stack so they
Weze976b732018-10-20 03:37:31890 // are contained in minidumps for diagnostic purposes. We place start
891 // and end marker values at either end, so we can scan captured stacks
892 // for the data easily.
893 struct {
894 uint32_t start_marker = 0xbedead01;
895 char data[1024];
896 uint32_t end_marker = 0x5050dead;
897 } str_stack;
898 base::strlcpy(str_stack.data, str_newline.data(),
899 base::size(str_stack.data));
900 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05901
Lukasz Anforowiczd3e19132017-12-06 19:44:27902 if (log_assert_handler_stack.IsCreated() &&
alex-accc1bde62017-04-19 08:33:55903 !log_assert_handler_stack.Get().empty()) {
904 LogAssertHandlerFunction log_assert_handler =
905 log_assert_handler_stack.Get().top();
906
907 if (log_assert_handler) {
908 log_assert_handler.Run(
909 file_, line_,
910 base::StringPiece(str_newline.c_str() + message_start_,
911 stack_start - message_start_),
912 base::StringPiece(str_newline.c_str() + stack_start));
913 }
[email protected]1ffe08c12008-08-13 11:15:11914 } else {
[email protected]82d89ab2014-02-28 18:25:34915 // Don't use the string with the newline, get a fresh version to send to
916 // the debug message process. We also don't display assertions to the
917 // user in release mode. The enduser can't do anything with this
918 // information, and displaying message boxes when the application is
919 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50920#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42921 if (!base::debug::BeingDebugged()) {
922 // Displaying a dialog is unnecessary when debugging and can complicate
923 // debugging.
924 DisplayDebugMessageInDialog(stream_.str());
925 }
[email protected]4d5901272008-11-06 00:33:50926#endif
[email protected]82d89ab2014-02-28 18:25:34927 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52928#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
929 IMMEDIATE_CRASH();
930#else
[email protected]82d89ab2014-02-28 18:25:34931 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52932#endif
initial.commitd7cae122008-07-26 21:49:38933 }
934 }
935}
936
[email protected]eae9c062011-01-11 00:50:59937// writes the common header info to the stream
938void LogMessage::Init(const char* file, int line) {
939 base::StringPiece filename(file);
940 size_t last_slash_pos = filename.find_last_of("\\/");
941 if (last_slash_pos != base::StringPiece::npos)
942 filename.remove_prefix(last_slash_pos + 1);
943
944 // TODO(darin): It might be nice if the columns were fixed width.
945
946 stream_ << '[';
James Cooka0536c32018-08-01 20:13:31947 if (g_log_prefix)
948 stream_ << g_log_prefix << ':';
thestig3e4787d2015-05-19 19:31:52949 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59950 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52951 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09952 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52953 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39954#if defined(OS_WIN)
955 SYSTEMTIME local_time;
956 GetLocalTime(&local_time);
957 stream_ << std::setfill('0')
958 << std::setw(2) << local_time.wMonth
959 << std::setw(2) << local_time.wDay
960 << '/'
961 << std::setw(2) << local_time.wHour
962 << std::setw(2) << local_time.wMinute
963 << std::setw(2) << local_time.wSecond
964 << '.'
965 << std::setw(3)
966 << local_time.wMilliseconds
967 << ':';
968#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
djkurtz543a3be2016-11-30 14:17:34969 timeval tv;
970 gettimeofday(&tv, nullptr);
971 time_t t = tv.tv_sec;
972 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59973 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59974 struct tm* tm_time = &local_time;
975 stream_ << std::setfill('0')
976 << std::setw(2) << 1 + tm_time->tm_mon
977 << std::setw(2) << tm_time->tm_mday
978 << '/'
979 << std::setw(2) << tm_time->tm_hour
980 << std::setw(2) << tm_time->tm_min
981 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34982 << '.'
983 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59984 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39985#else
986#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34987#endif
[email protected]eae9c062011-01-11 00:50:59988 }
thestig3e4787d2015-05-19 19:31:52989 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59990 stream_ << TickCount() << ':';
991 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19992 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59993 else
994 stream_ << "VERBOSE" << -severity_;
995
996 stream_ << ":" << filename << "(" << line << ")] ";
997
pkasting9cf9b94a2014-10-01 22:18:43998 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59999}
1000
[email protected]d8617a62009-10-09 23:52:201001#if defined(OS_WIN)
1002// This has already been defined in the header, but defining it again as DWORD
1003// ensures that the type used in the header is equivalent to DWORD. If not,
1004// the redefinition is a compile error.
1005typedef DWORD SystemErrorCode;
1006#endif
1007
1008SystemErrorCode GetLastSystemErrorCode() {
1009#if defined(OS_WIN)
1010 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391011#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201012 return errno;
[email protected]d8617a62009-10-09 23:52:201013#endif
1014}
1015
[email protected]c914d8a2014-04-23 01:11:011016BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391017#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:271018 const int kErrorMessageBufferSize = 256;
1019 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011020 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521021 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Avi Drissmane3b70bf2019-01-04 19:50:221022 base::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011023 if (len) {
1024 // Messages returned by system end with line breaks.
1025 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451026 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011027 }
Bruce Dawson19175842017-08-02 17:00:451028 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011029 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391030#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141031 return base::safe_strerror(error_code) +
1032 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:521033#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391034}
[email protected]d8617a62009-10-09 23:52:201035
[email protected]c914d8a2014-04-23 01:11:011036
1037#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201038Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1039 int line,
1040 LogSeverity severity,
1041 SystemErrorCode err)
1042 : err_(err),
[email protected]d8617a62009-10-09 23:52:201043 log_message_(file, line, severity) {
1044}
1045
1046Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011047 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061048 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1049 // field) and use Alias in hopes that it makes it into crash dumps.
1050 DWORD last_error = err_;
1051 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201052}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391053#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201054ErrnoLogMessage::ErrnoLogMessage(const char* file,
1055 int line,
1056 LogSeverity severity,
1057 SystemErrorCode err)
1058 : err_(err),
1059 log_message_(file, line, severity) {
1060}
1061
1062ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011063 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141064 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1065 // field) and use Alias in hopes that it makes it into crash dumps.
1066 int last_error = err_;
1067 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201068}
thestig3e4787d2015-05-19 19:31:521069#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201070
initial.commitd7cae122008-07-26 21:49:381071void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391072#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:551073 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:091074#endif
[email protected]17dcf752013-07-15 21:47:091075 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381076}
1077
[email protected]e36ddc82009-12-08 04:22:501078void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491079 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501080 size_t bytes_written = 0;
1081 const size_t message_len = strlen(message);
1082 int rv;
1083 while (bytes_written < message_len) {
1084 rv = HANDLE_EINTR(
1085 write(STDERR_FILENO, message + bytes_written,
1086 message_len - bytes_written));
1087 if (rv < 0) {
1088 // Give up, nothing we can do now.
1089 break;
1090 }
1091 bytes_written += rv;
1092 }
1093
1094 if (message_len > 0 && message[message_len - 1] != '\n') {
1095 do {
1096 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1097 if (rv < 0) {
1098 // Give up, nothing we can do now.
1099 break;
1100 }
1101 } while (rv != 1);
1102 }
1103 }
1104
1105 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501106 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501107}
1108
[email protected]34a907732012-01-20 06:33:271109// This was defined at the beginning of this file.
1110#undef write
1111
[email protected]f01b88a2013-02-27 22:04:001112#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091113bool IsLoggingToFileEnabled() {
1114 return g_logging_destination & LOG_TO_FILE;
1115}
1116
jdoerrie5c4dc4e2019-02-01 18:02:331117base::string16 GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521118 if (g_log_file_name)
1119 return *g_log_file_name;
jdoerrie5c4dc4e2019-02-01 18:02:331120 return base::string16();
[email protected]f01b88a2013-02-27 22:04:001121}
1122#endif
1123
tnagel80388e682015-05-26 13:27:561124BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:141125 LogMessage(file, line, LOG_ERROR).stream()
1126 << "NOTREACHED() hit.";
1127}
1128
[email protected]96fd0032009-04-24 00:13:081129} // namespace logging
initial.commitd7cae122008-07-26 21:49:381130
[email protected]81411c62014-07-08 23:03:061131std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491132 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381133}