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