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 /* Implementations of runtime and static assertion macros for C and C++. */
8 
9 #ifndef mozilla_Assertions_h
10 #define mozilla_Assertions_h
11 
12 #if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus)
13 #define MOZ_DUMP_ASSERTION_STACK
14 #endif
15 
16 #include "mozilla/Attributes.h"
17 #include "mozilla/Compiler.h"
18 #include "mozilla/Likely.h"
19 #include "mozilla/MacroArgs.h"
20 #ifdef MOZ_DUMP_ASSERTION_STACK
21 #include "nsTraceRefcnt.h"
22 #endif
23 
24 #if defined(MOZ_CRASHREPORTER) && defined(MOZILLA_INTERNAL_API) && \
25     !defined(MOZILLA_EXTERNAL_LINKAGE) && defined(__cplusplus)
26 namespace CrashReporter {
27 // This declaration is present here as well as in nsExceptionHandler.h
28 // nsExceptionHandler.h is not directly included in this file as it includes
29 // windows.h, which can cause problems when it is imported into some files due
30 // to the number of macros defined.
31 // XXX If you change this definition - also change the definition in
32 // nsExceptionHandler.h
33 void AnnotateMozCrashReason(const char* aReason);
34 } // namespace CrashReporter
35 
36 #  define MOZ_CRASH_ANNOTATE(...) CrashReporter::AnnotateMozCrashReason("" __VA_ARGS__)
37 #else
38 #  define MOZ_CRASH_ANNOTATE(...) do { /* nothing */ } while (0)
39 #endif
40 
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #ifdef WIN32
45    /*
46     * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
47     * further depends on <windef.h>.  We hardcode these few definitions manually
48     * because those headers clutter the global namespace with a significant
49     * number of undesired macros and symbols.
50     */
51 #  ifdef __cplusplus
52 extern "C" {
53 #  endif
54 __declspec(dllimport) int __stdcall
55 TerminateProcess(void* hProcess, unsigned int uExitCode);
56 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
57 #  ifdef __cplusplus
58 }
59 #  endif
60 #else
61 #  include <signal.h>
62 #endif
63 #ifdef ANDROID
64 #  include <android/log.h>
65 #endif
66 
67 /*
68  * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C.
69  * In C++11, static_assert is provided by the compiler to the same effect.
70  * This can be useful when you make certain assumptions about what must hold for
71  * optimal, or even correct, behavior.  For example, you might assert that the
72  * size of a struct is a multiple of the target architecture's word size:
73  *
74  *   struct S { ... };
75  *   // C
76  *   MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
77  *                     "S should be a multiple of word size for efficiency");
78  *   // C++11
79  *   static_assert(sizeof(S) % sizeof(size_t) == 0,
80  *                 "S should be a multiple of word size for efficiency");
81  *
82  * This macro can be used in any location where both an extern declaration and a
83  * typedef could be used.
84  */
85 #ifndef __cplusplus
86    /*
87     * Some of the definitions below create an otherwise-unused typedef.  This
88     * triggers compiler warnings with some versions of gcc, so mark the typedefs
89     * as permissibly-unused to disable the warnings.
90     */
91 #  if defined(__GNUC__)
92 #    define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
93 #  else
94 #    define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
95 #  endif
96 #  define MOZ_STATIC_ASSERT_GLUE1(x, y)          x##y
97 #  define MOZ_STATIC_ASSERT_GLUE(x, y)           MOZ_STATIC_ASSERT_GLUE1(x, y)
98 #  if defined(__SUNPRO_CC)
99      /*
100       * The Sun Studio C++ compiler is buggy when declaring, inside a function,
101       * another extern'd function with an array argument whose length contains a
102       * sizeof, triggering the error message "sizeof expression not accepted as
103       * size of array parameter".  This bug (6688515, not public yet) would hit
104       * defining moz_static_assert as a function, so we always define an extern
105       * array for Sun Studio.
106       *
107       * We include the line number in the symbol name in a best-effort attempt
108       * to avoid conflicts (see below).
109       */
110 #    define MOZ_STATIC_ASSERT(cond, reason) \
111        extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1]
112 #  elif defined(__COUNTER__)
113      /*
114       * If there was no preferred alternative, use a compiler-agnostic version.
115       *
116       * Note that the non-__COUNTER__ version has a bug in C++: it can't be used
117       * in both |extern "C"| and normal C++ in the same translation unit.  (Alas
118       * |extern "C"| isn't allowed in a function.)  The only affected compiler
119       * we really care about is gcc 4.2.  For that compiler and others like it,
120       * we include the line number in the function name to do the best we can to
121       * avoid conflicts.  These should be rare: a conflict would require use of
122       * MOZ_STATIC_ASSERT on the same line in separate files in the same
123       * translation unit, *and* the uses would have to be in code with
124       * different linkage, *and* the first observed use must be in C++-linkage
125       * code.
126       */
127 #    define MOZ_STATIC_ASSERT(cond, reason) \
128        typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
129 #  else
130 #    define MOZ_STATIC_ASSERT(cond, reason) \
131        extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
132 #  endif
133 
134 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason)  MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
135 #else
136 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason)  static_assert(!(cond) || (expr), reason)
137 #endif
138 
139 #ifdef __cplusplus
140 extern "C" {
141 #endif
142 
143 /*
144  * Prints |aStr| as an assertion failure (using aFilename and aLine as the
145  * location of the assertion) to the standard debug-output channel.
146  *
147  * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method.  This
148  * method is primarily for internal use in this header, and only secondarily
149  * for use in implementing release-build assertions.
150  */
151 static MOZ_COLD MOZ_ALWAYS_INLINE void
MOZ_ReportAssertionFailure(const char * aStr,const char * aFilename,int aLine)152 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine)
153   MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
154 {
155 #ifdef ANDROID
156   __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
157                       "Assertion failure: %s, at %s:%d\n",
158                       aStr, aFilename, aLine);
159 #else
160   fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
161 #if defined (MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API)
162   nsTraceRefcnt::WalkTheStack(stderr);
163 #endif
164   fflush(stderr);
165 #endif
166 }
167 
168 static MOZ_COLD MOZ_ALWAYS_INLINE void
MOZ_ReportCrash(const char * aStr,const char * aFilename,int aLine)169 MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine)
170   MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
171 {
172 #ifdef ANDROID
173   __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
174                       "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
175 #else
176   fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
177 #if defined(MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API)
178   nsTraceRefcnt::WalkTheStack(stderr);
179 #endif
180   fflush(stderr);
181 #endif
182 }
183 
184 /**
185  * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH().  You should
186  * call MOZ_CRASH instead.
187  */
188 #if defined(_MSC_VER)
189    /*
190     * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
191     * (not nested in a system function) breakpoint.  This distinctively invokes
192     * Breakpad without requiring system library symbols on all stack-processing
193     * machines, as a nested breakpoint would require.
194     *
195     * We use TerminateProcess with the exit code aborting would generate
196     * because we don't want to invoke atexit handlers, destructors, library
197     * unload handlers, and so on when our process might be in a compromised
198     * state.
199     *
200     * We don't use abort() because it'd cause Windows to annoyingly pop up the
201     * process error dialog multiple times.  See bug 345118 and bug 426163.
202     *
203     * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the
204     * compiler doesn't hassle us to provide a return statement after a
205     * MOZ_REALLY_CRASH() call.
206     *
207     * (Technically these are Windows requirements, not MSVC requirements.  But
208     * practically you need MSVC for debugging, and we only ship builds created
209     * by MSVC, so doing it this way reduces complexity.)
210     */
211 
MOZ_NoReturn()212 __declspec(noreturn) __inline void MOZ_NoReturn() {}
213 
214 #  ifdef __cplusplus
215 #    define MOZ_REALLY_CRASH() \
216        do { \
217          ::__debugbreak(); \
218          *((volatile int*) NULL) = __LINE__; \
219          ::TerminateProcess(::GetCurrentProcess(), 3); \
220          ::MOZ_NoReturn(); \
221        } while (0)
222 #  else
223 #    define MOZ_REALLY_CRASH() \
224        do { \
225          __debugbreak(); \
226          *((volatile int*) NULL) = __LINE__; \
227          TerminateProcess(GetCurrentProcess(), 3); \
228          MOZ_NoReturn(); \
229        } while (0)
230 #  endif
231 #else
232 #  ifdef __cplusplus
233 #    define MOZ_REALLY_CRASH() \
234        do { \
235          *((volatile int*) NULL) = __LINE__; \
236          ::abort(); \
237        } while (0)
238 #  else
239 #    define MOZ_REALLY_CRASH() \
240        do { \
241          *((volatile int*) NULL) = __LINE__; \
242          abort(); \
243        } while (0)
244 #  endif
245 #endif
246 
247 /*
248  * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
249  * Breakpad-compatible way, in both debug and release builds.
250  *
251  * MOZ_CRASH is a good solution for "handling" failure cases when you're
252  * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
253  * corruption, and so on.  It's also a good solution if you need safe behavior
254  * in release builds as well as debug builds.  But if the failure is one that
255  * should be debugged and fixed, MOZ_ASSERT is generally preferable.
256  *
257  * The optional explanation-string, if provided, must be a string literal
258  * explaining why we're crashing.  This argument is intended for use with
259  * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
260  * obvious why we're crashing.
261  *
262  * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
263  * explanation-string, we print the string to stderr.  Otherwise, we don't
264  * print anything; this is because we want MOZ_CRASH to be 100% safe in release
265  * builds, and it's hard to print to stderr safely when memory might have been
266  * corrupted.
267  */
268 #ifndef DEBUG
269 #  define MOZ_CRASH(...) \
270      do { \
271        MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
272        MOZ_REALLY_CRASH(); \
273      } while (0)
274 #else
275 #  define MOZ_CRASH(...) \
276      do { \
277        MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
278        MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
279        MOZ_REALLY_CRASH(); \
280      } while (0)
281 #endif
282 
283 #ifdef __cplusplus
284 } /* extern "C" */
285 #endif
286 
287 /*
288  * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
289  * debug builds.  If it is, execution continues.  Otherwise, an error message
290  * including the expression and the explanation-string (if provided) is printed,
291  * an attempt is made to invoke any existing debugger, and execution halts.
292  * MOZ_ASSERT is fatal: no recovery is possible.  Do not assert a condition
293  * which can correctly be falsy.
294  *
295  * The optional explanation-string, if provided, must be a string literal
296  * explaining the assertion.  It is intended for use with assertions whose
297  * correctness or rationale is non-obvious, and for assertions where the "real"
298  * condition being tested is best described prosaically.  Don't provide an
299  * explanation if it's not actually helpful.
300  *
301  *   // No explanation needed: pointer arguments often must not be NULL.
302  *   MOZ_ASSERT(arg);
303  *
304  *   // An explanation can be helpful to explain exactly how we know an
305  *   // assertion is valid.
306  *   MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
307  *              "given that <thingA> and <thingB>, we must have...");
308  *
309  *   // Or it might disambiguate multiple identical (save for their location)
310  *   // assertions of the same expression.
311  *   MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
312  *              "we already set [[PrimitiveThis]] for this Boolean object");
313  *   MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
314  *              "we already set [[PrimitiveThis]] for this String object");
315  *
316  * MOZ_ASSERT has no effect in non-debug builds.  It is designed to catch bugs
317  * *only* during debugging, not "in the field". If you want the latter, use
318  * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
319  *
320  * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
321  * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
322  * enough to require real user testing to hit, but is not security-sensitive.
323  * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
324  * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
325  * is being investigated, rather than letting users suffer.
326  */
327 
328 /*
329  * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
330  * accidentally passing something unintended in lieu of an assertion condition.
331  */
332 
333 #ifdef __cplusplus
334 #  include "mozilla/TypeTraits.h"
335 namespace mozilla {
336 namespace detail {
337 
338 template<typename T>
339 struct AssertionConditionType
340 {
341   typedef typename RemoveReference<T>::Type ValueT;
342   static_assert(!IsArray<ValueT>::value,
343                 "Expected boolean assertion condition, got an array or a "
344                 "string!");
345   static_assert(!IsFunction<ValueT>::value,
346                 "Expected boolean assertion condition, got a function! Did "
347                 "you intend to call that function?");
348   static_assert(!IsFloatingPoint<ValueT>::value,
349                 "It's often a bad idea to assert that a floating-point number "
350                 "is nonzero, because such assertions tend to intermittently "
351                 "fail. Shouldn't your code gracefully handle this case instead "
352                 "of asserting? Anyway, if you really want to do that, write an "
353                 "explicit boolean condition, like !!x or x!=0.");
354 
355   static const bool isValid = true;
356 };
357 
358 } // namespace detail
359 } // namespace mozilla
360 #  define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
361      static_assert(mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
362                    "invalid assertion condition")
363 #else
364 #  define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
365 #endif
366 
367 /* First the single-argument form. */
368 #define MOZ_ASSERT_HELPER1(expr) \
369   do { \
370     MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
371     if (MOZ_UNLIKELY(!(expr))) { \
372       MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
373       MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ")"); \
374       MOZ_REALLY_CRASH(); \
375     } \
376   } while (0)
377 /* Now the two-argument form. */
378 #define MOZ_ASSERT_HELPER2(expr, explain) \
379   do { \
380     MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
381     if (MOZ_UNLIKELY(!(expr))) { \
382       MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
383       MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ") (" explain ")"); \
384       MOZ_REALLY_CRASH(); \
385     } \
386   } while (0)
387 
388 #define MOZ_RELEASE_ASSERT_GLUE(a, b) a b
389 #define MOZ_RELEASE_ASSERT(...) \
390   MOZ_RELEASE_ASSERT_GLUE( \
391     MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
392     (__VA_ARGS__))
393 
394 #ifdef DEBUG
395 #  define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
396 #else
397 #  define MOZ_ASSERT(...) do { } while (0)
398 #endif /* DEBUG */
399 
400 #ifdef RELEASE_BUILD
401 #  define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT
402 #else
403 #  define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT
404 #endif
405 
406 /*
407  * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
408  * true.
409  *
410  *   MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
411  *
412  * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds.  It is
413  * designed to catch bugs during debugging, not "in the field".
414  */
415 #ifdef DEBUG
416 #  define MOZ_ASSERT_IF(cond, expr) \
417      do { \
418        if (cond) { \
419          MOZ_ASSERT(expr); \
420        } \
421      } while (0)
422 #else
423 #  define MOZ_ASSERT_IF(cond, expr)  do { } while (0)
424 #endif
425 
426 /*
427  * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
428  * it is undefined behavior for execution to reach this point.  No guarantees
429  * are made about what will happen if this is reached at runtime.  Most code
430  * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
431  * asserts.
432  */
433 #if defined(__clang__) || defined(__GNUC__)
434 #  define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
435 #elif defined(_MSC_VER)
436 #  define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
437 #else
438 #  ifdef __cplusplus
439 #    define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
440 #  else
441 #    define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
442 #  endif
443 #endif
444 
445 /*
446  * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
447  * can assume that the macro call cannot be reached during execution.  This lets
448  * the compiler generate better-optimized code under some circumstances, at the
449  * expense of the program's behavior being undefined if control reaches the
450  * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
451  *
452  * In Gecko, you probably should not use this macro outside of performance- or
453  * size-critical code, because it's unsafe.  If you don't care about code size
454  * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
455  *
456  * SpiderMonkey is a different beast, and there it's acceptable to use
457  * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
458  *
459  * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
460  * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
461  * call.
462  *
463  * Example usage:
464  *
465  *   enum ValueType {
466  *     VALUE_STRING,
467  *     VALUE_INT,
468  *     VALUE_FLOAT
469  *   };
470  *
471  *   int ptrToInt(ValueType type, void* value) {
472  *   {
473  *     // We know for sure that type is either INT or FLOAT, and we want this
474  *     // code to run as quickly as possible.
475  *     switch (type) {
476  *     case VALUE_INT:
477  *       return *(int*) value;
478  *     case VALUE_FLOAT:
479  *       return (int) *(float*) value;
480  *     default:
481  *       MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
482  *     }
483  *   }
484  */
485 
486 /*
487  * Unconditional assert in debug builds for (assumed) unreachable code paths
488  * that have a safe return without crashing in release builds.
489  */
490 #define MOZ_ASSERT_UNREACHABLE(reason) \
491    MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
492 
493 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
494    do { \
495      MOZ_ASSERT_UNREACHABLE(reason); \
496      MOZ_ASSUME_UNREACHABLE_MARKER(); \
497    } while (0)
498 
499 /*
500  * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
501  * expression, in debug builds and in release builds both.  Then, in debug
502  * builds only, the value of the expression is asserted either true or false
503  * using MOZ_ASSERT.
504  */
505 #ifdef DEBUG
506 #  define MOZ_ALWAYS_TRUE(expr)      MOZ_ASSERT((expr))
507 #  define MOZ_ALWAYS_FALSE(expr)     MOZ_ASSERT(!(expr))
508 #else
509 #  define MOZ_ALWAYS_TRUE(expr) \
510   do { \
511     if ( ( expr ) ) {                       \
512       /* Silence MOZ_WARN_UNUSED_RESULT. */ \
513     } \
514   } while (0)
515 #  define MOZ_ALWAYS_FALSE(expr) \
516   do { \
517     if ( ( expr ) ) {                       \
518       /* Silence MOZ_WARN_UNUSED_RESULT. */ \
519     } \
520   } while (0)
521 #endif
522 
523 #undef MOZ_DUMP_ASSERTION_STACK
524 #undef MOZ_CRASH_CRASHREPORT
525 
526 #endif /* mozilla_Assertions_h */
527