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