blob: 17969f40c8daf1b9a1bc1dc6ee1f1230969c2dd8 [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"
Nicolò Mazzucato6c278d9b2019-08-02 16:25:4413#include "base/trace_event/trace_event.h"
avi9b6f42932015-12-26 22:15:1414#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5015
[email protected]b16ef312008-08-19 18:36:2316#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5017#include <io.h>
alex-accc1bde62017-04-19 08:33:5518#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2819typedef HANDLE FileHandle;
20typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5021// Windows warns on using write(). It prefers _write().
22#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
23// Windows doesn't define STDERR_FILENO. Define it here.
24#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3425
[email protected]052f1b52008-11-06 21:43:0726#elif defined(OS_MACOSX)
Eric Noyaufce100702017-10-16 09:46:3427// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
28// in favor of OS_LOG (Unified Logging).
29#include <AvailabilityMacros.h>
30#if defined(OS_IOS)
31#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
32#define USE_ASL
33#endif
34#else // !defined(OS_IOS)
35#if !defined(MAC_OS_X_VERSION_10_12) || \
36 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
37#define USE_ASL
38#endif
39#endif // defined(OS_IOS)
40
41#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4242#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3443#else
44#include <os/log.h>
45#endif
46
mark4c7449c2015-11-10 19:53:4247#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2848#include <mach/mach.h>
49#include <mach/mach_time.h>
50#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3451
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3952#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]19ea84ca2010-11-12 08:37:0853#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2754#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0855#endif
[email protected]052f1b52008-11-06 21:43:0756#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5957#endif
58
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3959#if defined(OS_FUCHSIA)
Sharon Yanga4b908de2019-05-07 22:19:0360#include <lib/syslog/global.h>
61#include <lib/syslog/logger.h>
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3962#include <zircon/process.h>
63#include <zircon/syscalls.h>
64#endif
65
66#if defined(OS_ANDROID)
67#include <android/log.h>
68#endif
69
70#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2071#include <errno.h>
mark4c7449c2015-11-10 19:53:4272#include <paths.h>
[email protected]166326c62010-08-05 15:50:2373#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2874#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0075#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2876#include <string.h>
mark4c7449c2015-11-10 19:53:4277#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2878#include <unistd.h>
79#define MAX_PATH PATH_MAX
80typedef FILE* FileHandle;
81typedef pthread_mutex_t* MutexHandle;
82#endif
83
[email protected]1f88b5162011-04-01 00:02:2984#include <algorithm>
85#include <cstring>
initial.commitd7cae122008-07-26 21:49:3886#include <ctime>
87#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2988#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0189#include <string>
alex-accc1bde62017-04-19 08:33:5590#include <utility>
[email protected]b16ef312008-08-19 18:36:2391
initial.commitd7cae122008-07-26 21:49:3892#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5593#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3894#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2895#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5596#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0597#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5098#include "base/debug/debugger.h"
99#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:16100#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45101#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:03102#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35103#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00104#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13105#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01106#include "base/strings/string_util.h"
107#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42108#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07109#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:20110#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:09111#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36112#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39113
Cliff Smolinskyc5c52102019-05-03 20:51:54114#if defined(OS_WIN)
115#include "base/win/win_util.h"
116#endif
117
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39118#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24119#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04120#endif
[email protected]52a261f2009-03-03 15:01:12121
initial.commitd7cae122008-07-26 21:49:38122namespace logging {
123
[email protected]064aa162011-12-03 00:30:08124namespace {
125
thestig3e4787d2015-05-19 19:31:52126VlogInfo* g_vlog_info = nullptr;
127VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38128
weza245bd072017-06-18 23:26:34129const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Avi Drissmane3b70bf2019-01-04 19:50:22130static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
weza245bd072017-06-18 23:26:34131 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38132
thestig75f87352014-12-03 21:42:27133const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19134 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
135 return log_severity_names[severity];
136 return "UNKNOWN";
137}
138
thestig3e4787d2015-05-19 19:31:52139int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32140
Sharon Yang7cb919a2019-05-20 20:27:15141// Specifies the process' logging sink(s), represented as a combination of
142// LoggingDestination values joined by bitwise OR.
143int g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38144
[email protected]a33c9892008-08-25 20:10:31145// For LOG_ERROR and above, always print to stderr.
146const int kAlwaysPrintErrorLevel = LOG_ERROR;
147
[email protected]614e9fa2008-08-11 22:52:59148// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38149// will be lazily initialized to the default value when it is
150// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33151using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52152PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38153
thestig3e4787d2015-05-19 19:31:52154// This file is lazily opened and the handle may be nullptr
155FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38156
thestig3e4787d2015-05-19 19:31:52157// What should be prepended to each message?
158bool g_log_process_id = false;
159bool g_log_thread_id = false;
160bool g_log_timestamp = true;
161bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31162const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38163
[email protected]81e0a852010-08-17 00:38:12164// Should we pop up fatal debug messages in a dialog?
165bool show_error_dialogs = false;
166
initial.commitd7cae122008-07-26 21:49:38167// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55168// the debug message dialog and process termination. Assert handlers are stored
169// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45170base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
171 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
172 return *instance;
173}
alex-accc1bde62017-04-19 08:33:55174
[email protected]2b07b8412009-11-25 15:26:34175// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52176LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38177
[email protected]f6abeba2008-08-08 13:27:28178// Helper functions to wrap platform differences.
179
avi9b6f42932015-12-26 22:15:14180int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24181#if defined(OS_WIN)
182 return GetCurrentProcessId();
Wezb0501302018-03-09 05:18:45183#elif defined(OS_FUCHSIA)
184 zx_info_handle_basic_t basic = {};
185 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
186 sizeof(basic), nullptr, nullptr);
187 return basic.koid;
[email protected]f8588472008-11-05 23:17:24188#elif defined(OS_POSIX)
189 return getpid();
190#endif
191}
192
avi9b6f42932015-12-26 22:15:14193uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24194#if defined(OS_WIN)
195 return GetTickCount();
Wezb0501302018-03-09 05:18:45196#elif defined(OS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35197 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45198 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39199#elif defined(OS_MACOSX)
200 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08201#elif defined(OS_NACL)
202 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
203 // So we have to use clock() for now.
204 return clock();
[email protected]e43eddf12009-12-29 00:32:52205#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07206 struct timespec ts;
207 clock_gettime(CLOCK_MONOTONIC, &ts);
208
avi9b6f42932015-12-26 22:15:14209 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
210 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07211
212 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24213#endif
214}
215
[email protected]614e9fa2008-08-11 22:52:59216void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28217#if defined(OS_WIN)
jdoerriebacc1962019-02-07 13:39:22218 DeleteFile(base::as_wcstr(log_name));
thestig75f87352014-12-03 21:42:27219#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45220 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39221#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59222 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39223#else
224#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28225#endif
226}
initial.commitd7cae122008-07-26 21:49:38227
[email protected]5f95d532010-10-01 17:16:58228PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55229#if defined(OS_WIN)
230 // On Windows we use the same path as the exe.
jdoerrie5c4dc4e2019-02-01 18:02:33231 base::char16 module_name[MAX_PATH];
jdoerriebacc1962019-02-07 13:39:22232 GetModuleFileName(nullptr, base::as_writable_wcstr(module_name), MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58233
scottmgfc5b7072015-01-27 21:46:28234 PathString log_name = module_name;
235 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58236 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28237 log_name.erase(last_backslash + 1);
jdoerrie5c4dc4e2019-02-01 18:02:33238 log_name += STRING16_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28239 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39240#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55241 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58242 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55243#endif
244}
245
ananta61762fb2015-09-18 01:00:09246// We don't need locks on Windows for atomically appending to files. The OS
247// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39248#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55249// This class acts as a wrapper for locking the logging files.
250// LoggingLock::Init() should be called from the main thread before any logging
251// is done. Then whenever logging, be sure to have a local LoggingLock
252// instance on the stack. This will ensure that the lock is unlocked upon
253// exiting the frame.
254// LoggingLocks can not be nested.
255class LoggingLock {
256 public:
257 LoggingLock() {
258 LockLogging();
259 }
260
261 ~LoggingLock() {
262 UnlockLogging();
263 }
264
265 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
266 if (initialized)
267 return;
268 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58269
ananta61762fb2015-09-18 01:00:09270 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20271 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09272
[email protected]5b84fe32010-09-14 22:24:55273 initialized = true;
274 }
275
276 private:
277 static void LockLogging() {
278 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55279 pthread_mutex_lock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55280 } else {
281 // use the lock
282 log_lock->Lock();
283 }
284 }
285
286 static void UnlockLogging() {
287 if (lock_log_file == LOCK_LOG_FILE) {
[email protected]5b84fe32010-09-14 22:24:55288 pthread_mutex_unlock(&log_mutex);
[email protected]5b84fe32010-09-14 22:24:55289 } else {
290 log_lock->Unlock();
291 }
292 }
293
294 // The lock is used if log file locking is false. It helps us avoid problems
295 // with multiple threads writing to the log file at the same time. Use
296 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20297 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55298
299 // When we don't use a lock, we are using a global mutex. We need to do this
300 // because LockFileEx is not thread safe.
[email protected]5b84fe32010-09-14 22:24:55301 static pthread_mutex_t log_mutex;
[email protected]5b84fe32010-09-14 22:24:55302
303 static bool initialized;
304 static LogLockingState lock_log_file;
305};
306
307// static
308bool LoggingLock::initialized = false;
309// static
thestig3e4787d2015-05-19 19:31:52310base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55311// static
312LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
313
[email protected]5b84fe32010-09-14 22:24:55314pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
[email protected]5b84fe32010-09-14 22:24:55315
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39316#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09317
thestig3e4787d2015-05-19 19:31:52318// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38319// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52320// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38321bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52322 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38323 return true;
324
thestig3e4787d2015-05-19 19:31:52325 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59326 // Nobody has called InitLogging to specify a debug log file, so here we
327 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52328 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38329 }
330
thestig3e4787d2015-05-19 19:31:52331 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59332#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09333 // The FILE_APPEND_DATA access mask ensures that the file is atomically
334 // appended to across accesses from multiple threads.
335 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
336 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
jdoerriebacc1962019-02-07 13:39:22337 g_log_file = CreateFile(base::as_wcstr(*g_log_file_name), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52338 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
339 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
340 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02341 // We are intentionally not using FilePath or FileUtil here to reduce the
342 // dependencies of the logging implementation. For e.g. FilePath and
343 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
344 // some consumers of base logging like chrome_elf, etc.
345 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32346 // try the current directory
jdoerrie5c4dc4e2019-02-01 18:02:33347 base::char16 system_buffer[MAX_PATH];
anantaf2651872016-06-16 22:21:02348 system_buffer[0] = 0;
jdoerrie5c4dc4e2019-02-01 18:02:33349 DWORD len = ::GetCurrentDirectory(base::size(system_buffer),
jdoerriebacc1962019-02-07 13:39:22350 base::as_writable_wcstr(system_buffer));
Avi Drissmane3b70bf2019-01-04 19:50:22351 if (len == 0 || len > base::size(system_buffer))
ananta61762fb2015-09-18 01:00:09352 return false;
353
anantaf2651872016-06-16 22:21:02354 *g_log_file_name = system_buffer;
355 // Append a trailing backslash if needed.
356 if (g_log_file_name->back() != L'\\')
jdoerrie5c4dc4e2019-02-01 18:02:33357 *g_log_file_name += STRING16_LITERAL("\\");
358 *g_log_file_name += STRING16_LITERAL("debug.log");
ananta61762fb2015-09-18 01:00:09359
jdoerriebacc1962019-02-07 13:39:22360 g_log_file =
361 CreateFile(base::as_wcstr(*g_log_file_name), FILE_APPEND_DATA,
362 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS,
363 FILE_ATTRIBUTE_NORMAL, nullptr);
thestig3e4787d2015-05-19 19:31:52364 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
365 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32366 return false;
367 }
initial.commitd7cae122008-07-26 21:49:38368 }
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39369#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52370 g_log_file = fopen(g_log_file_name->c_str(), "a");
371 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11372 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39373#else
374#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28375#endif
[email protected]1d8c2702008-08-19 23:39:32376 }
377
initial.commitd7cae122008-07-26 21:49:38378 return true;
379}
380
[email protected]17dcf752013-07-15 21:47:09381void CloseFile(FileHandle log) {
382#if defined(OS_WIN)
383 CloseHandle(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39384#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09385 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39386#else
387#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09388#endif
389}
390
391void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52392 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09393 return;
394
thestig3e4787d2015-05-19 19:31:52395 CloseFile(g_log_file);
396 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09397}
398
[email protected]064aa162011-12-03 00:30:08399} // namespace
400
Tomas Popelaafffa972018-11-13 20:42:05401#if defined(DCHECK_IS_CONFIGURABLE)
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51402// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30403// determined at run-time. We default it to INFO, to avoid it triggering
404// crashes before the run-time has explicitly chosen the behaviour.
405BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Tomas Popelaafffa972018-11-13 20:42:05406#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30407
scottmg3c957a52016-12-10 20:57:59408// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
409// an object of the correct type on the LHS of the unused part of the ternary
410// operator.
411std::ostream* g_swallow_stream;
412
[email protected]5e3f7c22013-06-21 21:15:33413bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45414#if defined(OS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15415 // Can log only to the system debug log and stderr.
416 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
417 0u);
[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
Wez224c0bf62019-05-24 19:26:13438#if defined(OS_FUCHSIA)
439 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
440 fx_logger_config_t config;
441 config.min_severity = FX_LOG_INFO;
442 config.console_fd = -1;
443 config.log_service_channel = ZX_HANDLE_INVALID;
444 std::string log_tag = command_line->GetProgram().BaseName().AsUTF8Unsafe();
445 const char* log_tag_data = log_tag.data();
446 config.tags = &log_tag_data;
447 config.num_tags = 1;
448 fx_log_init_with_config(&config);
449 }
450#endif
451
[email protected]5e3f7c22013-06-21 21:15:33452 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52453 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21454 return true;
initial.commitd7cae122008-07-26 21:49:38455
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39456#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09457 LoggingLock::Init(settings.lock_log, settings.log_file);
458 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09459#endif
[email protected]17dcf752013-07-15 21:47:09460
461 // Calling InitLogging twice or after some log call has already opened the
462 // default log file will re-initialize to the new options.
463 CloseLogFileUnlocked();
464
thestig3e4787d2015-05-19 19:31:52465 if (!g_log_file_name)
466 g_log_file_name = new PathString();
467 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33468 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52469 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38470
[email protected]c7d5da992010-10-28 00:20:21471 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38472}
473
474void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52475 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38476}
477
478int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52479 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38480}
481
skobesc78c0ad72015-12-07 20:21:23482bool ShouldCreateLogMessage(int severity) {
483 if (severity < g_min_log_level)
484 return false;
485
Wez6c8acb82019-07-18 00:32:59486 // Return true here unless we know ~LogMessage won't do anything.
skobesc78c0ad72015-12-07 20:21:23487 return g_logging_destination != LOG_NONE || log_message_handler ||
488 severity >= kAlwaysPrintErrorLevel;
489}
490
Wez6c8acb82019-07-18 00:32:59491// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
492// If |severity| is high then true will be returned when no log destinations are
493// set, or only LOG_TO_FILE is set, since that is useful for local development
494// and debugging.
495bool ShouldLogToStderr(int severity) {
496 if (g_logging_destination & LOG_TO_STDERR)
497 return true;
498 if (severity >= kAlwaysPrintErrorLevel)
499 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
500 return false;
501}
502
[email protected]162ac0f2010-11-04 15:50:49503int GetVlogVerbosity() {
504 return std::max(-1, LOG_INFO - GetMinLogLevel());
505}
506
[email protected]99b7c57f2010-09-29 19:26:36507int GetVlogLevelHelper(const char* file, size_t N) {
508 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52509 // Note: |g_vlog_info| may change on a different thread during startup
510 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08511 VlogInfo* vlog_info = g_vlog_info;
512 return vlog_info ?
513 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49514 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36515}
516
initial.commitd7cae122008-07-26 21:49:38517void SetLogItems(bool enable_process_id, bool enable_thread_id,
518 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52519 g_log_process_id = enable_process_id;
520 g_log_thread_id = enable_thread_id;
521 g_log_timestamp = enable_timestamp;
522 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38523}
524
James Cooka0536c32018-08-01 20:13:31525void SetLogPrefix(const char* prefix) {
526 DCHECK(!prefix ||
527 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
528 g_log_prefix = prefix;
529}
530
[email protected]81e0a852010-08-17 00:38:12531void SetShowErrorDialogs(bool enable_dialogs) {
532 show_error_dialogs = enable_dialogs;
533}
534
alex-accc1bde62017-04-19 08:33:55535ScopedLogAssertHandler::ScopedLogAssertHandler(
536 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45537 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55538}
539
540ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45541 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38542}
543
[email protected]2b07b8412009-11-25 15:26:34544void SetLogMessageHandler(LogMessageHandlerFunction handler) {
545 log_message_handler = handler;
546}
547
[email protected]64e5cc02010-11-03 19:20:27548LogMessageHandlerFunction GetLogMessageHandler() {
549 return log_message_handler;
550}
551
[email protected]6d445d32010-09-30 19:10:03552// Explicit instantiations for commonly used comparisons.
553template std::string* MakeCheckOpString<int, int>(
554 const int&, const int&, const char* names);
555template std::string* MakeCheckOpString<unsigned long, unsigned long>(
556 const unsigned long&, const unsigned long&, const char* names);
557template std::string* MakeCheckOpString<unsigned long, unsigned int>(
558 const unsigned long&, const unsigned int&, const char* names);
559template std::string* MakeCheckOpString<unsigned int, unsigned long>(
560 const unsigned int&, const unsigned long&, const char* names);
561template std::string* MakeCheckOpString<std::string, std::string>(
562 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34563
jbroman6bcfec422016-05-26 00:28:46564void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16565 (*os) << "nullptr";
566}
567
[email protected]f2c05492014-06-17 12:04:23568#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22569// Displays a message box to the user with the error message in it.
570// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25571// This is for developers only; we don't use this in circumstances
572// (like release builds) where users could see it, since users don't
573// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22574void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38575 if (str.empty())
576 return;
577
[email protected]81e0a852010-08-17 00:38:12578 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44579 return;
580
[email protected]f6abeba2008-08-08 13:27:28581#if defined(OS_WIN)
[email protected]561513f2010-12-16 23:29:25582 // We intentionally don't implement a dialog on other platforms.
583 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54584 if (base::win::IsUser32AndGdi32Available()) {
585 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
586 MB_OK | MB_ICONHAND | MB_TOPMOST);
587 } else {
588 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
589 }
thestig3e4787d2015-05-19 19:31:52590#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38591}
[email protected]f2c05492014-06-17 12:04:23592#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38593
[email protected]eae9c062011-01-11 00:50:59594LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
595 : severity_(severity), file_(file), line_(line) {
596 Init(file, line);
597}
598
tnagel4a045d3f2015-07-12 14:19:28599LogMessage::LogMessage(const char* file, int line, const char* condition)
600 : severity_(LOG_FATAL), file_(file), line_(line) {
601 Init(file, line);
602 stream_ << "Check failed: " << condition << ". ";
603}
604
[email protected]9c7132e2011-02-08 07:39:08605LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49606 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38607 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08608 stream_ << "Check failed: " << *result;
609 delete result;
initial.commitd7cae122008-07-26 21:49:38610}
611
[email protected]fb62a532009-02-12 01:19:05612LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08613 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49614 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05615 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08616 stream_ << "Check failed: " << *result;
617 delete result;
[email protected]fb62a532009-02-12 01:19:05618}
619
initial.commitd7cae122008-07-26 21:49:38620LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55621 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08622#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
623 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42624 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
625 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16626 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24627 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16628 stack_trace.OutputToStream(&stream_);
629 base::debug::TaskTrace task_trace;
630 if (!task_trace.empty())
631 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36632
Chris Hamilton888085312019-05-30 00:53:30633 // Include the IPC context, if any.
634 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36635 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30636 if (task && task->ipc_hash) {
637 stream_ << "IPC message handler context: "
638 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36639 }
[email protected]d1ccc35a2010-03-24 05:03:24640 }
[email protected]1d8c2702008-08-19 23:39:32641#endif
[email protected]d1ccc35a2010-03-24 05:03:24642 stream_ << std::endl;
643 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44644 TRACE_LOG_MESSAGE(
645 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24646
[email protected]2b07b8412009-11-25 15:26:34647 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33648 if (log_message_handler &&
649 log_message_handler(severity_, file_, line_,
650 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49651 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34652 return;
[email protected]162ac0f2010-11-04 15:50:49653 }
initial.commitd7cae122008-07-26 21:49:38654
thestig3e4787d2015-05-19 19:31:52655 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28656#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38657 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42658#elif defined(OS_MACOSX)
659 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34660 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
661 // its successor OS_LOG. If there's something weird about stderr, assume
662 // that log messages are going nowhere and log via ASL/OS_LOG too.
663 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42664 //
665 // Programs started by launchd, as UI applications normally are, have had
666 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
667 // a pipe to launchd, which logged what it received (see log_redirect_fd in
668 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
669 //
670 // Another alternative would be to determine whether stderr is a pipe to
671 // launchd and avoid logging via ASL only in that case. See 10.7.5
672 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34673 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
674 // to the system log at all.
mark4c7449c2015-11-10 19:53:42675 //
676 // Note that the ASL client by default discards messages whose levels are
677 // below ASL_LEVEL_NOTICE. It's possible to change that with
678 // asl_set_filter(), but this is pointless because syslogd normally applies
679 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34680 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42681 struct stat stderr_stat;
682 if (fstat(fileno(stderr), &stderr_stat) == -1) {
683 return true;
684 }
685 if (!S_ISCHR(stderr_stat.st_mode)) {
686 return false;
687 }
688
689 struct stat dev_null_stat;
690 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
691 return true;
692 }
693
694 return !S_ISCHR(dev_null_stat.st_mode) ||
695 stderr_stat.st_rdev == dev_null_stat.st_rdev;
696 }();
697
Eric Noyaufce100702017-10-16 09:46:34698 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42699 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
700 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42701 CFBundleRef main_bundle = CFBundleGetMainBundle();
702 CFStringRef main_bundle_id_cf =
703 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34704 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42705 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34706 : std::string("");
707#if defined(USE_ASL)
708 // The facility is set to the main bundle ID if available. Otherwise,
709 // "com.apple.console" is used.
710 const class ASLClient {
mark4c7449c2015-11-10 19:53:42711 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59712 explicit ASLClient(const std::string& facility)
713 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
mark4c7449c2015-11-10 19:53:42714 ~ASLClient() { asl_close(client_); }
715
716 aslclient get() const { return client_; }
717
718 private:
719 aslclient client_;
720 DISALLOW_COPY_AND_ASSIGN(ASLClient);
Eric Noyaufce100702017-10-16 09:46:34721 } asl_client(main_bundle_id.empty() ? main_bundle_id
722 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42723
Eric Noyaufce100702017-10-16 09:46:34724 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42725 public:
726 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
727 ~ASLMessage() { asl_free(message_); }
728
729 aslmsg get() const { return message_; }
730
731 private:
732 aslmsg message_;
733 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
734 } asl_message;
735
736 // By default, messages are only readable by the admin group. Explicitly
737 // make them readable by the user generating the messages.
738 char euid_string[12];
Avi Drissmane3b70bf2019-01-04 19:50:22739 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42740 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
741
742 // Map Chrome log severities to ASL log levels.
743 const char* const asl_level_string = [](LogSeverity severity) {
744 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
745 // non-obvious two-step macro trick achieves what's needed.
746 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
747#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
748#define ASL_LEVEL_STR_X(level) #level
749 switch (severity) {
750 case LOG_INFO:
751 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
752 case LOG_WARNING:
753 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
754 case LOG_ERROR:
755 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
756 case LOG_FATAL:
757 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
758 default:
759 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
760 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
761 }
762#undef ASL_LEVEL_STR
763#undef ASL_LEVEL_STR_X
764 }(severity_);
765 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
766
767 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
768
769 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34770#else // !defined(USE_ASL)
771 const class OSLog {
772 public:
773 explicit OSLog(const char* subsystem)
774 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
775 : OS_LOG_DEFAULT) {}
776 ~OSLog() {
777 if (os_log_ != OS_LOG_DEFAULT) {
778 os_release(os_log_);
779 }
780 }
781 os_log_t get() const { return os_log_; }
782
783 private:
784 os_log_t os_log_;
785 DISALLOW_COPY_AND_ASSIGN(OSLog);
786 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
787 const os_log_type_t os_log_type = [](LogSeverity severity) {
788 switch (severity) {
789 case LOG_INFO:
790 return OS_LOG_TYPE_INFO;
791 case LOG_WARNING:
792 return OS_LOG_TYPE_DEFAULT;
793 case LOG_ERROR:
794 return OS_LOG_TYPE_ERROR;
795 case LOG_FATAL:
796 return OS_LOG_TYPE_FAULT;
797 default:
798 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
799 }
800 }(severity_);
801 os_log_with_type(log.get(), os_log_type, "%{public}s",
802 str_newline.c_str());
803#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42804 }
[email protected]3132e35c2011-07-07 20:46:50805#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25806 android_LogPriority priority =
807 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50808 switch (severity_) {
809 case LOG_INFO:
810 priority = ANDROID_LOG_INFO;
811 break;
812 case LOG_WARNING:
813 priority = ANDROID_LOG_WARN;
814 break;
815 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50816 priority = ANDROID_LOG_ERROR;
817 break;
818 case LOG_FATAL:
819 priority = ANDROID_LOG_FATAL;
820 break;
821 }
Tomasz Ĺšniatowski23dd15af2019-02-15 08:32:03822 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13823#if DCHECK_IS_ON()
824 // Split the output by new lines to prevent the Android system from
825 // truncating the log.
Tomasz Ĺšniatowski23dd15af2019-02-15 08:32:03826 std::vector<std::string> lines = base::SplitString(
827 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
828 // str_newline has an extra newline appended to it (at the top of this
829 // function), so skip the last split element to avoid needlessly
830 // logging an empty string.
831 lines.pop_back();
832 for (const auto& line : lines)
833 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13834#else
835 // The Android system may truncate the string if it's too long.
Tomasz Ĺšniatowski23dd15af2019-02-15 08:32:03836 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18837#endif
Sharon Yanga4b908de2019-05-07 22:19:03838#elif defined(OS_FUCHSIA)
839 fx_log_severity_t severity = FX_LOG_INFO;
Wez224c0bf62019-05-24 19:26:13840 switch (severity_) {
Sharon Yanga4b908de2019-05-07 22:19:03841 case LOG_INFO:
842 severity = FX_LOG_INFO;
843 break;
844 case LOG_WARNING:
845 severity = FX_LOG_WARNING;
846 break;
847 case LOG_ERROR:
848 severity = FX_LOG_ERROR;
849 break;
850 case LOG_FATAL:
Wez224c0bf62019-05-24 19:26:13851 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
852 severity = FX_LOG_ERROR;
Sharon Yanga4b908de2019-05-07 22:19:03853 break;
854 }
855
856 fx_logger_t* logger = fx_log_get_logger();
857 if (logger) {
Wez224c0bf62019-05-24 19:26:13858 // Temporarily pop the trailing newline, since fx_logger will add one.
859 str_newline.pop_back();
860 fx_logger_log(logger, severity, nullptr, str_newline.c_str());
861 str_newline.push_back('\n');
Sharon Yanga4b908de2019-05-07 22:19:03862 }
863#endif // OS_FUCHSIA
Sharon Yang7cb919a2019-05-20 20:27:15864 }
865
Wez6c8acb82019-07-18 00:32:59866 if (ShouldLogToStderr(severity_)) {
[email protected]51105382014-03-14 17:02:15867 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02868 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28869 }
[email protected]52a261f2009-03-03 15:01:12870
thestig3e4787d2015-05-19 19:31:52871 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09872 // We can have multiple threads and/or processes, so try to prevent them
873 // from clobbering each other's writes.
874 // If the client app did not call InitLogging, and the lock has not
875 // been created do it now. We do this on demand, but if two threads try
876 // to do this at the same time, there will be a race condition to create
877 // the lock. This is why InitLogging should be called from the main
878 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39879#if defined(OS_POSIX) || defined(OS_FUCHSIA)
thestig3e4787d2015-05-19 19:31:52880 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55881 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09882#endif
[email protected]5b84fe32010-09-14 22:24:55883 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28884#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55885 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52886 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55887 static_cast<const void*>(str_newline.c_str()),
888 static_cast<DWORD>(str_newline.length()),
889 &num_written,
thestig3e4787d2015-05-19 19:31:52890 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39891#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15892 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52893 str_newline.data(), str_newline.size(), 1, g_log_file));
894 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39895#else
896#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55897#endif
initial.commitd7cae122008-07-26 21:49:38898 }
899 }
900
901 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40902 // Write the log message to the global activity tracker, if running.
903 base::debug::GlobalActivityTracker* tracker =
904 base::debug::GlobalActivityTracker::Get();
905 if (tracker)
906 tracker->RecordLogMessage(str_newline);
907
[email protected]eb4c4d032012-04-03 18:45:05908 // Ensure the first characters of the string are on the stack so they
Weze976b732018-10-20 03:37:31909 // are contained in minidumps for diagnostic purposes. We place start
910 // and end marker values at either end, so we can scan captured stacks
911 // for the data easily.
912 struct {
913 uint32_t start_marker = 0xbedead01;
914 char data[1024];
915 uint32_t end_marker = 0x5050dead;
916 } str_stack;
917 base::strlcpy(str_stack.data, str_newline.data(),
918 base::size(str_stack.data));
919 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05920
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45921 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55922 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45923 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55924
925 if (log_assert_handler) {
926 log_assert_handler.Run(
927 file_, line_,
928 base::StringPiece(str_newline.c_str() + message_start_,
929 stack_start - message_start_),
930 base::StringPiece(str_newline.c_str() + stack_start));
931 }
[email protected]1ffe08c12008-08-13 11:15:11932 } else {
[email protected]82d89ab2014-02-28 18:25:34933 // Don't use the string with the newline, get a fresh version to send to
934 // the debug message process. We also don't display assertions to the
935 // user in release mode. The enduser can't do anything with this
936 // information, and displaying message boxes when the application is
937 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50938#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42939 if (!base::debug::BeingDebugged()) {
940 // Displaying a dialog is unnecessary when debugging and can complicate
941 // debugging.
942 DisplayDebugMessageInDialog(stream_.str());
943 }
[email protected]4d5901272008-11-06 00:33:50944#endif
[email protected]82d89ab2014-02-28 18:25:34945 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52946#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
947 IMMEDIATE_CRASH();
948#else
[email protected]82d89ab2014-02-28 18:25:34949 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52950#endif
initial.commitd7cae122008-07-26 21:49:38951 }
952 }
953}
954
[email protected]eae9c062011-01-11 00:50:59955// writes the common header info to the stream
956void LogMessage::Init(const char* file, int line) {
957 base::StringPiece filename(file);
958 size_t last_slash_pos = filename.find_last_of("\\/");
959 if (last_slash_pos != base::StringPiece::npos)
960 filename.remove_prefix(last_slash_pos + 1);
961
962 // TODO(darin): It might be nice if the columns were fixed width.
963
964 stream_ << '[';
James Cooka0536c32018-08-01 20:13:31965 if (g_log_prefix)
966 stream_ << g_log_prefix << ':';
thestig3e4787d2015-05-19 19:31:52967 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59968 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52969 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09970 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52971 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39972#if defined(OS_WIN)
973 SYSTEMTIME local_time;
974 GetLocalTime(&local_time);
975 stream_ << std::setfill('0')
976 << std::setw(2) << local_time.wMonth
977 << std::setw(2) << local_time.wDay
978 << '/'
979 << std::setw(2) << local_time.wHour
980 << std::setw(2) << local_time.wMinute
981 << std::setw(2) << local_time.wSecond
982 << '.'
983 << std::setw(3)
984 << local_time.wMilliseconds
985 << ':';
986#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
djkurtz543a3be2016-11-30 14:17:34987 timeval tv;
988 gettimeofday(&tv, nullptr);
989 time_t t = tv.tv_sec;
990 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59991 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59992 struct tm* tm_time = &local_time;
993 stream_ << std::setfill('0')
994 << std::setw(2) << 1 + tm_time->tm_mon
995 << std::setw(2) << tm_time->tm_mday
996 << '/'
997 << std::setw(2) << tm_time->tm_hour
998 << std::setw(2) << tm_time->tm_min
999 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:341000 << '.'
1001 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:591002 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391003#else
1004#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:341005#endif
[email protected]eae9c062011-01-11 00:50:591006 }
thestig3e4787d2015-05-19 19:31:521007 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:591008 stream_ << TickCount() << ':';
1009 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:191010 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:591011 else
1012 stream_ << "VERBOSE" << -severity_;
1013
1014 stream_ << ":" << filename << "(" << line << ")] ";
1015
pkasting9cf9b94a2014-10-01 22:18:431016 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:591017}
1018
[email protected]d8617a62009-10-09 23:52:201019#if defined(OS_WIN)
1020// This has already been defined in the header, but defining it again as DWORD
1021// ensures that the type used in the header is equivalent to DWORD. If not,
1022// the redefinition is a compile error.
1023typedef DWORD SystemErrorCode;
1024#endif
1025
1026SystemErrorCode GetLastSystemErrorCode() {
1027#if defined(OS_WIN)
1028 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391029#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201030 return errno;
[email protected]d8617a62009-10-09 23:52:201031#endif
1032}
1033
[email protected]c914d8a2014-04-23 01:11:011034BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391035#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:271036 const int kErrorMessageBufferSize = 256;
1037 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011038 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521039 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Avi Drissmane3b70bf2019-01-04 19:50:221040 base::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011041 if (len) {
1042 // Messages returned by system end with line breaks.
1043 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451044 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011045 }
Bruce Dawson19175842017-08-02 17:00:451046 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011047 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391048#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141049 return base::safe_strerror(error_code) +
1050 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:521051#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391052}
[email protected]d8617a62009-10-09 23:52:201053
[email protected]c914d8a2014-04-23 01:11:011054
1055#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201056Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1057 int line,
1058 LogSeverity severity,
1059 SystemErrorCode err)
1060 : err_(err),
[email protected]d8617a62009-10-09 23:52:201061 log_message_(file, line, severity) {
1062}
1063
1064Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011065 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061066 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1067 // field) and use Alias in hopes that it makes it into crash dumps.
1068 DWORD last_error = err_;
1069 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201070}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391071#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201072ErrnoLogMessage::ErrnoLogMessage(const char* file,
1073 int line,
1074 LogSeverity severity,
1075 SystemErrorCode err)
1076 : err_(err),
1077 log_message_(file, line, severity) {
1078}
1079
1080ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011081 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141082 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1083 // field) and use Alias in hopes that it makes it into crash dumps.
1084 int last_error = err_;
1085 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201086}
thestig3e4787d2015-05-19 19:31:521087#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201088
initial.commitd7cae122008-07-26 21:49:381089void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391090#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:551091 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:091092#endif
[email protected]17dcf752013-07-15 21:47:091093 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381094}
1095
[email protected]e36ddc82009-12-08 04:22:501096void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491097 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501098 size_t bytes_written = 0;
1099 const size_t message_len = strlen(message);
1100 int rv;
1101 while (bytes_written < message_len) {
1102 rv = HANDLE_EINTR(
1103 write(STDERR_FILENO, message + bytes_written,
1104 message_len - bytes_written));
1105 if (rv < 0) {
1106 // Give up, nothing we can do now.
1107 break;
1108 }
1109 bytes_written += rv;
1110 }
1111
1112 if (message_len > 0 && message[message_len - 1] != '\n') {
1113 do {
1114 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1115 if (rv < 0) {
1116 // Give up, nothing we can do now.
1117 break;
1118 }
1119 } while (rv != 1);
1120 }
1121 }
1122
1123 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501124 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501125}
1126
[email protected]34a907732012-01-20 06:33:271127// This was defined at the beginning of this file.
1128#undef write
1129
[email protected]f01b88a2013-02-27 22:04:001130#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091131bool IsLoggingToFileEnabled() {
1132 return g_logging_destination & LOG_TO_FILE;
1133}
1134
jdoerrie5c4dc4e2019-02-01 18:02:331135base::string16 GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521136 if (g_log_file_name)
1137 return *g_log_file_name;
jdoerrie5c4dc4e2019-02-01 18:02:331138 return base::string16();
[email protected]f01b88a2013-02-27 22:04:001139}
1140#endif
1141
tnagel80388e682015-05-26 13:27:561142BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:141143 LogMessage(file, line, LOG_ERROR).stream()
1144 << "NOTREACHED() hit.";
1145}
1146
[email protected]96fd0032009-04-24 00:13:081147} // namespace logging
initial.commitd7cae122008-07-26 21:49:381148
[email protected]81411c62014-07-08 23:03:061149std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491150 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381151}