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