blob: 11ed652eaa6cb32ab4c34e4e64fea6b48989cbcb [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
scottmg3c957a52016-12-10 20:57:59354// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
355// an object of the correct type on the LHS of the unused part of the ternary
356// operator.
357std::ostream* g_swallow_stream;
358
[email protected]5e3f7c22013-06-21 21:15:33359LoggingSettings::LoggingSettings()
360 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52361 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33362 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38363 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08364
[email protected]5e3f7c22013-06-21 21:15:33365bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45366#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33367 // Can log only to the system debug log.
368 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45369#endif
pgal.u-szeged421dddb2014-11-25 12:55:02370 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52371 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36372 // vlog switches.
373 if (command_line->HasSwitch(switches::kV) ||
374 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52375 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08376 // by another thread. Don't delete the old VLogInfo, just create a second
377 // one. We keep track of both to avoid memory leak warnings.
378 CHECK(!g_vlog_info_prev);
379 g_vlog_info_prev = g_vlog_info;
380
[email protected]99b7c57f2010-09-29 19:26:36381 g_vlog_info =
382 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49383 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52384 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36385 }
386
thestig3e4787d2015-05-19 19:31:52387 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38388
[email protected]5e3f7c22013-06-21 21:15:33389 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52390 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21391 return true;
initial.commitd7cae122008-07-26 21:49:38392
ananta61762fb2015-09-18 01:00:09393#if !defined(OS_WIN)
[email protected]17dcf752013-07-15 21:47:09394 LoggingLock::Init(settings.lock_log, settings.log_file);
395 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09396#endif
[email protected]17dcf752013-07-15 21:47:09397
398 // Calling InitLogging twice or after some log call has already opened the
399 // default log file will re-initialize to the new options.
400 CloseLogFileUnlocked();
401
thestig3e4787d2015-05-19 19:31:52402 if (!g_log_file_name)
403 g_log_file_name = new PathString();
404 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33405 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52406 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38407
[email protected]c7d5da992010-10-28 00:20:21408 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38409}
410
411void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52412 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38413}
414
415int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52416 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38417}
418
skobesc78c0ad72015-12-07 20:21:23419bool ShouldCreateLogMessage(int severity) {
420 if (severity < g_min_log_level)
421 return false;
422
423 // Return true here unless we know ~LogMessage won't do anything. Note that
424 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
425 // when g_logging_destination is LOG_NONE.
426 return g_logging_destination != LOG_NONE || log_message_handler ||
427 severity >= kAlwaysPrintErrorLevel;
428}
429
[email protected]162ac0f2010-11-04 15:50:49430int GetVlogVerbosity() {
431 return std::max(-1, LOG_INFO - GetMinLogLevel());
432}
433
[email protected]99b7c57f2010-09-29 19:26:36434int GetVlogLevelHelper(const char* file, size_t N) {
435 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52436 // Note: |g_vlog_info| may change on a different thread during startup
437 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08438 VlogInfo* vlog_info = g_vlog_info;
439 return vlog_info ?
440 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49441 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36442}
443
initial.commitd7cae122008-07-26 21:49:38444void SetLogItems(bool enable_process_id, bool enable_thread_id,
445 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52446 g_log_process_id = enable_process_id;
447 g_log_thread_id = enable_thread_id;
448 g_log_timestamp = enable_timestamp;
449 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38450}
451
[email protected]81e0a852010-08-17 00:38:12452void SetShowErrorDialogs(bool enable_dialogs) {
453 show_error_dialogs = enable_dialogs;
454}
455
alex-accc1bde62017-04-19 08:33:55456ScopedLogAssertHandler::ScopedLogAssertHandler(
457 LogAssertHandlerFunction handler) {
458 log_assert_handler_stack.Get().push(std::move(handler));
459}
460
461ScopedLogAssertHandler::~ScopedLogAssertHandler() {
462 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38463}
464
[email protected]2b07b8412009-11-25 15:26:34465void SetLogMessageHandler(LogMessageHandlerFunction handler) {
466 log_message_handler = handler;
467}
468
[email protected]64e5cc02010-11-03 19:20:27469LogMessageHandlerFunction GetLogMessageHandler() {
470 return log_message_handler;
471}
472
[email protected]6d445d32010-09-30 19:10:03473// Explicit instantiations for commonly used comparisons.
474template std::string* MakeCheckOpString<int, int>(
475 const int&, const int&, const char* names);
476template std::string* MakeCheckOpString<unsigned long, unsigned long>(
477 const unsigned long&, const unsigned long&, const char* names);
478template std::string* MakeCheckOpString<unsigned long, unsigned int>(
479 const unsigned long&, const unsigned int&, const char* names);
480template std::string* MakeCheckOpString<unsigned int, unsigned long>(
481 const unsigned int&, const unsigned long&, const char* names);
482template std::string* MakeCheckOpString<std::string, std::string>(
483 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34484
jbroman6bcfec422016-05-26 00:28:46485void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16486 (*os) << "nullptr";
487}
488
[email protected]f2c05492014-06-17 12:04:23489#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22490// Displays a message box to the user with the error message in it.
491// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25492// This is for developers only; we don't use this in circumstances
493// (like release builds) where users could see it, since users don't
494// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22495void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38496 if (str.empty())
497 return;
498
[email protected]81e0a852010-08-17 00:38:12499 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44500 return;
501
[email protected]f6abeba2008-08-08 13:27:28502#if defined(OS_WIN)
brettwe33526852015-10-03 00:46:01503 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
504 MB_OK | MB_ICONHAND | MB_TOPMOST);
[email protected]f6abeba2008-08-08 13:27:28505#else
[email protected]561513f2010-12-16 23:29:25506 // We intentionally don't implement a dialog on other platforms.
507 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52508#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38509}
[email protected]f2c05492014-06-17 12:04:23510#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38511
[email protected]3f85caa2009-04-14 16:52:11512#if defined(OS_WIN)
513LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
514}
515
516LogMessage::SaveLastError::~SaveLastError() {
517 ::SetLastError(last_error_);
518}
519#endif // defined(OS_WIN)
520
[email protected]eae9c062011-01-11 00:50:59521LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
522 : severity_(severity), file_(file), line_(line) {
523 Init(file, line);
524}
525
tnagel4a045d3f2015-07-12 14:19:28526LogMessage::LogMessage(const char* file, int line, const char* condition)
527 : severity_(LOG_FATAL), file_(file), line_(line) {
528 Init(file, line);
529 stream_ << "Check failed: " << condition << ". ";
530}
531
[email protected]9c7132e2011-02-08 07:39:08532LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49533 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38534 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08535 stream_ << "Check failed: " << *result;
536 delete result;
initial.commitd7cae122008-07-26 21:49:38537}
538
[email protected]fb62a532009-02-12 01:19:05539LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08540 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49541 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05542 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08543 stream_ << "Check failed: " << *result;
544 delete result;
[email protected]fb62a532009-02-12 01:19:05545}
546
initial.commitd7cae122008-07-26 21:49:38547LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55548 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08549#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
550 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42551 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
552 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50553 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24554 stream_ << std::endl; // Newline to separate from log message.
555 trace.OutputToStream(&stream_);
556 }
[email protected]1d8c2702008-08-19 23:39:32557#endif
[email protected]d1ccc35a2010-03-24 05:03:24558 stream_ << std::endl;
559 std::string str_newline(stream_.str());
560
[email protected]2b07b8412009-11-25 15:26:34561 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33562 if (log_message_handler &&
563 log_message_handler(severity_, file_, line_,
564 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49565 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34566 return;
[email protected]162ac0f2010-11-04 15:50:49567 }
initial.commitd7cae122008-07-26 21:49:38568
thestig3e4787d2015-05-19 19:31:52569 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28570#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38571 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42572#elif defined(OS_MACOSX)
573 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
574 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log). If
575 // there's something weird about stderr, assume that log messages are going
576 // nowhere and log via ASL too. Messages logged via ASL show up in
577 // Console.app.
578 //
579 // Programs started by launchd, as UI applications normally are, have had
580 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
581 // a pipe to launchd, which logged what it received (see log_redirect_fd in
582 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
583 //
584 // Another alternative would be to determine whether stderr is a pipe to
585 // launchd and avoid logging via ASL only in that case. See 10.7.5
586 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
587 // both stderr and ASL even in tests, where it's undesirable to log to the
588 // system log at all.
589 //
590 // Note that the ASL client by default discards messages whose levels are
591 // below ASL_LEVEL_NOTICE. It's possible to change that with
592 // asl_set_filter(), but this is pointless because syslogd normally applies
593 // the same filter.
594 const bool log_via_asl = []() {
595 struct stat stderr_stat;
596 if (fstat(fileno(stderr), &stderr_stat) == -1) {
597 return true;
598 }
599 if (!S_ISCHR(stderr_stat.st_mode)) {
600 return false;
601 }
602
603 struct stat dev_null_stat;
604 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
605 return true;
606 }
607
608 return !S_ISCHR(dev_null_stat.st_mode) ||
609 stderr_stat.st_rdev == dev_null_stat.st_rdev;
610 }();
611
612 if (log_via_asl) {
613 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
614 // CF-1153.18/CFUtilities.c __CFLogCString().
615 //
616 // The ASL facility is set to the main bundle ID if available. Otherwise,
617 // "com.apple.console" is used.
618 CFBundleRef main_bundle = CFBundleGetMainBundle();
619 CFStringRef main_bundle_id_cf =
620 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
621 std::string asl_facility =
622 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
623 : std::string("com.apple.console");
624
625 class ASLClient {
626 public:
627 explicit ASLClient(const std::string& asl_facility)
628 : client_(asl_open(nullptr,
629 asl_facility.c_str(),
630 ASL_OPT_NO_DELAY)) {}
631 ~ASLClient() { asl_close(client_); }
632
633 aslclient get() const { return client_; }
634
635 private:
636 aslclient client_;
637 DISALLOW_COPY_AND_ASSIGN(ASLClient);
638 } asl_client(asl_facility);
639
640 class ASLMessage {
641 public:
642 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
643 ~ASLMessage() { asl_free(message_); }
644
645 aslmsg get() const { return message_; }
646
647 private:
648 aslmsg message_;
649 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
650 } asl_message;
651
652 // By default, messages are only readable by the admin group. Explicitly
653 // make them readable by the user generating the messages.
654 char euid_string[12];
655 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
656 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
657
658 // Map Chrome log severities to ASL log levels.
659 const char* const asl_level_string = [](LogSeverity severity) {
660 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
661 // non-obvious two-step macro trick achieves what's needed.
662 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
663#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
664#define ASL_LEVEL_STR_X(level) #level
665 switch (severity) {
666 case LOG_INFO:
667 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
668 case LOG_WARNING:
669 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
670 case LOG_ERROR:
671 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
672 case LOG_FATAL:
673 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
674 default:
675 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
676 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
677 }
678#undef ASL_LEVEL_STR
679#undef ASL_LEVEL_STR_X
680 }(severity_);
681 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
682
683 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
684
685 asl_send(asl_client.get(), asl_message.get());
686 }
[email protected]3132e35c2011-07-07 20:46:50687#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25688 android_LogPriority priority =
689 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50690 switch (severity_) {
691 case LOG_INFO:
692 priority = ANDROID_LOG_INFO;
693 break;
694 case LOG_WARNING:
695 priority = ANDROID_LOG_WARN;
696 break;
697 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50698 priority = ANDROID_LOG_ERROR;
699 break;
700 case LOG_FATAL:
701 priority = ANDROID_LOG_FATAL;
702 break;
703 }
704 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18705#endif
[email protected]51105382014-03-14 17:02:15706 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06707 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31708 } else if (severity_ >= kAlwaysPrintErrorLevel) {
709 // When we're only outputting to a log file, above a certain log level, we
710 // should still output to stderr so that we can better detect and diagnose
711 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15712 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02713 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28714 }
[email protected]52a261f2009-03-03 15:01:12715
initial.commitd7cae122008-07-26 21:49:38716 // write to log file
thestig3e4787d2015-05-19 19:31:52717 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09718 // We can have multiple threads and/or processes, so try to prevent them
719 // from clobbering each other's writes.
720 // If the client app did not call InitLogging, and the lock has not
721 // been created do it now. We do this on demand, but if two threads try
722 // to do this at the same time, there will be a race condition to create
723 // the lock. This is why InitLogging should be called from the main
724 // thread at the beginning of execution.
ananta61762fb2015-09-18 01:00:09725#if !defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52726 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55727 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09728#endif
[email protected]5b84fe32010-09-14 22:24:55729 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28730#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55731 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52732 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55733 static_cast<const void*>(str_newline.c_str()),
734 static_cast<DWORD>(str_newline.length()),
735 &num_written,
thestig3e4787d2015-05-19 19:31:52736 nullptr);
[email protected]cba21962010-08-31 22:35:55737#else
[email protected]51105382014-03-14 17:02:15738 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52739 str_newline.data(), str_newline.size(), 1, g_log_file));
740 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55741#endif
initial.commitd7cae122008-07-26 21:49:38742 }
743 }
744
745 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40746 // Write the log message to the global activity tracker, if running.
747 base::debug::GlobalActivityTracker* tracker =
748 base::debug::GlobalActivityTracker::Get();
749 if (tracker)
750 tracker->RecordLogMessage(str_newline);
751
[email protected]eb4c4d032012-04-03 18:45:05752 // Ensure the first characters of the string are on the stack so they
753 // are contained in minidumps for diagnostic purposes.
754 char str_stack[1024];
755 str_newline.copy(str_stack, arraysize(str_stack));
756 base::debug::Alias(str_stack);
757
alex-accc1bde62017-04-19 08:33:55758 if (!(log_assert_handler_stack == nullptr) &&
759 !log_assert_handler_stack.Get().empty()) {
760 LogAssertHandlerFunction log_assert_handler =
761 log_assert_handler_stack.Get().top();
762
763 if (log_assert_handler) {
764 log_assert_handler.Run(
765 file_, line_,
766 base::StringPiece(str_newline.c_str() + message_start_,
767 stack_start - message_start_),
768 base::StringPiece(str_newline.c_str() + stack_start));
769 }
[email protected]1ffe08c12008-08-13 11:15:11770 } else {
[email protected]82d89ab2014-02-28 18:25:34771 // Don't use the string with the newline, get a fresh version to send to
772 // the debug message process. We also don't display assertions to the
773 // user in release mode. The enduser can't do anything with this
774 // information, and displaying message boxes when the application is
775 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50776#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42777 if (!base::debug::BeingDebugged()) {
778 // Displaying a dialog is unnecessary when debugging and can complicate
779 // debugging.
780 DisplayDebugMessageInDialog(stream_.str());
781 }
[email protected]4d5901272008-11-06 00:33:50782#endif
[email protected]82d89ab2014-02-28 18:25:34783 // Crash the process to generate a dump.
784 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38785 }
786 }
787}
788
[email protected]eae9c062011-01-11 00:50:59789// writes the common header info to the stream
790void LogMessage::Init(const char* file, int line) {
791 base::StringPiece filename(file);
792 size_t last_slash_pos = filename.find_last_of("\\/");
793 if (last_slash_pos != base::StringPiece::npos)
794 filename.remove_prefix(last_slash_pos + 1);
795
796 // TODO(darin): It might be nice if the columns were fixed width.
797
798 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52799 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59800 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52801 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09802 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52803 if (g_log_timestamp) {
djkurtz543a3be2016-11-30 14:17:34804#if defined(OS_POSIX)
805 timeval tv;
806 gettimeofday(&tv, nullptr);
807 time_t t = tv.tv_sec;
808 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59809 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59810 struct tm* tm_time = &local_time;
811 stream_ << std::setfill('0')
812 << std::setw(2) << 1 + tm_time->tm_mon
813 << std::setw(2) << tm_time->tm_mday
814 << '/'
815 << std::setw(2) << tm_time->tm_hour
816 << std::setw(2) << tm_time->tm_min
817 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34818 << '.'
819 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59820 << ':';
djkurtz543a3be2016-11-30 14:17:34821#elif defined(OS_WIN)
822 SYSTEMTIME local_time;
823 GetLocalTime(&local_time);
824 stream_ << std::setfill('0')
825 << std::setw(2) << local_time.wMonth
826 << std::setw(2) << local_time.wDay
827 << '/'
828 << std::setw(2) << local_time.wHour
829 << std::setw(2) << local_time.wMinute
830 << std::setw(2) << local_time.wSecond
831 << '.'
832 << std::setw(3) << local_time.wMilliseconds
833 << ':';
834#endif
[email protected]eae9c062011-01-11 00:50:59835 }
thestig3e4787d2015-05-19 19:31:52836 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59837 stream_ << TickCount() << ':';
838 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19839 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59840 else
841 stream_ << "VERBOSE" << -severity_;
842
843 stream_ << ":" << filename << "(" << line << ")] ";
844
pkasting9cf9b94a2014-10-01 22:18:43845 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59846}
847
[email protected]d8617a62009-10-09 23:52:20848#if defined(OS_WIN)
849// This has already been defined in the header, but defining it again as DWORD
850// ensures that the type used in the header is equivalent to DWORD. If not,
851// the redefinition is a compile error.
852typedef DWORD SystemErrorCode;
853#endif
854
855SystemErrorCode GetLastSystemErrorCode() {
856#if defined(OS_WIN)
857 return ::GetLastError();
858#elif defined(OS_POSIX)
859 return errno;
860#else
861#error Not implemented
862#endif
863}
864
865#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01866BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27867 const int kErrorMessageBufferSize = 256;
868 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01869 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52870 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
871 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01872 if (len) {
873 // Messages returned by system end with line breaks.
874 return base::CollapseWhitespaceASCII(msgbuf, true) +
875 base::StringPrintf(" (0x%X)", error_code);
876 }
877 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
878 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20879}
[email protected]c914d8a2014-04-23 01:11:01880#elif defined(OS_POSIX)
881BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
brettw6ee6fd62015-06-09 18:05:24882 return base::safe_strerror(error_code);
[email protected]c914d8a2014-04-23 01:11:01883}
884#else
885#error Not implemented
thestig3e4787d2015-05-19 19:31:52886#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20887
[email protected]c914d8a2014-04-23 01:11:01888
889#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20890Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
891 int line,
892 LogSeverity severity,
893 SystemErrorCode err)
894 : err_(err),
[email protected]d8617a62009-10-09 23:52:20895 log_message_(file, line, severity) {
896}
897
898Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01899 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06900 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
901 // field) and use Alias in hopes that it makes it into crash dumps.
902 DWORD last_error = err_;
903 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20904}
905#elif defined(OS_POSIX)
906ErrnoLogMessage::ErrnoLogMessage(const char* file,
907 int line,
908 LogSeverity severity,
909 SystemErrorCode err)
910 : err_(err),
911 log_message_(file, line, severity) {
912}
913
914ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01915 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]d8617a62009-10-09 23:52:20916}
thestig3e4787d2015-05-19 19:31:52917#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20918
initial.commitd7cae122008-07-26 21:49:38919void CloseLogFile() {
ananta61762fb2015-09-18 01:00:09920#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55921 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09922#endif
[email protected]17dcf752013-07-15 21:47:09923 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38924}
925
[email protected]e36ddc82009-12-08 04:22:50926void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:49927 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:50928 size_t bytes_written = 0;
929 const size_t message_len = strlen(message);
930 int rv;
931 while (bytes_written < message_len) {
932 rv = HANDLE_EINTR(
933 write(STDERR_FILENO, message + bytes_written,
934 message_len - bytes_written));
935 if (rv < 0) {
936 // Give up, nothing we can do now.
937 break;
938 }
939 bytes_written += rv;
940 }
941
942 if (message_len > 0 && message[message_len - 1] != '\n') {
943 do {
944 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
945 if (rv < 0) {
946 // Give up, nothing we can do now.
947 break;
948 }
949 } while (rv != 1);
950 }
951 }
952
953 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50954 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50955}
956
[email protected]34a907732012-01-20 06:33:27957// This was defined at the beginning of this file.
958#undef write
959
[email protected]f01b88a2013-02-27 22:04:00960#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09961bool IsLoggingToFileEnabled() {
962 return g_logging_destination & LOG_TO_FILE;
963}
964
[email protected]f01b88a2013-02-27 22:04:00965std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:52966 if (g_log_file_name)
967 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:00968 return std::wstring();
969}
970#endif
971
tnagel80388e682015-05-26 13:27:56972BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:14973 LogMessage(file, line, LOG_ERROR).stream()
974 << "NOTREACHED() hit.";
975}
976
[email protected]96fd0032009-04-24 00:13:08977} // namespace logging
initial.commitd7cae122008-07-26 21:49:38978
[email protected]81411c62014-07-08 23:03:06979std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:49980 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:38981}