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 <string_view>
15 #include <type_traits>
16 #include <utility>
17
18 #include "base/compiler_specific.h"
19 #include "base/macros.h"
20 #include "base/template_util.h"
21 #include "util/build_config.h"
22
23 //
24 // Optional message capabilities
25 // -----------------------------
26 // Assertion failed messages and fatal errors are displayed in a dialog box
27 // before the application exits. However, running this UI creates a message
28 // loop, which causes application messages to be processed and potentially
29 // dispatched to existing application windows. Since the application is in a
30 // bad state when this assertion dialog is displayed, these messages may not
31 // get processed and hang the dialog, or the application might go crazy.
32 //
33 // Therefore, it can be beneficial to display the error dialog in a separate
34 // process from the main application. When the logging system needs to display
35 // a fatal error dialog box, it will look for a program called
36 // "DebugMessage.exe" in the same directory as the application executable. It
37 // will run this application with the message as the command line, and will
38 // not include the name of the application as is traditional for easier
39 // parsing.
40 //
41 // The code for DebugMessage.exe is only one line. In WinMain, do:
42 // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
43 //
44 // If DebugMessage.exe is not found, the logging code will use a normal
45 // MessageBox, potentially causing the problems discussed above.
46
47 // Instructions
48 // ------------
49 //
50 // Make a bunch of macros for logging. The way to log things is to stream
51 // things to LOG(<a particular severity level>). E.g.,
52 //
53 // LOG(INFO) << "Found " << num_cookies << " cookies";
54 //
55 // You can also do conditional logging:
56 //
57 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
58 //
59 // The CHECK(condition) macro is active in both debug and release builds and
60 // effectively performs a LOG(FATAL) which terminates the process and
61 // generates a crashdump unless a debugger is attached.
62 //
63 // There are also "debug mode" logging macros like the ones above:
64 //
65 // DLOG(INFO) << "Found cookies";
66 //
67 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
68 //
69 // All "debug mode" logging is compiled away to nothing for non-debug mode
70 // compiles. LOG_IF and development flags also work well together
71 // because the code can be compiled away sometimes.
72 //
73 // We also have
74 //
75 // LOG_ASSERT(assertion);
76 // DLOG_ASSERT(assertion);
77 //
78 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
79 //
80 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
81 //
82 // Lastly, there is:
83 //
84 // PLOG(ERROR) << "Couldn't do foo";
85 // DPLOG(ERROR) << "Couldn't do foo";
86 // PLOG_IF(ERROR, cond) << "Couldn't do foo";
87 // DPLOG_IF(ERROR, cond) << "Couldn't do foo";
88 // PCHECK(condition) << "Couldn't do foo";
89 // DPCHECK(condition) << "Couldn't do foo";
90 //
91 // which append the last system error to the message in string form (taken from
92 // GetLastError() on Windows and errno on POSIX).
93 //
94 // The supported severity levels for macros that allow you to specify one
95 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
96 //
97 // Very important: logging a message at the FATAL severity level causes
98 // the program to terminate (after the message is logged).
99 //
100 // There is the special severity of DFATAL, which logs FATAL in debug mode,
101 // ERROR in normal mode.
102
103 namespace logging {
104
105 // Sets the log level. Anything at or above this level will be written to the
106 // log file/displayed to the user (if applicable). Anything below this level
107 // will be silently ignored. The log level defaults to 0 (everything is logged
108 // up to level INFO) if this function is not called.
109 void SetMinLogLevel(int level);
110
111 // Gets the current log level.
112 int GetMinLogLevel();
113
114 // Used by LOG_IS_ON to lazy-evaluate stream arguments.
115 bool ShouldCreateLogMessage(int severity);
116
117 // The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
118 // to Clang which control what code paths are statically analyzed,
119 // and is meant to be used in conjunction with assert & assert-like functions.
120 // The expression is passed straight through if analysis isn't enabled.
121 //
122 // ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
123 // codepath and any other branching codepaths that might follow.
124 #if defined(__clang_analyzer__)
125
AnalyzerNoReturn()126 inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
127 return false;
128 }
129
AnalyzerAssumeTrue(bool arg)130 inline constexpr bool AnalyzerAssumeTrue(bool arg) {
131 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
132 // false.
133 return arg || AnalyzerNoReturn();
134 }
135
136 #define ANALYZER_ASSUME_TRUE(arg) logging::AnalyzerAssumeTrue(!!(arg))
137 #define ANALYZER_SKIP_THIS_PATH() \
138 static_cast<void>(::logging::AnalyzerNoReturn())
139 #define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
140
141 #else // !defined(__clang_analyzer__)
142
143 #define ANALYZER_ASSUME_TRUE(arg) (arg)
144 #define ANALYZER_SKIP_THIS_PATH()
145 #define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
146
147 #endif // defined(__clang_analyzer__)
148
149 typedef int LogSeverity;
150 const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
151 // Note: the log severities are used to index into the array of names,
152 // see log_severity_names.
153 const LogSeverity LOG_INFO = 0;
154 const LogSeverity LOG_WARNING = 1;
155 const LogSeverity LOG_ERROR = 2;
156 const LogSeverity LOG_FATAL = 3;
157 const LogSeverity LOG_NUM_SEVERITIES = 4;
158
159 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
160 #if defined(NDEBUG)
161 const LogSeverity LOG_DFATAL = LOG_ERROR;
162 #else
163 const LogSeverity LOG_DFATAL = LOG_FATAL;
164 #endif
165
166 // A few definitions of macros that don't generate much code. These are used
167 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
168 // better to have compact code for these operations.
169 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
170 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_INFO, ##__VA_ARGS__)
171 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
172 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_WARNING, \
173 ##__VA_ARGS__)
174 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
175 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
176 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
177 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
178 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
179 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
180 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
181 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DCHECK, ##__VA_ARGS__)
182
183 #define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
184 #define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
185 #define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
186 #define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
187 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
188 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_EX_DCHECK(LogMessage)
189
190 #if defined(OS_WIN)
191 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
192 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
193 // to keep using this syntax, we define this macro to do the same thing
194 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
195 // the Windows SDK does for consistency.
196 #define ERROR 0
197 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
198 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ##__VA_ARGS__)
199 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
200 // Needed for LOG_IS_ON(ERROR).
201 const LogSeverity LOG_0 = LOG_ERROR;
202 #endif
203
204 // As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
205 // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
206 // always fire if they fail.
207 #define LOG_IS_ON(severity) \
208 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
209
210 // Helper macro which avoids evaluating the arguments to a stream if
211 // the condition doesn't hold. Condition is evaluated once and only once.
212 #define LAZY_STREAM(stream, condition) \
213 !(condition) ? (void)0 : ::logging::LogMessageVoidify() & (stream)
214
215 // We use the preprocessor's merging operator, "##", so that, e.g.,
216 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
217 // subtle difference between ostream member streaming functions (e.g.,
218 // ostream::operator<<(int) and ostream non-member streaming functions
219 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
220 // impossible to stream something like a string directly to an unnamed
221 // ostream. We employ a neat hack by calling the stream() member
222 // function of LogMessage which seems to avoid the problem.
223 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_##severity.stream()
224
225 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
226 #define LOG_IF(severity, condition) \
227 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
228
229 #define LOG_ASSERT(condition) \
230 LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
231 << "Assert failed: " #condition ". "
232
233 #if defined(OS_WIN)
234 #define PLOG_STREAM(severity) \
235 COMPACT_GOOGLE_LOG_EX_##severity(Win32ErrorLogMessage, \
236 ::logging::GetLastSystemErrorCode()) \
237 .stream()
238 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
239 #define PLOG_STREAM(severity) \
240 COMPACT_GOOGLE_LOG_EX_##severity(ErrnoLogMessage, \
241 ::logging::GetLastSystemErrorCode()) \
242 .stream()
243 #endif
244
245 #define PLOG(severity) LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
246
247 #define PLOG_IF(severity, condition) \
248 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
249
250 extern std::ostream* g_swallow_stream;
251
252 // Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
253 // avoid the creation of an object with a non-trivial destructor (LogMessage).
254 // On MSVC x86 (checked on 2015 Update 3), this causes a few additional
255 // pointless instructions to be emitted even at full optimization level, even
256 // though the : arm of the ternary operator is clearly never executed. Using a
257 // simpler object to be &'d with Voidify() avoids these extra instructions.
258 // Using a simpler POD object with a templated operator<< also works to avoid
259 // these instructions. However, this causes warnings on statically defined
260 // implementations of operator<<(std::ostream, ...) in some .cc files, because
261 // they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
262 // ostream* also is not suitable, because some compilers warn of undefined
263 // behavior.
264 #define EAT_STREAM_PARAMETERS \
265 true ? (void)0 \
266 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
267
268 // Captures the result of a CHECK_EQ (for example) and facilitates testing as a
269 // boolean.
270 class CheckOpResult {
271 public:
272 // |message| must be non-null if and only if the check failed.
CheckOpResult(std::string * message)273 CheckOpResult(std::string* message) : message_(message) {}
274 // Returns true if the check succeeded.
275 operator bool() const { return !message_; }
276 // Returns the message.
message()277 std::string* message() { return message_; }
278
279 private:
280 std::string* message_;
281 };
282
283 // Crashes in the fastest possible way with no attempt at logging.
284 // There are different constraints to satisfy here, see http://crbug.com/664209
285 // for more context:
286 // - The trap instructions, and hence the PC value at crash time, have to be
287 // distinct and not get folded into the same opcode by the compiler.
288 // On Linux/Android this is tricky because GCC still folds identical
289 // asm volatile blocks. The workaround is generating distinct opcodes for
290 // each CHECK using the __COUNTER__ macro.
291 // - The debug info for the trap instruction has to be attributed to the source
292 // line that has the CHECK(), to make crash reports actionable. This rules
293 // out the ability of using a inline function, at least as long as clang
294 // doesn't support attribute(artificial).
295 // - Failed CHECKs should produce a signal that is distinguishable from an
296 // invalid memory access, to improve the actionability of crash reports.
297 // - The compiler should treat the CHECK as no-return instructions, so that the
298 // trap code can be efficiently packed in the prologue of the function and
299 // doesn't interfere with the main execution flow.
300 // - When debugging, developers shouldn't be able to accidentally step over a
301 // CHECK. This is achieved by putting opcodes that will cause a non
302 // continuable exception after the actual trap instruction.
303 // - Don't cause too much binary bloat.
304 #if defined(COMPILER_GCC)
305
306 #if defined(ARCH_CPU_X86_FAMILY)
307 // int 3 will generate a SIGTRAP.
308 #define TRAP_SEQUENCE() \
309 asm volatile( \
310 "int3; ud2; push %0;" ::"i"(static_cast<unsigned char>(__COUNTER__)))
311
312 #elif defined(ARCH_CPU_ARMEL)
313 // bkpt will generate a SIGBUS when running on armv7 and a SIGTRAP when running
314 // as a 32 bit userspace app on arm64. There doesn't seem to be any way to
315 // cause a SIGTRAP from userspace without using a syscall (which would be a
316 // problem for sandboxing).
317 #define TRAP_SEQUENCE() \
318 asm volatile("bkpt #0; udf %0;" ::"i"(__COUNTER__ % 256))
319
320 #elif defined(ARCH_CPU_ARM64)
321 // This will always generate a SIGTRAP on arm64.
322 #define TRAP_SEQUENCE() \
323 asm volatile("brk #0; hlt %0;" ::"i"(__COUNTER__ % 65536))
324
325 #else
326 // Crash report accuracy will not be guaranteed on other architectures, but at
327 // least this will crash as expected.
328 #define TRAP_SEQUENCE() __builtin_trap()
329 #endif // ARCH_CPU_*
330
331 // CHECK() and the trap sequence can be invoked from a constexpr function.
332 // This could make compilation fail on GCC, as it forbids directly using inline
333 // asm inside a constexpr function. However, it allows calling a lambda
334 // expression including the same asm.
335 // The side effect is that the top of the stacktrace will not point to the
336 // calling function, but to this anonymous lambda. This is still useful as the
337 // full name of the lambda will typically include the name of the function that
338 // calls CHECK() and the debugger will still break at the right line of code.
339 #if !defined(__clang__)
340 #define WRAPPED_TRAP_SEQUENCE() \
341 do { \
342 [] { TRAP_SEQUENCE(); }(); \
343 } while (false)
344 #else
345 #define WRAPPED_TRAP_SEQUENCE() TRAP_SEQUENCE()
346 #endif
347
348 #define IMMEDIATE_CRASH() \
349 ({ \
350 WRAPPED_TRAP_SEQUENCE(); \
351 __builtin_unreachable(); \
352 })
353
354 #elif defined(COMPILER_MSVC)
355
356 // Clang is cleverer about coalescing int3s, so we need to add a unique-ish
357 // instruction following the __debugbreak() to have it emit distinct locations
358 // for CHECKs rather than collapsing them all together. It would be nice to use
359 // a short intrinsic to do this (and perhaps have only one implementation for
360 // both clang and MSVC), however clang-cl currently does not support intrinsics.
361 // On the flip side, MSVC x64 doesn't support inline asm. So, we have to have
362 // two implementations. Normally clang-cl's version will be 5 bytes (1 for
363 // `int3`, 2 for `ud2`, 2 for `push byte imm`, however, TODO(scottmg):
364 // https://crbug.com/694670 clang-cl doesn't currently support %'ing
365 // __COUNTER__, so eventually it will emit the dword form of push.
366 // TODO(scottmg): Reinvestigate a short sequence that will work on both
367 // compilers once clang supports more intrinsics. See https://crbug.com/693713.
368 #if defined(__clang__)
369 #define IMMEDIATE_CRASH() \
370 ({ \
371 {__asm int 3 __asm ud2 __asm push __COUNTER__}; \
372 __builtin_unreachable(); \
373 })
374 #else
375 #define IMMEDIATE_CRASH() __debugbreak()
376 #endif // __clang__
377
378 #else
379 #error Port
380 #endif
381
382 // CHECK dies with a fatal error if condition is not true. It is *not*
383 // controlled by NDEBUG, so the check will be executed regardless of
384 // compilation mode.
385 //
386 // We make sure CHECK et al. always evaluates their arguments, as
387 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
388
389 #if defined(OFFICIAL_BUILD) && defined(NDEBUG)
390
391 // Make all CHECK functions discard their log strings to reduce code bloat, and
392 // improve performance, for official release builds.
393 //
394 // This is not calling BreakDebugger since this is called frequently, and
395 // calling an out-of-line function instead of a noreturn inline macro prevents
396 // compiler optimizations.
397 #define CHECK(condition) \
398 UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_STREAM_PARAMETERS
399
400 // PCHECK includes the system error code, which is useful for determining
401 // why the condition failed. In official builds, preserve only the error code
402 // message so that it is available in crash reports. The stringified
403 // condition and any additional stream parameters are dropped.
404 #define PCHECK(condition) \
405 LAZY_STREAM(PLOG_STREAM(FATAL), UNLIKELY(!(condition))); \
406 EAT_STREAM_PARAMETERS
407
408 #define CHECK_OP(name, op, val1, val2) CHECK((val1)op(val2))
409
410 #else // !(OFFICIAL_BUILD && NDEBUG)
411
412 #if defined(_PREFAST_) && defined(OS_WIN)
413 // Use __analysis_assume to tell the VC++ static analysis engine that
414 // assert conditions are true, to suppress warnings. The LAZY_STREAM
415 // parameter doesn't reference 'condition' in /analyze builds because
416 // this evaluation confuses /analyze. The !! before condition is because
417 // __analysis_assume gets confused on some conditions:
418 // http://randomascii.wordpress.com/2011/09/13/analyze-for-visual-studio-the-ugly-part-5/
419
420 #define CHECK(condition) \
421 __analysis_assume(!!(condition)), LAZY_STREAM(LOG_STREAM(FATAL), false) \
422 << "Check failed: " #condition ". "
423
424 #define PCHECK(condition) \
425 __analysis_assume(!!(condition)), LAZY_STREAM(PLOG_STREAM(FATAL), false) \
426 << "Check failed: " #condition ". "
427
428 #else // _PREFAST_
429
430 // Do as much work as possible out of line to reduce inline code size.
431 #define CHECK(condition) \
432 LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
433 !ANALYZER_ASSUME_TRUE(condition))
434
435 #define PCHECK(condition) \
436 LAZY_STREAM(PLOG_STREAM(FATAL), !ANALYZER_ASSUME_TRUE(condition)) \
437 << "Check failed: " #condition ". "
438
439 #endif // _PREFAST_
440
441 // Helper macro for binary operators.
442 // Don't use this macro directly in your code, use CHECK_EQ et al below.
443 // The 'switch' is used to prevent the 'else' from being ambiguous when the
444 // macro is used in an 'if' clause such as:
445 // if (a == 1)
446 // CHECK_EQ(2, a);
447 #define CHECK_OP(name, op, val1, val2) \
448 switch (0) \
449 case 0: \
450 default: \
451 if (::logging::CheckOpResult true_if_passed = \
452 ::logging::Check##name##Impl((val1), (val2), \
453 #val1 " " #op " " #val2)) \
454 ; \
455 else \
456 ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()) \
457 .stream()
458
459 #endif // !(OFFICIAL_BUILD && NDEBUG)
460
461 // This formats a value for a failing CHECK_XX statement. Ordinarily,
462 // it uses the definition for operator<<, with a few special cases below.
463 template <typename T>
464 inline typename std::enable_if<
465 base::internal::SupportsOstreamOperator<const T&>::value &&
466 !std::is_function<typename std::remove_pointer<T>::type>::value,
467 void>::type
MakeCheckOpValueString(std::ostream * os,const T & v)468 MakeCheckOpValueString(std::ostream* os, const T& v) {
469 (*os) << v;
470 }
471
472 // Provide an overload for functions and function pointers. Function pointers
473 // don't implicitly convert to void* but do implicitly convert to bool, so
474 // without this function pointers are always printed as 1 or 0. (MSVC isn't
475 // standards-conforming here and converts function pointers to regular
476 // pointers, so this is a no-op for MSVC.)
477 template <typename T>
478 inline typename std::enable_if<
479 std::is_function<typename std::remove_pointer<T>::type>::value,
480 void>::type
MakeCheckOpValueString(std::ostream * os,const T & v)481 MakeCheckOpValueString(std::ostream* os, const T& v) {
482 (*os) << reinterpret_cast<const void*>(v);
483 }
484
485 // We need overloads for enums that don't support operator<<.
486 // (i.e. scoped enums where no operator<< overload was declared).
487 template <typename T>
488 inline typename std::enable_if<
489 !base::internal::SupportsOstreamOperator<const T&>::value &&
490 std::is_enum<T>::value,
491 void>::type
MakeCheckOpValueString(std::ostream * os,const T & v)492 MakeCheckOpValueString(std::ostream* os, const T& v) {
493 (*os) << static_cast<typename std::underlying_type<T>::type>(v);
494 }
495
496 // We need an explicit overload for std::nullptr_t.
497 void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
498
499 // Build the error message string. This is separate from the "Impl"
500 // function template because it is not performance critical and so can
501 // be out of line, while the "Impl" code should be inline. Caller
502 // takes ownership of the returned string.
503 template <class t1, class t2>
MakeCheckOpString(const t1 & v1,const t2 & v2,const char * names)504 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
505 std::ostringstream ss;
506 ss << names << " (";
507 MakeCheckOpValueString(&ss, v1);
508 ss << " vs. ";
509 MakeCheckOpValueString(&ss, v2);
510 ss << ")";
511 std::string* msg = new std::string(ss.str());
512 return msg;
513 }
514
515 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
516 // in logging.cc.
517 extern template std::string* MakeCheckOpString<int, int>(const int&,
518 const int&,
519 const char* names);
520 extern template std::string* MakeCheckOpString<unsigned long, unsigned long>(
521 const unsigned long&,
522 const unsigned long&,
523 const char* names);
524 extern template std::string* MakeCheckOpString<unsigned long, unsigned int>(
525 const unsigned long&,
526 const unsigned int&,
527 const char* names);
528 extern template std::string* MakeCheckOpString<unsigned int, unsigned long>(
529 const unsigned int&,
530 const unsigned long&,
531 const char* names);
532 extern template std::string* MakeCheckOpString<std::string, std::string>(
533 const std::string&,
534 const std::string&,
535 const char* name);
536
537 // Helper functions for CHECK_OP macro.
538 // The (int, int) specialization works around the issue that the compiler
539 // will not instantiate the template version of the function on values of
540 // unnamed enum type - see comment below.
541 //
542 // The checked condition is wrapped with ANALYZER_ASSUME_TRUE, which under
543 // static analysis builds, blocks analysis of the current path if the
544 // condition is false.
545 #define DEFINE_CHECK_OP_IMPL(name, op) \
546 template <class t1, class t2> \
547 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
548 const char* names) { \
549 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
550 return NULL; \
551 else \
552 return ::logging::MakeCheckOpString(v1, v2, names); \
553 } \
554 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
555 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
556 return NULL; \
557 else \
558 return ::logging::MakeCheckOpString(v1, v2, names); \
559 }
560 DEFINE_CHECK_OP_IMPL(EQ, ==)
561 DEFINE_CHECK_OP_IMPL(NE, !=)
562 DEFINE_CHECK_OP_IMPL(LE, <=)
563 DEFINE_CHECK_OP_IMPL(LT, <)
564 DEFINE_CHECK_OP_IMPL(GE, >=)
565 DEFINE_CHECK_OP_IMPL(GT, >)
566 #undef DEFINE_CHECK_OP_IMPL
567
568 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
569 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
570 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
571 #define CHECK_LT(val1, val2) CHECK_OP(LT, <, val1, val2)
572 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
573 #define CHECK_GT(val1, val2) CHECK_OP(GT, >, val1, val2)
574
575 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
576 #define DCHECK_IS_ON() 0
577 #else
578 #define DCHECK_IS_ON() 1
579 #endif
580
581 // Definitions for DLOG et al.
582
583 #if DCHECK_IS_ON()
584
585 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
586 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
587 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
588 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
589
590 #else // DCHECK_IS_ON()
591
592 // If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
593 // (which may reference a variable defined only if DCHECK_IS_ON()).
594 // Contrast this with DCHECK et al., which has different behavior.
595
596 #define DLOG_IS_ON(severity) false
597 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
598 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
599 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
600
601 #endif // DCHECK_IS_ON()
602
603 #define DLOG(severity) LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
604
605 #define DPLOG(severity) LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
606
607 // Definitions for DCHECK et al.
608
609 #if DCHECK_IS_ON()
610
611 #if DCHECK_IS_CONFIGURABLE
612 extern LogSeverity LOG_DCHECK;
613 #else
614 const LogSeverity LOG_DCHECK = LOG_FATAL;
615 #endif
616
617 #else // DCHECK_IS_ON()
618
619 // There may be users of LOG_DCHECK that are enabled independently
620 // of DCHECK_IS_ON(), so default to FATAL logging for those.
621 const LogSeverity LOG_DCHECK = LOG_FATAL;
622
623 #endif // DCHECK_IS_ON()
624
625 // DCHECK et al. make sure to reference |condition| regardless of
626 // whether DCHECKs are enabled; this is so that we don't get unused
627 // variable warnings if the only use of a variable is in a DCHECK.
628 // This behavior is different from DLOG_IF et al.
629 //
630 // Note that the definition of the DCHECK macros depends on whether or not
631 // DCHECK_IS_ON() is true. When DCHECK_IS_ON() is false, the macros use
632 // EAT_STREAM_PARAMETERS to avoid expressions that would create temporaries.
633
634 #if defined(_PREFAST_) && defined(OS_WIN)
635 // See comments on the previous use of __analysis_assume.
636
637 #define DCHECK(condition) \
638 __analysis_assume(!!(condition)), LAZY_STREAM(LOG_STREAM(DCHECK), false) \
639 << "Check failed: " #condition ". "
640
641 #define DPCHECK(condition) \
642 __analysis_assume(!!(condition)), LAZY_STREAM(PLOG_STREAM(DCHECK), false) \
643 << "Check failed: " #condition ". "
644
645 #else // !(defined(_PREFAST_) && defined(OS_WIN))
646
647 #if DCHECK_IS_ON()
648
649 #define DCHECK(condition) \
650 LAZY_STREAM(LOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
651 << "Check failed: " #condition ". "
652 #define DPCHECK(condition) \
653 LAZY_STREAM(PLOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
654 << "Check failed: " #condition ". "
655
656 #else // DCHECK_IS_ON()
657
658 #define DCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
659 #define DPCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
660
661 #endif // DCHECK_IS_ON()
662
663 #endif // defined(_PREFAST_) && defined(OS_WIN)
664
665 // Helper macro for binary operators.
666 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
667 // The 'switch' is used to prevent the 'else' from being ambiguous when the
668 // macro is used in an 'if' clause such as:
669 // if (a == 1)
670 // DCHECK_EQ(2, a);
671 #if DCHECK_IS_ON()
672
673 #define DCHECK_OP(name, op, val1, val2) \
674 switch (0) \
675 case 0: \
676 default: \
677 if (::logging::CheckOpResult true_if_passed = \
678 DCHECK_IS_ON() ? ::logging::Check##name##Impl( \
679 (val1), (val2), #val1 " " #op " " #val2) \
680 : nullptr) \
681 ; \
682 else \
683 ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
684 true_if_passed.message()) \
685 .stream()
686
687 #else // DCHECK_IS_ON()
688
689 // When DCHECKs aren't enabled, DCHECK_OP still needs to reference operator<<
690 // overloads for |val1| and |val2| to avoid potential compiler warnings about
691 // unused functions. For the same reason, it also compares |val1| and |val2|
692 // using |op|.
693 //
694 // Note that the contract of DCHECK_EQ, etc is that arguments are only evaluated
695 // once. Even though |val1| and |val2| appear twice in this version of the macro
696 // expansion, this is OK, since the expression is never actually evaluated.
697 #define DCHECK_OP(name, op, val1, val2) \
698 EAT_STREAM_PARAMETERS << (::logging::MakeCheckOpValueString( \
699 ::logging::g_swallow_stream, val1), \
700 ::logging::MakeCheckOpValueString( \
701 ::logging::g_swallow_stream, val2), \
702 (val1)op(val2))
703
704 #endif // DCHECK_IS_ON()
705
706 // Equality/Inequality checks - compare two values, and log a
707 // LOG_DCHECK message including the two values when the result is not
708 // as expected. The values must have operator<<(ostream, ...)
709 // defined.
710 //
711 // You may append to the error message like so:
712 // DCHECK_NE(1, 2) << "The world must be ending!";
713 //
714 // We are very careful to ensure that each argument is evaluated exactly
715 // once, and that anything which is legal to pass as a function argument is
716 // legal here. In particular, the arguments may be temporary expressions
717 // which will end up being destroyed at the end of the apparent statement,
718 // for example:
719 // DCHECK_EQ(string("abc")[1], 'b');
720 //
721 // WARNING: These don't compile correctly if one of the arguments is a pointer
722 // and the other is NULL. In new code, prefer nullptr instead. To
723 // work around this for C++98, simply static_cast NULL to the type of the
724 // desired pointer.
725
726 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
727 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
728 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
729 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, <, val1, val2)
730 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
731 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, >, val1, val2)
732
733 #define NOTREACHED() DCHECK(false)
734
735 // Redefine the standard assert to use our nice log files
736 #undef assert
737 #define assert(x) DLOG_ASSERT(x)
738
739 // This class more or less represents a particular log message. You
740 // create an instance of LogMessage and then stream stuff to it.
741 // When you finish streaming to it, ~LogMessage is called and the
742 // full message gets streamed to the appropriate destination.
743 //
744 // You shouldn't actually use LogMessage's constructor to log things,
745 // though. You should use the LOG() macro (and variants thereof)
746 // above.
747 class LogMessage {
748 public:
749 // Used for LOG(severity).
750 LogMessage(const char* file, int line, LogSeverity severity);
751
752 // Used for CHECK(). Implied severity = LOG_FATAL.
753 LogMessage(const char* file, int line, const char* condition);
754
755 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
756 // Implied severity = LOG_FATAL.
757 LogMessage(const char* file, int line, std::string* result);
758
759 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
760 LogMessage(const char* file,
761 int line,
762 LogSeverity severity,
763 std::string* result);
764
765 ~LogMessage();
766
stream()767 std::ostream& stream() { return stream_; }
768
severity()769 LogSeverity severity() { return severity_; }
str()770 std::string str() { return stream_.str(); }
771
772 private:
773 void Init(const char* file, int line);
774
775 LogSeverity severity_;
776 std::ostringstream stream_;
777 size_t message_start_; // Offset of the start of the message (past prefix
778 // info).
779
780 #if defined(OS_WIN)
781 // Stores the current value of GetLastError in the constructor and restores
782 // it in the destructor by calling SetLastError.
783 // This is useful since the LogMessage class uses a lot of Win32 calls
784 // that will lose the value of GLE and the code that called the log function
785 // will have lost the thread error value when the log call returns.
786 class SaveLastError {
787 public:
788 SaveLastError();
789 ~SaveLastError();
790
get_error()791 unsigned long get_error() const { return last_error_; }
792
793 protected:
794 unsigned long last_error_;
795 };
796
797 SaveLastError last_error_;
798 #endif
799
800 DISALLOW_COPY_AND_ASSIGN(LogMessage);
801 };
802
803 // This class is used to explicitly ignore values in the conditional
804 // logging macros. This avoids compiler warnings like "value computed
805 // is not used" and "statement has no effect".
806 class LogMessageVoidify {
807 public:
808 LogMessageVoidify() = default;
809 // This has to be an operator with a precedence lower than << but
810 // higher than ?:
811 void operator&(std::ostream&) {}
812 };
813
814 #if defined(OS_WIN)
815 typedef unsigned long SystemErrorCode;
816 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
817 typedef int SystemErrorCode;
818 #endif
819
820 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
821 // pull in windows.h just for GetLastError() and DWORD.
822 SystemErrorCode GetLastSystemErrorCode();
823 std::string SystemErrorCodeToString(SystemErrorCode error_code);
824
825 #if defined(OS_WIN)
826 // Appends a formatted system message of the GetLastError() type.
827 class Win32ErrorLogMessage {
828 public:
829 Win32ErrorLogMessage(const char* file,
830 int line,
831 LogSeverity severity,
832 SystemErrorCode err);
833
834 // Appends the error message before destructing the encapsulated class.
835 ~Win32ErrorLogMessage();
836
stream()837 std::ostream& stream() { return log_message_.stream(); }
838
839 private:
840 SystemErrorCode err_;
841 LogMessage log_message_;
842
843 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
844 };
845 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
846 // Appends a formatted system message of the errno type
847 class ErrnoLogMessage {
848 public:
849 ErrnoLogMessage(const char* file,
850 int line,
851 LogSeverity severity,
852 SystemErrorCode err);
853
854 // Appends the error message before destructing the encapsulated class.
855 ~ErrnoLogMessage();
856
stream()857 std::ostream& stream() { return log_message_.stream(); }
858
859 private:
860 SystemErrorCode err_;
861 LogMessage log_message_;
862
863 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
864 };
865 #endif // OS_WIN
866
867 // Closes the log file explicitly if open.
868 // NOTE: Since the log file is opened as necessary by the action of logging
869 // statements, there's no guarantee that it will stay closed
870 // after this call.
871 void CloseLogFile();
872
873 // Async signal safe logging mechanism.
874 void RawLog(int level, const char* message);
875
876 #define RAW_LOG(level, message) \
877 ::logging::RawLog(::logging::LOG_##level, message)
878
879 #define RAW_CHECK(condition) \
880 do { \
881 if (!(condition)) \
882 ::logging::RawLog(::logging::LOG_FATAL, \
883 "Check failed: " #condition "\n"); \
884 } while (0)
885
886 #if defined(OS_WIN)
887 // Returns true if logging to file is enabled.
888 bool IsLoggingToFileEnabled();
889
890 // Returns the default log file path.
891 std::u16string GetLogFileFullPath();
892 #endif
893
894 } // namespace logging
895
896 // The NOTIMPLEMENTED() macro annotates codepaths which have not been
897 // implemented yet. If output spam is a serious concern,
898 // NOTIMPLEMENTED_LOG_ONCE can be used.
899
900 #if defined(COMPILER_GCC)
901 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
902 // of the current function in the NOTIMPLEMENTED message.
903 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
904 #else
905 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
906 #endif
907
908 #if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
909 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
910 #define NOTIMPLEMENTED_LOG_ONCE() EAT_STREAM_PARAMETERS
911 #else
912 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
913 #define NOTIMPLEMENTED_LOG_ONCE() \
914 do { \
915 static bool logged_once = false; \
916 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG; \
917 logged_once = true; \
918 } while (0); \
919 EAT_STREAM_PARAMETERS
920 #endif
921
922 #endif // BASE_LOGGING_H_
923