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