blob: bd9e2d808140c1a44e19beb6e383ffa10b6b96cf [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)
59#include <zircon/process.h>
60#include <zircon/syscalls.h>
61#endif
62
63#if defined(OS_ANDROID)
64#include <android/log.h>
65#endif
66
67#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2068#include <errno.h>
mark4c7449c2015-11-10 19:53:4269#include <paths.h>
[email protected]166326c62010-08-05 15:50:2370#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2871#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0072#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2873#include <string.h>
mark4c7449c2015-11-10 19:53:4274#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2875#include <unistd.h>
76#define MAX_PATH PATH_MAX
77typedef FILE* FileHandle;
78typedef pthread_mutex_t* MutexHandle;
79#endif
80
[email protected]1f88b5162011-04-01 00:02:2981#include <algorithm>
82#include <cstring>
initial.commitd7cae122008-07-26 21:49:3883#include <ctime>
84#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2985#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0186#include <string>
alex-accc1bde62017-04-19 08:33:5587#include <utility>
[email protected]b16ef312008-08-19 18:36:2388
initial.commitd7cae122008-07-26 21:49:3889#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5590#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3891#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2892#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5593#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0594#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5095#include "base/debug/debugger.h"
96#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:1697#include "base/debug/task_trace.h"
alex-accc1bde62017-04-19 08:33:5598#include "base/lazy_instance.h"
[email protected]2025d002012-11-14 20:54:3599#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00100#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13101#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01102#include "base/strings/string_util.h"
103#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42104#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07105#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:20106#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:09107#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36108#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39109
Cliff Smolinskyc5c52102019-05-03 20:51:54110#if defined(OS_WIN)
111#include "base/win/win_util.h"
112#endif
113
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39114#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24115#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04116#endif
[email protected]52a261f2009-03-03 15:01:12117
initial.commitd7cae122008-07-26 21:49:38118namespace logging {
119
[email protected]064aa162011-12-03 00:30:08120namespace {
121
thestig3e4787d2015-05-19 19:31:52122VlogInfo* g_vlog_info = nullptr;
123VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38124
weza245bd072017-06-18 23:26:34125const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Avi Drissmane3b70bf2019-01-04 19:50:22126static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
weza245bd072017-06-18 23:26:34127 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38128
thestig75f87352014-12-03 21:42:27129const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19130 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
131 return log_severity_names[severity];
132 return "UNKNOWN";
133}
134
thestig3e4787d2015-05-19 19:31:52135int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32136
thestig3e4787d2015-05-19 19:31:52137LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38138
[email protected]a33c9892008-08-25 20:10:31139// For LOG_ERROR and above, always print to stderr.
140const int kAlwaysPrintErrorLevel = LOG_ERROR;
141
[email protected]614e9fa2008-08-11 22:52:59142// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38143// will be lazily initialized to the default value when it is
144// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33145using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52146PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38147
thestig3e4787d2015-05-19 19:31:52148// This file is lazily opened and the handle may be nullptr
149FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38150
thestig3e4787d2015-05-19 19:31:52151// What should be prepended to each message?
152bool g_log_process_id = false;
153bool g_log_thread_id = false;
154bool g_log_timestamp = true;
155bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31156const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38157
[email protected]81e0a852010-08-17 00:38:12158// Should we pop up fatal debug messages in a dialog?
159bool show_error_dialogs = false;
160
initial.commitd7cae122008-07-26 21:49:38161// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55162// the debug message dialog and process termination. Assert handlers are stored
163// in stack to allow overriding and restoring.
Brett Wilson1f07f20e2017-10-02 18:55:28164base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
alex-accc1bde62017-04-19 08:33:55165 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
166
[email protected]2b07b8412009-11-25 15:26:34167// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52168LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38169
[email protected]f6abeba2008-08-08 13:27:28170// Helper functions to wrap platform differences.
171
avi9b6f42932015-12-26 22:15:14172int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24173#if defined(OS_WIN)
174 return GetCurrentProcessId();
Wezb0501302018-03-09 05:18:45175#elif defined(OS_FUCHSIA)
176 zx_info_handle_basic_t basic = {};
177 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
178 sizeof(basic), nullptr, nullptr);
179 return basic.koid;
[email protected]f8588472008-11-05 23:17:24180#elif defined(OS_POSIX)
181 return getpid();
182#endif
183}
184
avi9b6f42932015-12-26 22:15:14185uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24186#if defined(OS_WIN)
187 return GetTickCount();
Wezb0501302018-03-09 05:18:45188#elif defined(OS_FUCHSIA)
189 return zx_clock_get(ZX_CLOCK_MONOTONIC) /
190 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39191#elif defined(OS_MACOSX)
192 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08193#elif defined(OS_NACL)
194 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
195 // So we have to use clock() for now.
196 return clock();
[email protected]e43eddf12009-12-29 00:32:52197#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07198 struct timespec ts;
199 clock_gettime(CLOCK_MONOTONIC, &ts);
200
avi9b6f42932015-12-26 22:15:14201 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
202 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07203
204 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24205#endif
206}
207
[email protected]614e9fa2008-08-11 22:52:59208void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28209#if defined(OS_WIN)
jdoerriebacc1962019-02-07 13:39:22210 DeleteFile(base::as_wcstr(log_name));
thestig75f87352014-12-03 21:42:27211#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45212 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39213#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59214 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39215#else
216#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28217#endif
218}
initial.commitd7cae122008-07-26 21:49:38219
[email protected]5f95d532010-10-01 17:16:58220PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55221#if defined(OS_WIN)
222 // On Windows we use the same path as the exe.
jdoerrie5c4dc4e2019-02-01 18:02:33223 base::char16 module_name[MAX_PATH];
jdoerriebacc1962019-02-07 13:39:22224 GetModuleFileName(nullptr, base::as_writable_wcstr(module_name), MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58225
scottmgfc5b7072015-01-27 21:46:28226 PathString log_name = module_name;
227 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58228 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28229 log_name.erase(last_backslash + 1);
jdoerrie5c4dc4e2019-02-01 18:02:33230 log_name += STRING16_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28231 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39232#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55233 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58234 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55235#endif
236}
237
ananta61762fb2015-09-18 01:00:09238// We don't need locks on Windows for atomically appending to files. The OS
239// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39240#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55241// This class acts as a wrapper for locking the logging files.
242// LoggingLock::Init() should be called from the main thread before any logging
243// is done. Then whenever logging, be sure to have a local LoggingLock
244// instance on the stack. This will ensure that the lock is unlocked upon
245// exiting the frame.
246// LoggingLocks can not be nested.
247class LoggingLock {
248 public:
249 LoggingLock() {
250 LockLogging();
251 }
252
253 ~LoggingLock() {
254 UnlockLogging();
255 }
256
257 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
258 if (initialized)
259 return;
260 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58261
ananta61762fb2015-09-18 01:00:09262 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20263 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09264
[email protected]5b84fe32010-09-14 22:24:55265 initialized = true;
266 }
267
268 private:
269 static void LockLogging() {
270 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55271 pthread_mutex_lock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55272 } else {
273 // use the lock
274 log_lock->Lock();
275 }
276 }
277
278 static void UnlockLogging() {
279 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55280 pthread_mutex_unlock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55281 } else {
282 log_lock->Unlock();
283 }
284 }
285
286 // The lock is used if log file locking is false. It helps us avoid problems
287 // with multiple threads writing to the log file at the same time. Use
288 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20289 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55290
291 // When we don't use a lock, we are using a global mutex. We need to do this
292 // because LockFileEx is not thread safe.
[email protected]5b84fe32010-09-14 22:24:55293 static pthread_mutex_t log_mutex;
[email protected]5b84fe32010-09-14 22:24:55294
295 static bool initialized;
296 static LogLockingState lock_log_file;
297};
298
299// static
300bool LoggingLock::initialized = false;
301// static
thestig3e4787d2015-05-19 19:31:52302base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55303// static
304LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
305
[email protected]5b84fe32010-09-14 22:24:55306pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
[email protected]5b84fe32010-09-14 22:24:55307
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39308#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09309
thestig3e4787d2015-05-19 19:31:52310// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38311// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52312// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38313bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52314 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38315 return true;
316
thestig3e4787d2015-05-19 19:31:52317 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59318 // Nobody has called InitLogging to specify a debug log file, so here we
319 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52320 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38321 }
322
thestig3e4787d2015-05-19 19:31:52323 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59324#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09325 // The FILE_APPEND_DATA access mask ensures that the file is atomically
326 // appended to across accesses from multiple threads.
327 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
328 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
jdoerriebacc1962019-02-07 13:39:22329 g_log_file = CreateFile(base::as_wcstr(*g_log_file_name), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52330 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
331 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
332 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02333 // We are intentionally not using FilePath or FileUtil here to reduce the
334 // dependencies of the logging implementation. For e.g. FilePath and
335 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
336 // some consumers of base logging like chrome_elf, etc.
337 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32338 // try the current directory
jdoerrie5c4dc4e2019-02-01 18:02:33339 base::char16 system_buffer[MAX_PATH];
anantaf2651872016-06-16 22:21:02340 system_buffer[0] = 0;
jdoerrie5c4dc4e2019-02-01 18:02:33341 DWORD len = ::GetCurrentDirectory(base::size(system_buffer),
jdoerriebacc1962019-02-07 13:39:22342 base::as_writable_wcstr(system_buffer));
Avi Drissmane3b70bf2019-01-04 19:50:22343 if (len == 0 || len > base::size(system_buffer))
ananta61762fb2015-09-18 01:00:09344 return false;
345
anantaf2651872016-06-16 22:21:02346 *g_log_file_name = system_buffer;
347 // Append a trailing backslash if needed.
348 if (g_log_file_name->back() != L'\\')
jdoerrie5c4dc4e2019-02-01 18:02:33349 *g_log_file_name += STRING16_LITERAL("\\");
350 *g_log_file_name += STRING16_LITERAL("debug.log");
ananta61762fb2015-09-18 01:00:09351
jdoerriebacc1962019-02-07 13:39:22352 g_log_file =
353 CreateFile(base::as_wcstr(*g_log_file_name), FILE_APPEND_DATA,
354 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS,
355 FILE_ATTRIBUTE_NORMAL, nullptr);
thestig3e4787d2015-05-19 19:31:52356 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
357 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32358 return false;
359 }
initial.commitd7cae122008-07-26 21:49:38360 }
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39361#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52362 g_log_file = fopen(g_log_file_name->c_str(), "a");
363 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11364 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39365#else
366#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28367#endif
[email protected]1d8c2702008-08-19 23:39:32368 }
369
initial.commitd7cae122008-07-26 21:49:38370 return true;
371}
372
[email protected]17dcf752013-07-15 21:47:09373void CloseFile(FileHandle log) {
374#if defined(OS_WIN)
375 CloseHandle(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39376#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09377 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39378#else
379#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09380#endif
381}
382
383void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52384 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09385 return;
386
thestig3e4787d2015-05-19 19:31:52387 CloseFile(g_log_file);
388 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09389}
390
[email protected]064aa162011-12-03 00:30:08391} // namespace
392
Tomas Popelaafffa972018-11-13 20:42:05393#if defined(DCHECK_IS_CONFIGURABLE)
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51394// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30395// determined at run-time. We default it to INFO, to avoid it triggering
396// crashes before the run-time has explicitly chosen the behaviour.
397BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Tomas Popelaafffa972018-11-13 20:42:05398#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30399
scottmg3c957a52016-12-10 20:57:59400// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
401// an object of the correct type on the LHS of the unused part of the ternary
402// operator.
403std::ostream* g_swallow_stream;
404
[email protected]5e3f7c22013-06-21 21:15:33405LoggingSettings::LoggingSettings()
406 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52407 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33408 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38409 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08410
[email protected]5e3f7c22013-06-21 21:15:33411bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45412#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33413 // Can log only to the system debug log.
414 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45415#endif
pgal.u-szeged421dddb2014-11-25 12:55:02416 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52417 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36418 // vlog switches.
419 if (command_line->HasSwitch(switches::kV) ||
420 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52421 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08422 // by another thread. Don't delete the old VLogInfo, just create a second
423 // one. We keep track of both to avoid memory leak warnings.
424 CHECK(!g_vlog_info_prev);
425 g_vlog_info_prev = g_vlog_info;
426
[email protected]99b7c57f2010-09-29 19:26:36427 g_vlog_info =
428 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49429 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52430 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36431 }
432
thestig3e4787d2015-05-19 19:31:52433 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38434
[email protected]5e3f7c22013-06-21 21:15:33435 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52436 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21437 return true;
initial.commitd7cae122008-07-26 21:49:38438
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39439#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09440 LoggingLock::Init(settings.lock_log, settings.log_file);
441 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09442#endif
[email protected]17dcf752013-07-15 21:47:09443
444 // Calling InitLogging twice or after some log call has already opened the
445 // default log file will re-initialize to the new options.
446 CloseLogFileUnlocked();
447
thestig3e4787d2015-05-19 19:31:52448 if (!g_log_file_name)
449 g_log_file_name = new PathString();
450 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33451 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52452 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38453
[email protected]c7d5da992010-10-28 00:20:21454 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38455}
456
457void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52458 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38459}
460
461int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52462 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38463}
464
skobesc78c0ad72015-12-07 20:21:23465bool ShouldCreateLogMessage(int severity) {
466 if (severity < g_min_log_level)
467 return false;
468
469 // Return true here unless we know ~LogMessage won't do anything. Note that
470 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
471 // when g_logging_destination is LOG_NONE.
472 return g_logging_destination != LOG_NONE || log_message_handler ||
473 severity >= kAlwaysPrintErrorLevel;
474}
475
[email protected]162ac0f2010-11-04 15:50:49476int GetVlogVerbosity() {
477 return std::max(-1, LOG_INFO - GetMinLogLevel());
478}
479
[email protected]99b7c57f2010-09-29 19:26:36480int GetVlogLevelHelper(const char* file, size_t N) {
481 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52482 // Note: |g_vlog_info| may change on a different thread during startup
483 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08484 VlogInfo* vlog_info = g_vlog_info;
485 return vlog_info ?
486 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49487 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36488}
489
initial.commitd7cae122008-07-26 21:49:38490void SetLogItems(bool enable_process_id, bool enable_thread_id,
491 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52492 g_log_process_id = enable_process_id;
493 g_log_thread_id = enable_thread_id;
494 g_log_timestamp = enable_timestamp;
495 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38496}
497
James Cooka0536c32018-08-01 20:13:31498void SetLogPrefix(const char* prefix) {
499 DCHECK(!prefix ||
500 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
501 g_log_prefix = prefix;
502}
503
[email protected]81e0a852010-08-17 00:38:12504void SetShowErrorDialogs(bool enable_dialogs) {
505 show_error_dialogs = enable_dialogs;
506}
507
alex-accc1bde62017-04-19 08:33:55508ScopedLogAssertHandler::ScopedLogAssertHandler(
509 LogAssertHandlerFunction handler) {
510 log_assert_handler_stack.Get().push(std::move(handler));
511}
512
513ScopedLogAssertHandler::~ScopedLogAssertHandler() {
514 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38515}
516
[email protected]2b07b8412009-11-25 15:26:34517void SetLogMessageHandler(LogMessageHandlerFunction handler) {
518 log_message_handler = handler;
519}
520
[email protected]64e5cc02010-11-03 19:20:27521LogMessageHandlerFunction GetLogMessageHandler() {
522 return log_message_handler;
523}
524
[email protected]6d445d32010-09-30 19:10:03525// Explicit instantiations for commonly used comparisons.
526template std::string* MakeCheckOpString<int, int>(
527 const int&, const int&, const char* names);
528template std::string* MakeCheckOpString<unsigned long, unsigned long>(
529 const unsigned long&, const unsigned long&, const char* names);
530template std::string* MakeCheckOpString<unsigned long, unsigned int>(
531 const unsigned long&, const unsigned int&, const char* names);
532template std::string* MakeCheckOpString<unsigned int, unsigned long>(
533 const unsigned int&, const unsigned long&, const char* names);
534template std::string* MakeCheckOpString<std::string, std::string>(
535 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34536
jbroman6bcfec422016-05-26 00:28:46537void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16538 (*os) << "nullptr";
539}
540
[email protected]f2c05492014-06-17 12:04:23541#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22542// Displays a message box to the user with the error message in it.
543// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25544// This is for developers only; we don't use this in circumstances
545// (like release builds) where users could see it, since users don't
546// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22547void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38548 if (str.empty())
549 return;
550
[email protected]81e0a852010-08-17 00:38:12551 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44552 return;
553
[email protected]f6abeba2008-08-08 13:27:28554#if defined(OS_WIN)
[email protected]561513f2010-12-16 23:29:25555 // We intentionally don't implement a dialog on other platforms.
556 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54557 if (base::win::IsUser32AndGdi32Available()) {
558 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
559 MB_OK | MB_ICONHAND | MB_TOPMOST);
560 } else {
561 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
562 }
thestig3e4787d2015-05-19 19:31:52563#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38564}
[email protected]f2c05492014-06-17 12:04:23565#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38566
[email protected]eae9c062011-01-11 00:50:59567LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
568 : severity_(severity), file_(file), line_(line) {
569 Init(file, line);
570}
571
tnagel4a045d3f2015-07-12 14:19:28572LogMessage::LogMessage(const char* file, int line, const char* condition)
573 : severity_(LOG_FATAL), file_(file), line_(line) {
574 Init(file, line);
575 stream_ << "Check failed: " << condition << ". ";
576}
577
[email protected]9c7132e2011-02-08 07:39:08578LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49579 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38580 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08581 stream_ << "Check failed: " << *result;
582 delete result;
initial.commitd7cae122008-07-26 21:49:38583}
584
[email protected]fb62a532009-02-12 01:19:05585LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08586 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49587 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05588 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08589 stream_ << "Check failed: " << *result;
590 delete result;
[email protected]fb62a532009-02-12 01:19:05591}
592
initial.commitd7cae122008-07-26 21:49:38593LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55594 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08595#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
596 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42597 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
598 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16599 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24600 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16601 stack_trace.OutputToStream(&stream_);
602 base::debug::TaskTrace task_trace;
603 if (!task_trace.empty())
604 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36605
606 // Include the IPC context, if any. This is output as a stack trace with a
607 // single frame.
608 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
609 if (task && task->ipc_program_counter) {
610 stream_ << "IPC message handler context:" << std::endl;
611 base::debug::StackTrace ipc_trace(&task->ipc_program_counter, 1);
612 ipc_trace.OutputToStream(&stream_);
613 }
[email protected]d1ccc35a2010-03-24 05:03:24614 }
[email protected]1d8c2702008-08-19 23:39:32615#endif
[email protected]d1ccc35a2010-03-24 05:03:24616 stream_ << std::endl;
617 std::string str_newline(stream_.str());
618
[email protected]2b07b8412009-11-25 15:26:34619 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33620 if (log_message_handler &&
621 log_message_handler(severity_, file_, line_,
622 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49623 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34624 return;
[email protected]162ac0f2010-11-04 15:50:49625 }
initial.commitd7cae122008-07-26 21:49:38626
thestig3e4787d2015-05-19 19:31:52627 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28628#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38629 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42630#elif defined(OS_MACOSX)
631 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34632 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
633 // its successor OS_LOG. If there's something weird about stderr, assume
634 // that log messages are going nowhere and log via ASL/OS_LOG too.
635 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42636 //
637 // Programs started by launchd, as UI applications normally are, have had
638 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
639 // a pipe to launchd, which logged what it received (see log_redirect_fd in
640 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
641 //
642 // Another alternative would be to determine whether stderr is a pipe to
643 // launchd and avoid logging via ASL only in that case. See 10.7.5
644 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34645 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
646 // to the system log at all.
mark4c7449c2015-11-10 19:53:42647 //
648 // Note that the ASL client by default discards messages whose levels are
649 // below ASL_LEVEL_NOTICE. It's possible to change that with
650 // asl_set_filter(), but this is pointless because syslogd normally applies
651 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34652 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42653 struct stat stderr_stat;
654 if (fstat(fileno(stderr), &stderr_stat) == -1) {
655 return true;
656 }
657 if (!S_ISCHR(stderr_stat.st_mode)) {
658 return false;
659 }
660
661 struct stat dev_null_stat;
662 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
663 return true;
664 }
665
666 return !S_ISCHR(dev_null_stat.st_mode) ||
667 stderr_stat.st_rdev == dev_null_stat.st_rdev;
668 }();
669
Eric Noyaufce100702017-10-16 09:46:34670 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42671 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
672 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42673 CFBundleRef main_bundle = CFBundleGetMainBundle();
674 CFStringRef main_bundle_id_cf =
675 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34676 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42677 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34678 : std::string("");
679#if defined(USE_ASL)
680 // The facility is set to the main bundle ID if available. Otherwise,
681 // "com.apple.console" is used.
682 const class ASLClient {
mark4c7449c2015-11-10 19:53:42683 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59684 explicit ASLClient(const std::string& facility)
685 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42686 ~ASLClient() { asl_close(client_); }
687
688 aslclient get() const { return client_; }
689
690 private:
691 aslclient client_;
692 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34693 } asl_client(main_bundle_id.empty() ? main_bundle_id
694 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42695
Eric Noyaufce100702017-10-16 09:46:34696 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42697 public:
698 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
699 ~ASLMessage() { asl_free(message_); }
700
701 aslmsg get() const { return message_; }
702
703 private:
704 aslmsg message_;
705 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
706 } asl_message;
707
708 // By default, messages are only readable by the admin group. Explicitly
709 // make them readable by the user generating the messages.
710 char euid_string[12];
Avi Drissmane3b70bf2019-01-04 19:50:22711 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42712 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
713
714 // Map Chrome log severities to ASL log levels.
715 const char* const asl_level_string = [](LogSeverity severity) {
716 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
717 // non-obvious two-step macro trick achieves what's needed.
718 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
719#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
720#define ASL_LEVEL_STR_X(level) #level
721 switch (severity) {
722 case LOG_INFO:
723 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
724 case LOG_WARNING:
725 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
726 case LOG_ERROR:
727 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
728 case LOG_FATAL:
729 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
730 default:
731 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
732 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
733 }
734#undef ASL_LEVEL_STR
735#undef ASL_LEVEL_STR_X
736 }(severity_);
737 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
738
739 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
740
741 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34742#else // !defined(USE_ASL)
743 const class OSLog {
744 public:
745 explicit OSLog(const char* subsystem)
746 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
747 : OS_LOG_DEFAULT) {}
748 ~OSLog() {
749 if (os_log_ != OS_LOG_DEFAULT) {
750 os_release(os_log_);
751 }
752 }
753 os_log_t get() const { return os_log_; }
754
755 private:
756 os_log_t os_log_;
757 DISALLOW_COPY_AND_ASSIGN(OSLog);
758 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
759 const os_log_type_t os_log_type = [](LogSeverity severity) {
760 switch (severity) {
761 case LOG_INFO:
762 return OS_LOG_TYPE_INFO;
763 case LOG_WARNING:
764 return OS_LOG_TYPE_DEFAULT;
765 case LOG_ERROR:
766 return OS_LOG_TYPE_ERROR;
767 case LOG_FATAL:
768 return OS_LOG_TYPE_FAULT;
769 default:
770 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
771 }
772 }(severity_);
773 os_log_with_type(log.get(), os_log_type, "%{public}s",
774 str_newline.c_str());
775#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42776 }
[email protected]3132e35c2011-07-07 20:46:50777#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25778 android_LogPriority priority =
779 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50780 switch (severity_) {
781 case LOG_INFO:
782 priority = ANDROID_LOG_INFO;
783 break;
784 case LOG_WARNING:
785 priority = ANDROID_LOG_WARN;
786 break;
787 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50788 priority = ANDROID_LOG_ERROR;
789 break;
790 case LOG_FATAL:
791 priority = ANDROID_LOG_FATAL;
792 break;
793 }
Tomasz Åšniatowski23dd15af2019-02-15 08:32:03794 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13795#if DCHECK_IS_ON()
796 // Split the output by new lines to prevent the Android system from
797 // truncating the log.
Tomasz Åšniatowski23dd15af2019-02-15 08:32:03798 std::vector<std::string> lines = base::SplitString(
799 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
800 // str_newline has an extra newline appended to it (at the top of this
801 // function), so skip the last split element to avoid needlessly
802 // logging an empty string.
803 lines.pop_back();
804 for (const auto& line : lines)
805 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13806#else
807 // The Android system may truncate the string if it's too long.
Tomasz Åšniatowski23dd15af2019-02-15 08:32:03808 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18809#endif
Xianzhu Wangae8d96a32018-10-16 20:41:13810#endif // OS_ANDROID
[email protected]51105382014-03-14 17:02:15811 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06812 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31813 } else if (severity_ >= kAlwaysPrintErrorLevel) {
814 // When we're only outputting to a log file, above a certain log level, we
815 // should still output to stderr so that we can better detect and diagnose
816 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15817 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02818 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28819 }
[email protected]52a261f2009-03-03 15:01:12820
initial.commitd7cae122008-07-26 21:49:38821 // write to log file
thestig3e4787d2015-05-19 19:31:52822 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09823 // We can have multiple threads and/or processes, so try to prevent them
824 // from clobbering each other's writes.
825 // If the client app did not call InitLogging, and the lock has not
826 // been created do it now. We do this on demand, but if two threads try
827 // to do this at the same time, there will be a race condition to create
828 // the lock. This is why InitLogging should be called from the main
829 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39830#if defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52831 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55832 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09833#endif
[email protected]5b84fe32010-09-14 22:24:55834 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28835#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55836 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52837 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55838 static_cast<const void*>(str_newline.c_str()),
839 static_cast<DWORD>(str_newline.length()),
840 &num_written,
thestig3e4787d2015-05-19 19:31:52841 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39842#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15843 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52844 str_newline.data(), str_newline.size(), 1, g_log_file));
845 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39846#else
847#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55848#endif
initial.commitd7cae122008-07-26 21:49:38849 }
850 }
851
852 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40853 // Write the log message to the global activity tracker, if running.
854 base::debug::GlobalActivityTracker* tracker =
855 base::debug::GlobalActivityTracker::Get();
856 if (tracker)
857 tracker->RecordLogMessage(str_newline);
858
[email protected]eb4c4d032012-04-03 18:45:05859 // Ensure the first characters of the string are on the stack so they
Weze976b732018-10-20 03:37:31860 // are contained in minidumps for diagnostic purposes. We place start
861 // and end marker values at either end, so we can scan captured stacks
862 // for the data easily.
863 struct {
864 uint32_t start_marker = 0xbedead01;
865 char data[1024];
866 uint32_t end_marker = 0x5050dead;
867 } str_stack;
868 base::strlcpy(str_stack.data, str_newline.data(),
869 base::size(str_stack.data));
870 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05871
Lukasz Anforowiczd3e19132017-12-06 19:44:27872 if (log_assert_handler_stack.IsCreated() &&
alex-accc1bde62017-04-19 08:33:55873 !log_assert_handler_stack.Get().empty()) {
874 LogAssertHandlerFunction log_assert_handler =
875 log_assert_handler_stack.Get().top();
876
877 if (log_assert_handler) {
878 log_assert_handler.Run(
879 file_, line_,
880 base::StringPiece(str_newline.c_str() + message_start_,
881 stack_start - message_start_),
882 base::StringPiece(str_newline.c_str() + stack_start));
883 }
[email protected]1ffe08c12008-08-13 11:15:11884 } else {
[email protected]82d89ab2014-02-28 18:25:34885 // Don't use the string with the newline, get a fresh version to send to
886 // the debug message process. We also don't display assertions to the
887 // user in release mode. The enduser can't do anything with this
888 // information, and displaying message boxes when the application is
889 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50890#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42891 if (!base::debug::BeingDebugged()) {
892 // Displaying a dialog is unnecessary when debugging and can complicate
893 // debugging.
894 DisplayDebugMessageInDialog(stream_.str());
895 }
[email protected]4d5901272008-11-06 00:33:50896#endif
[email protected]82d89ab2014-02-28 18:25:34897 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52898#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
899 IMMEDIATE_CRASH();
900#else
[email protected]82d89ab2014-02-28 18:25:34901 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52902#endif
initial.commitd7cae122008-07-26 21:49:38903 }
904 }
905}
906
[email protected]eae9c062011-01-11 00:50:59907// writes the common header info to the stream
908void LogMessage::Init(const char* file, int line) {
909 base::StringPiece filename(file);
910 size_t last_slash_pos = filename.find_last_of("\\/");
911 if (last_slash_pos != base::StringPiece::npos)
912 filename.remove_prefix(last_slash_pos + 1);
913
914 // TODO(darin): It might be nice if the columns were fixed width.
915
916 stream_ << '[';
James Cooka0536c32018-08-01 20:13:31917 if (g_log_prefix)
918 stream_ << g_log_prefix << ':';
thestig3e4787d2015-05-19 19:31:52919 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59920 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52921 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09922 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52923 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39924#if defined(OS_WIN)
925 SYSTEMTIME local_time;
926 GetLocalTime(&local_time);
927 stream_ << std::setfill('0')
928 << std::setw(2) << local_time.wMonth
929 << std::setw(2) << local_time.wDay
930 << '/'
931 << std::setw(2) << local_time.wHour
932 << std::setw(2) << local_time.wMinute
933 << std::setw(2) << local_time.wSecond
934 << '.'
935 << std::setw(3)
936 << local_time.wMilliseconds
937 << ':';
938#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
djkurtz543a3be2016-11-30 14:17:34939 timeval tv;
940 gettimeofday(&tv, nullptr);
941 time_t t = tv.tv_sec;
942 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59943 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59944 struct tm* tm_time = &local_time;
945 stream_ << std::setfill('0')
946 << std::setw(2) << 1 + tm_time->tm_mon
947 << std::setw(2) << tm_time->tm_mday
948 << '/'
949 << std::setw(2) << tm_time->tm_hour
950 << std::setw(2) << tm_time->tm_min
951 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34952 << '.'
953 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59954 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39955#else
956#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34957#endif
[email protected]eae9c062011-01-11 00:50:59958 }
thestig3e4787d2015-05-19 19:31:52959 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59960 stream_ << TickCount() << ':';
961 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19962 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59963 else
964 stream_ << "VERBOSE" << -severity_;
965
966 stream_ << ":" << filename << "(" << line << ")] ";
967
pkasting9cf9b94a2014-10-01 22:18:43968 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59969}
970
[email protected]d8617a62009-10-09 23:52:20971#if defined(OS_WIN)
972// This has already been defined in the header, but defining it again as DWORD
973// ensures that the type used in the header is equivalent to DWORD. If not,
974// the redefinition is a compile error.
975typedef DWORD SystemErrorCode;
976#endif
977
978SystemErrorCode GetLastSystemErrorCode() {
979#if defined(OS_WIN)
980 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39981#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20982 return errno;
[email protected]d8617a62009-10-09 23:52:20983#endif
984}
985
[email protected]c914d8a2014-04-23 01:11:01986BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39987#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:27988 const int kErrorMessageBufferSize = 256;
989 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01990 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52991 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Avi Drissmane3b70bf2019-01-04 19:50:22992 base::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01993 if (len) {
994 // Messages returned by system end with line breaks.
995 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:45996 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:01997 }
Bruce Dawson19175842017-08-02 17:00:45998 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:01999 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391000#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141001 return base::safe_strerror(error_code) +
1002 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:521003#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391004}
[email protected]d8617a62009-10-09 23:52:201005
[email protected]c914d8a2014-04-23 01:11:011006
1007#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201008Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1009 int line,
1010 LogSeverity severity,
1011 SystemErrorCode err)
1012 : err_(err),
[email protected]d8617a62009-10-09 23:52:201013 log_message_(file, line, severity) {
1014}
1015
1016Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011017 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061018 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1019 // field) and use Alias in hopes that it makes it into crash dumps.
1020 DWORD last_error = err_;
1021 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201022}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391023#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201024ErrnoLogMessage::ErrnoLogMessage(const char* file,
1025 int line,
1026 LogSeverity severity,
1027 SystemErrorCode err)
1028 : err_(err),
1029 log_message_(file, line, severity) {
1030}
1031
1032ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011033 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141034 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1035 // field) and use Alias in hopes that it makes it into crash dumps.
1036 int last_error = err_;
1037 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201038}
thestig3e4787d2015-05-19 19:31:521039#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201040
initial.commitd7cae122008-07-26 21:49:381041void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391042#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:551043 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:091044#endif
[email protected]17dcf752013-07-15 21:47:091045 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381046}
1047
[email protected]e36ddc82009-12-08 04:22:501048void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491049 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501050 size_t bytes_written = 0;
1051 const size_t message_len = strlen(message);
1052 int rv;
1053 while (bytes_written < message_len) {
1054 rv = HANDLE_EINTR(
1055 write(STDERR_FILENO, message + bytes_written,
1056 message_len - bytes_written));
1057 if (rv < 0) {
1058 // Give up, nothing we can do now.
1059 break;
1060 }
1061 bytes_written += rv;
1062 }
1063
1064 if (message_len > 0 && message[message_len - 1] != '\n') {
1065 do {
1066 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1067 if (rv < 0) {
1068 // Give up, nothing we can do now.
1069 break;
1070 }
1071 } while (rv != 1);
1072 }
1073 }
1074
1075 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501076 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501077}
1078
[email protected]34a907732012-01-20 06:33:271079// This was defined at the beginning of this file.
1080#undef write
1081
[email protected]f01b88a2013-02-27 22:04:001082#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091083bool IsLoggingToFileEnabled() {
1084 return g_logging_destination & LOG_TO_FILE;
1085}
1086
jdoerrie5c4dc4e2019-02-01 18:02:331087base::string16 GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521088 if (g_log_file_name)
1089 return *g_log_file_name;
jdoerrie5c4dc4e2019-02-01 18:02:331090 return base::string16();
[email protected]f01b88a2013-02-27 22:04:001091}
1092#endif
1093
tnagel80388e682015-05-26 13:27:561094BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:141095 LogMessage(file, line, LOG_ERROR).stream()
1096 << "NOTREACHED() hit.";
1097}
1098
[email protected]96fd0032009-04-24 00:13:081099} // namespace logging
initial.commitd7cae122008-07-26 21:49:381100
[email protected]81411c62014-07-08 23:03:061101std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491102 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381103}