blob: c0f318c29bcb729db61b9a23f60c71b6cbe10fdf [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
10#include "base/macros.h"
11#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5012
[email protected]b16ef312008-08-19 18:36:2313#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5014#include <io.h>
alex-accc1bde62017-04-19 08:33:5515#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2816typedef HANDLE FileHandle;
17typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5018// Windows warns on using write(). It prefers _write().
19#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
20// Windows doesn't define STDERR_FILENO. Define it here.
21#define STDERR_FILENO 2
[email protected]052f1b52008-11-06 21:43:0722#elif defined(OS_MACOSX)
mark4c7449c2015-11-10 19:53:4223#include <asl.h>
24#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2825#include <mach/mach.h>
26#include <mach/mach_time.h>
27#include <mach-o/dyld.h>
[email protected]e43eddf12009-12-29 00:32:5228#elif defined(OS_POSIX)
[email protected]19ea84ca2010-11-12 08:37:0829#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2730#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0831#endif
[email protected]052f1b52008-11-06 21:43:0732#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5933#endif
34
35#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2036#include <errno.h>
mark4c7449c2015-11-10 19:53:4237#include <paths.h>
[email protected]166326c62010-08-05 15:50:2338#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2839#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0040#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2841#include <string.h>
mark4c7449c2015-11-10 19:53:4242#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2843#include <unistd.h>
44#define MAX_PATH PATH_MAX
45typedef FILE* FileHandle;
46typedef pthread_mutex_t* MutexHandle;
47#endif
48
[email protected]1f88b5162011-04-01 00:02:2949#include <algorithm>
50#include <cstring>
initial.commitd7cae122008-07-26 21:49:3851#include <ctime>
52#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2953#include <ostream>
alex-accc1bde62017-04-19 08:33:5554#include <stack>
[email protected]c914d8a2014-04-23 01:11:0155#include <string>
alex-accc1bde62017-04-19 08:33:5556#include <utility>
[email protected]b16ef312008-08-19 18:36:2357
initial.commitd7cae122008-07-26 21:49:3858#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5559#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3860#include "base/command_line.h"
alex-accc1bde62017-04-19 08:33:5561#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0562#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5063#include "base/debug/debugger.h"
64#include "base/debug/stack_trace.h"
alex-accc1bde62017-04-19 08:33:5565#include "base/lazy_instance.h"
[email protected]2025d002012-11-14 20:54:3566#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0067#include "base/strings/string_piece.h"
[email protected]c914d8a2014-04-23 01:11:0168#include "base/strings/string_util.h"
69#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:4270#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:0771#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2072#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0973#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3674#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0475#if defined(OS_POSIX)
brettw6ee6fd62015-06-09 18:05:2476#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:0477#endif
[email protected]52a261f2009-03-03 15:01:1278
[email protected]3132e35c2011-07-07 20:46:5079#if defined(OS_ANDROID)
80#include <android/log.h>
81#endif
82
initial.commitd7cae122008-07-26 21:49:3883namespace logging {
84
[email protected]064aa162011-12-03 00:30:0885namespace {
86
thestig3e4787d2015-05-19 19:31:5287VlogInfo* g_vlog_info = nullptr;
88VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:3889
weza245bd072017-06-18 23:26:3490const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
91static_assert(LOG_NUM_SEVERITIES == arraysize(log_severity_names),
92 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:3893
thestig75f87352014-12-03 21:42:2794const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:1995 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
96 return log_severity_names[severity];
97 return "UNKNOWN";
98}
99
thestig3e4787d2015-05-19 19:31:52100int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32101
thestig3e4787d2015-05-19 19:31:52102LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38103
[email protected]a33c9892008-08-25 20:10:31104// For LOG_ERROR and above, always print to stderr.
105const int kAlwaysPrintErrorLevel = LOG_ERROR;
106
[email protected]614e9fa2008-08-11 22:52:59107// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38108// will be lazily initialized to the default value when it is
109// first needed.
[email protected]f6abeba2008-08-08 13:27:28110#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59111typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:28112#else
[email protected]614e9fa2008-08-11 22:52:59113typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28114#endif
thestig3e4787d2015-05-19 19:31:52115PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38116
thestig3e4787d2015-05-19 19:31:52117// This file is lazily opened and the handle may be nullptr
118FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38119
thestig3e4787d2015-05-19 19:31:52120// What should be prepended to each message?
121bool g_log_process_id = false;
122bool g_log_thread_id = false;
123bool g_log_timestamp = true;
124bool g_log_tickcount = false;
initial.commitd7cae122008-07-26 21:49:38125
[email protected]81e0a852010-08-17 00:38:12126// Should we pop up fatal debug messages in a dialog?
127bool show_error_dialogs = false;
128
initial.commitd7cae122008-07-26 21:49:38129// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55130// the debug message dialog and process termination. Assert handlers are stored
131// in stack to allow overriding and restoring.
132base::LazyInstance<std::stack<LogAssertHandlerFunction>>::Leaky
133 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
134
[email protected]2b07b8412009-11-25 15:26:34135// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52136LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38137
[email protected]f6abeba2008-08-08 13:27:28138// Helper functions to wrap platform differences.
139
avi9b6f42932015-12-26 22:15:14140int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24141#if defined(OS_WIN)
142 return GetCurrentProcessId();
143#elif defined(OS_POSIX)
144 return getpid();
145#endif
146}
147
avi9b6f42932015-12-26 22:15:14148uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24149#if defined(OS_WIN)
150 return GetTickCount();
151#elif defined(OS_MACOSX)
152 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08153#elif defined(OS_NACL)
154 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
155 // So we have to use clock() for now.
156 return clock();
[email protected]e43eddf12009-12-29 00:32:52157#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07158 struct timespec ts;
159 clock_gettime(CLOCK_MONOTONIC, &ts);
160
avi9b6f42932015-12-26 22:15:14161 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
162 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07163
164 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24165#endif
166}
167
[email protected]614e9fa2008-08-11 22:52:59168void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28169#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59170 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27171#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45172 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28173#else
[email protected]614e9fa2008-08-11 22:52:59174 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28175#endif
176}
initial.commitd7cae122008-07-26 21:49:38177
[email protected]5f95d532010-10-01 17:16:58178PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55179#if defined(OS_WIN)
180 // On Windows we use the same path as the exe.
181 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52182 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58183
scottmgfc5b7072015-01-27 21:46:28184 PathString log_name = module_name;
185 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58186 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28187 log_name.erase(last_backslash + 1);
188 log_name += L"debug.log";
189 return log_name;
[email protected]5b84fe32010-09-14 22:24:55190#elif defined(OS_POSIX)
191 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58192 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55193#endif
194}
195
ananta61762fb2015-09-18 01:00:09196// We don't need locks on Windows for atomically appending to files. The OS
197// provides this functionality.
198#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55199// This class acts as a wrapper for locking the logging files.
200// LoggingLock::Init() should be called from the main thread before any logging
201// is done. Then whenever logging, be sure to have a local LoggingLock
202// instance on the stack. This will ensure that the lock is unlocked upon
203// exiting the frame.
204// LoggingLocks can not be nested.
205class LoggingLock {
206 public:
207 LoggingLock() {
208 LockLogging();
209 }
210
211 ~LoggingLock() {
212 UnlockLogging();
213 }
214
215 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
216 if (initialized)
217 return;
218 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58219
ananta61762fb2015-09-18 01:00:09220 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20221 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09222
[email protected]5b84fe32010-09-14 22:24:55223 initialized = true;
224 }
225
226 private:
227 static void LockLogging() {
228 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09229#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55230 pthread_mutex_lock(&log_mutex);
231#endif
232 } else {
233 // use the lock
234 log_lock->Lock();
235 }
236 }
237
238 static void UnlockLogging() {
239 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09240#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55241 pthread_mutex_unlock(&log_mutex);
242#endif
243 } else {
244 log_lock->Unlock();
245 }
246 }
247
248 // The lock is used if log file locking is false. It helps us avoid problems
249 // with multiple threads writing to the log file at the same time. Use
250 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20251 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55252
253 // When we don't use a lock, we are using a global mutex. We need to do this
254 // because LockFileEx is not thread safe.
ananta61762fb2015-09-18 01:00:09255#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55256 static pthread_mutex_t log_mutex;
257#endif
258
259 static bool initialized;
260 static LogLockingState lock_log_file;
261};
262
263// static
264bool LoggingLock::initialized = false;
265// static
thestig3e4787d2015-05-19 19:31:52266base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55267// static
268LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
269
ananta61762fb2015-09-18 01:00:09270#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55271pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
272#endif
273
ananta61762fb2015-09-18 01:00:09274#endif // OS_WIN
275
thestig3e4787d2015-05-19 19:31:52276// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38277// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52278// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38279bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52280 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38281 return true;
282
thestig3e4787d2015-05-19 19:31:52283 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59284 // Nobody has called InitLogging to specify a debug log file, so here we
285 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52286 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38287 }
288
thestig3e4787d2015-05-19 19:31:52289 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59290#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09291 // The FILE_APPEND_DATA access mask ensures that the file is atomically
292 // appended to across accesses from multiple threads.
293 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
294 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
295 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52296 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
297 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
298 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02299 // We are intentionally not using FilePath or FileUtil here to reduce the
300 // dependencies of the logging implementation. For e.g. FilePath and
301 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
302 // some consumers of base logging like chrome_elf, etc.
303 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32304 // try the current directory
anantaf2651872016-06-16 22:21:02305 wchar_t system_buffer[MAX_PATH];
306 system_buffer[0] = 0;
307 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
308 system_buffer);
309 if (len == 0 || len > arraysize(system_buffer))
ananta61762fb2015-09-18 01:00:09310 return false;
311
anantaf2651872016-06-16 22:21:02312 *g_log_file_name = system_buffer;
313 // Append a trailing backslash if needed.
314 if (g_log_file_name->back() != L'\\')
315 *g_log_file_name += L"\\";
316 *g_log_file_name += L"debug.log";
ananta61762fb2015-09-18 01:00:09317
318 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52319 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
320 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
321 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
322 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32323 return false;
324 }
initial.commitd7cae122008-07-26 21:49:38325 }
[email protected]78c6dd62009-06-08 23:29:11326#elif defined(OS_POSIX)
thestig3e4787d2015-05-19 19:31:52327 g_log_file = fopen(g_log_file_name->c_str(), "a");
328 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11329 return false;
[email protected]f6abeba2008-08-08 13:27:28330#endif
[email protected]1d8c2702008-08-19 23:39:32331 }
332
initial.commitd7cae122008-07-26 21:49:38333 return true;
334}
335
[email protected]17dcf752013-07-15 21:47:09336void CloseFile(FileHandle log) {
337#if defined(OS_WIN)
338 CloseHandle(log);
339#else
340 fclose(log);
341#endif
342}
343
344void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52345 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09346 return;
347
thestig3e4787d2015-05-19 19:31:52348 CloseFile(g_log_file);
349 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09350}
351
[email protected]064aa162011-12-03 00:30:08352} // namespace
353
Wez289477f2017-08-24 20:51:30354#if DCHECK_IS_ON() && defined(SYZYASAN)
355// In DCHECK-enabled SyzyASAN builds, allow the meaning of LOG_DCHECK to be
356// determined at run-time. We default it to INFO, to avoid it triggering
357// crashes before the run-time has explicitly chosen the behaviour.
358BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
359#endif
360
scottmg3c957a52016-12-10 20:57:59361// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
362// an object of the correct type on the LHS of the unused part of the ternary
363// operator.
364std::ostream* g_swallow_stream;
365
[email protected]5e3f7c22013-06-21 21:15:33366LoggingSettings::LoggingSettings()
367 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52368 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33369 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38370 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08371
[email protected]5e3f7c22013-06-21 21:15:33372bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45373#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33374 // Can log only to the system debug log.
375 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45376#endif
pgal.u-szeged421dddb2014-11-25 12:55:02377 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52378 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36379 // vlog switches.
380 if (command_line->HasSwitch(switches::kV) ||
381 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52382 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08383 // by another thread. Don't delete the old VLogInfo, just create a second
384 // one. We keep track of both to avoid memory leak warnings.
385 CHECK(!g_vlog_info_prev);
386 g_vlog_info_prev = g_vlog_info;
387
[email protected]99b7c57f2010-09-29 19:26:36388 g_vlog_info =
389 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49390 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52391 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36392 }
393
thestig3e4787d2015-05-19 19:31:52394 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38395
[email protected]5e3f7c22013-06-21 21:15:33396 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52397 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21398 return true;
initial.commitd7cae122008-07-26 21:49:38399
ananta61762fb2015-09-18 01:00:09400#if !defined(OS_WIN)
[email protected]17dcf752013-07-15 21:47:09401 LoggingLock::Init(settings.lock_log, settings.log_file);
402 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09403#endif
[email protected]17dcf752013-07-15 21:47:09404
405 // Calling InitLogging twice or after some log call has already opened the
406 // default log file will re-initialize to the new options.
407 CloseLogFileUnlocked();
408
thestig3e4787d2015-05-19 19:31:52409 if (!g_log_file_name)
410 g_log_file_name = new PathString();
411 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33412 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52413 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38414
[email protected]c7d5da992010-10-28 00:20:21415 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38416}
417
418void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52419 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38420}
421
422int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52423 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38424}
425
skobesc78c0ad72015-12-07 20:21:23426bool ShouldCreateLogMessage(int severity) {
427 if (severity < g_min_log_level)
428 return false;
429
430 // Return true here unless we know ~LogMessage won't do anything. Note that
431 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
432 // when g_logging_destination is LOG_NONE.
433 return g_logging_destination != LOG_NONE || log_message_handler ||
434 severity >= kAlwaysPrintErrorLevel;
435}
436
[email protected]162ac0f2010-11-04 15:50:49437int GetVlogVerbosity() {
438 return std::max(-1, LOG_INFO - GetMinLogLevel());
439}
440
[email protected]99b7c57f2010-09-29 19:26:36441int GetVlogLevelHelper(const char* file, size_t N) {
442 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52443 // Note: |g_vlog_info| may change on a different thread during startup
444 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08445 VlogInfo* vlog_info = g_vlog_info;
446 return vlog_info ?
447 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49448 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36449}
450
initial.commitd7cae122008-07-26 21:49:38451void SetLogItems(bool enable_process_id, bool enable_thread_id,
452 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52453 g_log_process_id = enable_process_id;
454 g_log_thread_id = enable_thread_id;
455 g_log_timestamp = enable_timestamp;
456 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38457}
458
[email protected]81e0a852010-08-17 00:38:12459void SetShowErrorDialogs(bool enable_dialogs) {
460 show_error_dialogs = enable_dialogs;
461}
462
alex-accc1bde62017-04-19 08:33:55463ScopedLogAssertHandler::ScopedLogAssertHandler(
464 LogAssertHandlerFunction handler) {
465 log_assert_handler_stack.Get().push(std::move(handler));
466}
467
468ScopedLogAssertHandler::~ScopedLogAssertHandler() {
469 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38470}
471
[email protected]2b07b8412009-11-25 15:26:34472void SetLogMessageHandler(LogMessageHandlerFunction handler) {
473 log_message_handler = handler;
474}
475
[email protected]64e5cc02010-11-03 19:20:27476LogMessageHandlerFunction GetLogMessageHandler() {
477 return log_message_handler;
478}
479
[email protected]6d445d32010-09-30 19:10:03480// Explicit instantiations for commonly used comparisons.
481template std::string* MakeCheckOpString<int, int>(
482 const int&, const int&, const char* names);
483template std::string* MakeCheckOpString<unsigned long, unsigned long>(
484 const unsigned long&, const unsigned long&, const char* names);
485template std::string* MakeCheckOpString<unsigned long, unsigned int>(
486 const unsigned long&, const unsigned int&, const char* names);
487template std::string* MakeCheckOpString<unsigned int, unsigned long>(
488 const unsigned int&, const unsigned long&, const char* names);
489template std::string* MakeCheckOpString<std::string, std::string>(
490 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34491
jbroman6bcfec422016-05-26 00:28:46492void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16493 (*os) << "nullptr";
494}
495
[email protected]f2c05492014-06-17 12:04:23496#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22497// Displays a message box to the user with the error message in it.
498// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25499// This is for developers only; we don't use this in circumstances
500// (like release builds) where users could see it, since users don't
501// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22502void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38503 if (str.empty())
504 return;
505
[email protected]81e0a852010-08-17 00:38:12506 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44507 return;
508
[email protected]f6abeba2008-08-08 13:27:28509#if defined(OS_WIN)
brettwe33526852015-10-03 00:46:01510 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
511 MB_OK | MB_ICONHAND | MB_TOPMOST);
[email protected]f6abeba2008-08-08 13:27:28512#else
[email protected]561513f2010-12-16 23:29:25513 // We intentionally don't implement a dialog on other platforms.
514 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52515#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38516}
[email protected]f2c05492014-06-17 12:04:23517#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38518
[email protected]3f85caa2009-04-14 16:52:11519#if defined(OS_WIN)
520LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
521}
522
523LogMessage::SaveLastError::~SaveLastError() {
524 ::SetLastError(last_error_);
525}
526#endif // defined(OS_WIN)
527
[email protected]eae9c062011-01-11 00:50:59528LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
529 : severity_(severity), file_(file), line_(line) {
530 Init(file, line);
531}
532
tnagel4a045d3f2015-07-12 14:19:28533LogMessage::LogMessage(const char* file, int line, const char* condition)
534 : severity_(LOG_FATAL), file_(file), line_(line) {
535 Init(file, line);
536 stream_ << "Check failed: " << condition << ". ";
537}
538
[email protected]9c7132e2011-02-08 07:39:08539LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49540 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38541 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08542 stream_ << "Check failed: " << *result;
543 delete result;
initial.commitd7cae122008-07-26 21:49:38544}
545
[email protected]fb62a532009-02-12 01:19:05546LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08547 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49548 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05549 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08550 stream_ << "Check failed: " << *result;
551 delete result;
[email protected]fb62a532009-02-12 01:19:05552}
553
initial.commitd7cae122008-07-26 21:49:38554LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55555 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08556#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
557 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42558 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
559 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50560 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24561 stream_ << std::endl; // Newline to separate from log message.
562 trace.OutputToStream(&stream_);
563 }
[email protected]1d8c2702008-08-19 23:39:32564#endif
[email protected]d1ccc35a2010-03-24 05:03:24565 stream_ << std::endl;
566 std::string str_newline(stream_.str());
567
[email protected]2b07b8412009-11-25 15:26:34568 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33569 if (log_message_handler &&
570 log_message_handler(severity_, file_, line_,
571 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49572 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34573 return;
[email protected]162ac0f2010-11-04 15:50:49574 }
initial.commitd7cae122008-07-26 21:49:38575
thestig3e4787d2015-05-19 19:31:52576 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28577#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38578 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42579#elif defined(OS_MACOSX)
580 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
581 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log). If
582 // there's something weird about stderr, assume that log messages are going
583 // nowhere and log via ASL too. Messages logged via ASL show up in
584 // Console.app.
585 //
586 // Programs started by launchd, as UI applications normally are, have had
587 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
588 // a pipe to launchd, which logged what it received (see log_redirect_fd in
589 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
590 //
591 // Another alternative would be to determine whether stderr is a pipe to
592 // launchd and avoid logging via ASL only in that case. See 10.7.5
593 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
594 // both stderr and ASL even in tests, where it's undesirable to log to the
595 // system log at all.
596 //
597 // Note that the ASL client by default discards messages whose levels are
598 // below ASL_LEVEL_NOTICE. It's possible to change that with
599 // asl_set_filter(), but this is pointless because syslogd normally applies
600 // the same filter.
601 const bool log_via_asl = []() {
602 struct stat stderr_stat;
603 if (fstat(fileno(stderr), &stderr_stat) == -1) {
604 return true;
605 }
606 if (!S_ISCHR(stderr_stat.st_mode)) {
607 return false;
608 }
609
610 struct stat dev_null_stat;
611 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
612 return true;
613 }
614
615 return !S_ISCHR(dev_null_stat.st_mode) ||
616 stderr_stat.st_rdev == dev_null_stat.st_rdev;
617 }();
618
619 if (log_via_asl) {
620 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
621 // CF-1153.18/CFUtilities.c __CFLogCString().
622 //
623 // The ASL facility is set to the main bundle ID if available. Otherwise,
624 // "com.apple.console" is used.
625 CFBundleRef main_bundle = CFBundleGetMainBundle();
626 CFStringRef main_bundle_id_cf =
627 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
628 std::string asl_facility =
629 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
630 : std::string("com.apple.console");
631
632 class ASLClient {
633 public:
634 explicit ASLClient(const std::string& asl_facility)
635 : client_(asl_open(nullptr,
636 asl_facility.c_str(),
637 ASL_OPT_NO_DELAY)) {}
638 ~ASLClient() { asl_close(client_); }
639
640 aslclient get() const { return client_; }
641
642 private:
643 aslclient client_;
644 DISALLOW_COPY_AND_ASSIGN(ASLClient);
645 } asl_client(asl_facility);
646
647 class ASLMessage {
648 public:
649 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
650 ~ASLMessage() { asl_free(message_); }
651
652 aslmsg get() const { return message_; }
653
654 private:
655 aslmsg message_;
656 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
657 } asl_message;
658
659 // By default, messages are only readable by the admin group. Explicitly
660 // make them readable by the user generating the messages.
661 char euid_string[12];
662 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
663 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
664
665 // Map Chrome log severities to ASL log levels.
666 const char* const asl_level_string = [](LogSeverity severity) {
667 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
668 // non-obvious two-step macro trick achieves what's needed.
669 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
670#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
671#define ASL_LEVEL_STR_X(level) #level
672 switch (severity) {
673 case LOG_INFO:
674 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
675 case LOG_WARNING:
676 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
677 case LOG_ERROR:
678 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
679 case LOG_FATAL:
680 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
681 default:
682 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
683 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
684 }
685#undef ASL_LEVEL_STR
686#undef ASL_LEVEL_STR_X
687 }(severity_);
688 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
689
690 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
691
692 asl_send(asl_client.get(), asl_message.get());
693 }
[email protected]3132e35c2011-07-07 20:46:50694#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25695 android_LogPriority priority =
696 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50697 switch (severity_) {
698 case LOG_INFO:
699 priority = ANDROID_LOG_INFO;
700 break;
701 case LOG_WARNING:
702 priority = ANDROID_LOG_WARN;
703 break;
704 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50705 priority = ANDROID_LOG_ERROR;
706 break;
707 case LOG_FATAL:
708 priority = ANDROID_LOG_FATAL;
709 break;
710 }
711 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18712#endif
[email protected]51105382014-03-14 17:02:15713 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06714 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31715 } else if (severity_ >= kAlwaysPrintErrorLevel) {
716 // When we're only outputting to a log file, above a certain log level, we
717 // should still output to stderr so that we can better detect and diagnose
718 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15719 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02720 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28721 }
[email protected]52a261f2009-03-03 15:01:12722
initial.commitd7cae122008-07-26 21:49:38723 // write to log file
thestig3e4787d2015-05-19 19:31:52724 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09725 // We can have multiple threads and/or processes, so try to prevent them
726 // from clobbering each other's writes.
727 // If the client app did not call InitLogging, and the lock has not
728 // been created do it now. We do this on demand, but if two threads try
729 // to do this at the same time, there will be a race condition to create
730 // the lock. This is why InitLogging should be called from the main
731 // thread at the beginning of execution.
ananta61762fb2015-09-18 01:00:09732#if !defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52733 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55734 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09735#endif
[email protected]5b84fe32010-09-14 22:24:55736 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28737#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55738 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52739 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55740 static_cast<const void*>(str_newline.c_str()),
741 static_cast<DWORD>(str_newline.length()),
742 &num_written,
thestig3e4787d2015-05-19 19:31:52743 nullptr);
[email protected]cba21962010-08-31 22:35:55744#else
[email protected]51105382014-03-14 17:02:15745 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52746 str_newline.data(), str_newline.size(), 1, g_log_file));
747 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55748#endif
initial.commitd7cae122008-07-26 21:49:38749 }
750 }
751
752 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40753 // Write the log message to the global activity tracker, if running.
754 base::debug::GlobalActivityTracker* tracker =
755 base::debug::GlobalActivityTracker::Get();
756 if (tracker)
757 tracker->RecordLogMessage(str_newline);
758
[email protected]eb4c4d032012-04-03 18:45:05759 // Ensure the first characters of the string are on the stack so they
760 // are contained in minidumps for diagnostic purposes.
761 char str_stack[1024];
762 str_newline.copy(str_stack, arraysize(str_stack));
763 base::debug::Alias(str_stack);
764
alex-accc1bde62017-04-19 08:33:55765 if (!(log_assert_handler_stack == nullptr) &&
766 !log_assert_handler_stack.Get().empty()) {
767 LogAssertHandlerFunction log_assert_handler =
768 log_assert_handler_stack.Get().top();
769
770 if (log_assert_handler) {
771 log_assert_handler.Run(
772 file_, line_,
773 base::StringPiece(str_newline.c_str() + message_start_,
774 stack_start - message_start_),
775 base::StringPiece(str_newline.c_str() + stack_start));
776 }
[email protected]1ffe08c12008-08-13 11:15:11777 } else {
[email protected]82d89ab2014-02-28 18:25:34778 // Don't use the string with the newline, get a fresh version to send to
779 // the debug message process. We also don't display assertions to the
780 // user in release mode. The enduser can't do anything with this
781 // information, and displaying message boxes when the application is
782 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50783#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42784 if (!base::debug::BeingDebugged()) {
785 // Displaying a dialog is unnecessary when debugging and can complicate
786 // debugging.
787 DisplayDebugMessageInDialog(stream_.str());
788 }
[email protected]4d5901272008-11-06 00:33:50789#endif
[email protected]82d89ab2014-02-28 18:25:34790 // Crash the process to generate a dump.
791 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38792 }
793 }
794}
795
[email protected]eae9c062011-01-11 00:50:59796// writes the common header info to the stream
797void LogMessage::Init(const char* file, int line) {
798 base::StringPiece filename(file);
799 size_t last_slash_pos = filename.find_last_of("\\/");
800 if (last_slash_pos != base::StringPiece::npos)
801 filename.remove_prefix(last_slash_pos + 1);
802
803 // TODO(darin): It might be nice if the columns were fixed width.
804
805 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52806 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59807 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52808 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09809 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52810 if (g_log_timestamp) {
djkurtz543a3be2016-11-30 14:17:34811#if defined(OS_POSIX)
812 timeval tv;
813 gettimeofday(&tv, nullptr);
814 time_t t = tv.tv_sec;
815 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59816 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59817 struct tm* tm_time = &local_time;
818 stream_ << std::setfill('0')
819 << std::setw(2) << 1 + tm_time->tm_mon
820 << std::setw(2) << tm_time->tm_mday
821 << '/'
822 << std::setw(2) << tm_time->tm_hour
823 << std::setw(2) << tm_time->tm_min
824 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34825 << '.'
826 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59827 << ':';
djkurtz543a3be2016-11-30 14:17:34828#elif defined(OS_WIN)
829 SYSTEMTIME local_time;
830 GetLocalTime(&local_time);
831 stream_ << std::setfill('0')
832 << std::setw(2) << local_time.wMonth
833 << std::setw(2) << local_time.wDay
834 << '/'
835 << std::setw(2) << local_time.wHour
836 << std::setw(2) << local_time.wMinute
837 << std::setw(2) << local_time.wSecond
838 << '.'
839 << std::setw(3) << local_time.wMilliseconds
840 << ':';
841#endif
[email protected]eae9c062011-01-11 00:50:59842 }
thestig3e4787d2015-05-19 19:31:52843 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59844 stream_ << TickCount() << ':';
845 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19846 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59847 else
848 stream_ << "VERBOSE" << -severity_;
849
850 stream_ << ":" << filename << "(" << line << ")] ";
851
pkasting9cf9b94a2014-10-01 22:18:43852 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59853}
854
[email protected]d8617a62009-10-09 23:52:20855#if defined(OS_WIN)
856// This has already been defined in the header, but defining it again as DWORD
857// ensures that the type used in the header is equivalent to DWORD. If not,
858// the redefinition is a compile error.
859typedef DWORD SystemErrorCode;
860#endif
861
862SystemErrorCode GetLastSystemErrorCode() {
863#if defined(OS_WIN)
864 return ::GetLastError();
865#elif defined(OS_POSIX)
866 return errno;
867#else
868#error Not implemented
869#endif
870}
871
872#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01873BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27874 const int kErrorMessageBufferSize = 256;
875 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01876 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52877 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
878 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01879 if (len) {
880 // Messages returned by system end with line breaks.
881 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:45882 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:01883 }
Bruce Dawson19175842017-08-02 17:00:45884 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:01885 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20886}
[email protected]c914d8a2014-04-23 01:11:01887#elif defined(OS_POSIX)
888BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Robert Sesekd2f495f2017-07-25 22:03:14889 return base::safe_strerror(error_code) +
890 base::StringPrintf(" (%d)", error_code);
[email protected]c914d8a2014-04-23 01:11:01891}
892#else
893#error Not implemented
thestig3e4787d2015-05-19 19:31:52894#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20895
[email protected]c914d8a2014-04-23 01:11:01896
897#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20898Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
899 int line,
900 LogSeverity severity,
901 SystemErrorCode err)
902 : err_(err),
[email protected]d8617a62009-10-09 23:52:20903 log_message_(file, line, severity) {
904}
905
906Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01907 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06908 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
909 // field) and use Alias in hopes that it makes it into crash dumps.
910 DWORD last_error = err_;
911 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20912}
913#elif defined(OS_POSIX)
914ErrnoLogMessage::ErrnoLogMessage(const char* file,
915 int line,
916 LogSeverity severity,
917 SystemErrorCode err)
918 : err_(err),
919 log_message_(file, line, severity) {
920}
921
922ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01923 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:14924 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
925 // field) and use Alias in hopes that it makes it into crash dumps.
926 int last_error = err_;
927 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20928}
thestig3e4787d2015-05-19 19:31:52929#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20930
initial.commitd7cae122008-07-26 21:49:38931void CloseLogFile() {
ananta61762fb2015-09-18 01:00:09932#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55933 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09934#endif
[email protected]17dcf752013-07-15 21:47:09935 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38936}
937
[email protected]e36ddc82009-12-08 04:22:50938void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:49939 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:50940 size_t bytes_written = 0;
941 const size_t message_len = strlen(message);
942 int rv;
943 while (bytes_written < message_len) {
944 rv = HANDLE_EINTR(
945 write(STDERR_FILENO, message + bytes_written,
946 message_len - bytes_written));
947 if (rv < 0) {
948 // Give up, nothing we can do now.
949 break;
950 }
951 bytes_written += rv;
952 }
953
954 if (message_len > 0 && message[message_len - 1] != '\n') {
955 do {
956 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
957 if (rv < 0) {
958 // Give up, nothing we can do now.
959 break;
960 }
961 } while (rv != 1);
962 }
963 }
964
965 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50966 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50967}
968
[email protected]34a907732012-01-20 06:33:27969// This was defined at the beginning of this file.
970#undef write
971
[email protected]f01b88a2013-02-27 22:04:00972#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09973bool IsLoggingToFileEnabled() {
974 return g_logging_destination & LOG_TO_FILE;
975}
976
[email protected]f01b88a2013-02-27 22:04:00977std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:52978 if (g_log_file_name)
979 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:00980 return std::wstring();
981}
982#endif
983
tnagel80388e682015-05-26 13:27:56984BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:14985 LogMessage(file, line, LOG_ERROR).stream()
986 << "NOTREACHED() hit.";
987}
988
[email protected]96fd0032009-04-24 00:13:08989} // namespace logging
initial.commitd7cae122008-07-26 21:49:38990
[email protected]81411c62014-07-08 23:03:06991std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:49992 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:38993}