1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef nsDebug_h___
8 #define nsDebug_h___
9 
10 #include "nscore.h"
11 #include "nsError.h"
12 
13 #include "nsXPCOM.h"
14 #include "mozilla/Assertions.h"
15 #include "mozilla/DbgMacro.h"
16 #include "mozilla/Likely.h"
17 #include <stdarg.h>
18 
19 #ifdef DEBUG
20 #  include "mozilla/ErrorNames.h"
21 #  include "mozilla/IntegerPrintfMacros.h"
22 #  include "mozilla/Printf.h"
23 #endif
24 
25 /**
26  * Warn if the given condition is true. The condition is evaluated in both
27  * release and debug builds, and the result is an expression which can be
28  * used in subsequent expressions, such as:
29  *
30  * if (NS_WARN_IF(NS_FAILED(rv)) {
31  *   return rv;
32  * }
33  *
34  * This explicit warning and return is preferred to the NS_ENSURE_* macros
35  * which hide the warning and the return control flow.
36  *
37  * This macro can also be used outside of conditions just to issue a warning,
38  * like so:
39  *
40  *   Unused << NS_WARN_IF(NS_FAILED(FnWithSideEffects());
41  *
42  * (The |Unused <<| is necessary because of the [[nodiscard]] annotation.)
43  *
44  * However, note that the argument to this macro is evaluated in all builds. If
45  * you just want a warning assertion, it is better to use NS_WARNING_ASSERTION
46  * (which evaluates the condition only in debug builds) like so:
47  *
48  *   NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "operation failed");
49  *
50  * @note This is C++-only
51  */
52 #ifdef __cplusplus
53 #  ifdef DEBUG
NS_warn_if_impl(bool aCondition,const char * aExpr,const char * aFile,int32_t aLine)54 [[nodiscard]] inline bool NS_warn_if_impl(bool aCondition, const char* aExpr,
55                                           const char* aFile, int32_t aLine) {
56   if (MOZ_UNLIKELY(aCondition)) {
57     NS_DebugBreak(NS_DEBUG_WARNING, nullptr, aExpr, aFile, aLine);
58   }
59   return aCondition;
60 }
61 #    define NS_WARN_IF(condition) \
62       NS_warn_if_impl(condition, #condition, __FILE__, __LINE__)
63 #  else
64 #    define NS_WARN_IF(condition) (bool)(condition)
65 #  endif
66 #endif
67 
68 /**
69  * Test an assertion for truth. If the expression is not true then
70  * emit a warning.
71  *
72  * Program execution continues past the usage of this macro.
73  *
74  * Note also that the non-debug version of this macro does <b>not</b>
75  * evaluate the message argument.
76  */
77 #ifdef DEBUG
78 #  define NS_WARNING_ASSERTION(_expr, _msg)                                \
79     do {                                                                   \
80       if (!(_expr)) {                                                      \
81         NS_DebugBreak(NS_DEBUG_WARNING, _msg, #_expr, __FILE__, __LINE__); \
82       }                                                                    \
83     } while (false)
84 #else
85 #  define NS_WARNING_ASSERTION(_expr, _msg) \
86     do { /* nothing */                      \
87     } while (false)
88 #endif
89 
90 /**
91  * Test an assertion for truth. If the expression is not true then
92  * trigger a program failure.
93  *
94  * Note that the non-debug version of this macro does <b>not</b>
95  * evaluate the message argument.
96  */
97 #ifdef DEBUG
MOZ_PretendNoReturn()98 inline void MOZ_PretendNoReturn() MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {}
99 #  define NS_ASSERTION(expr, str)                                          \
100     do {                                                                   \
101       if (!(expr)) {                                                       \
102         NS_DebugBreak(NS_DEBUG_ASSERTION, str, #expr, __FILE__, __LINE__); \
103         MOZ_PretendNoReturn();                                             \
104       }                                                                    \
105     } while (0)
106 #else
107 #  define NS_ASSERTION(expr, str) \
108     do { /* nothing */            \
109     } while (0)
110 #endif
111 
112 /**
113  * Log an error message.
114  */
115 #ifdef DEBUG
116 #  define NS_ERROR(str)                                                    \
117     do {                                                                   \
118       NS_DebugBreak(NS_DEBUG_ASSERTION, str, "Error", __FILE__, __LINE__); \
119       MOZ_PretendNoReturn();                                               \
120     } while (0)
121 #else
122 #  define NS_ERROR(str) \
123     do { /* nothing */  \
124     } while (0)
125 #endif
126 
127 /**
128  * Log a warning message.
129  */
130 #ifdef DEBUG
131 #  define NS_WARNING(str) \
132     NS_DebugBreak(NS_DEBUG_WARNING, str, nullptr, __FILE__, __LINE__)
133 #else
134 #  define NS_WARNING(str) \
135     do { /* nothing */    \
136     } while (0)
137 #endif
138 
139 /**
140  * Trigger a debugger breakpoint, only in debug builds.
141  */
142 #ifdef DEBUG
143 #  define NS_BREAK()                                                       \
144     do {                                                                   \
145       NS_DebugBreak(NS_DEBUG_BREAK, nullptr, nullptr, __FILE__, __LINE__); \
146       MOZ_PretendNoReturn();                                               \
147     } while (0)
148 #else
149 #  define NS_BREAK()   \
150     do { /* nothing */ \
151     } while (0)
152 #endif
153 
154 /******************************************************************************
155 ** Macros for static assertions.  These are used by the sixgill tool.
156 ** When the tool is not running these macros are no-ops.
157 ******************************************************************************/
158 
159 /* Avoid name collision if included with other headers defining annotations. */
160 #ifndef HAVE_STATIC_ANNOTATIONS
161 #  define HAVE_STATIC_ANNOTATIONS
162 
163 #  ifdef XGILL_PLUGIN
164 
165 #    define STATIC_PRECONDITION(COND) __attribute__((precondition(#    COND)))
166 #    define STATIC_PRECONDITION_ASSUME(COND) \
167       __attribute__((precondition_assume(#COND)))
168 #    define STATIC_POSTCONDITION(COND) __attribute__((postcondition(#    COND)))
169 #    define STATIC_POSTCONDITION_ASSUME(COND) \
170       __attribute__((postcondition_assume(#COND)))
171 #    define STATIC_INVARIANT(COND) __attribute__((invariant(#    COND)))
172 #    define STATIC_INVARIANT_ASSUME(COND) \
173       __attribute__((invariant_assume(#COND)))
174 
175 /* Used to make identifiers for assert/assume annotations in a function. */
176 #    define STATIC_PASTE2(X, Y) X##Y
177 #    define STATIC_PASTE1(X, Y) STATIC_PASTE2(X, Y)
178 
179 #    define STATIC_ASSUME(COND)                                          \
180       do {                                                               \
181         __attribute__((assume_static(#COND), unused)) int STATIC_PASTE1( \
182             assume_static_, __COUNTER__);                                \
183       } while (false)
184 
185 #    define STATIC_ASSERT_RUNTIME(COND)                                   \
186       do {                                                                \
187         __attribute__((assert_static_runtime(#COND),                      \
188                        unused)) int STATIC_PASTE1(assert_static_runtime_, \
189                                                   __COUNTER__);           \
190       } while (false)
191 
192 #  else /* XGILL_PLUGIN */
193 
194 #    define STATIC_PRECONDITION(COND)         /* nothing */
195 #    define STATIC_PRECONDITION_ASSUME(COND)  /* nothing */
196 #    define STATIC_POSTCONDITION(COND)        /* nothing */
197 #    define STATIC_POSTCONDITION_ASSUME(COND) /* nothing */
198 #    define STATIC_INVARIANT(COND)            /* nothing */
199 #    define STATIC_INVARIANT_ASSUME(COND)     /* nothing */
200 
201 #    define STATIC_ASSUME(COND) \
202       do { /* nothing */        \
203       } while (false)
204 #    define STATIC_ASSERT_RUNTIME(COND) \
205       do { /* nothing */                \
206       } while (false)
207 
208 #  endif /* XGILL_PLUGIN */
209 
210 #  define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference())
211 
212 #endif /* HAVE_STATIC_ANNOTATIONS */
213 
214 /******************************************************************************
215 ** Macros for terminating execution when an unrecoverable condition is
216 ** reached.  These need to be compiled regardless of the DEBUG flag.
217 ******************************************************************************/
218 
219 /* Macros for checking the trueness of an expression passed in within an
220  * interface implementation.  These need to be compiled regardless of the
221  * DEBUG flag. New code should use NS_WARN_IF(condition) instead!
222  * @status deprecated
223  */
224 
225 #define NS_ENSURE_TRUE(x, ret)                     \
226   do {                                             \
227     if (MOZ_UNLIKELY(!(x))) {                      \
228       NS_WARNING("NS_ENSURE_TRUE(" #x ") failed"); \
229       return ret;                                  \
230     }                                              \
231   } while (false)
232 
233 #define NS_ENSURE_FALSE(x, ret) NS_ENSURE_TRUE(!(x), ret)
234 
235 #define NS_ENSURE_TRUE_VOID(x)                     \
236   do {                                             \
237     if (MOZ_UNLIKELY(!(x))) {                      \
238       NS_WARNING("NS_ENSURE_TRUE(" #x ") failed"); \
239       return;                                      \
240     }                                              \
241   } while (false)
242 
243 #define NS_ENSURE_FALSE_VOID(x) NS_ENSURE_TRUE_VOID(!(x))
244 
245 /******************************************************************************
246 ** Macros for checking results
247 ******************************************************************************/
248 
249 #if defined(DEBUG) && !defined(XPCOM_GLUE_AVOID_NSPR)
250 
251 #  define NS_ENSURE_SUCCESS_BODY(res, ret)                         \
252     const char* name = mozilla::GetStaticErrorName(__rv);          \
253     mozilla::SmprintfPointer msg = mozilla::Smprintf(              \
254         "NS_ENSURE_SUCCESS(%s, %s) failed with "                   \
255         "result 0x%" PRIX32 "%s%s%s",                              \
256         #res, #ret, static_cast<uint32_t>(__rv), name ? " (" : "", \
257         name ? name : "", name ? ")" : "");                        \
258     NS_WARNING(msg.get());
259 
260 #  define NS_ENSURE_SUCCESS_BODY_VOID(res)                                     \
261     const char* name = mozilla::GetStaticErrorName(__rv);                      \
262     mozilla::SmprintfPointer msg = mozilla::Smprintf(                          \
263         "NS_ENSURE_SUCCESS_VOID(%s) failed with "                              \
264         "result 0x%" PRIX32 "%s%s%s",                                          \
265         #res, static_cast<uint32_t>(__rv), name ? " (" : "", name ? name : "", \
266         name ? ")" : "");                                                      \
267     NS_WARNING(msg.get());
268 
269 #else
270 
271 #  define NS_ENSURE_SUCCESS_BODY(res, ret) \
272     NS_WARNING("NS_ENSURE_SUCCESS(" #res ", " #ret ") failed");
273 
274 #  define NS_ENSURE_SUCCESS_BODY_VOID(res) \
275     NS_WARNING("NS_ENSURE_SUCCESS_VOID(" #res ") failed");
276 
277 #endif
278 
279 #define NS_ENSURE_SUCCESS(res, ret)                                \
280   do {                                                             \
281     nsresult __rv = res; /* Don't evaluate |res| more than once */ \
282     if (NS_FAILED(__rv)) {                                         \
283       NS_ENSURE_SUCCESS_BODY(res, ret)                             \
284       return ret;                                                  \
285     }                                                              \
286   } while (false)
287 
288 #define NS_ENSURE_SUCCESS_VOID(res)    \
289   do {                                 \
290     nsresult __rv = res;               \
291     if (NS_FAILED(__rv)) {             \
292       NS_ENSURE_SUCCESS_BODY_VOID(res) \
293       return;                          \
294     }                                  \
295   } while (false)
296 
297 /******************************************************************************
298 ** Macros for checking state and arguments upon entering interface boundaries
299 ******************************************************************************/
300 
301 #define NS_ENSURE_ARG(arg) NS_ENSURE_TRUE(arg, NS_ERROR_INVALID_ARG)
302 
303 #define NS_ENSURE_ARG_POINTER(arg) NS_ENSURE_TRUE(arg, NS_ERROR_INVALID_POINTER)
304 
305 #define NS_ENSURE_ARG_MIN(arg, min) \
306   NS_ENSURE_TRUE((arg) >= min, NS_ERROR_INVALID_ARG)
307 
308 #define NS_ENSURE_ARG_MAX(arg, max) \
309   NS_ENSURE_TRUE((arg) <= max, NS_ERROR_INVALID_ARG)
310 
311 #define NS_ENSURE_ARG_RANGE(arg, min, max) \
312   NS_ENSURE_TRUE(((arg) >= min) && ((arg) <= max), NS_ERROR_INVALID_ARG)
313 
314 #define NS_ENSURE_STATE(state) NS_ENSURE_TRUE(state, NS_ERROR_UNEXPECTED)
315 
316 #define NS_ENSURE_NO_AGGREGATION(outer) \
317   NS_ENSURE_FALSE(outer, NS_ERROR_NO_AGGREGATION)
318 
319 /*****************************************************************************/
320 
321 #if (defined(DEBUG) || (defined(NIGHTLY_BUILD) && !defined(MOZ_PROFILING))) && \
322     !defined(XPCOM_GLUE_AVOID_NSPR)
323 #  define MOZ_THREAD_SAFETY_OWNERSHIP_CHECKS_SUPPORTED 1
324 #endif
325 
326 #ifdef MOZILLA_INTERNAL_API
327 void NS_ABORT_OOM(size_t aSize);
328 #else
NS_ABORT_OOM(size_t)329 inline void NS_ABORT_OOM(size_t) { MOZ_CRASH(); }
330 #endif
331 
332 /* When compiling the XPCOM Glue on Windows, we pretend that it's going to
333  * be linked with a static CRT (-MT) even when it's not. This means that we
334  * cannot link to data exports from the CRT, only function exports. So,
335  * instead of referencing "stderr" directly, use fdopen.
336  */
337 #ifdef __cplusplus
338 extern "C" {
339 #endif
340 
341 /**
342  * printf_stderr(...) is much like fprintf(stderr, ...), except that:
343  *  - on Android and Firefox OS, *instead* of printing to stderr, it
344  *    prints to logcat.  (Newlines in the string lead to multiple lines
345  *    of logcat, but each function call implicitly completes a line even
346  *    if the string does not end with a newline.)
347  *  - on Windows, if a debugger is present, it calls OutputDebugString
348  *    in *addition* to writing to stderr
349  */
350 void printf_stderr(const char* aFmt, ...) MOZ_FORMAT_PRINTF(1, 2);
351 
352 /**
353  * Same as printf_stderr, but taking va_list instead of varargs
354  */
355 void vprintf_stderr(const char* aFmt, va_list aArgs) MOZ_FORMAT_PRINTF(1, 0);
356 
357 /**
358  * fprintf_stderr is like fprintf, except that if its file argument
359  * is stderr, it invokes printf_stderr instead.
360  *
361  * This is useful for general debugging code that logs information to a
362  * file, but that you would like to be useful on Android and Firefox OS.
363  * If you use fprintf_stderr instead of fprintf in such debugging code,
364  * then callers can pass stderr to get logging that works on Android and
365  * Firefox OS (and also the other side-effects of using printf_stderr).
366  *
367  * Code that is structured this way needs to be careful not to split a
368  * line of output across multiple calls to fprintf_stderr, since doing
369  * so will cause it to appear in multiple lines in logcat output.
370  * (Producing multiple lines at once is fine.)
371  */
372 void fprintf_stderr(FILE* aFile, const char* aFmt, ...) MOZ_FORMAT_PRINTF(2, 3);
373 
374 /*
375  * print_stderr and fprint_stderr are like printf_stderr and fprintf_stderr,
376  * except they deal with Android logcat line length limitations. They do this
377  * by printing individual lines out of the provided stringstream using separate
378  * calls to logcat.
379  */
380 void print_stderr(std::stringstream& aStr);
381 void fprint_stderr(FILE* aFile, std::stringstream& aStr);
382 
383 #ifdef __cplusplus
384 }
385 #endif
386 
387 #endif /* nsDebug_h___ */
388