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