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