blob: c67b937e5b08607736e860dd349f1de6204c6a5b [file] [log] [blame]
[email protected]34a907732012-01-20 06:33:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]39be4242008-08-07 18:31:405#ifndef BASE_LOGGING_H_
6#define BASE_LOGGING_H_
initial.commitd7cae122008-07-26 21:49:387
avi9b6f42932015-12-26 22:15:148#include <stddef.h>
9
[email protected]e7972d12011-06-18 11:53:1410#include <cassert>
initial.commitd7cae122008-07-26 21:49:3811#include <cstring>
12#include <sstream>
avi9b6f42932015-12-26 22:15:1413#include <string>
jbroman6bcfec422016-05-26 00:28:4614#include <type_traits>
15#include <utility>
initial.commitd7cae122008-07-26 21:49:3816
[email protected]0bea7252011-08-05 15:34:0017#include "base/base_export.h"
danakjcb7c5292016-12-20 19:05:3518#include "base/compiler_specific.h"
[email protected]ddb9b332011-12-02 07:31:0919#include "base/debug/debugger.h"
avi9b6f42932015-12-26 22:15:1420#include "base/macros.h"
jbroman6bcfec422016-05-26 00:28:4621#include "base/template_util.h"
[email protected]90509cb2011-03-25 18:46:3822#include "build/build_config.h"
initial.commitd7cae122008-07-26 21:49:3823
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//
initial.commitd7cae122008-07-26 21:49:3861// 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//
[email protected]99b7c57f2010-09-29 19:26:3682// 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,
[email protected]b0d38d4c2010-10-29 00:39:4889// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
[email protected]99b7c57f2010-09-29 19:26:3690// 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"
[email protected]e11de722010-11-01 20:50:5595// d. VLOG(4) and lower messages to be printed from files under a
[email protected]b0d38d4c2010-10-29 00:39:4896// "chromeos" directory.
[email protected]e11de722010-11-01 20:50:5597// e. VLOG(0) and lower messages to be printed from elsewhere
[email protected]99b7c57f2010-09-29 19:26:3698//
99// The wildcarding functionality shown by (c) supports both '*' (match
[email protected]b0d38d4c2010-10-29 00:39:48100// 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.
[email protected]99b7c57f2010-09-29 19:26:36105//
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//
initial.commitd7cae122008-07-26 21:49:38121// We also override the standard 'assert' to use 'DLOG_ASSERT'.
122//
[email protected]d8617a62009-10-09 23:52:20123// 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//
initial.commitd7cae122008-07-26 21:49:38135// The supported severity levels for macros that allow you to specify one
[email protected]f2c05492014-06-17 12:04:23136// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
initial.commitd7cae122008-07-26 21:49:38137//
138// Very important: logging a message at the FATAL severity level causes
139// the program to terminate (after the message is logged).
[email protected]fb62a532009-02-12 01:19:05140//
[email protected]f2c05492014-06-17 12:04:23141// There is the special severity of DFATAL, which logs FATAL in debug mode,
142// ERROR in normal mode.
initial.commitd7cae122008-07-26 21:49:38143
144namespace logging {
145
[email protected]5e3f7c22013-06-21 21:15:33146// TODO(avi): do we want to do a unification of character types here?
147#if defined(OS_WIN)
148typedef wchar_t PathChar;
149#else
150typedef char PathChar;
151#endif
152
153// Where to record logging output? A flat file and/or system debug log
154// via OutputDebugString.
155enum 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};
initial.commitd7cae122008-07-26 21:49:38171
172// Indicates that the log file should be locked when being written to.
[email protected]5e3f7c22013-06-21 21:15:33173// 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
[email protected]3ee50d12014-03-05 01:43:27175// log output atomic. Other writers will block.
initial.commitd7cae122008-07-26 21:49:38176//
177// All processes writing to the log file must have their locking set for it to
[email protected]5e3f7c22013-06-21 21:15:33178// work properly. Defaults to LOCK_LOG_FILE.
initial.commitd7cae122008-07-26 21:49:38179enum 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.
183enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
184
[email protected]5e3f7c22013-06-21 21:15:33185struct 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
[email protected]5e3f7c22013-06-21 21:15:33192 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;
[email protected]5e3f7c22013-06-21 21:15:33201};
[email protected]ff3d0c32010-08-23 19:57:46202
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".
[email protected]5e3f7c22013-06-21 21:15:33216BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
[email protected]ff3d0c32010-08-23 19:57:46217
initial.commitd7cae122008-07-26 21:49:38218// 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.
[email protected]064aa162011-12-03 00:30:08228//
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.
[email protected]5e3f7c22013-06-21 21:15:33232inline bool InitLogging(const LoggingSettings& settings) {
233 return BaseInitLoggingImpl(settings);
[email protected]ff3d0c32010-08-23 19:57:46234}
initial.commitd7cae122008-07-26 21:49:38235
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
[email protected]162ac0f2010-11-04 15:50:49238// 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.
[email protected]0bea7252011-08-05 15:34:00242BASE_EXPORT void SetMinLogLevel(int level);
initial.commitd7cae122008-07-26 21:49:38243
[email protected]8a2986ca2009-04-10 19:13:42244// Gets the current log level.
[email protected]0bea7252011-08-05 15:34:00245BASE_EXPORT int GetMinLogLevel();
initial.commitd7cae122008-07-26 21:49:38246
skobesc78c0ad72015-12-07 20:21:23247// Used by LOG_IS_ON to lazy-evaluate stream arguments.
248BASE_EXPORT bool ShouldCreateLogMessage(int severity);
249
[email protected]162ac0f2010-11-04 15:50:49250// Gets the VLOG default verbosity level.
[email protected]0bea7252011-08-05 15:34:00251BASE_EXPORT int GetVlogVerbosity();
[email protected]162ac0f2010-11-04 15:50:49252
[email protected]99b7c57f2010-09-29 19:26:36253// Gets the current vlog level for the given file (usually taken from
254// __FILE__).
[email protected]2f4e9a62010-09-29 21:25:14255
256// Note that |N| is the size *with* the null terminator.
[email protected]0bea7252011-08-05 15:34:00257BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
[email protected]2f4e9a62010-09-29 21:25:14258
[email protected]99b7c57f2010-09-29 19:26:36259template <size_t N>
260int GetVlogLevel(const char (&file)[N]) {
261 return GetVlogLevelHelper(file, N);
262}
initial.commitd7cae122008-07-26 21:49:38263
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.
[email protected]0bea7252011-08-05 15:34:00268BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
269 bool enable_timestamp, bool enable_tickcount);
initial.commitd7cae122008-07-26 21:49:38270
[email protected]81e0a852010-08-17 00:38:12271// 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.
[email protected]0bea7252011-08-05 15:34:00274BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
[email protected]81e0a852010-08-17 00:38:12275
initial.commitd7cae122008-07-26 21:49:38276// Sets the Log Assert Handler that will be used to notify of check failures.
[email protected]fb62a532009-02-12 01:19:05277// 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)
initial.commitd7cae122008-07-26 21:49:38280typedef void (*LogAssertHandlerFunction)(const std::string& str);
[email protected]0bea7252011-08-05 15:34:00281BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
[email protected]64e5cc02010-11-03 19:20:27282
[email protected]2b07b8412009-11-25 15:26:34283// 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.
[email protected]162ac0f2010-11-04 15:50:49287typedef bool (*LogMessageHandlerFunction)(int severity,
288 const char* file, int line, size_t message_start, const std::string& str);
[email protected]0bea7252011-08-05 15:34:00289BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
290BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
[email protected]2b07b8412009-11-25 15:26:34291
initial.commitd7cae122008-07-26 21:49:38292typedef int LogSeverity;
[email protected]162ac0f2010-11-04 15:50:49293const 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.
initial.commitd7cae122008-07-26 21:49:38296const LogSeverity LOG_INFO = 0;
297const LogSeverity LOG_WARNING = 1;
298const LogSeverity LOG_ERROR = 2;
[email protected]f2c05492014-06-17 12:04:23299const LogSeverity LOG_FATAL = 3;
300const LogSeverity LOG_NUM_SEVERITIES = 4;
initial.commitd7cae122008-07-26 21:49:38301
[email protected]521b0c42010-10-01 23:02:36302// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
initial.commitd7cae122008-07-26 21:49:38303#ifdef NDEBUG
[email protected]521b0c42010-10-01 23:02:36304const LogSeverity LOG_DFATAL = LOG_ERROR;
initial.commitd7cae122008-07-26 21:49:38305#else
[email protected]521b0c42010-10-01 23:02:36306const LogSeverity LOG_DFATAL = LOG_FATAL;
initial.commitd7cae122008-07-26 21:49:38307#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.
[email protected]d8617a62009-10-09 23:52:20312#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20313 ::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__)
[email protected]d8617a62009-10-09 23:52:20317#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20318 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20319#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20320 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20321#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20322 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20323
initial.commitd7cae122008-07-26 21:49:38324#define COMPACT_GOOGLE_LOG_INFO \
[email protected]d8617a62009-10-09 23:52:20325 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
initial.commitd7cae122008-07-26 21:49:38326#define COMPACT_GOOGLE_LOG_WARNING \
[email protected]d8617a62009-10-09 23:52:20327 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
initial.commitd7cae122008-07-26 21:49:38328#define COMPACT_GOOGLE_LOG_ERROR \
[email protected]d8617a62009-10-09 23:52:20329 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
initial.commitd7cae122008-07-26 21:49:38330#define COMPACT_GOOGLE_LOG_FATAL \
[email protected]d8617a62009-10-09 23:52:20331 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38332#define COMPACT_GOOGLE_LOG_DFATAL \
[email protected]d8617a62009-10-09 23:52:20333 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38334
[email protected]8d127302013-01-10 02:41:57335#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38336// 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
[email protected]d8617a62009-10-09 23:52:20342#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
[email protected]521b0c42010-10-01 23:02:36345// Needed for LOG_IS_ON(ERROR).
346const LogSeverity LOG_0 = LOG_ERROR;
[email protected]8d127302013-01-10 02:41:57347#endif
[email protected]521b0c42010-10-01 23:02:36348
[email protected]f2c05492014-06-17 12:04:23349// 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.
[email protected]521b0c42010-10-01 23:02:36352#define LOG_IS_ON(severity) \
skobesc78c0ad72015-12-07 20:21:23353 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
[email protected]521b0c42010-10-01 23:02:36354
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
chcunninghamf6a96082015-02-07 01:58:37363// the condition doesn't hold. Condition is evaluated once and only once.
[email protected]521b0c42010-10-01 23:02:36364#define LAZY_STREAM(stream, condition) \
365 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
initial.commitd7cae122008-07-26 21:49:38366
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.
[email protected]521b0c42010-10-01 23:02:36375#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
initial.commitd7cae122008-07-26 21:49:38376
[email protected]521b0c42010-10-01 23:02:36377#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
[email protected]162ac0f2010-11-04 15:50:49381// The VLOG macros log with negative verbosities.
382#define VLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20383 ::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
[email protected]162ac0f2010-11-04 15:50:49384
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))
[email protected]99b7c57f2010-09-29 19:26:36391
[email protected]fb879b1a2011-03-06 18:16:31392#if defined (OS_WIN)
393#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20394 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
[email protected]fb879b1a2011-03-06 18:16:31395 ::logging::GetLastSystemErrorCode()).stream()
396#elif defined(OS_POSIX)
397#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20398 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
[email protected]fb879b1a2011-03-06 18:16:31399 ::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
[email protected]99b7c57f2010-09-29 19:26:36409// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
initial.commitd7cae122008-07-26 21:49:38410
kmarshall08c892f72017-02-28 03:46:18411#define LOG_ASSERT(condition) \
412 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38413
[email protected]d8617a62009-10-09 23:52:20414#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01415#define PLOG_STREAM(severity) \
[email protected]d8617a62009-10-09 23:52:20416 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
417 ::logging::GetLastSystemErrorCode()).stream()
[email protected]d8617a62009-10-09 23:52:20418#elif defined(OS_POSIX)
[email protected]c914d8a2014-04-23 01:11:01419#define PLOG_STREAM(severity) \
[email protected]d8617a62009-10-09 23:52:20420 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
421 ::logging::GetLastSystemErrorCode()).stream()
[email protected]d8617a62009-10-09 23:52:20422#endif
423
[email protected]521b0c42010-10-01 23:02:36424#define PLOG(severity) \
425 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
426
[email protected]d8617a62009-10-09 23:52:20427#define PLOG_IF(severity, condition) \
[email protected]521b0c42010-10-01 23:02:36428 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
[email protected]d8617a62009-10-09 23:52:20429
scottmg3c957a52016-12-10 20:57:59430BASE_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)
[email protected]ddb9b332011-12-02 07:31:09447
erikwright6ad937b2015-07-22 20:05:52448// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
449// boolean.
450class CheckOpResult {
451 public:
wezf01a9b72016-03-19 01:18:07452 // |message| must be non-null if and only if the check failed.
erikwright6ad937b2015-07-22 20:05:52453 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
primianof5316722017-02-21 13:09:26463// 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.
scottmga17c8db2017-02-15 21:35:49484#if defined(COMPILER_GCC)
primianof5316722017-02-21 13:09:26485
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
scottmga17c8db2017-02-15 21:35:49517#elif defined(COMPILER_MSVC)
scottmg92bbdc392017-02-20 21:06:25518
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
scottmg6a233062017-02-21 23:52:14523// 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.
scottmg92bbdc392017-02-20 21:06:25529// 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__)
scottmg6a233062017-02-21 23:52:14532#define IMMEDIATE_CRASH() ({__asm int 3 __asm ud2 __asm push __COUNTER__})
scottmg92bbdc392017-02-20 21:06:25533#else
scottmga17c8db2017-02-15 21:35:49534#define IMMEDIATE_CRASH() __debugbreak()
scottmg92bbdc392017-02-20 21:06:25535#endif // __clang__
536
Chris Palmer61343b02016-11-29 20:44:10537#else
scottmga17c8db2017-02-15 21:35:49538#error Port
Chris Palmer61343b02016-11-29 20:44:10539#endif
540
initial.commitd7cae122008-07-26 21:49:38541// 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.
[email protected]521b0c42010-10-01 23:02:36544//
545// We make sure CHECK et al. always evaluates their arguments, as
546// doing CHECK(FunctionWithSideEffect()) is a common idiom.
[email protected]ddb9b332011-12-02 07:31:09547
danakjb9d59312016-05-04 20:06:31548#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09549
Chris Palmer61343b02016-11-29 20:44:10550// Make all CHECK functions discard their log strings to reduce code bloat, and
551// improve performance, for official release builds.
552//
primianoba910a62016-07-07 22:14:48553// 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.
Chris Palmer61343b02016-11-29 20:44:10556#define CHECK(condition) \
danakjcb7c5292016-12-20 19:05:35557 UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_STREAM_PARAMETERS
[email protected]ddb9b332011-12-02 07:31:09558
559#define PCHECK(condition) CHECK(condition)
560
561#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
562
danakjb9d59312016-05-04 20:06:31563#else // !(OFFICIAL_BUILD && NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09564
kmarshall08c892f72017-02-28 03:46:18565#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
tnagel4a045d3f2015-07-12 14:19:28585// Do as much work as possible out of line to reduce inline code size.
tsniatowski612550f2016-07-21 18:26:20586#define CHECK(condition) \
587 LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
kmarshall08c892f72017-02-28 03:46:18588 !(condition))
initial.commitd7cae122008-07-26 21:49:38589
kmarshall08c892f72017-02-28 03:46:18590#define PCHECK(condition) \
591 LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
kmarshalle23eed02017-02-11 02:13:23592 << "Check failed: " #condition ". "
brucedawson9d160252014-10-23 20:14:14593
kmarshall08c892f72017-02-28 03:46:18594#endif // _PREFAST_
595
[email protected]ddb9b332011-12-02 07:31:09596// Helper macro for binary operators.
597// Don't use this macro directly in your code, use CHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52598// 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: \
tsniatowski612550f2016-07-21 18:26:20604 if (::logging::CheckOpResult true_if_passed = \
605 ::logging::Check##name##Impl((val1), (val2), \
606 #val1 " " #op " " #val2)) \
erikwright6ad937b2015-07-22 20:05:52607 ; \
608 else \
tsniatowski612550f2016-07-21 18:26:20609 ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
[email protected]ddb9b332011-12-02 07:31:09610
danakjb9d59312016-05-04 20:06:31611#endif // !(OFFICIAL_BUILD && NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09612
brucedawson93a60b8c2016-04-28 20:46:16613// This formats a value for a failing CHECK_XX statement. Ordinarily,
614// it uses the definition for operator<<, with a few special cases below.
615template <typename T>
jbroman6bcfec422016-05-26 00:28:46616inline typename std::enable_if<
raphael.kubo.da.costa81f21202016-11-28 18:36:36617 base::internal::SupportsOstreamOperator<const T&>::value &&
618 !std::is_function<typename std::remove_pointer<T>::type>::value,
jbroman6bcfec422016-05-26 00:28:46619 void>::type
620MakeCheckOpValueString(std::ostream* os, const T& v) {
brucedawson93a60b8c2016-04-28 20:46:16621 (*os) << v;
622}
623
raphael.kubo.da.costa81f21202016-11-28 18:36:36624// 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.)
629template <typename T>
630inline typename std::enable_if<
631 std::is_function<typename std::remove_pointer<T>::type>::value,
632 void>::type
633MakeCheckOpValueString(std::ostream* os, const T& v) {
634 (*os) << reinterpret_cast<const void*>(v);
635}
636
jbroman6bcfec422016-05-26 00:28:46637// We need overloads for enums that don't support operator<<.
638// (i.e. scoped enums where no operator<< overload was declared).
639template <typename T>
640inline typename std::enable_if<
641 !base::internal::SupportsOstreamOperator<const T&>::value &&
642 std::is_enum<T>::value,
643 void>::type
644MakeCheckOpValueString(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.
649BASE_EXPORT void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
brucedawson93a60b8c2016-04-28 20:46:16650
initial.commitd7cae122008-07-26 21:49:38651// Build the error message string. This is separate from the "Impl"
652// function template because it is not performance critical and so can
[email protected]9c7132e2011-02-08 07:39:08653// be out of line, while the "Impl" code should be inline. Caller
654// takes ownership of the returned string.
initial.commitd7cae122008-07-26 21:49:38655template<class t1, class t2>
656std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
657 std::ostringstream ss;
brucedawson93a60b8c2016-04-28 20:46:16658 ss << names << " (";
659 MakeCheckOpValueString(&ss, v1);
660 ss << " vs. ";
661 MakeCheckOpValueString(&ss, v2);
662 ss << ")";
initial.commitd7cae122008-07-26 21:49:38663 std::string* msg = new std::string(ss.str());
664 return msg;
665}
666
[email protected]6d445d32010-09-30 19:10:03667// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
668// in logging.cc.
[email protected]dc72da32011-10-24 20:20:30669extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
[email protected]6d445d32010-09-30 19:10:03670 const int&, const int&, const char* names);
[email protected]dc72da32011-10-24 20:20:30671extern template BASE_EXPORT
672std::string* MakeCheckOpString<unsigned long, unsigned long>(
[email protected]6d445d32010-09-30 19:10:03673 const unsigned long&, const unsigned long&, const char* names);
[email protected]dc72da32011-10-24 20:20:30674extern template BASE_EXPORT
675std::string* MakeCheckOpString<unsigned long, unsigned int>(
[email protected]6d445d32010-09-30 19:10:03676 const unsigned long&, const unsigned int&, const char* names);
[email protected]dc72da32011-10-24 20:20:30677extern template BASE_EXPORT
678std::string* MakeCheckOpString<unsigned int, unsigned long>(
[email protected]6d445d32010-09-30 19:10:03679 const unsigned int&, const unsigned long&, const char* names);
[email protected]dc72da32011-10-24 20:20:30680extern template BASE_EXPORT
681std::string* MakeCheckOpString<std::string, std::string>(
[email protected]6d445d32010-09-30 19:10:03682 const std::string&, const std::string&, const char* name);
initial.commitd7cae122008-07-26 21:49:38683
[email protected]71512602010-11-01 22:19:56684// 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.
kmarshall9db26fb2017-02-15 01:05:33688#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) { \
kmarshall08c892f72017-02-28 03:46:18692 if (v1 op v2) \
kmarshall9db26fb2017-02-15 01:05:33693 return NULL; \
694 else \
695 return ::logging::MakeCheckOpString(v1, v2, names); \
696 } \
[email protected]71512602010-11-01 22:19:56697 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
kmarshall08c892f72017-02-28 03:46:18698 if (v1 op v2) \
kmarshall9db26fb2017-02-15 01:05:33699 return NULL; \
700 else \
701 return ::logging::MakeCheckOpString(v1, v2, names); \
[email protected]71512602010-11-01 22:19:56702 }
703DEFINE_CHECK_OP_IMPL(EQ, ==)
704DEFINE_CHECK_OP_IMPL(NE, !=)
705DEFINE_CHECK_OP_IMPL(LE, <=)
706DEFINE_CHECK_OP_IMPL(LT, < )
707DEFINE_CHECK_OP_IMPL(GE, >=)
708DEFINE_CHECK_OP_IMPL(GT, > )
709#undef DEFINE_CHECK_OP_IMPL
[email protected]e150c0382010-03-02 00:41:12710
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
jam121900aa2016-04-19 00:07:34718#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
danakje649f572015-01-08 23:35:58719#define DCHECK_IS_ON() 0
[email protected]1a1505512014-03-10 18:23:38720#else
danakje649f572015-01-08 23:35:58721#define DCHECK_IS_ON() 1
[email protected]e3cca332009-08-20 01:20:29722#endif
723
[email protected]d15e56c2010-09-30 21:12:33724// Definitions for DLOG et al.
725
gab190f7542016-08-01 20:03:41726#if DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24727
[email protected]5e987802010-11-01 19:49:22728#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
[email protected]d926c202010-10-01 02:58:24729#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
730#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
[email protected]d926c202010-10-01 02:58:24731#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
[email protected]521b0c42010-10-01 23:02:36732#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
[email protected]fb879b1a2011-03-06 18:16:31733#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
[email protected]d926c202010-10-01 02:58:24734
gab190f7542016-08-01 20:03:41735#else // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24736
gab190f7542016-08-01 20:03:41737// 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.
[email protected]d926c202010-10-01 02:58:24740
[email protected]5e987802010-11-01 19:49:22741#define DLOG_IS_ON(severity) false
[email protected]ddb9b332011-12-02 07:31:09742#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
[email protected]d926c202010-10-01 02:58:24747
gab190f7542016-08-01 20:03:41748#endif // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24749
gab190f7542016-08-01 20:03:41750// DEBUG_MODE is for runtime uses like
[email protected]d15e56c2010-09-30 21:12:33751// if (DEBUG_MODE) foo.CheckThatFoo();
gab190f7542016-08-01 20:03:41752// We tie its state to DCHECK_IS_ON().
[email protected]d15e56c2010-09-30 21:12:33753//
gab190f7542016-08-01 20:03:41754// For compile-time checks, #if DCHECK_IS_ON() can be used.
755enum { DEBUG_MODE = DCHECK_IS_ON() };
[email protected]d15e56c2010-09-30 21:12:33756
[email protected]521b0c42010-10-01 23:02:36757#define DLOG(severity) \
758 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
759
[email protected]521b0c42010-10-01 23:02:36760#define DPLOG(severity) \
761 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
762
[email protected]c3ab11c2011-10-25 06:28:45763#define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
[email protected]521b0c42010-10-01 23:02:36764
[email protected]fb879b1a2011-03-06 18:16:31765#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
766
[email protected]521b0c42010-10-01 23:02:36767// Definitions for DCHECK et al.
[email protected]d926c202010-10-01 02:58:24768
danakje649f572015-01-08 23:35:58769#if DCHECK_IS_ON()
[email protected]e3cca332009-08-20 01:20:29770
[email protected]deba0ff2010-11-03 05:30:14771#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
772 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
773#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
[email protected]521b0c42010-10-01 23:02:36774const LogSeverity LOG_DCHECK = LOG_FATAL;
775
danakje649f572015-01-08 23:35:58776#else // DCHECK_IS_ON()
[email protected]521b0c42010-10-01 23:02:36777
[email protected]c02cb8012014-03-14 18:39:53778// These are just dummy values.
[email protected]deba0ff2010-11-03 05:30:14779#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
780 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
781#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
782const LogSeverity LOG_DCHECK = LOG_INFO;
[email protected]521b0c42010-10-01 23:02:36783
danakje649f572015-01-08 23:35:58784#endif // DCHECK_IS_ON()
[email protected]521b0c42010-10-01 23:02:36785
[email protected]deba0ff2010-11-03 05:30:14786// DCHECK et al. make sure to reference |condition| regardless of
[email protected]521b0c42010-10-01 23:02:36787// whether DCHECKs are enabled; this is so that we don't get unused
788// variable warnings if the only use of a variable is in a DCHECK.
789// This behavior is different from DLOG_IF et al.
dchengfc670f472017-01-25 17:48:43790//
791// Note that the definition of the DCHECK macros depends on whether or not
792// DCHECK_IS_ON() is true. When DCHECK_IS_ON() is false, the macros use
793// EAT_STREAM_PARAMETERS to avoid expressions that would create temporaries.
[email protected]521b0c42010-10-01 23:02:36794
kmarshall08c892f72017-02-28 03:46:18795#if defined(_PREFAST_) && defined(OS_WIN)
796// See comments on the previous use of __analysis_assume.
797
798#define DCHECK(condition) \
799 __analysis_assume(!!(condition)), \
800 LAZY_STREAM(LOG_STREAM(DCHECK), false) \
801 << "Check failed: " #condition ". "
802
803#define DPCHECK(condition) \
804 __analysis_assume(!!(condition)), \
805 LAZY_STREAM(PLOG_STREAM(DCHECK), false) \
806 << "Check failed: " #condition ". "
807
808#elif defined(__clang_analyzer__)
809
810// Keeps the static analyzer from proceeding along the current codepath,
811// otherwise false positive errors may be generated by null pointer checks.
812inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
813 return false;
814}
815
816#define DCHECK(condition) \
817 LAZY_STREAM( \
818 LOG_STREAM(DCHECK), \
819 DCHECK_IS_ON() ? (logging::AnalyzerNoReturn() || !(condition)) : false) \
820 << "Check failed: " #condition ". "
821
822#define DPCHECK(condition) \
823 LAZY_STREAM( \
824 PLOG_STREAM(DCHECK), \
825 DCHECK_IS_ON() ? (logging::AnalyzerNoReturn() || !(condition)) : false) \
826 << "Check failed: " #condition ". "
827
828#else
829
dchengfc670f472017-01-25 17:48:43830#if DCHECK_IS_ON()
831
kmarshall08c892f72017-02-28 03:46:18832#define DCHECK(condition) \
833 LAZY_STREAM(LOG_STREAM(DCHECK), !(condition)) \
dchengfc670f472017-01-25 17:48:43834 << "Check failed: " #condition ". "
kmarshall08c892f72017-02-28 03:46:18835#define DPCHECK(condition) \
836 LAZY_STREAM(PLOG_STREAM(DCHECK), !(condition)) \
danakje649f572015-01-08 23:35:58837 << "Check failed: " #condition ". "
[email protected]521b0c42010-10-01 23:02:36838
dchengfc670f472017-01-25 17:48:43839#else // DCHECK_IS_ON()
840
kmarshall08c892f72017-02-28 03:46:18841#define DCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
842#define DPCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
dchengfc670f472017-01-25 17:48:43843
844#endif // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24845
kmarshall08c892f72017-02-28 03:46:18846#endif
brucedawson9d160252014-10-23 20:14:14847
[email protected]d926c202010-10-01 02:58:24848// Helper macro for binary operators.
849// Don't use this macro directly in your code, use DCHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52850// The 'switch' is used to prevent the 'else' from being ambiguous when the
851// macro is used in an 'if' clause such as:
852// if (a == 1)
853// DCHECK_EQ(2, a);
dchengfc670f472017-01-25 17:48:43854#if DCHECK_IS_ON()
855
tsniatowski612550f2016-07-21 18:26:20856#define DCHECK_OP(name, op, val1, val2) \
857 switch (0) case 0: default: \
858 if (::logging::CheckOpResult true_if_passed = \
859 DCHECK_IS_ON() ? \
860 ::logging::Check##name##Impl((val1), (val2), \
861 #val1 " " #op " " #val2) : nullptr) \
862 ; \
863 else \
864 ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
865 true_if_passed.message()).stream()
initial.commitd7cae122008-07-26 21:49:38866
dchengfc670f472017-01-25 17:48:43867#else // DCHECK_IS_ON()
868
869// When DCHECKs aren't enabled, DCHECK_OP still needs to reference operator<<
870// overloads for |val1| and |val2| to avoid potential compiler warnings about
871// unused functions. For the same reason, it also compares |val1| and |val2|
872// using |op|.
873//
874// Note that the contract of DCHECK_EQ, etc is that arguments are only evaluated
875// once. Even though |val1| and |val2| appear twice in this version of the macro
876// expansion, this is OK, since the expression is never actually evaluated.
877#define DCHECK_OP(name, op, val1, val2) \
878 EAT_STREAM_PARAMETERS << (::logging::MakeCheckOpValueString( \
879 ::logging::g_swallow_stream, val1), \
880 ::logging::MakeCheckOpValueString( \
881 ::logging::g_swallow_stream, val2), \
kmarshall08c892f72017-02-28 03:46:18882 (val1)op(val2))
dchengfc670f472017-01-25 17:48:43883
884#endif // DCHECK_IS_ON()
885
[email protected]deba0ff2010-11-03 05:30:14886// Equality/Inequality checks - compare two values, and log a
887// LOG_DCHECK message including the two values when the result is not
888// as expected. The values must have operator<<(ostream, ...)
889// defined.
initial.commitd7cae122008-07-26 21:49:38890//
891// You may append to the error message like so:
pwnall7ae42b462016-09-22 02:26:12892// DCHECK_NE(1, 2) << "The world must be ending!";
initial.commitd7cae122008-07-26 21:49:38893//
894// We are very careful to ensure that each argument is evaluated exactly
895// once, and that anything which is legal to pass as a function argument is
896// legal here. In particular, the arguments may be temporary expressions
897// which will end up being destroyed at the end of the apparent statement,
898// for example:
899// DCHECK_EQ(string("abc")[1], 'b');
900//
brucedawson93a60b8c2016-04-28 20:46:16901// WARNING: These don't compile correctly if one of the arguments is a pointer
902// and the other is NULL. In new code, prefer nullptr instead. To
903// work around this for C++98, simply static_cast NULL to the type of the
904// desired pointer.
initial.commitd7cae122008-07-26 21:49:38905
906#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
907#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
908#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
909#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
910#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
911#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
912
danakje649f572015-01-08 23:35:58913#if !DCHECK_IS_ON() && defined(OS_CHROMEOS)
tnagelff3f34a2015-05-24 12:59:14914// Implement logging of NOTREACHED() as a dedicated function to get function
915// call overhead down to a minimum.
916void LogErrorNotReached(const char* file, int line);
917#define NOTREACHED() \
918 true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
919 : EAT_STREAM_PARAMETERS
[email protected]7c67fbe2013-09-26 07:55:21920#else
initial.commitd7cae122008-07-26 21:49:38921#define NOTREACHED() DCHECK(false)
[email protected]7c67fbe2013-09-26 07:55:21922#endif
initial.commitd7cae122008-07-26 21:49:38923
924// Redefine the standard assert to use our nice log files
925#undef assert
926#define assert(x) DLOG_ASSERT(x)
927
928// This class more or less represents a particular log message. You
929// create an instance of LogMessage and then stream stuff to it.
930// When you finish streaming to it, ~LogMessage is called and the
931// full message gets streamed to the appropriate destination.
932//
933// You shouldn't actually use LogMessage's constructor to log things,
934// though. You should use the LOG() macro (and variants thereof)
935// above.
[email protected]0bea7252011-08-05 15:34:00936class BASE_EXPORT LogMessage {
initial.commitd7cae122008-07-26 21:49:38937 public:
[email protected]bf8ddf13a2014-06-18 15:02:22938 // Used for LOG(severity).
initial.commitd7cae122008-07-26 21:49:38939 LogMessage(const char* file, int line, LogSeverity severity);
940
tnagel4a045d3f2015-07-12 14:19:28941 // Used for CHECK(). Implied severity = LOG_FATAL.
942 LogMessage(const char* file, int line, const char* condition);
943
[email protected]bf8ddf13a2014-06-18 15:02:22944 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
945 // Implied severity = LOG_FATAL.
[email protected]9c7132e2011-02-08 07:39:08946 LogMessage(const char* file, int line, std::string* result);
initial.commitd7cae122008-07-26 21:49:38947
[email protected]bf8ddf13a2014-06-18 15:02:22948 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
[email protected]fb62a532009-02-12 01:19:05949 LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08950 std::string* result);
[email protected]fb62a532009-02-12 01:19:05951
initial.commitd7cae122008-07-26 21:49:38952 ~LogMessage();
953
954 std::ostream& stream() { return stream_; }
955
pastarmovj89f7ee12016-09-20 14:58:13956 LogSeverity severity() { return severity_; }
957 std::string str() { return stream_.str(); }
958
initial.commitd7cae122008-07-26 21:49:38959 private:
960 void Init(const char* file, int line);
961
962 LogSeverity severity_;
963 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03964 size_t message_start_; // Offset of the start of the message (past prefix
965 // info).
[email protected]162ac0f2010-11-04 15:50:49966 // The file and line information passed in to the constructor.
967 const char* file_;
968 const int line_;
969
[email protected]3f85caa2009-04-14 16:52:11970#if defined(OS_WIN)
971 // Stores the current value of GetLastError in the constructor and restores
972 // it in the destructor by calling SetLastError.
973 // This is useful since the LogMessage class uses a lot of Win32 calls
974 // that will lose the value of GLE and the code that called the log function
975 // will have lost the thread error value when the log call returns.
976 class SaveLastError {
977 public:
978 SaveLastError();
979 ~SaveLastError();
980
981 unsigned long get_error() const { return last_error_; }
982
983 protected:
984 unsigned long last_error_;
985 };
986
987 SaveLastError last_error_;
988#endif
initial.commitd7cae122008-07-26 21:49:38989
[email protected]39be4242008-08-07 18:31:40990 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38991};
992
initial.commitd7cae122008-07-26 21:49:38993// This class is used to explicitly ignore values in the conditional
994// logging macros. This avoids compiler warnings like "value computed
995// is not used" and "statement has no effect".
[email protected]23bb71f2011-04-21 22:22:10996class LogMessageVoidify {
initial.commitd7cae122008-07-26 21:49:38997 public:
998 LogMessageVoidify() { }
999 // This has to be an operator with a precedence lower than << but
1000 // higher than ?:
1001 void operator&(std::ostream&) { }
1002};
1003
[email protected]d8617a62009-10-09 23:52:201004#if defined(OS_WIN)
1005typedef unsigned long SystemErrorCode;
1006#elif defined(OS_POSIX)
1007typedef int SystemErrorCode;
1008#endif
1009
1010// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
1011// pull in windows.h just for GetLastError() and DWORD.
[email protected]0bea7252011-08-05 15:34:001012BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
[email protected]c914d8a2014-04-23 01:11:011013BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
[email protected]d8617a62009-10-09 23:52:201014
1015#if defined(OS_WIN)
1016// Appends a formatted system message of the GetLastError() type.
[email protected]0bea7252011-08-05 15:34:001017class BASE_EXPORT Win32ErrorLogMessage {
[email protected]d8617a62009-10-09 23:52:201018 public:
1019 Win32ErrorLogMessage(const char* file,
1020 int line,
1021 LogSeverity severity,
[email protected]d8617a62009-10-09 23:52:201022 SystemErrorCode err);
1023
[email protected]d8617a62009-10-09 23:52:201024 // Appends the error message before destructing the encapsulated class.
1025 ~Win32ErrorLogMessage();
1026
[email protected]a502bbe72011-01-07 18:06:451027 std::ostream& stream() { return log_message_.stream(); }
1028
[email protected]d8617a62009-10-09 23:52:201029 private:
1030 SystemErrorCode err_;
[email protected]d8617a62009-10-09 23:52:201031 LogMessage log_message_;
1032
1033 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
1034};
1035#elif defined(OS_POSIX)
1036// Appends a formatted system message of the errno type
[email protected]0bea7252011-08-05 15:34:001037class BASE_EXPORT ErrnoLogMessage {
[email protected]d8617a62009-10-09 23:52:201038 public:
1039 ErrnoLogMessage(const char* file,
1040 int line,
1041 LogSeverity severity,
1042 SystemErrorCode err);
1043
[email protected]d8617a62009-10-09 23:52:201044 // Appends the error message before destructing the encapsulated class.
1045 ~ErrnoLogMessage();
1046
[email protected]a502bbe72011-01-07 18:06:451047 std::ostream& stream() { return log_message_.stream(); }
1048
[email protected]d8617a62009-10-09 23:52:201049 private:
1050 SystemErrorCode err_;
1051 LogMessage log_message_;
1052
1053 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
1054};
1055#endif // OS_WIN
1056
initial.commitd7cae122008-07-26 21:49:381057// Closes the log file explicitly if open.
1058// NOTE: Since the log file is opened as necessary by the action of logging
1059// statements, there's no guarantee that it will stay closed
1060// after this call.
[email protected]0bea7252011-08-05 15:34:001061BASE_EXPORT void CloseLogFile();
initial.commitd7cae122008-07-26 21:49:381062
[email protected]e36ddc82009-12-08 04:22:501063// Async signal safe logging mechanism.
[email protected]0bea7252011-08-05 15:34:001064BASE_EXPORT void RawLog(int level, const char* message);
[email protected]e36ddc82009-12-08 04:22:501065
tsniatowski612550f2016-07-21 18:26:201066#define RAW_LOG(level, message) \
1067 ::logging::RawLog(::logging::LOG_##level, message)
[email protected]e36ddc82009-12-08 04:22:501068
tsniatowski612550f2016-07-21 18:26:201069#define RAW_CHECK(condition) \
1070 do { \
kmarshall08c892f72017-02-28 03:46:181071 if (!(condition)) \
tsniatowski612550f2016-07-21 18:26:201072 ::logging::RawLog(::logging::LOG_FATAL, \
1073 "Check failed: " #condition "\n"); \
[email protected]e36ddc82009-12-08 04:22:501074 } while (0)
1075
[email protected]f01b88a2013-02-27 22:04:001076#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091077// Returns true if logging to file is enabled.
1078BASE_EXPORT bool IsLoggingToFileEnabled();
1079
[email protected]f01b88a2013-02-27 22:04:001080// Returns the default log file path.
1081BASE_EXPORT std::wstring GetLogFileFullPath();
1082#endif
1083
[email protected]39be4242008-08-07 18:31:401084} // namespace logging
initial.commitd7cae122008-07-26 21:49:381085
[email protected]81411c62014-07-08 23:03:061086// Note that "The behavior of a C++ program is undefined if it adds declarations
1087// or definitions to namespace std or to a namespace within namespace std unless
1088// otherwise specified." --C++11[namespace.std]
1089//
1090// We've checked that this particular definition has the intended behavior on
1091// our implementations, but it's prone to breaking in the future, and please
1092// don't imitate this in your own definitions without checking with some
1093// standard library experts.
1094namespace std {
[email protected]46ce5b562010-06-16 18:39:531095// These functions are provided as a convenience for logging, which is where we
1096// use streams (it is against Google style to use streams in other places). It
1097// is designed to allow you to emit non-ASCII Unicode strings to the log file,
1098// which is normally ASCII. It is relatively slow, so try not to use it for
1099// common cases. Non-ASCII characters will be converted to UTF-8 by these
1100// operators.
[email protected]0bea7252011-08-05 15:34:001101BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
[email protected]46ce5b562010-06-16 18:39:531102inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
1103 return out << wstr.c_str();
1104}
[email protected]81411c62014-07-08 23:03:061105} // namespace std
[email protected]46ce5b562010-06-16 18:39:531106
[email protected]0dfc81b2008-08-25 03:44:401107// The NOTIMPLEMENTED() macro annotates codepaths which have
1108// not been implemented yet.
1109//
1110// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
1111// 0 -- Do nothing (stripped by compiler)
1112// 1 -- Warn at compile time
1113// 2 -- Fail at compile time
1114// 3 -- Fail at runtime (DCHECK)
1115// 4 -- [default] LOG(ERROR) at runtime
1116// 5 -- LOG(ERROR) at runtime, only once per call-site
1117
1118#ifndef NOTIMPLEMENTED_POLICY
[email protected]f5c7758a2012-07-25 16:17:571119#if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
1120#define NOTIMPLEMENTED_POLICY 0
1121#else
[email protected]0dfc81b2008-08-25 03:44:401122// Select default policy: LOG(ERROR)
1123#define NOTIMPLEMENTED_POLICY 4
1124#endif
[email protected]f5c7758a2012-07-25 16:17:571125#endif
[email protected]0dfc81b2008-08-25 03:44:401126
[email protected]f6cda752008-10-30 23:54:261127#if defined(COMPILER_GCC)
1128// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
1129// of the current function in the NOTIMPLEMENTED message.
1130#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
1131#else
1132#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
1133#endif
1134
[email protected]0dfc81b2008-08-25 03:44:401135#if NOTIMPLEMENTED_POLICY == 0
[email protected]38227292012-01-30 19:41:541136#define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
[email protected]0dfc81b2008-08-25 03:44:401137#elif NOTIMPLEMENTED_POLICY == 1
1138// TODO, figure out how to generate a warning
avi4ec0dff2015-11-24 14:26:241139#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
[email protected]0dfc81b2008-08-25 03:44:401140#elif NOTIMPLEMENTED_POLICY == 2
avi4ec0dff2015-11-24 14:26:241141#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
[email protected]0dfc81b2008-08-25 03:44:401142#elif NOTIMPLEMENTED_POLICY == 3
1143#define NOTIMPLEMENTED() NOTREACHED()
1144#elif NOTIMPLEMENTED_POLICY == 4
[email protected]f6cda752008-10-30 23:54:261145#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
[email protected]0dfc81b2008-08-25 03:44:401146#elif NOTIMPLEMENTED_POLICY == 5
1147#define NOTIMPLEMENTED() do {\
[email protected]b70ff012013-02-13 08:32:141148 static bool logged_once = false;\
1149 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
1150 logged_once = true;\
1151} while(0);\
1152EAT_STREAM_PARAMETERS
[email protected]0dfc81b2008-08-25 03:44:401153#endif
1154
[email protected]39be4242008-08-07 18:31:401155#endif // BASE_LOGGING_H_