1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_LOGGING_H_
6#define BASE_LOGGING_H_
7
8#include <stddef.h>
9
10#include <cassert>
11#include <cstring>
12#include <sstream>
13#include <string>
14#include <type_traits>
15#include <utility>
16
17#include "base/base_export.h"
18#include "base/callback_forward.h"
19#include "base/compiler_specific.h"
20#include "base/debug/debugger.h"
21#include "base/macros.h"
22#include "base/scoped_clear_last_error.h"
23#include "base/strings/string_piece_forward.h"
24#include "base/template_util.h"
25#include "build/build_config.h"
26
27//
28// Optional message capabilities
29// -----------------------------
30// Assertion failed messages and fatal errors are displayed in a dialog box
31// before the application exits. However, running this UI creates a message
32// loop, which causes application messages to be processed and potentially
33// dispatched to existing application windows. Since the application is in a
34// bad state when this assertion dialog is displayed, these messages may not
35// get processed and hang the dialog, or the application might go crazy.
36//
37// Therefore, it can be beneficial to display the error dialog in a separate
38// process from the main application. When the logging system needs to display
39// a fatal error dialog box, it will look for a program called
40// "DebugMessage.exe" in the same directory as the application executable. It
41// will run this application with the message as the command line, and will
42// not include the name of the application as is traditional for easier
43// parsing.
44//
45// The code for DebugMessage.exe is only one line. In WinMain, do:
46// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
47//
48// If DebugMessage.exe is not found, the logging code will use a normal
49// MessageBox, potentially causing the problems discussed above.
50
51// Instructions
52// ------------
53//
54// Make a bunch of macros for logging. The way to log things is to stream
55// things to LOG(<a particular severity level>). E.g.,
56//
57// LOG(INFO) << "Found " << num_cookies << " cookies";
58//
59// You can also do conditional logging:
60//
61// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
62//
63// The CHECK(condition) macro is active in both debug and release builds and
64// effectively performs a LOG(FATAL) which terminates the process and
65// generates a crashdump unless a debugger is attached.
66//
67// There are also "debug mode" logging macros like the ones above:
68//
69// DLOG(INFO) << "Found cookies";
70//
71// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
72//
73// All "debug mode" logging is compiled away to nothing for non-debug mode
74// compiles. LOG_IF and development flags also work well together
75// because the code can be compiled away sometimes.
76//
77// We also have
78//
79// LOG_ASSERT(assertion);
80// DLOG_ASSERT(assertion);
81//
82// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
83//
84// There are "verbose level" logging macros. They look like
85//
86// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
87// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
88//
89// These always log at the INFO log level (when they log at all).
90// The verbose logging can also be turned on module-by-module. For instance,
91// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
92// will cause:
93// a. VLOG(2) and lower messages to be printed from profile.{h,cc}
94// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
95// c. VLOG(3) and lower messages to be printed from files prefixed with
96// "browser"
97// d. VLOG(4) and lower messages to be printed from files under a
98// "chromeos" directory.
99// e. VLOG(0) and lower messages to be printed from elsewhere
100//
101// The wildcarding functionality shown by (c) supports both '*' (match
102// 0 or more characters) and '?' (match any single character)
103// wildcards. Any pattern containing a forward or backward slash will
104// be tested against the whole pathname and not just the module.
105// E.g., "*/foo/bar/*=2" would change the logging level for all code
106// in source files under a "foo/bar" directory.
107//
108// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
109//
110// if (VLOG_IS_ON(2)) {
111// // do some logging preparation and logging
112// // that can't be accomplished with just VLOG(2) << ...;
113// }
114//
115// There is also a VLOG_IF "verbose level" condition macro for sample
116// cases, when some extra computation and preparation for logs is not
117// needed.
118//
119// VLOG_IF(1, (size > 1024))
120// << "I'm printed when size is more than 1024 and when you run the "
121// "program with --v=1 or more";
122//
123// We also override the standard 'assert' to use 'DLOG_ASSERT'.
124//
125// Lastly, there is:
126//
127// PLOG(ERROR) << "Couldn't do foo";
128// DPLOG(ERROR) << "Couldn't do foo";
129// PLOG_IF(ERROR, cond) << "Couldn't do foo";
130// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
131// PCHECK(condition) << "Couldn't do foo";
132// DPCHECK(condition) << "Couldn't do foo";
133//
134// which append the last system error to the message in string form (taken from
135// GetLastError() on Windows and errno on POSIX).
136//
137// The supported severity levels for macros that allow you to specify one
138// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
139//
140// Very important: logging a message at the FATAL severity level causes
141// the program to terminate (after the message is logged).
142//
143// There is the special severity of DFATAL, which logs FATAL in debug mode,
144// ERROR in normal mode.
145//
146// Output is of the format, for example:
147// [3816:3877:0812/234555.406952:VERBOSE1:drm_device_handle.cc(90)] Succeeded
148// authenticating /dev/dri/card0 in 0 ms with 1 attempt(s)
149//
150// The colon separated fields inside the brackets are as follows:
151// 0. An optional Logfile prefix (not included in this example)
152// 1. Process ID
153// 2. Thread ID
154// 3. The date/time of the log message, in MMDD/HHMMSS.Milliseconds format
155// 4. The log level
156// 5. The filename and line number where the log was instantiated
157//
158// Note that the visibility can be changed by setting preferences in
159// SetLogItems()
160
161namespace logging {
162
163// TODO(avi): do we want to do a unification of character types here?
164#if defined(OS_WIN)
165typedef base::char16 PathChar;
166#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
167typedef char PathChar;
168#endif
169
170// Where to record logging output? A flat file and/or system debug log
171// via OutputDebugString.
172enum LoggingDestination {
173 LOG_NONE = 0,
174 LOG_TO_FILE = 1 << 0,
175 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
176
177 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
178
179 // On Windows, use a file next to the exe; on POSIX platforms, where
180 // it may not even be possible to locate the executable on disk, use
181 // stderr.
182#if defined(OS_WIN)
183 LOG_DEFAULT = LOG_TO_FILE,
184#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
185 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
186#endif
187};
188
189// Indicates that the log file should be locked when being written to.
190// Unless there is only one single-threaded process that is logging to
191// the log file, the file should be locked during writes to make each
192// log output atomic. Other writers will block.
193//
194// All processes writing to the log file must have their locking set for it to
195// work properly. Defaults to LOCK_LOG_FILE.
196enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
197
198// On startup, should we delete or append to an existing log file (if any)?
199// Defaults to APPEND_TO_OLD_LOG_FILE.
200enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
201
202struct BASE_EXPORT LoggingSettings {
203 // The defaults values are:
204 //
205 // logging_dest: LOG_DEFAULT
206 // log_file: NULL
207 // lock_log: LOCK_LOG_FILE
208 // delete_old: APPEND_TO_OLD_LOG_FILE
209 LoggingSettings();
210
211 LoggingDestination logging_dest;
212
213 // The three settings below have an effect only when LOG_TO_FILE is
214 // set in |logging_dest|.
215 const PathChar* log_file;
216 LogLockingState lock_log;
217 OldFileDeletionState delete_old;
218};
219
220// Define different names for the BaseInitLoggingImpl() function depending on
221// whether NDEBUG is defined or not so that we'll fail to link if someone tries
222// to compile logging.cc with NDEBUG but includes logging.h without defining it,
223// or vice versa.
224#if defined(NDEBUG)
225#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
226#else
227#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
228#endif
229
230// Implementation of the InitLogging() method declared below. We use a
231// more-specific name so we can #define it above without affecting other code
232// that has named stuff "InitLogging".
233BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
234
235// Sets the log file name and other global logging state. Calling this function
236// is recommended, and is normally done at the beginning of application init.
237// If you don't call it, all the flags will be initialized to their default
238// values, and there is a race condition that may leak a critical section
239// object if two threads try to do the first log at the same time.
240// See the definition of the enums above for descriptions and default values.
241//
242// The default log file is initialized to "debug.log" in the application
243// directory. You probably don't want this, especially since the program
244// directory may not be writable on an enduser's system.
245//
246// This function may be called a second time to re-direct logging (e.g after
247// loging in to a user partition), however it should never be called more than
248// twice.
249inline bool InitLogging(const LoggingSettings& settings) {
250 return BaseInitLoggingImpl(settings);
251}
252
253// Sets the log level. Anything at or above this level will be written to the
254// log file/displayed to the user (if applicable). Anything below this level
255// will be silently ignored. The log level defaults to 0 (everything is logged
256// up to level INFO) if this function is not called.
257// Note that log messages for VLOG(x) are logged at level -x, so setting
258// the min log level to negative values enables verbose logging.
259BASE_EXPORT void SetMinLogLevel(int level);
260
261// Gets the current log level.
262BASE_EXPORT int GetMinLogLevel();
263
264// Used by LOG_IS_ON to lazy-evaluate stream arguments.
265BASE_EXPORT bool ShouldCreateLogMessage(int severity);
266
267// Gets the VLOG default verbosity level.
268BASE_EXPORT int GetVlogVerbosity();
269
270// Note that |N| is the size *with* the null terminator.
271BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
272
273// Gets the current vlog level for the given file (usually taken from __FILE__).
274template <size_t N>
275int GetVlogLevel(const char (&file)[N]) {
276 return GetVlogLevelHelper(file, N);
277}
278
279// Sets the common items you want to be prepended to each log message.
280// process and thread IDs default to off, the timestamp defaults to on.
281// If this function is not called, logging defaults to writing the timestamp
282// only.
283BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
284 bool enable_timestamp, bool enable_tickcount);
285
286// Sets an optional prefix to add to each log message. |prefix| is not copied
287// and should be a raw string constant. |prefix| must only contain ASCII letters
288// to avoid confusion with PIDs and timestamps. Pass null to remove the prefix.
289// Logging defaults to no prefix.
290BASE_EXPORT void SetLogPrefix(const char* prefix);
291
292// Sets whether or not you'd like to see fatal debug messages popped up in
293// a dialog box or not.
294// Dialogs are not shown by default.
295BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
296
297// Sets the Log Assert Handler that will be used to notify of check failures.
298// Resets Log Assert Handler on object destruction.
299// The default handler shows a dialog box and then terminate the process,
300// however clients can use this function to override with their own handling
301// (e.g. a silent one for Unit Tests)
302using LogAssertHandlerFunction =
303 base::RepeatingCallback<void(const char* file,
304 int line,
305 const base::StringPiece message,
306 const base::StringPiece stack_trace)>;
307
308class BASE_EXPORT ScopedLogAssertHandler {
309 public:
310 explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
311 ~ScopedLogAssertHandler();
312
313 private:
314 DISALLOW_COPY_AND_ASSIGN(ScopedLogAssertHandler);
315};
316
317// Sets the Log Message Handler that gets passed every log message before
318// it's sent to other log destinations (if any).
319// Returns true to signal that it handled the message and the message
320// should not be sent to other log destinations.
321typedef bool (*LogMessageHandlerFunction)(int severity,
322 const char* file, int line, size_t message_start, const std::string& str);
323BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
324BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
325
326// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
327// to Clang which control what code paths are statically analyzed,
328// and is meant to be used in conjunction with assert & assert-like functions.
329// The expression is passed straight through if analysis isn't enabled.
330//
331// ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
332// codepath and any other branching codepaths that might follow.
333#if defined(__clang_analyzer__)
334
335inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
336 return false;
337}
338
339inline constexpr bool AnalyzerAssumeTrue(bool arg) {
340 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
341 // false.
342 return arg || AnalyzerNoReturn();
343}
344
345#define ANALYZER_ASSUME_TRUE(arg) logging::AnalyzerAssumeTrue(!!(arg))
346#define ANALYZER_SKIP_THIS_PATH() \
347 static_cast<void>(::logging::AnalyzerNoReturn())
348#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
349
350#else // !defined(__clang_analyzer__)
351
352#define ANALYZER_ASSUME_TRUE(arg) (arg)
353#define ANALYZER_SKIP_THIS_PATH()
354#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
355
356#endif // defined(__clang_analyzer__)
357
358typedef int LogSeverity;
359const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
360// Note: the log severities are used to index into the array of names,
361// see log_severity_names.
362const LogSeverity LOG_INFO = 0;
363const LogSeverity LOG_WARNING = 1;
364const LogSeverity LOG_ERROR = 2;
365const LogSeverity LOG_FATAL = 3;
366const LogSeverity LOG_NUM_SEVERITIES = 4;
367
368// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
369#if defined(NDEBUG)
370const LogSeverity LOG_DFATAL = LOG_ERROR;
371#else
372const LogSeverity LOG_DFATAL = LOG_FATAL;
373#endif
374
375// A few definitions of macros that don't generate much code. These are used
376// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
377// better to have compact code for these operations.
378#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
379 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_INFO, ##__VA_ARGS__)
380#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
381 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_WARNING, \
382 ##__VA_ARGS__)
383#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
384 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
385#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
386 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
387#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
388 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
389#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
390 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DCHECK, ##__VA_ARGS__)
391
392#define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
393#define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
394#define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
395#define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
396#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
397#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_EX_DCHECK(LogMessage)
398
399#if defined(OS_WIN)
400// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
401// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
402// to keep using this syntax, we define this macro to do the same thing
403// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
404// the Windows SDK does for consistency.
405#define ERROR 0
406#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
407 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
408#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
409// Needed for LOG_IS_ON(ERROR).
410const LogSeverity LOG_0 = LOG_ERROR;
411#endif
412
413// As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
414// LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
415// always fire if they fail.
416#define LOG_IS_ON(severity) \
417 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
418
419// We don't do any caching tricks with VLOG_IS_ON() like the
420// google-glog version since it increases binary size. This means
421// that using the v-logging functions in conjunction with --vmodule
422// may be slow.
423#define VLOG_IS_ON(verboselevel) \
424 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
425
426// Helper macro which avoids evaluating the arguments to a stream if
427// the condition doesn't hold. Condition is evaluated once and only once.
428#define LAZY_STREAM(stream, condition) \
429 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
430
431// We use the preprocessor's merging operator, "##", so that, e.g.,
432// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
433// subtle difference between ostream member streaming functions (e.g.,
434// ostream::operator<<(int) and ostream non-member streaming functions
435// (e.g., ::operator<<(ostream&, string&): it turns out that it's
436// impossible to stream something like a string directly to an unnamed
437// ostream. We employ a neat hack by calling the stream() member
438// function of LogMessage which seems to avoid the problem.
439#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
440
441#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
442#define LOG_IF(severity, condition) \
443 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
444
445// The VLOG macros log with negative verbosities.
446#define VLOG_STREAM(verbose_level) \
447 ::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
448
449#define VLOG(verbose_level) \
450 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
451
452#define VLOG_IF(verbose_level, condition) \
453 LAZY_STREAM(VLOG_STREAM(verbose_level), \
454 VLOG_IS_ON(verbose_level) && (condition))
455
456#if defined (OS_WIN)
457#define VPLOG_STREAM(verbose_level) \
458 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
459 ::logging::GetLastSystemErrorCode()).stream()
460#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
461#define VPLOG_STREAM(verbose_level) \
462 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
463 ::logging::GetLastSystemErrorCode()).stream()
464#endif
465
466#define VPLOG(verbose_level) \
467 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
468
469#define VPLOG_IF(verbose_level, condition) \
470 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
471 VLOG_IS_ON(verbose_level) && (condition))
472
473// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
474
475#define LOG_ASSERT(condition) \
476 LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
477 << "Assert failed: " #condition ". "
478
479#if defined(OS_WIN)
480#define PLOG_STREAM(severity) \
481 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
482 ::logging::GetLastSystemErrorCode()).stream()
483#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
484#define PLOG_STREAM(severity) \
485 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
486 ::logging::GetLastSystemErrorCode()).stream()
487#endif
488
489#define PLOG(severity) \
490 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
491
492#define PLOG_IF(severity, condition) \
493 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
494
495BASE_EXPORT extern std::ostream* g_swallow_stream;
496
497// Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
498// avoid the creation of an object with a non-trivial destructor (LogMessage).
499// On MSVC x86 (checked on 2015 Update 3), this causes a few additional
500// pointless instructions to be emitted even at full optimization level, even
501// though the : arm of the ternary operator is clearly never executed. Using a
502// simpler object to be &'d with Voidify() avoids these extra instructions.
503// Using a simpler POD object with a templated operator<< also works to avoid
504// these instructions. However, this causes warnings on statically defined
505// implementations of operator<<(std::ostream, ...) in some .cc files, because
506// they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
507// ostream* also is not suitable, because some compilers warn of undefined
508// behavior.
509#define EAT_STREAM_PARAMETERS \
510 true ? (void)0 \
511 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
512
513// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
514// boolean.
515class CheckOpResult {
516 public:
517 // |message| must be non-null if and only if the check failed.
518 CheckOpResult(std::string* message) : message_(message) {}
519 // Returns true if the check succeeded.
520 operator bool() const { return !message_; }
521 // Returns the message.
522 std::string* message() { return message_; }
523
524 private:
525 std::string* message_;
526};
527
528// Crashes in the fastest possible way with no attempt at logging.
529// There are different constraints to satisfy here, see http://crbug.com/664209
530// for more context:
531// - The trap instructions, and hence the PC value at crash time, have to be
532// distinct and not get folded into the same opcode by the compiler.
533// On Linux/Android this is tricky because GCC still folds identical
534// asm volatile blocks. The workaround is generating distinct opcodes for
535// each CHECK using the __COUNTER__ macro.
536// - The debug info for the trap instruction has to be attributed to the source
537// line that has the CHECK(), to make crash reports actionable. This rules
538// out the ability of using a inline function, at least as long as clang
539// doesn't support attribute(artificial).
540// - Failed CHECKs should produce a signal that is distinguishable from an
541// invalid memory access, to improve the actionability of crash reports.
542// - The compiler should treat the CHECK as no-return instructions, so that the
543// trap code can be efficiently packed in the prologue of the function and
544// doesn't interfere with the main execution flow.
545// - When debugging, developers shouldn't be able to accidentally step over a
546// CHECK. This is achieved by putting opcodes that will cause a non
547// continuable exception after the actual trap instruction.
548// - Don't cause too much binary bloat.
549#if defined(COMPILER_GCC)
550
551#if defined(ARCH_CPU_X86_FAMILY) && !defined(OS_NACL)
552// int 3 will generate a SIGTRAP.
553#define TRAP_SEQUENCE() \
554 asm volatile( \
555 "int3; ud2; push %0;" ::"i"(static_cast<unsigned char>(__COUNTER__)))
556
557#elif defined(ARCH_CPU_ARMEL) && !defined(OS_NACL)
558// bkpt will generate a SIGBUS when running on armv7 and a SIGTRAP when running
559// as a 32 bit userspace app on arm64. There doesn't seem to be any way to
560// cause a SIGTRAP from userspace without using a syscall (which would be a
561// problem for sandboxing).
562#define TRAP_SEQUENCE() \
563 asm volatile("bkpt #0; udf %0;" ::"i"(__COUNTER__ % 256))
564
565#elif defined(ARCH_CPU_ARM64) && !defined(OS_NACL)
566// This will always generate a SIGTRAP on arm64.
567#define TRAP_SEQUENCE() \
568 asm volatile("brk #0; hlt %0;" ::"i"(__COUNTER__ % 65536))
569
570#else
571// Crash report accuracy will not be guaranteed on other architectures, but at
572// least this will crash as expected.
573#define TRAP_SEQUENCE() __builtin_trap()
574#endif // ARCH_CPU_*
575
576#elif defined(COMPILER_MSVC)
577
578// Clang is cleverer about coalescing int3s, so we need to add a unique-ish
579// instruction following the __debugbreak() to have it emit distinct locations
580// for CHECKs rather than collapsing them all together. It would be nice to use
581// a short intrinsic to do this (and perhaps have only one implementation for
582// both clang and MSVC), however clang-cl currently does not support intrinsics.
583// On the flip side, MSVC x64 doesn't support inline asm. So, we have to have
584// two implementations. Normally clang-cl's version will be 5 bytes (1 for
585// `int3`, 2 for `ud2`, 2 for `push byte imm`, however, TODO(scottmg):
586// https://crbug.com/694670 clang-cl doesn't currently support %'ing
587// __COUNTER__, so eventually it will emit the dword form of push.
588// TODO(scottmg): Reinvestigate a short sequence that will work on both
589// compilers once clang supports more intrinsics. See https://crbug.com/693713.
590#if !defined(__clang__)
591#define TRAP_SEQUENCE() __debugbreak()
592#elif defined(ARCH_CPU_ARM64)
593#define TRAP_SEQUENCE() \
594 __asm volatile("brk #0\n hlt %0\n" ::"i"(__COUNTER__ % 65536));
595#else
596#define TRAP_SEQUENCE() ({ {__asm int 3 __asm ud2 __asm push __COUNTER__}; })
597#endif // __clang__
598
599#else
600#error Port
601#endif // COMPILER_GCC
602
603// CHECK() and the trap sequence can be invoked from a constexpr function.
604// This could make compilation fail on GCC, as it forbids directly using inline
605// asm inside a constexpr function. However, it allows calling a lambda
606// expression including the same asm.
607// The side effect is that the top of the stacktrace will not point to the
608// calling function, but to this anonymous lambda. This is still useful as the
609// full name of the lambda will typically include the name of the function that
610// calls CHECK() and the debugger will still break at the right line of code.
611#if !defined(COMPILER_GCC)
612#define WRAPPED_TRAP_SEQUENCE() TRAP_SEQUENCE()
613#else
614#define WRAPPED_TRAP_SEQUENCE() \
615 do { \
616 [] { TRAP_SEQUENCE(); }(); \
617 } while (false)
618#endif
619
620#if defined(__clang__) || defined(COMPILER_GCC)
621#define IMMEDIATE_CRASH() \
622 ({ \
623 WRAPPED_TRAP_SEQUENCE(); \
624 __builtin_unreachable(); \
625 })
626#else
627// This is supporting non-chromium user of logging.h to build with MSVC, like
628// pdfium. On MSVC there is no __builtin_unreachable().
629#define IMMEDIATE_CRASH() WRAPPED_TRAP_SEQUENCE()
630#endif
631
632// CHECK dies with a fatal error if condition is not true. It is *not*
633// controlled by NDEBUG, so the check will be executed regardless of
634// compilation mode.
635//
636// We make sure CHECK et al. always evaluates their arguments, as
637// doing CHECK(FunctionWithSideEffect()) is a common idiom.
638
639#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
640
641// Make all CHECK functions discard their log strings to reduce code bloat, and
642// improve performance, for official release builds.
643//
644// This is not calling BreakDebugger since this is called frequently, and
645// calling an out-of-line function instead of a noreturn inline macro prevents
646// compiler optimizations.
647#define CHECK(condition) \
648 UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_STREAM_PARAMETERS
649
650// PCHECK includes the system error code, which is useful for determining
651// why the condition failed. In official builds, preserve only the error code
652// message so that it is available in crash reports. The stringified
653// condition and any additional stream parameters are dropped.
654#define PCHECK(condition) \
655 LAZY_STREAM(PLOG_STREAM(FATAL), UNLIKELY(!(condition))); \
656 EAT_STREAM_PARAMETERS
657
658#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
659
660#else // !(OFFICIAL_BUILD && NDEBUG)
661
662// Do as much work as possible out of line to reduce inline code size.
663#define CHECK(condition) \
664 LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
665 !ANALYZER_ASSUME_TRUE(condition))
666
667#define PCHECK(condition) \
668 LAZY_STREAM(PLOG_STREAM(FATAL), !ANALYZER_ASSUME_TRUE(condition)) \
669 << "Check failed: " #condition ". "
670
671// Helper macro for binary operators.
672// Don't use this macro directly in your code, use CHECK_EQ et al below.
673// The 'switch' is used to prevent the 'else' from being ambiguous when the
674// macro is used in an 'if' clause such as:
675// if (a == 1)
676// CHECK_EQ(2, a);
677#define CHECK_OP(name, op, val1, val2) \
678 switch (0) case 0: default: \
679 if (::logging::CheckOpResult true_if_passed = \
680 ::logging::Check##name##Impl((val1), (val2), \
681 #val1 " " #op " " #val2)) \
682 ; \
683 else \
684 ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
685
686#endif // !(OFFICIAL_BUILD && NDEBUG)
687
688#ifdef __GNUC__
689#pragma GCC diagnostic push
690#pragma GCC diagnostic ignored "-Waddress"
691#endif // __GNUC__
692
693// This formats a value for a failing CHECK_XX statement. Ordinarily,
694// it uses the definition for operator<<, with a few special cases below.
695template <typename T>
696inline typename std::enable_if<
697 base::internal::SupportsOstreamOperator<const T&>::value &&
698 !std::is_function<typename std::remove_pointer<T>::type>::value,
699 void>::type
700MakeCheckOpValueString(std::ostream* os, const T& v) {
701 (*os) << v;
702}
703
704// Provide an overload for functions and function pointers. Function pointers
705// don't implicitly convert to void* but do implicitly convert to bool, so
706// without this function pointers are always printed as 1 or 0. (MSVC isn't
707// standards-conforming here and converts function pointers to regular
708// pointers, so this is a no-op for MSVC.)
709template <typename T>
710inline typename std::enable_if<
711 std::is_function<typename std::remove_pointer<T>::type>::value,
712 void>::type
713MakeCheckOpValueString(std::ostream* os, const T& v) {
714 (*os) << reinterpret_cast<const void*>(v);
715}
716
717// We need overloads for enums that don't support operator<<.
718// (i.e. scoped enums where no operator<< overload was declared).
719template <typename T>
720inline typename std::enable_if<
721 !base::internal::SupportsOstreamOperator<const T&>::value &&
722 std::is_enum<T>::value,
723 void>::type
724MakeCheckOpValueString(std::ostream* os, const T& v) {
725 (*os) << static_cast<typename std::underlying_type<T>::type>(v);
726}
727
728#ifdef __GNUC__
729#pragma GCC diagnostic pop
730#endif
731
732// We need an explicit overload for std::nullptr_t.
733BASE_EXPORT void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
734
735// Build the error message string. This is separate from the "Impl"
736// function template because it is not performance critical and so can
737// be out of line, while the "Impl" code should be inline. Caller
738// takes ownership of the returned string.
739template<class t1, class t2>
740std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
741 std::ostringstream ss;
742 ss << names << " (";
743 MakeCheckOpValueString(&ss, v1);
744 ss << " vs. ";
745 MakeCheckOpValueString(&ss, v2);
746 ss << ")";
747 std::string* msg = new std::string(ss.str());
748 return msg;
749}
750
751// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
752// in logging.cc.
753extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
754 const int&, const int&, const char* names);
755extern template BASE_EXPORT
756std::string* MakeCheckOpString<unsigned long, unsigned long>(
757 const unsigned long&, const unsigned long&, const char* names);
758extern template BASE_EXPORT
759std::string* MakeCheckOpString<unsigned long, unsigned int>(
760 const unsigned long&, const unsigned int&, const char* names);
761extern template BASE_EXPORT
762std::string* MakeCheckOpString<unsigned int, unsigned long>(
763 const unsigned int&, const unsigned long&, const char* names);
764extern template BASE_EXPORT
765std::string* MakeCheckOpString<std::string, std::string>(
766 const std::string&, const std::string&, const char* name);
767
768// Helper functions for CHECK_OP macro.
769// The (int, int) specialization works around the issue that the compiler
770// will not instantiate the template version of the function on values of
771// unnamed enum type - see comment below.
772//
773// The checked condition is wrapped with ANALYZER_ASSUME_TRUE, which under
774// static analysis builds, blocks analysis of the current path if the
775// condition is false.
776#define DEFINE_CHECK_OP_IMPL(name, op) \
777 template <class t1, class t2> \
778 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
779 const char* names) { \
780 if (!!ANALYZER_ASSUME_TRUE(v1 op v2)) \
781 return NULL; \
782 else \
783 return ::logging::MakeCheckOpString(v1, v2, names); \
784 } \
785 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
786 if (!!ANALYZER_ASSUME_TRUE(v1 op v2)) \
787 return NULL; \
788 else \
789 return ::logging::MakeCheckOpString(v1, v2, names); \
790 }
791DEFINE_CHECK_OP_IMPL(EQ, ==)
792DEFINE_CHECK_OP_IMPL(NE, !=)
793DEFINE_CHECK_OP_IMPL(LE, <=)
794DEFINE_CHECK_OP_IMPL(LT, < )
795DEFINE_CHECK_OP_IMPL(GE, >=)
796DEFINE_CHECK_OP_IMPL(GT, > )
797#undef DEFINE_CHECK_OP_IMPL
798
799#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
800#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
801#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
802#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
803#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
804#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
805
806#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
807#define DCHECK_IS_ON() 0
808#else
809#define DCHECK_IS_ON() 1
810#endif
811
812// Definitions for DLOG et al.
813
814#if DCHECK_IS_ON()
815
816#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
817#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
818#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
819#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
820#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
821#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
822
823#else // DCHECK_IS_ON()
824
825// If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
826// (which may reference a variable defined only if DCHECK_IS_ON()).
827// Contrast this with DCHECK et al., which has different behavior.
828
829#define DLOG_IS_ON(severity) false
830#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
831#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
832#define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
833#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
834#define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
835
836#endif // DCHECK_IS_ON()
837
838#define DLOG(severity) \
839 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
840
841#define DPLOG(severity) \
842 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
843
844#define DVLOG(verboselevel) DVLOG_IF(verboselevel, true)
845
846#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, true)
847
848// Definitions for DCHECK et al.
849
850#if DCHECK_IS_ON()
851
852#if defined(DCHECK_IS_CONFIGURABLE)
853BASE_EXPORT extern LogSeverity LOG_DCHECK;
854#else
855const LogSeverity LOG_DCHECK = LOG_FATAL;
856#endif // defined(DCHECK_IS_CONFIGURABLE)
857
858#else // DCHECK_IS_ON()
859
860// There may be users of LOG_DCHECK that are enabled independently
861// of DCHECK_IS_ON(), so default to FATAL logging for those.
862const LogSeverity LOG_DCHECK = LOG_FATAL;
863
864#endif // DCHECK_IS_ON()
865
866// DCHECK et al. make sure to reference |condition| regardless of
867// whether DCHECKs are enabled; this is so that we don't get unused
868// variable warnings if the only use of a variable is in a DCHECK.
869// This behavior is different from DLOG_IF et al.
870//
871// Note that the definition of the DCHECK macros depends on whether or not
872// DCHECK_IS_ON() is true. When DCHECK_IS_ON() is false, the macros use
873// EAT_STREAM_PARAMETERS to avoid expressions that would create temporaries.
874
875#if DCHECK_IS_ON()
876
877#define DCHECK(condition) \
878 LAZY_STREAM(LOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
879 << "Check failed: " #condition ". "
880#define DPCHECK(condition) \
881 LAZY_STREAM(PLOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
882 << "Check failed: " #condition ". "
883
884#else // DCHECK_IS_ON()
885
886#define DCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
887#define DPCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
888
889#endif // DCHECK_IS_ON()
890
891// Helper macro for binary operators.
892// Don't use this macro directly in your code, use DCHECK_EQ et al below.
893// The 'switch' is used to prevent the 'else' from being ambiguous when the
894// macro is used in an 'if' clause such as:
895// if (a == 1)
896// DCHECK_EQ(2, a);
897#if DCHECK_IS_ON()
898
899#define DCHECK_OP(name, op, val1, val2) \
900 switch (0) case 0: default: \
901 if (::logging::CheckOpResult true_if_passed = \
902 ::logging::Check##name##Impl((val1), (val2), \
903 #val1 " " #op " " #val2)) \
904 ; \
905 else \
906 ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
907 true_if_passed.message()).stream()
908
909#else // DCHECK_IS_ON()
910
911// When DCHECKs aren't enabled, DCHECK_OP still needs to reference operator<<
912// overloads for |val1| and |val2| to avoid potential compiler warnings about
913// unused functions. For the same reason, it also compares |val1| and |val2|
914// using |op|.
915//
916// Note that the contract of DCHECK_EQ, etc is that arguments are only evaluated
917// once. Even though |val1| and |val2| appear twice in this version of the macro
918// expansion, this is OK, since the expression is never actually evaluated.
919#define DCHECK_OP(name, op, val1, val2) \
920 EAT_STREAM_PARAMETERS << (::logging::MakeCheckOpValueString( \
921 ::logging::g_swallow_stream, val1), \
922 ::logging::MakeCheckOpValueString( \
923 ::logging::g_swallow_stream, val2), \
924 (val1)op(val2))
925
926#endif // DCHECK_IS_ON()
927
928// Equality/Inequality checks - compare two values, and log a
929// LOG_DCHECK message including the two values when the result is not
930// as expected. The values must have operator<<(ostream, ...)
931// defined.
932//
933// You may append to the error message like so:
934// DCHECK_NE(1, 2) << "The world must be ending!";
935//
936// We are very careful to ensure that each argument is evaluated exactly
937// once, and that anything which is legal to pass as a function argument is
938// legal here. In particular, the arguments may be temporary expressions
939// which will end up being destroyed at the end of the apparent statement,
940// for example:
941// DCHECK_EQ(string("abc")[1], 'b');
942//
943// WARNING: These don't compile correctly if one of the arguments is a pointer
944// and the other is NULL. In new code, prefer nullptr instead. To
945// work around this for C++98, simply static_cast NULL to the type of the
946// desired pointer.
947
948#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
949#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
950#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
951#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
952#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
953#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
954
955#if !DCHECK_IS_ON() && defined(OS_CHROMEOS)
956// Implement logging of NOTREACHED() as a dedicated function to get function
957// call overhead down to a minimum.
958void LogErrorNotReached(const char* file, int line);
959#define NOTREACHED() \
960 true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
961 : EAT_STREAM_PARAMETERS
962#else
963#define NOTREACHED() DCHECK(false)
964#endif
965
966// Redefine the standard assert to use our nice log files
967#undef assert
968#define assert(x) DLOG_ASSERT(x)
969
970// This class more or less represents a particular log message. You
971// create an instance of LogMessage and then stream stuff to it.
972// When you finish streaming to it, ~LogMessage is called and the
973// full message gets streamed to the appropriate destination.
974//
975// You shouldn't actually use LogMessage's constructor to log things,
976// though. You should use the LOG() macro (and variants thereof)
977// above.
978class BASE_EXPORT LogMessage {
979 public:
980 // Used for LOG(severity).
981 LogMessage(const char* file, int line, LogSeverity severity);
982
983 // Used for CHECK(). Implied severity = LOG_FATAL.
984 LogMessage(const char* file, int line, const char* condition);
985
986 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
987 // Implied severity = LOG_FATAL.
988 LogMessage(const char* file, int line, std::string* result);
989
990 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
991 LogMessage(const char* file, int line, LogSeverity severity,
992 std::string* result);
993
994 ~LogMessage();
995
996 std::ostream& stream() { return stream_; }
997
998 LogSeverity severity() { return severity_; }
999 std::string str() { return stream_.str(); }
1000
1001 private:
1002 void Init(const char* file, int line);
1003
1004 LogSeverity severity_;
1005 std::ostringstream stream_;
1006 size_t message_start_; // Offset of the start of the message (past prefix
1007 // info).
1008 // The file and line information passed in to the constructor.
1009 const char* file_;
1010 const int line_;
1011
1012 // This is useful since the LogMessage class uses a lot of Win32 calls
1013 // that will lose the value of GLE and the code that called the log function
1014 // will have lost the thread error value when the log call returns.
1015 base::internal::ScopedClearLastError last_error_;
1016
1017 DISALLOW_COPY_AND_ASSIGN(LogMessage);
1018};
1019
1020// This class is used to explicitly ignore values in the conditional
1021// logging macros. This avoids compiler warnings like "value computed
1022// is not used" and "statement has no effect".
1023class LogMessageVoidify {
1024 public:
1025 LogMessageVoidify() = default;
1026 // This has to be an operator with a precedence lower than << but
1027 // higher than ?:
1028 constexpr void operator&(std::ostream&) { }
1029};
1030
1031#if defined(OS_WIN)
1032typedef unsigned long SystemErrorCode;
1033#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1034typedef int SystemErrorCode;
1035#endif
1036
1037// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
1038// pull in windows.h just for GetLastError() and DWORD.
1039BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
1040BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
1041
1042#if defined(OS_WIN)
1043// Appends a formatted system message of the GetLastError() type.
1044class BASE_EXPORT Win32ErrorLogMessage {
1045 public:
1046 Win32ErrorLogMessage(const char* file,
1047 int line,
1048 LogSeverity severity,
1049 SystemErrorCode err);
1050
1051 // Appends the error message before destructing the encapsulated class.
1052 ~Win32ErrorLogMessage();
1053
1054 std::ostream& stream() { return log_message_.stream(); }
1055
1056 private:
1057 SystemErrorCode err_;
1058 LogMessage log_message_;
1059
1060 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
1061};
1062#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1063// Appends a formatted system message of the errno type
1064class BASE_EXPORT ErrnoLogMessage {
1065 public:
1066 ErrnoLogMessage(const char* file,
1067 int line,
1068 LogSeverity severity,
1069 SystemErrorCode err);
1070
1071 // Appends the error message before destructing the encapsulated class.
1072 ~ErrnoLogMessage();
1073
1074 std::ostream& stream() { return log_message_.stream(); }
1075
1076 private:
1077 SystemErrorCode err_;
1078 LogMessage log_message_;
1079
1080 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
1081};
1082#endif // OS_WIN
1083
1084// Closes the log file explicitly if open.
1085// NOTE: Since the log file is opened as necessary by the action of logging
1086// statements, there's no guarantee that it will stay closed
1087// after this call.
1088BASE_EXPORT void CloseLogFile();
1089
1090// Async signal safe logging mechanism.
1091BASE_EXPORT void RawLog(int level, const char* message);
1092
1093#define RAW_LOG(level, message) \
1094 ::logging::RawLog(::logging::LOG_##level, message)
1095
1096#define RAW_CHECK(condition) \
1097 do { \
1098 if (!(condition)) \
1099 ::logging::RawLog(::logging::LOG_FATAL, \
1100 "Check failed: " #condition "\n"); \
1101 } while (0)
1102
1103#if defined(OS_WIN)
1104// Returns true if logging to file is enabled.
1105BASE_EXPORT bool IsLoggingToFileEnabled();
1106
1107// Returns the default log file path.
1108BASE_EXPORT base::string16 GetLogFileFullPath();
1109#endif
1110
1111} // namespace logging
1112
1113// Note that "The behavior of a C++ program is undefined if it adds declarations
1114// or definitions to namespace std or to a namespace within namespace std unless
1115// otherwise specified." --C++11[namespace.std]
1116//
1117// We've checked that this particular definition has the intended behavior on
1118// our implementations, but it's prone to breaking in the future, and please
1119// don't imitate this in your own definitions without checking with some
1120// standard library experts.
1121namespace std {
1122// These functions are provided as a convenience for logging, which is where we
1123// use streams (it is against Google style to use streams in other places). It
1124// is designed to allow you to emit non-ASCII Unicode strings to the log file,
1125// which is normally ASCII. It is relatively slow, so try not to use it for
1126// common cases. Non-ASCII characters will be converted to UTF-8 by these
1127// operators.
1128BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
1129inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
1130 return out << wstr.c_str();
1131}
1132} // namespace std
1133
1134// The NOTIMPLEMENTED() macro annotates codepaths which have not been
1135// implemented yet. If output spam is a serious concern,
1136// NOTIMPLEMENTED_LOG_ONCE can be used.
1137
1138#if defined(COMPILER_GCC)
1139// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
1140// of the current function in the NOTIMPLEMENTED message.
1141#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
1142#else
1143#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
1144#endif
1145
1146#if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
1147#define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
1148#define NOTIMPLEMENTED_LOG_ONCE() EAT_STREAM_PARAMETERS
1149#else
1150#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
1151#define NOTIMPLEMENTED_LOG_ONCE() \
1152 do { \
1153 static bool logged_once = false; \
1154 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG; \
1155 logged_once = true; \
1156 } while (0); \
1157 EAT_STREAM_PARAMETERS
1158#endif
1159
1160#endif // BASE_LOGGING_H_
1161