• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2002 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // debug.h: Debugging utilities. A lot of the logging code is adapted from Chromium's
8 // base/logging.h.
9 
10 #ifndef COMMON_DEBUG_H_
11 #define COMMON_DEBUG_H_
12 
13 #include <assert.h>
14 #include <stdio.h>
15 
16 #include <iomanip>
17 #include <ios>
18 #include <sstream>
19 #include <string>
20 
21 #include "common/angleutils.h"
22 #include "common/platform.h"
23 
24 #if !defined(TRACE_OUTPUT_FILE)
25 #    define TRACE_OUTPUT_FILE "angle_debug.txt"
26 #endif
27 
28 namespace gl
29 {
30 
31 // Pairs a D3D begin event with an end event.
32 class ScopedPerfEventHelper : angle::NonCopyable
33 {
34   public:
35     ANGLE_FORMAT_PRINTF(2, 3)
36     ScopedPerfEventHelper(const char *format, ...);
37     ~ScopedPerfEventHelper();
38 
39   private:
40     const char *mFunctionName;
41 };
42 
43 using LogSeverity = int;
44 // Note: the log severities are used to index into the array of names,
45 // see g_logSeverityNames.
46 constexpr LogSeverity LOG_EVENT          = 0;
47 constexpr LogSeverity LOG_INFO           = 1;
48 constexpr LogSeverity LOG_WARN           = 2;
49 constexpr LogSeverity LOG_ERR            = 3;
50 constexpr LogSeverity LOG_FATAL          = 4;
51 constexpr LogSeverity LOG_NUM_SEVERITIES = 5;
52 
53 void Trace(LogSeverity severity, const char *message);
54 
55 // This class more or less represents a particular log message.  You
56 // create an instance of LogMessage and then stream stuff to it.
57 // When you finish streaming to it, ~LogMessage is called and the
58 // full message gets streamed to the appropriate destination.
59 //
60 // You shouldn't actually use LogMessage's constructor to log things,
61 // though.  You should use the ERR() and WARN() macros.
62 class LogMessage : angle::NonCopyable
63 {
64   public:
65     // Used for ANGLE_LOG(severity).
66     LogMessage(const char *function, int line, LogSeverity severity);
67     ~LogMessage();
stream()68     std::ostream &stream() { return mStream; }
69 
70     LogSeverity getSeverity() const;
71     std::string getMessage() const;
72 
73   private:
74     const char *mFunction;
75     const int mLine;
76     const LogSeverity mSeverity;
77 
78     std::ostringstream mStream;
79 };
80 
81 // Wraps the API/Platform-specific debug annotation functions.
82 // Also handles redirecting logging destination.
83 class DebugAnnotator : angle::NonCopyable
84 {
85   public:
DebugAnnotator()86     DebugAnnotator() {}
~DebugAnnotator()87     virtual ~DebugAnnotator() {}
88     virtual void beginEvent(const char *eventName, const char *eventMessage) = 0;
89     virtual void endEvent(const char *eventName)                             = 0;
90     virtual void setMarker(const char *markerName)                           = 0;
91     virtual bool getStatus()                                                 = 0;
92     // Log Message Handler that gets passed every log message,
93     // when debug annotations are initialized,
94     // replacing default handling by LogMessage.
95     virtual void logMessage(const LogMessage &msg) const = 0;
96 };
97 
98 void InitializeDebugAnnotations(DebugAnnotator *debugAnnotator);
99 void UninitializeDebugAnnotations();
100 bool DebugAnnotationsActive();
101 bool DebugAnnotationsInitialized();
102 
103 void InitializeDebugMutexIfNeeded();
104 
105 namespace priv
106 {
107 // This class is used to explicitly ignore values in the conditional logging macros. This avoids
108 // compiler warnings like "value computed is not used" and "statement has no effect".
109 class LogMessageVoidify
110 {
111   public:
LogMessageVoidify()112     LogMessageVoidify() {}
113     // This has to be an operator with a precedence lower than << but higher than ?:
114     void operator&(std::ostream &) {}
115 };
116 
117 extern std::ostream *gSwallowStream;
118 
119 // Used by ANGLE_LOG_IS_ON to lazy-evaluate stream arguments.
120 bool ShouldCreatePlatformLogMessage(LogSeverity severity);
121 
122 template <int N, typename T>
FmtHex(std::ostream & os,T value)123 std::ostream &FmtHex(std::ostream &os, T value)
124 {
125     os << "0x";
126 
127     std::ios_base::fmtflags oldFlags = os.flags();
128     std::streamsize oldWidth         = os.width();
129     std::ostream::char_type oldFill  = os.fill();
130 
131     os << std::hex << std::uppercase << std::setw(N) << std::setfill('0') << value;
132 
133     os.flags(oldFlags);
134     os.width(oldWidth);
135     os.fill(oldFill);
136 
137     return os;
138 }
139 
140 template <typename T>
FmtHexAutoSized(std::ostream & os,T value)141 std::ostream &FmtHexAutoSized(std::ostream &os, T value)
142 {
143     constexpr int N = sizeof(T) * 2;
144     return priv::FmtHex<N>(os, value);
145 }
146 
147 template <typename T>
148 class FmtHexHelper
149 {
150   public:
FmtHexHelper(const char * prefix,T value)151     FmtHexHelper(const char *prefix, T value) : mPrefix(prefix), mValue(value) {}
FmtHexHelper(T value)152     explicit FmtHexHelper(T value) : mPrefix(nullptr), mValue(value) {}
153 
154   private:
155     const char *mPrefix;
156     T mValue;
157 
158     friend std::ostream &operator<<(std::ostream &os, const FmtHexHelper &fmt)
159     {
160         if (fmt.mPrefix)
161         {
162             os << fmt.mPrefix;
163         }
164         return FmtHexAutoSized(os, fmt.mValue);
165     }
166 };
167 
168 }  // namespace priv
169 
170 template <typename T>
FmtHex(T value)171 priv::FmtHexHelper<T> FmtHex(T value)
172 {
173     return priv::FmtHexHelper<T>(value);
174 }
175 
176 #if defined(ANGLE_PLATFORM_WINDOWS)
177 priv::FmtHexHelper<HRESULT> FmtHR(HRESULT value);
178 priv::FmtHexHelper<DWORD> FmtErr(DWORD value);
179 #endif  // defined(ANGLE_PLATFORM_WINDOWS)
180 
181 template <typename T>
FmtHex(std::ostream & os,T value)182 std::ostream &FmtHex(std::ostream &os, T value)
183 {
184     return priv::FmtHexAutoSized(os, value);
185 }
186 
187 // A few definitions of macros that don't generate much code. These are used
188 // by ANGLE_LOG(). Since these are used all over our code, it's
189 // better to have compact code for these operations.
190 #define COMPACT_ANGLE_LOG_EX_EVENT(ClassName, ...) \
191     ::gl::ClassName(__FUNCTION__, __LINE__, ::gl::LOG_EVENT, ##__VA_ARGS__)
192 #define COMPACT_ANGLE_LOG_EX_INFO(ClassName, ...) \
193     ::gl::ClassName(__FUNCTION__, __LINE__, ::gl::LOG_INFO, ##__VA_ARGS__)
194 #define COMPACT_ANGLE_LOG_EX_WARN(ClassName, ...) \
195     ::gl::ClassName(__FUNCTION__, __LINE__, ::gl::LOG_WARN, ##__VA_ARGS__)
196 #define COMPACT_ANGLE_LOG_EX_ERR(ClassName, ...) \
197     ::gl::ClassName(__FUNCTION__, __LINE__, ::gl::LOG_ERR, ##__VA_ARGS__)
198 #define COMPACT_ANGLE_LOG_EX_FATAL(ClassName, ...) \
199     ::gl::ClassName(__FUNCTION__, __LINE__, ::gl::LOG_FATAL, ##__VA_ARGS__)
200 
201 #define COMPACT_ANGLE_LOG_EVENT COMPACT_ANGLE_LOG_EX_EVENT(LogMessage)
202 #define COMPACT_ANGLE_LOG_INFO COMPACT_ANGLE_LOG_EX_INFO(LogMessage)
203 #define COMPACT_ANGLE_LOG_WARN COMPACT_ANGLE_LOG_EX_WARN(LogMessage)
204 #define COMPACT_ANGLE_LOG_ERR COMPACT_ANGLE_LOG_EX_ERR(LogMessage)
205 #define COMPACT_ANGLE_LOG_FATAL COMPACT_ANGLE_LOG_EX_FATAL(LogMessage)
206 
207 #define ANGLE_LOG_IS_ON(severity) (::gl::priv::ShouldCreatePlatformLogMessage(::gl::LOG_##severity))
208 
209 // Helper macro which avoids evaluating the arguments to a stream if the condition doesn't hold.
210 // Condition is evaluated once and only once.
211 #define ANGLE_LAZY_STREAM(stream, condition) \
212     !(condition) ? static_cast<void>(0) : ::gl::priv::LogMessageVoidify() & (stream)
213 
214 // We use the preprocessor's merging operator, "##", so that, e.g.,
215 // ANGLE_LOG(EVENT) becomes the token COMPACT_ANGLE_LOG_EVENT.  There's some funny
216 // subtle difference between ostream member streaming functions (e.g.,
217 // ostream::operator<<(int) and ostream non-member streaming functions
218 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
219 // impossible to stream something like a string directly to an unnamed
220 // ostream. We employ a neat hack by calling the stream() member
221 // function of LogMessage which seems to avoid the problem.
222 #define ANGLE_LOG_STREAM(severity) COMPACT_ANGLE_LOG_##severity.stream()
223 
224 #define ANGLE_LOG(severity) ANGLE_LAZY_STREAM(ANGLE_LOG_STREAM(severity), ANGLE_LOG_IS_ON(severity))
225 
226 }  // namespace gl
227 
228 #if defined(ANGLE_ENABLE_DEBUG_TRACE) || defined(ANGLE_ENABLE_DEBUG_ANNOTATIONS)
229 #    define ANGLE_TRACE_ENABLED
230 #endif
231 
232 #if !defined(NDEBUG) || defined(ANGLE_ENABLE_RELEASE_ASSERTS)
233 #    define ANGLE_ENABLE_ASSERTS
234 #endif
235 
236 #define INFO() ANGLE_LOG(INFO)
237 #define WARN() ANGLE_LOG(WARN)
238 #define ERR() ANGLE_LOG(ERR)
239 #define FATAL() ANGLE_LOG(FATAL)
240 
241 // A macro to log a performance event around a scope.
242 #if defined(ANGLE_TRACE_ENABLED)
243 #    if defined(_MSC_VER)
244 #        define EVENT(message, ...)                                                      \
245             gl::ScopedPerfEventHelper scopedPerfEventHelper##__LINE__("%s" message "\n", \
246                                                                       __FUNCTION__, __VA_ARGS__)
247 #    else
248 #        define EVENT(message, ...)                                                          \
249             gl::ScopedPerfEventHelper scopedPerfEventHelper("%s" message "\n", __FUNCTION__, \
250                                                             ##__VA_ARGS__)
251 #    endif  // _MSC_VER
252 #else
253 #    define EVENT(message, ...) (void(0))
254 #endif
255 
256 #if defined(__GNUC__)
257 #    define ANGLE_CRASH() __builtin_trap()
258 #else
259 #    define ANGLE_CRASH() ((void)(*(volatile char *)0 = 0)), __assume(0)
260 #endif
261 
262 #if !defined(NDEBUG)
263 #    define ANGLE_ASSERT_IMPL(expression) assert(expression)
264 #else
265 // TODO(jmadill): Detect if debugger is attached and break.
266 #    define ANGLE_ASSERT_IMPL(expression) ANGLE_CRASH()
267 #endif  // !defined(NDEBUG)
268 
269 // Note that gSwallowStream is used instead of an arbitrary LOG() stream to avoid the creation of an
270 // object with a non-trivial destructor (LogMessage). On MSVC x86 (checked on 2015 Update 3), this
271 // causes a few additional pointless instructions to be emitted even at full optimization level,
272 // even though the : arm of the ternary operator is clearly never executed. Using a simpler object
273 // to be &'d with Voidify() avoids these extra instructions. Using a simpler POD object with a
274 // templated operator<< also works to avoid these instructions. However, this causes warnings on
275 // statically defined implementations of operator<<(std::ostream, ...) in some .cpp files, because
276 // they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an ostream* also is
277 // not suitable, because some compilers warn of undefined behavior.
278 #define ANGLE_EAT_STREAM_PARAMETERS \
279     true ? static_cast<void>(0) : ::gl::priv::LogMessageVoidify() & (*::gl::priv::gSwallowStream)
280 
281 // A macro asserting a condition and outputting failures to the debug log
282 #if defined(ANGLE_ENABLE_ASSERTS)
283 #    define ASSERT(expression)                                                                \
284         (expression ? static_cast<void>(0)                                                    \
285                     : (FATAL() << "\t! Assert failed in " << __FUNCTION__ << " (" << __FILE__ \
286                                << ":" << __LINE__ << "): " << #expression))
287 #else
288 #    define ASSERT(condition) ANGLE_EAT_STREAM_PARAMETERS << !(condition)
289 #endif  // defined(ANGLE_ENABLE_ASSERTS)
290 
291 #define UNREACHABLE_IS_NORETURN 0
292 
293 #define ANGLE_UNUSED_VARIABLE(variable) (static_cast<void>(variable))
294 
295 // A macro to indicate unimplemented functionality
296 #ifndef NOASSERT_UNIMPLEMENTED
297 #    define NOASSERT_UNIMPLEMENTED 1
298 #endif
299 
300 #if defined(ANGLE_TRACE_ENABLED) || defined(ANGLE_ENABLE_ASSERTS)
301 #    define UNIMPLEMENTED()                                                                       \
302         do                                                                                        \
303         {                                                                                         \
304             WARN() << "\t! Unimplemented: " << __FUNCTION__ << "(" << __FILE__ << ":" << __LINE__ \
305                    << ")";                                                                        \
306             ASSERT(NOASSERT_UNIMPLEMENTED);                                                       \
307         } while (0)
308 
309 // A macro for code which is not expected to be reached under valid assumptions
310 #    define UNREACHABLE()                                                                    \
311         do                                                                                   \
312         {                                                                                    \
313             FATAL() << "\t! Unreachable reached: " << __FUNCTION__ << "(" << __FILE__ << ":" \
314                     << __LINE__ << ")";                                                      \
315         } while (0)
316 #else
317 #    define UNIMPLEMENTED()                 \
318         do                                  \
319         {                                   \
320             ASSERT(NOASSERT_UNIMPLEMENTED); \
321         } while (0)
322 
323 // A macro for code which is not expected to be reached under valid assumptions
324 #    define UNREACHABLE()  \
325         do                 \
326         {                  \
327             ASSERT(false); \
328         } while (0)
329 #endif  // defined(ANGLE_TRACE_ENABLED) || defined(ANGLE_ENABLE_ASSERTS)
330 
331 #if defined(ANGLE_PLATFORM_WINDOWS)
332 #    define ANGLE_FUNCTION __FUNCTION__
333 #else
334 #    define ANGLE_FUNCTION __func__
335 #endif
336 
337 // Defining ANGLE_ENABLE_STRUCT_PADDING_WARNINGS will enable warnings when members are added to
338 // structs to enforce packing. This is helpful for diagnosing unexpected struct sizes when making
339 // fast cache variables.
340 #if defined(__clang__)
341 #    define ANGLE_ENABLE_STRUCT_PADDING_WARNINGS \
342         _Pragma("clang diagnostic push") _Pragma("clang diagnostic error \"-Wpadded\"")
343 #    define ANGLE_DISABLE_STRUCT_PADDING_WARNINGS _Pragma("clang diagnostic pop")
344 #elif defined(__GNUC__)
345 #    define ANGLE_ENABLE_STRUCT_PADDING_WARNINGS \
346         _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic error \"-Wpadded\"")
347 #    define ANGLE_DISABLE_STRUCT_PADDING_WARNINGS _Pragma("GCC diagnostic pop")
348 #elif defined(_MSC_VER)
349 #    define ANGLE_ENABLE_STRUCT_PADDING_WARNINGS \
350         __pragma(warning(push)) __pragma(warning(error : 4820))
351 #    define ANGLE_DISABLE_STRUCT_PADDING_WARNINGS __pragma(warning(pop))
352 #else
353 #    define ANGLE_ENABLE_STRUCT_PADDING_WARNINGS
354 #    define ANGLE_DISABLE_STRUCT_PADDING_WARNINGS
355 #endif
356 
357 #if defined(__clang__)
358 #    define ANGLE_DISABLE_EXTRA_SEMI_WARNING \
359         _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wextra-semi\"")
360 #    define ANGLE_REENABLE_EXTRA_SEMI_WARNING _Pragma("clang diagnostic pop")
361 #else
362 #    define ANGLE_DISABLE_EXTRA_SEMI_WARNING
363 #    define ANGLE_REENABLE_EXTRA_SEMI_WARNING
364 #endif
365 
366 #endif  // COMMON_DEBUG_H_
367