security/sandbox/chromium/base/logging.h

Wed, 31 Dec 2014 07:16:47 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 07:16:47 +0100
branch
TOR_BUG_9701
changeset 3
141e0f1194b1
permissions
-rw-r--r--

Revert simplistic fix pending revisit of Mozilla integration attempt.

     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.
     5 #ifndef BASE_LOGGING_H_
     6 #define BASE_LOGGING_H_
     8 #include <cassert>
     9 #include <string>
    10 #include <cstring>
    11 #include <sstream>
    13 #include "base/base_export.h"
    14 #include "base/basictypes.h"
    15 #include "base/debug/debugger.h"
    16 #include "build/build_config.h"
    18 //
    19 // Optional message capabilities
    20 // -----------------------------
    21 // Assertion failed messages and fatal errors are displayed in a dialog box
    22 // before the application exits. However, running this UI creates a message
    23 // loop, which causes application messages to be processed and potentially
    24 // dispatched to existing application windows. Since the application is in a
    25 // bad state when this assertion dialog is displayed, these messages may not
    26 // get processed and hang the dialog, or the application might go crazy.
    27 //
    28 // Therefore, it can be beneficial to display the error dialog in a separate
    29 // process from the main application. When the logging system needs to display
    30 // a fatal error dialog box, it will look for a program called
    31 // "DebugMessage.exe" in the same directory as the application executable. It
    32 // will run this application with the message as the command line, and will
    33 // not include the name of the application as is traditional for easier
    34 // parsing.
    35 //
    36 // The code for DebugMessage.exe is only one line. In WinMain, do:
    37 //   MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
    38 //
    39 // If DebugMessage.exe is not found, the logging code will use a normal
    40 // MessageBox, potentially causing the problems discussed above.
    43 // Instructions
    44 // ------------
    45 //
    46 // Make a bunch of macros for logging.  The way to log things is to stream
    47 // things to LOG(<a particular severity level>).  E.g.,
    48 //
    49 //   LOG(INFO) << "Found " << num_cookies << " cookies";
    50 //
    51 // You can also do conditional logging:
    52 //
    53 //   LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
    54 //
    55 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
    56 // times it is executed.  Note that the special COUNTER value is used to
    57 // identify which repetition is happening.
    58 //
    59 // The CHECK(condition) macro is active in both debug and release builds and
    60 // effectively performs a LOG(FATAL) which terminates the process and
    61 // generates a crashdump unless a debugger is attached.
    62 //
    63 // There are also "debug mode" logging macros like the ones above:
    64 //
    65 //   DLOG(INFO) << "Found cookies";
    66 //
    67 //   DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
    68 //
    69 // All "debug mode" logging is compiled away to nothing for non-debug mode
    70 // compiles.  LOG_IF and development flags also work well together
    71 // because the code can be compiled away sometimes.
    72 //
    73 // We also have
    74 //
    75 //   LOG_ASSERT(assertion);
    76 //   DLOG_ASSERT(assertion);
    77 //
    78 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
    79 //
    80 // There are "verbose level" logging macros.  They look like
    81 //
    82 //   VLOG(1) << "I'm printed when you run the program with --v=1 or more";
    83 //   VLOG(2) << "I'm printed when you run the program with --v=2 or more";
    84 //
    85 // These always log at the INFO log level (when they log at all).
    86 // The verbose logging can also be turned on module-by-module.  For instance,
    87 //    --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
    88 // will cause:
    89 //   a. VLOG(2) and lower messages to be printed from profile.{h,cc}
    90 //   b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
    91 //   c. VLOG(3) and lower messages to be printed from files prefixed with
    92 //      "browser"
    93 //   d. VLOG(4) and lower messages to be printed from files under a
    94 //     "chromeos" directory.
    95 //   e. VLOG(0) and lower messages to be printed from elsewhere
    96 //
    97 // The wildcarding functionality shown by (c) supports both '*' (match
    98 // 0 or more characters) and '?' (match any single character)
    99 // wildcards.  Any pattern containing a forward or backward slash will
   100 // be tested against the whole pathname and not just the module.
   101 // E.g., "*/foo/bar/*=2" would change the logging level for all code
   102 // in source files under a "foo/bar" directory.
   103 //
   104 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
   105 //
   106 //   if (VLOG_IS_ON(2)) {
   107 //     // do some logging preparation and logging
   108 //     // that can't be accomplished with just VLOG(2) << ...;
   109 //   }
   110 //
   111 // There is also a VLOG_IF "verbose level" condition macro for sample
   112 // cases, when some extra computation and preparation for logs is not
   113 // needed.
   114 //
   115 //   VLOG_IF(1, (size > 1024))
   116 //      << "I'm printed when size is more than 1024 and when you run the "
   117 //         "program with --v=1 or more";
   118 //
   119 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
   120 //
   121 // Lastly, there is:
   122 //
   123 //   PLOG(ERROR) << "Couldn't do foo";
   124 //   DPLOG(ERROR) << "Couldn't do foo";
   125 //   PLOG_IF(ERROR, cond) << "Couldn't do foo";
   126 //   DPLOG_IF(ERROR, cond) << "Couldn't do foo";
   127 //   PCHECK(condition) << "Couldn't do foo";
   128 //   DPCHECK(condition) << "Couldn't do foo";
   129 //
   130 // which append the last system error to the message in string form (taken from
   131 // GetLastError() on Windows and errno on POSIX).
   132 //
   133 // The supported severity levels for macros that allow you to specify one
   134 // are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
   135 // and FATAL.
   136 //
   137 // Very important: logging a message at the FATAL severity level causes
   138 // the program to terminate (after the message is logged).
   139 //
   140 // Note the special severity of ERROR_REPORT only available/relevant in normal
   141 // mode, which displays error dialog without terminating the program. There is
   142 // no error dialog for severity ERROR or below in normal mode.
   143 //
   144 // There is also the special severity of DFATAL, which logs FATAL in
   145 // debug mode, ERROR in normal mode.
   147 namespace logging {
   149 // TODO(avi): do we want to do a unification of character types here?
   150 #if defined(OS_WIN)
   151 typedef wchar_t PathChar;
   152 #else
   153 typedef char PathChar;
   154 #endif
   156 // Where to record logging output? A flat file and/or system debug log
   157 // via OutputDebugString.
   158 enum LoggingDestination {
   159   LOG_NONE                = 0,
   160   LOG_TO_FILE             = 1 << 0,
   161   LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
   163   LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
   165   // On Windows, use a file next to the exe; on POSIX platforms, where
   166   // it may not even be possible to locate the executable on disk, use
   167   // stderr.
   168 #if defined(OS_WIN)
   169   LOG_DEFAULT = LOG_TO_FILE,
   170 #elif defined(OS_POSIX)
   171   LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
   172 #endif
   173 };
   175 // Indicates that the log file should be locked when being written to.
   176 // Unless there is only one single-threaded process that is logging to
   177 // the log file, the file should be locked during writes to make each
   178 // log outut atomic. Other writers will block.
   179 //
   180 // All processes writing to the log file must have their locking set for it to
   181 // work properly. Defaults to LOCK_LOG_FILE.
   182 enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
   184 // On startup, should we delete or append to an existing log file (if any)?
   185 // Defaults to APPEND_TO_OLD_LOG_FILE.
   186 enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
   188 enum DcheckState {
   189   DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS,
   190   ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
   191 };
   193 struct BASE_EXPORT LoggingSettings {
   194   // The defaults values are:
   195   //
   196   //  logging_dest: LOG_DEFAULT
   197   //  log_file:     NULL
   198   //  lock_log:     LOCK_LOG_FILE
   199   //  delete_old:   APPEND_TO_OLD_LOG_FILE
   200   //  dcheck_state: DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
   201   LoggingSettings();
   203   LoggingDestination logging_dest;
   205   // The three settings below have an effect only when LOG_TO_FILE is
   206   // set in |logging_dest|.
   207   const PathChar* log_file;
   208   LogLockingState lock_log;
   209   OldFileDeletionState delete_old;
   211   DcheckState dcheck_state;
   212 };
   214 // Define different names for the BaseInitLoggingImpl() function depending on
   215 // whether NDEBUG is defined or not so that we'll fail to link if someone tries
   216 // to compile logging.cc with NDEBUG but includes logging.h without defining it,
   217 // or vice versa.
   218 #if NDEBUG
   219 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
   220 #else
   221 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
   222 #endif
   224 // Implementation of the InitLogging() method declared below.  We use a
   225 // more-specific name so we can #define it above without affecting other code
   226 // that has named stuff "InitLogging".
   227 BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
   229 // Sets the log file name and other global logging state. Calling this function
   230 // is recommended, and is normally done at the beginning of application init.
   231 // If you don't call it, all the flags will be initialized to their default
   232 // values, and there is a race condition that may leak a critical section
   233 // object if two threads try to do the first log at the same time.
   234 // See the definition of the enums above for descriptions and default values.
   235 //
   236 // The default log file is initialized to "debug.log" in the application
   237 // directory. You probably don't want this, especially since the program
   238 // directory may not be writable on an enduser's system.
   239 //
   240 // This function may be called a second time to re-direct logging (e.g after
   241 // loging in to a user partition), however it should never be called more than
   242 // twice.
   243 inline bool InitLogging(const LoggingSettings& settings) {
   244   return BaseInitLoggingImpl(settings);
   245 }
   247 // Sets the log level. Anything at or above this level will be written to the
   248 // log file/displayed to the user (if applicable). Anything below this level
   249 // will be silently ignored. The log level defaults to 0 (everything is logged
   250 // up to level INFO) if this function is not called.
   251 // Note that log messages for VLOG(x) are logged at level -x, so setting
   252 // the min log level to negative values enables verbose logging.
   253 BASE_EXPORT void SetMinLogLevel(int level);
   255 // Gets the current log level.
   256 BASE_EXPORT int GetMinLogLevel();
   258 // Gets the VLOG default verbosity level.
   259 BASE_EXPORT int GetVlogVerbosity();
   261 // Gets the current vlog level for the given file (usually taken from
   262 // __FILE__).
   264 // Note that |N| is the size *with* the null terminator.
   265 BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
   267 template <size_t N>
   268 int GetVlogLevel(const char (&file)[N]) {
   269   return GetVlogLevelHelper(file, N);
   270 }
   272 // Sets the common items you want to be prepended to each log message.
   273 // process and thread IDs default to off, the timestamp defaults to on.
   274 // If this function is not called, logging defaults to writing the timestamp
   275 // only.
   276 BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
   277                              bool enable_timestamp, bool enable_tickcount);
   279 // Sets whether or not you'd like to see fatal debug messages popped up in
   280 // a dialog box or not.
   281 // Dialogs are not shown by default.
   282 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
   284 // Sets the Log Assert Handler that will be used to notify of check failures.
   285 // The default handler shows a dialog box and then terminate the process,
   286 // however clients can use this function to override with their own handling
   287 // (e.g. a silent one for Unit Tests)
   288 typedef void (*LogAssertHandlerFunction)(const std::string& str);
   289 BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
   291 // Sets the Log Report Handler that will be used to notify of check failures
   292 // in non-debug mode. The default handler shows a dialog box and continues
   293 // the execution, however clients can use this function to override with their
   294 // own handling.
   295 typedef void (*LogReportHandlerFunction)(const std::string& str);
   296 BASE_EXPORT void SetLogReportHandler(LogReportHandlerFunction handler);
   298 // Sets the Log Message Handler that gets passed every log message before
   299 // it's sent to other log destinations (if any).
   300 // Returns true to signal that it handled the message and the message
   301 // should not be sent to other log destinations.
   302 typedef bool (*LogMessageHandlerFunction)(int severity,
   303     const char* file, int line, size_t message_start, const std::string& str);
   304 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
   305 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
   307 typedef int LogSeverity;
   308 const LogSeverity LOG_VERBOSE = -1;  // This is level 1 verbosity
   309 // Note: the log severities are used to index into the array of names,
   310 // see log_severity_names.
   311 const LogSeverity LOG_INFO = 0;
   312 const LogSeverity LOG_WARNING = 1;
   313 const LogSeverity LOG_ERROR = 2;
   314 const LogSeverity LOG_ERROR_REPORT = 3;
   315 const LogSeverity LOG_FATAL = 4;
   316 const LogSeverity LOG_NUM_SEVERITIES = 5;
   318 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
   319 #ifdef NDEBUG
   320 const LogSeverity LOG_DFATAL = LOG_ERROR;
   321 #else
   322 const LogSeverity LOG_DFATAL = LOG_FATAL;
   323 #endif
   325 // A few definitions of macros that don't generate much code. These are used
   326 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
   327 // better to have compact code for these operations.
   328 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
   329   logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
   330 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
   331   logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
   332 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
   333   logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
   334 #define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
   335   logging::ClassName(__FILE__, __LINE__, \
   336                      logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
   337 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
   338   logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
   339 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
   340   logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
   342 #define COMPACT_GOOGLE_LOG_INFO \
   343   COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
   344 #define COMPACT_GOOGLE_LOG_WARNING \
   345   COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
   346 #define COMPACT_GOOGLE_LOG_ERROR \
   347   COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
   348 #define COMPACT_GOOGLE_LOG_ERROR_REPORT \
   349   COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
   350 #define COMPACT_GOOGLE_LOG_FATAL \
   351   COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
   352 #define COMPACT_GOOGLE_LOG_DFATAL \
   353   COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
   355 #if defined(OS_WIN)
   356 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
   357 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
   358 // to keep using this syntax, we define this macro to do the same thing
   359 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
   360 // the Windows SDK does for consistency.
   361 #define ERROR 0
   362 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
   363   COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
   364 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
   365 // Needed for LOG_IS_ON(ERROR).
   366 const LogSeverity LOG_0 = LOG_ERROR;
   367 #endif
   369 // As special cases, we can assume that LOG_IS_ON(ERROR_REPORT) and
   370 // LOG_IS_ON(FATAL) always hold.  Also, LOG_IS_ON(DFATAL) always holds
   371 // in debug mode.  In particular, CHECK()s will always fire if they
   372 // fail.
   373 #define LOG_IS_ON(severity) \
   374   ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel())
   376 // We can't do any caching tricks with VLOG_IS_ON() like the
   377 // google-glog version since it requires GCC extensions.  This means
   378 // that using the v-logging functions in conjunction with --vmodule
   379 // may be slow.
   380 #define VLOG_IS_ON(verboselevel) \
   381   ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
   383 // Helper macro which avoids evaluating the arguments to a stream if
   384 // the condition doesn't hold.
   385 #define LAZY_STREAM(stream, condition)                                  \
   386   !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
   388 // We use the preprocessor's merging operator, "##", so that, e.g.,
   389 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO.  There's some funny
   390 // subtle difference between ostream member streaming functions (e.g.,
   391 // ostream::operator<<(int) and ostream non-member streaming functions
   392 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
   393 // impossible to stream something like a string directly to an unnamed
   394 // ostream. We employ a neat hack by calling the stream() member
   395 // function of LogMessage which seems to avoid the problem.
   396 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
   398 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
   399 #define LOG_IF(severity, condition) \
   400   LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
   402 #define SYSLOG(severity) LOG(severity)
   403 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
   405 // The VLOG macros log with negative verbosities.
   406 #define VLOG_STREAM(verbose_level) \
   407   logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
   409 #define VLOG(verbose_level) \
   410   LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
   412 #define VLOG_IF(verbose_level, condition) \
   413   LAZY_STREAM(VLOG_STREAM(verbose_level), \
   414       VLOG_IS_ON(verbose_level) && (condition))
   416 #if defined (OS_WIN)
   417 #define VPLOG_STREAM(verbose_level) \
   418   logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
   419     ::logging::GetLastSystemErrorCode()).stream()
   420 #elif defined(OS_POSIX)
   421 #define VPLOG_STREAM(verbose_level) \
   422   logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
   423     ::logging::GetLastSystemErrorCode()).stream()
   424 #endif
   426 #define VPLOG(verbose_level) \
   427   LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
   429 #define VPLOG_IF(verbose_level, condition) \
   430   LAZY_STREAM(VPLOG_STREAM(verbose_level), \
   431     VLOG_IS_ON(verbose_level) && (condition))
   433 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
   435 #define LOG_ASSERT(condition)  \
   436   LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
   437 #define SYSLOG_ASSERT(condition) \
   438   SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
   440 #if defined(OS_WIN)
   441 #define LOG_GETLASTERROR_STREAM(severity) \
   442   COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
   443       ::logging::GetLastSystemErrorCode()).stream()
   444 #define LOG_GETLASTERROR(severity) \
   445   LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), LOG_IS_ON(severity))
   446 #define LOG_GETLASTERROR_MODULE_STREAM(severity, module) \
   447   COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
   448       ::logging::GetLastSystemErrorCode(), module).stream()
   449 #define LOG_GETLASTERROR_MODULE(severity, module)                       \
   450   LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module),                \
   451               LOG_IS_ON(severity))
   452 // PLOG_STREAM is used by PLOG, which is the usual error logging macro
   453 // for each platform.
   454 #define PLOG_STREAM(severity) LOG_GETLASTERROR_STREAM(severity)
   455 #elif defined(OS_POSIX)
   456 #define LOG_ERRNO_STREAM(severity) \
   457   COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
   458       ::logging::GetLastSystemErrorCode()).stream()
   459 #define LOG_ERRNO(severity) \
   460   LAZY_STREAM(LOG_ERRNO_STREAM(severity), LOG_IS_ON(severity))
   461 // PLOG_STREAM is used by PLOG, which is the usual error logging macro
   462 // for each platform.
   463 #define PLOG_STREAM(severity) LOG_ERRNO_STREAM(severity)
   464 #endif
   466 #define PLOG(severity)                                          \
   467   LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
   469 #define PLOG_IF(severity, condition) \
   470   LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
   472 #if !defined(NDEBUG)
   473 // Debug builds always include DCHECK and DLOG.
   474 #undef LOGGING_IS_OFFICIAL_BUILD
   475 #define LOGGING_IS_OFFICIAL_BUILD 0
   476 #elif defined(OFFICIAL_BUILD)
   477 // Official release builds always disable and remove DCHECK and DLOG.
   478 #undef LOGGING_IS_OFFICIAL_BUILD
   479 #define LOGGING_IS_OFFICIAL_BUILD 1
   480 #elif !defined(LOGGING_IS_OFFICIAL_BUILD)
   481 // Unless otherwise specified, unofficial release builds include
   482 // DCHECK and DLOG.
   483 #define LOGGING_IS_OFFICIAL_BUILD 0
   484 #endif
   486 // The actual stream used isn't important.
   487 #define EAT_STREAM_PARAMETERS                                           \
   488   true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
   490 // CHECK dies with a fatal error if condition is not true.  It is *not*
   491 // controlled by NDEBUG, so the check will be executed regardless of
   492 // compilation mode.
   493 //
   494 // We make sure CHECK et al. always evaluates their arguments, as
   495 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
   497 #if LOGGING_IS_OFFICIAL_BUILD
   499 // Make all CHECK functions discard their log strings to reduce code
   500 // bloat for official builds.
   502 // TODO(akalin): This would be more valuable if there were some way to
   503 // remove BreakDebugger() from the backtrace, perhaps by turning it
   504 // into a macro (like __debugbreak() on Windows).
   505 #define CHECK(condition)                                                \
   506   !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
   508 #define PCHECK(condition) CHECK(condition)
   510 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
   512 #else
   514 #define CHECK(condition)                       \
   515   LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \
   516   << "Check failed: " #condition ". "
   518 #define PCHECK(condition) \
   519   LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
   520   << "Check failed: " #condition ". "
   522 // Helper macro for binary operators.
   523 // Don't use this macro directly in your code, use CHECK_EQ et al below.
   524 //
   525 // TODO(akalin): Rewrite this so that constructs like if (...)
   526 // CHECK_EQ(...) else { ... } work properly.
   527 #define CHECK_OP(name, op, val1, val2)                          \
   528   if (std::string* _result =                                    \
   529       logging::Check##name##Impl((val1), (val2),                \
   530                                  #val1 " " #op " " #val2))      \
   531     logging::LogMessage(__FILE__, __LINE__, _result).stream()
   533 #endif
   535 // Build the error message string.  This is separate from the "Impl"
   536 // function template because it is not performance critical and so can
   537 // be out of line, while the "Impl" code should be inline.  Caller
   538 // takes ownership of the returned string.
   539 template<class t1, class t2>
   540 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
   541   std::ostringstream ss;
   542   ss << names << " (" << v1 << " vs. " << v2 << ")";
   543   std::string* msg = new std::string(ss.str());
   544   return msg;
   545 }
   547 // MSVC doesn't like complex extern templates and DLLs.
   548 #if !defined(COMPILER_MSVC)
   549 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
   550 // in logging.cc.
   551 extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
   552     const int&, const int&, const char* names);
   553 extern template BASE_EXPORT
   554 std::string* MakeCheckOpString<unsigned long, unsigned long>(
   555     const unsigned long&, const unsigned long&, const char* names);
   556 extern template BASE_EXPORT
   557 std::string* MakeCheckOpString<unsigned long, unsigned int>(
   558     const unsigned long&, const unsigned int&, const char* names);
   559 extern template BASE_EXPORT
   560 std::string* MakeCheckOpString<unsigned int, unsigned long>(
   561     const unsigned int&, const unsigned long&, const char* names);
   562 extern template BASE_EXPORT
   563 std::string* MakeCheckOpString<std::string, std::string>(
   564     const std::string&, const std::string&, const char* name);
   565 #endif
   567 // Helper functions for CHECK_OP macro.
   568 // The (int, int) specialization works around the issue that the compiler
   569 // will not instantiate the template version of the function on values of
   570 // unnamed enum type - see comment below.
   571 #define DEFINE_CHECK_OP_IMPL(name, op) \
   572   template <class t1, class t2> \
   573   inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
   574                                         const char* names) { \
   575     if (v1 op v2) return NULL; \
   576     else return MakeCheckOpString(v1, v2, names); \
   577   } \
   578   inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
   579     if (v1 op v2) return NULL; \
   580     else return MakeCheckOpString(v1, v2, names); \
   581   }
   582 DEFINE_CHECK_OP_IMPL(EQ, ==)
   583 DEFINE_CHECK_OP_IMPL(NE, !=)
   584 DEFINE_CHECK_OP_IMPL(LE, <=)
   585 DEFINE_CHECK_OP_IMPL(LT, < )
   586 DEFINE_CHECK_OP_IMPL(GE, >=)
   587 DEFINE_CHECK_OP_IMPL(GT, > )
   588 #undef DEFINE_CHECK_OP_IMPL
   590 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
   591 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
   592 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
   593 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
   594 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
   595 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
   597 #if LOGGING_IS_OFFICIAL_BUILD
   598 // In order to have optimized code for official builds, remove DLOGs and
   599 // DCHECKs.
   600 #define ENABLE_DLOG 0
   601 #define ENABLE_DCHECK 0
   603 #elif defined(NDEBUG)
   604 // Otherwise, if we're a release build, remove DLOGs but not DCHECKs
   605 // (since those can still be turned on via a command-line flag).
   606 #define ENABLE_DLOG 0
   607 #define ENABLE_DCHECK 1
   609 #else
   610 // Otherwise, we're a debug build so enable DLOGs and DCHECKs.
   611 #define ENABLE_DLOG 1
   612 #define ENABLE_DCHECK 1
   613 #endif
   615 // Definitions for DLOG et al.
   617 #if ENABLE_DLOG
   619 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
   620 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
   621 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
   622 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
   623 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
   624 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
   626 #else  // ENABLE_DLOG
   628 // If ENABLE_DLOG is off, we want to avoid emitting any references to
   629 // |condition| (which may reference a variable defined only if NDEBUG
   630 // is not defined).  Contrast this with DCHECK et al., which has
   631 // different behavior.
   633 #define DLOG_IS_ON(severity) false
   634 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
   635 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
   636 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
   637 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
   638 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
   640 #endif  // ENABLE_DLOG
   642 // DEBUG_MODE is for uses like
   643 //   if (DEBUG_MODE) foo.CheckThatFoo();
   644 // instead of
   645 //   #ifndef NDEBUG
   646 //     foo.CheckThatFoo();
   647 //   #endif
   648 //
   649 // We tie its state to ENABLE_DLOG.
   650 enum { DEBUG_MODE = ENABLE_DLOG };
   652 #undef ENABLE_DLOG
   654 #define DLOG(severity)                                          \
   655   LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
   657 #if defined(OS_WIN)
   658 #define DLOG_GETLASTERROR(severity) \
   659   LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), DLOG_IS_ON(severity))
   660 #define DLOG_GETLASTERROR_MODULE(severity, module)                      \
   661   LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module),                \
   662               DLOG_IS_ON(severity))
   663 #elif defined(OS_POSIX)
   664 #define DLOG_ERRNO(severity)                                    \
   665   LAZY_STREAM(LOG_ERRNO_STREAM(severity), DLOG_IS_ON(severity))
   666 #endif
   668 #define DPLOG(severity)                                         \
   669   LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
   671 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
   673 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
   675 // Definitions for DCHECK et al.
   677 #if ENABLE_DCHECK
   679 #if defined(NDEBUG)
   681 BASE_EXPORT DcheckState get_dcheck_state();
   682 BASE_EXPORT void set_dcheck_state(DcheckState state);
   684 #if defined(DCHECK_ALWAYS_ON)
   686 #define DCHECK_IS_ON() true
   687 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
   688   COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
   689 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
   690 const LogSeverity LOG_DCHECK = LOG_FATAL;
   692 #else
   694 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
   695   COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName , ##__VA_ARGS__)
   696 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_ERROR_REPORT
   697 const LogSeverity LOG_DCHECK = LOG_ERROR_REPORT;
   698 #define DCHECK_IS_ON()                                                  \
   699   ((::logging::get_dcheck_state() ==                                        \
   700     ::logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) &&        \
   701    LOG_IS_ON(DCHECK))
   703 #endif  // defined(DCHECK_ALWAYS_ON)
   705 #else  // defined(NDEBUG)
   707 // On a regular debug build, we want to have DCHECKs enabled.
   708 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
   709   COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
   710 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
   711 const LogSeverity LOG_DCHECK = LOG_FATAL;
   712 #define DCHECK_IS_ON() true
   714 #endif  // defined(NDEBUG)
   716 #else  // ENABLE_DCHECK
   718 // These are just dummy values since DCHECK_IS_ON() is always false in
   719 // this case.
   720 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
   721   COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
   722 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
   723 const LogSeverity LOG_DCHECK = LOG_INFO;
   724 #define DCHECK_IS_ON() false
   726 #endif  // ENABLE_DCHECK
   727 #undef ENABLE_DCHECK
   729 // DCHECK et al. make sure to reference |condition| regardless of
   730 // whether DCHECKs are enabled; this is so that we don't get unused
   731 // variable warnings if the only use of a variable is in a DCHECK.
   732 // This behavior is different from DLOG_IF et al.
   734 #define DCHECK(condition)                                           \
   735   LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition))   \
   736   << "Check failed: " #condition ". "
   738 #define DPCHECK(condition)                                          \
   739   LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition))  \
   740   << "Check failed: " #condition ". "
   742 // Helper macro for binary operators.
   743 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
   744 #define DCHECK_OP(name, op, val1, val2)                         \
   745   if (DCHECK_IS_ON())                                           \
   746     if (std::string* _result =                                  \
   747         logging::Check##name##Impl((val1), (val2),              \
   748                                    #val1 " " #op " " #val2))    \
   749       logging::LogMessage(                                      \
   750           __FILE__, __LINE__, ::logging::LOG_DCHECK,            \
   751           _result).stream()
   753 // Equality/Inequality checks - compare two values, and log a
   754 // LOG_DCHECK message including the two values when the result is not
   755 // as expected.  The values must have operator<<(ostream, ...)
   756 // defined.
   757 //
   758 // You may append to the error message like so:
   759 //   DCHECK_NE(1, 2) << ": The world must be ending!";
   760 //
   761 // We are very careful to ensure that each argument is evaluated exactly
   762 // once, and that anything which is legal to pass as a function argument is
   763 // legal here.  In particular, the arguments may be temporary expressions
   764 // which will end up being destroyed at the end of the apparent statement,
   765 // for example:
   766 //   DCHECK_EQ(string("abc")[1], 'b');
   767 //
   768 // WARNING: These may not compile correctly if one of the arguments is a pointer
   769 // and the other is NULL. To work around this, simply static_cast NULL to the
   770 // type of the desired pointer.
   772 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
   773 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
   774 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
   775 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
   776 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
   777 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
   779 #define NOTREACHED() DCHECK(false)
   781 // Redefine the standard assert to use our nice log files
   782 #undef assert
   783 #define assert(x) DLOG_ASSERT(x)
   785 // This class more or less represents a particular log message.  You
   786 // create an instance of LogMessage and then stream stuff to it.
   787 // When you finish streaming to it, ~LogMessage is called and the
   788 // full message gets streamed to the appropriate destination.
   789 //
   790 // You shouldn't actually use LogMessage's constructor to log things,
   791 // though.  You should use the LOG() macro (and variants thereof)
   792 // above.
   793 class BASE_EXPORT LogMessage {
   794  public:
   795   LogMessage(const char* file, int line, LogSeverity severity, int ctr);
   797   // Two special constructors that generate reduced amounts of code at
   798   // LOG call sites for common cases.
   799   //
   800   // Used for LOG(INFO): Implied are:
   801   // severity = LOG_INFO, ctr = 0
   802   //
   803   // Using this constructor instead of the more complex constructor above
   804   // saves a couple of bytes per call site.
   805   LogMessage(const char* file, int line);
   807   // Used for LOG(severity) where severity != INFO.  Implied
   808   // are: ctr = 0
   809   //
   810   // Using this constructor instead of the more complex constructor above
   811   // saves a couple of bytes per call site.
   812   LogMessage(const char* file, int line, LogSeverity severity);
   814   // A special constructor used for check failures.  Takes ownership
   815   // of the given string.
   816   // Implied severity = LOG_FATAL
   817   LogMessage(const char* file, int line, std::string* result);
   819   // A special constructor used for check failures, with the option to
   820   // specify severity.  Takes ownership of the given string.
   821   LogMessage(const char* file, int line, LogSeverity severity,
   822              std::string* result);
   824   ~LogMessage();
   826   std::ostream& stream() { return stream_; }
   828  private:
   829   void Init(const char* file, int line);
   831   LogSeverity severity_;
   832   std::ostringstream stream_;
   833   size_t message_start_;  // Offset of the start of the message (past prefix
   834                           // info).
   835   // The file and line information passed in to the constructor.
   836   const char* file_;
   837   const int line_;
   839 #if defined(OS_WIN)
   840   // Stores the current value of GetLastError in the constructor and restores
   841   // it in the destructor by calling SetLastError.
   842   // This is useful since the LogMessage class uses a lot of Win32 calls
   843   // that will lose the value of GLE and the code that called the log function
   844   // will have lost the thread error value when the log call returns.
   845   class SaveLastError {
   846    public:
   847     SaveLastError();
   848     ~SaveLastError();
   850     unsigned long get_error() const { return last_error_; }
   852    protected:
   853     unsigned long last_error_;
   854   };
   856   SaveLastError last_error_;
   857 #endif
   859   DISALLOW_COPY_AND_ASSIGN(LogMessage);
   860 };
   862 // A non-macro interface to the log facility; (useful
   863 // when the logging level is not a compile-time constant).
   864 inline void LogAtLevel(int const log_level, std::string const &msg) {
   865   LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
   866 }
   868 // This class is used to explicitly ignore values in the conditional
   869 // logging macros.  This avoids compiler warnings like "value computed
   870 // is not used" and "statement has no effect".
   871 class LogMessageVoidify {
   872  public:
   873   LogMessageVoidify() { }
   874   // This has to be an operator with a precedence lower than << but
   875   // higher than ?:
   876   void operator&(std::ostream&) { }
   877 };
   879 #if defined(OS_WIN)
   880 typedef unsigned long SystemErrorCode;
   881 #elif defined(OS_POSIX)
   882 typedef int SystemErrorCode;
   883 #endif
   885 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
   886 // pull in windows.h just for GetLastError() and DWORD.
   887 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
   889 #if defined(OS_WIN)
   890 // Appends a formatted system message of the GetLastError() type.
   891 class BASE_EXPORT Win32ErrorLogMessage {
   892  public:
   893   Win32ErrorLogMessage(const char* file,
   894                        int line,
   895                        LogSeverity severity,
   896                        SystemErrorCode err,
   897                        const char* module);
   899   Win32ErrorLogMessage(const char* file,
   900                        int line,
   901                        LogSeverity severity,
   902                        SystemErrorCode err);
   904   // Appends the error message before destructing the encapsulated class.
   905   ~Win32ErrorLogMessage();
   907   std::ostream& stream() { return log_message_.stream(); }
   909  private:
   910   SystemErrorCode err_;
   911   // Optional name of the module defining the error.
   912   const char* module_;
   913   LogMessage log_message_;
   915   DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
   916 };
   917 #elif defined(OS_POSIX)
   918 // Appends a formatted system message of the errno type
   919 class BASE_EXPORT ErrnoLogMessage {
   920  public:
   921   ErrnoLogMessage(const char* file,
   922                   int line,
   923                   LogSeverity severity,
   924                   SystemErrorCode err);
   926   // Appends the error message before destructing the encapsulated class.
   927   ~ErrnoLogMessage();
   929   std::ostream& stream() { return log_message_.stream(); }
   931  private:
   932   SystemErrorCode err_;
   933   LogMessage log_message_;
   935   DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
   936 };
   937 #endif  // OS_WIN
   939 // Closes the log file explicitly if open.
   940 // NOTE: Since the log file is opened as necessary by the action of logging
   941 //       statements, there's no guarantee that it will stay closed
   942 //       after this call.
   943 BASE_EXPORT void CloseLogFile();
   945 // Async signal safe logging mechanism.
   946 BASE_EXPORT void RawLog(int level, const char* message);
   948 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
   950 #define RAW_CHECK(condition)                                                   \
   951   do {                                                                         \
   952     if (!(condition))                                                          \
   953       logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n");   \
   954   } while (0)
   956 #if defined(OS_WIN)
   957 // Returns the default log file path.
   958 BASE_EXPORT std::wstring GetLogFileFullPath();
   959 #endif
   961 }  // namespace logging
   963 // These functions are provided as a convenience for logging, which is where we
   964 // use streams (it is against Google style to use streams in other places). It
   965 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
   966 // which is normally ASCII. It is relatively slow, so try not to use it for
   967 // common cases. Non-ASCII characters will be converted to UTF-8 by these
   968 // operators.
   969 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
   970 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
   971   return out << wstr.c_str();
   972 }
   974 // The NOTIMPLEMENTED() macro annotates codepaths which have
   975 // not been implemented yet.
   976 //
   977 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
   978 //   0 -- Do nothing (stripped by compiler)
   979 //   1 -- Warn at compile time
   980 //   2 -- Fail at compile time
   981 //   3 -- Fail at runtime (DCHECK)
   982 //   4 -- [default] LOG(ERROR) at runtime
   983 //   5 -- LOG(ERROR) at runtime, only once per call-site
   985 #ifndef NOTIMPLEMENTED_POLICY
   986 #if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
   987 #define NOTIMPLEMENTED_POLICY 0
   988 #else
   989 // Select default policy: LOG(ERROR)
   990 #define NOTIMPLEMENTED_POLICY 4
   991 #endif
   992 #endif
   994 #if defined(COMPILER_GCC)
   995 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
   996 // of the current function in the NOTIMPLEMENTED message.
   997 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
   998 #else
   999 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
  1000 #endif
  1002 #if NOTIMPLEMENTED_POLICY == 0
  1003 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
  1004 #elif NOTIMPLEMENTED_POLICY == 1
  1005 // TODO, figure out how to generate a warning
  1006 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
  1007 #elif NOTIMPLEMENTED_POLICY == 2
  1008 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
  1009 #elif NOTIMPLEMENTED_POLICY == 3
  1010 #define NOTIMPLEMENTED() NOTREACHED()
  1011 #elif NOTIMPLEMENTED_POLICY == 4
  1012 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
  1013 #elif NOTIMPLEMENTED_POLICY == 5
  1014 #define NOTIMPLEMENTED() do {\
  1015   static bool logged_once = false;\
  1016   LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
  1017   logged_once = true;\
  1018 } while(0);\
  1019 EAT_STREAM_PARAMETERS
  1020 #endif
  1022 #endif  // BASE_LOGGING_H_

mercurial