Bug 1731994: part 4) Declare more methods around `ContentPermissionRequestBase` ...
[gecko.git] / mfbt / Assertions.h
blobd324624b12395880da634562c5105706813e444b
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(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)) && \
13 !defined(__wasi__)
14 # define MOZ_DUMP_ASSERTION_STACK
15 #endif
17 #include "mozilla/Attributes.h"
18 #include "mozilla/Compiler.h"
19 #include "mozilla/Likely.h"
20 #include "mozilla/MacroArgs.h"
21 #include "mozilla/StaticAnalysisFunctions.h"
22 #include "mozilla/Types.h"
23 #ifdef MOZ_DUMP_ASSERTION_STACK
24 # include "mozilla/StackWalk.h"
25 #endif
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.
33 MOZ_BEGIN_EXTERN_C
34 extern MFBT_DATA const char* gMozCrashReason;
35 MOZ_END_EXTERN_C
37 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
38 static inline void AnnotateMozCrashReason(const char* reason) {
39 gMozCrashReason = reason;
41 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
42 #else
43 # define MOZ_CRASH_ANNOTATE(...) \
44 do { /* nothing */ \
45 } while (false)
46 #endif
48 #include <stddef.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #ifdef _MSC_VER
53 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
54 * further depends on <windef.h>. We hardcode these few definitions manually
55 * because those headers clutter the global namespace with a significant
56 * number of undesired macros and symbols.
58 MOZ_BEGIN_EXTERN_C
59 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
60 unsigned int uExitCode);
61 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
62 MOZ_END_EXTERN_C
63 #elif defined(__wasi__)
65 * On Wasm/WASI platforms, we just call __builtin_trap().
67 #else
68 # include <signal.h>
69 #endif
70 #ifdef ANDROID
71 # include <android/log.h>
72 #endif
74 MOZ_BEGIN_EXTERN_C
76 #if defined(ANDROID) && defined(MOZ_DUMP_ASSERTION_STACK)
77 MOZ_MAYBE_UNUSED static void MOZ_ReportAssertionFailurePrintFrame(
78 const char* aBuf) {
79 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", "%s\n", aBuf);
81 #endif
84 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
85 * location of the assertion) to the standard debug-output channel.
87 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
88 * method is primarily for internal use in this header, and only secondarily
89 * for use in implementing release-build assertions.
91 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
92 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
93 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
94 #ifdef ANDROID
95 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
96 "Assertion failure: %s, at %s:%d\n", aStr, aFilename,
97 aLine);
98 # if defined(MOZ_DUMP_ASSERTION_STACK)
99 MozWalkTheStackWithWriter(MOZ_ReportAssertionFailurePrintFrame, CallerPC(),
100 /* aMaxFrames */ 0);
101 # endif
102 #else
103 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
104 # if defined(MOZ_DUMP_ASSERTION_STACK)
105 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
106 # endif
107 fflush(stderr);
108 #endif
111 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
112 const char* aStr, const char* aFilename,
113 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
114 #ifdef ANDROID
115 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
116 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
117 #else
118 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
119 # if defined(MOZ_DUMP_ASSERTION_STACK)
120 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
121 # endif
122 fflush(stderr);
123 #endif
127 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
128 * call MOZ_CRASH instead.
130 #if defined(_MSC_VER)
132 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
133 * (not nested in a system function) breakpoint. This distinctively invokes
134 * Breakpad without requiring system library symbols on all stack-processing
135 * machines, as a nested breakpoint would require.
137 * We use __LINE__ to prevent the compiler from folding multiple crash sites
138 * together, which would make crash reports hard to understand.
140 * We use TerminateProcess with the exit code aborting would generate
141 * because we don't want to invoke atexit handlers, destructors, library
142 * unload handlers, and so on when our process might be in a compromised
143 * state.
145 * We don't use abort() because it'd cause Windows to annoyingly pop up the
146 * process error dialog multiple times. See bug 345118 and bug 426163.
148 * (Technically these are Windows requirements, not MSVC requirements. But
149 * practically you need MSVC for debugging, and we only ship builds created
150 * by MSVC, so doing it this way reduces complexity.)
153 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
154 MOZ_NoReturn(int aLine) {
155 *((volatile int*)NULL) = aLine;
156 TerminateProcess(GetCurrentProcess(), 3);
159 # define MOZ_REALLY_CRASH(line) \
160 do { \
161 __debugbreak(); \
162 MOZ_NoReturn(line); \
163 } while (false)
165 #elif __wasi__
167 # define MOZ_REALLY_CRASH(line) __builtin_trap()
169 #else
172 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
173 * crash. NULL is preferred however if for some reason NULL cannot be used
174 * this makes choosing another value possible.
176 * In the case of UBSan certain checks, bounds specifically, cause the compiler
177 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
178 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
179 * SEGV at 0x0.
181 # ifdef MOZ_UBSAN
182 # define MOZ_CRASH_WRITE_ADDR 0x1
183 # else
184 # define MOZ_CRASH_WRITE_ADDR NULL
185 # endif
187 # ifdef __cplusplus
188 # define MOZ_REALLY_CRASH(line) \
189 do { \
190 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
191 ::abort(); \
192 } while (false)
193 # else
194 # define MOZ_REALLY_CRASH(line) \
195 do { \
196 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
197 abort(); \
198 } while (false)
199 # endif
200 #endif
203 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
204 * Breakpad-compatible way, in both debug and release builds.
206 * MOZ_CRASH is a good solution for "handling" failure cases when you're
207 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
208 * corruption, and so on. It's also a good solution if you need safe behavior
209 * in release builds as well as debug builds. But if the failure is one that
210 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
212 * The optional explanation-string, if provided, must be a string literal
213 * explaining why we're crashing. This argument is intended for use with
214 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
215 * obvious why we're crashing.
217 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
218 * explanation-string, we print the string to stderr. Otherwise, we don't
219 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
220 * builds, and it's hard to print to stderr safely when memory might have been
221 * corrupted.
223 #if !(defined(DEBUG) || defined(FUZZING))
224 # define MOZ_CRASH(...) \
225 do { \
226 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
227 MOZ_REALLY_CRASH(__LINE__); \
228 } while (false)
229 #else
230 # define MOZ_CRASH(...) \
231 do { \
232 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
233 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
234 MOZ_REALLY_CRASH(__LINE__); \
235 } while (false)
236 #endif
239 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
240 * cannot be a string literal (but no other processing needs to be done on it).
241 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
242 * strings from a potentially compromised process is not without risk. If the
243 * string being passed is the result of a printf-style function, consider using
244 * MOZ_CRASH_UNSAFE_PRINTF instead.
246 * @note This macro causes data collection because crash strings are annotated
247 * to crash-stats and are publicly visible. Firefox data stewards must do data
248 * review on usages of this macro.
250 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
251 const char* aFilename, int aLine, const char* aReason) {
252 #if defined(DEBUG) || defined(FUZZING)
253 MOZ_ReportCrash(aReason, aFilename, aLine);
254 #endif
255 MOZ_CRASH_ANNOTATE(aReason);
256 MOZ_REALLY_CRASH(aLine);
258 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
260 static const size_t sPrintfMaxArgs = 4;
261 static const size_t sPrintfCrashReasonSize = 1024;
263 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
264 char* MOZ_CrashPrintf(const char* aFormat, ...);
267 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
268 * information is desired than a string literal can supply. The caller provides
269 * a printf-style format string, which must be a string literal and between
270 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
271 * possible, as passing arbitrary strings to printf from a potentially
272 * compromised process is not without risk.
274 * @note This macro causes data collection because crash strings are annotated
275 * to crash-stats and are publicly visible. Firefox data stewards must do data
276 * review on usages of this macro.
278 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
279 do { \
280 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
281 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
282 "Or maybe you want MOZ_CRASH instead?"); \
283 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
284 "Only up to 4 additional arguments are allowed!"); \
285 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
286 "The supplied format string is too long!"); \
287 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
288 } while (false)
290 MOZ_END_EXTERN_C
293 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
294 * debug builds. If it is, execution continues. Otherwise, an error message
295 * including the expression and the explanation-string (if provided) is printed,
296 * an attempt is made to invoke any existing debugger, and execution halts.
297 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
298 * which can correctly be falsy.
300 * The optional explanation-string, if provided, must be a string literal
301 * explaining the assertion. It is intended for use with assertions whose
302 * correctness or rationale is non-obvious, and for assertions where the "real"
303 * condition being tested is best described prosaically. Don't provide an
304 * explanation if it's not actually helpful.
306 * // No explanation needed: pointer arguments often must not be NULL.
307 * MOZ_ASSERT(arg);
309 * // An explanation can be helpful to explain exactly how we know an
310 * // assertion is valid.
311 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
312 * "given that <thingA> and <thingB>, we must have...");
314 * // Or it might disambiguate multiple identical (save for their location)
315 * // assertions of the same expression.
316 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
317 * "we already set [[PrimitiveThis]] for this Boolean object");
318 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
319 * "we already set [[PrimitiveThis]] for this String object");
321 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
322 * *only* during debugging, not "in the field". If you want the latter, use
323 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
325 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
326 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
327 * enough to require real user testing to hit, but is not security-sensitive.
328 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
329 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
330 * is being investigated, rather than letting users suffer.
332 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
333 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
337 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
338 * accidentally passing something unintended in lieu of an assertion condition.
341 #ifdef __cplusplus
342 # include <type_traits>
343 namespace mozilla {
344 namespace detail {
346 template <typename T>
347 struct AssertionConditionType {
348 using ValueT = std::remove_reference_t<T>;
349 static_assert(!std::is_array_v<ValueT>,
350 "Expected boolean assertion condition, got an array or a "
351 "string!");
352 static_assert(!std::is_function_v<ValueT>,
353 "Expected boolean assertion condition, got a function! Did "
354 "you intend to call that function?");
355 static_assert(!std::is_floating_point_v<ValueT>,
356 "It's often a bad idea to assert that a floating-point number "
357 "is nonzero, because such assertions tend to intermittently "
358 "fail. Shouldn't your code gracefully handle this case instead "
359 "of asserting? Anyway, if you really want to do that, write an "
360 "explicit boolean condition, like !!x or x!=0.");
362 static const bool isValid = true;
365 } // namespace detail
366 } // namespace mozilla
367 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
368 static_assert( \
369 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
370 "invalid assertion condition")
371 #else
372 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
373 #endif
375 #if defined(DEBUG) || defined(MOZ_ASAN)
376 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
377 MOZ_ReportAssertionFailure(__VA_ARGS__)
378 #else
379 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
380 do { /* nothing */ \
381 } while (false)
382 #endif
384 /* First the single-argument form. */
385 #define MOZ_ASSERT_HELPER1(kind, expr) \
386 do { \
387 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
388 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
389 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
390 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
391 MOZ_REALLY_CRASH(__LINE__); \
393 } while (false)
394 /* Now the two-argument form. */
395 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
396 do { \
397 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
398 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
399 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
400 __LINE__); \
401 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
402 MOZ_REALLY_CRASH(__LINE__); \
404 } while (false)
406 #define MOZ_ASSERT_GLUE(a, b) a b
407 #define MOZ_RELEASE_ASSERT(...) \
408 MOZ_ASSERT_GLUE( \
409 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
410 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
412 #ifdef DEBUG
413 # define MOZ_ASSERT(...) \
414 MOZ_ASSERT_GLUE( \
415 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
416 ("MOZ_ASSERT", __VA_ARGS__))
417 #else
418 # define MOZ_ASSERT(...) \
419 do { \
420 } while (false)
421 #endif /* DEBUG */
423 #if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION) || defined(DEBUG)
424 # define MOZ_DIAGNOSTIC_ASSERT(...) \
425 MOZ_ASSERT_GLUE( \
426 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
427 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
428 # define MOZ_DIAGNOSTIC_ASSERT_ENABLED 1
429 #else
430 # define MOZ_DIAGNOSTIC_ASSERT(...) \
431 do { \
432 } while (false)
433 #endif
436 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
437 * true.
439 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
441 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
442 * designed to catch bugs during debugging, not "in the field".
444 #ifdef DEBUG
445 # define MOZ_ASSERT_IF(cond, expr) \
446 do { \
447 if (cond) { \
448 MOZ_ASSERT(expr); \
450 } while (false)
451 #else
452 # define MOZ_ASSERT_IF(cond, expr) \
453 do { \
454 } while (false)
455 #endif
458 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
459 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
461 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
462 * diagnostic assertions work and how to use them.
464 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
465 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
466 do { \
467 if (cond) { \
468 MOZ_DIAGNOSTIC_ASSERT(expr); \
470 } while (false)
471 #else
472 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
473 do { \
474 } while (false)
475 #endif
478 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
479 * it is undefined behavior for execution to reach this point. No guarantees
480 * are made about what will happen if this is reached at runtime. Most code
481 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
482 * asserts.
484 #if defined(__clang__) || defined(__GNUC__)
485 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
486 #elif defined(_MSC_VER)
487 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
488 #else
489 # ifdef __cplusplus
490 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
491 # else
492 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
493 # endif
494 #endif
497 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
498 * can assume that the macro call cannot be reached during execution. This lets
499 * the compiler generate better-optimized code under some circumstances, at the
500 * expense of the program's behavior being undefined if control reaches the
501 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
503 * In Gecko, you probably should not use this macro outside of performance- or
504 * size-critical code, because it's unsafe. If you don't care about code size
505 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
507 * SpiderMonkey is a different beast, and there it's acceptable to use
508 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
510 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
511 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
512 * call.
514 * Example usage:
516 * enum ValueType {
517 * VALUE_STRING,
518 * VALUE_INT,
519 * VALUE_FLOAT
520 * };
522 * int ptrToInt(ValueType type, void* value) {
524 * // We know for sure that type is either INT or FLOAT, and we want this
525 * // code to run as quickly as possible.
526 * switch (type) {
527 * case VALUE_INT:
528 * return *(int*) value;
529 * case VALUE_FLOAT:
530 * return (int) *(float*) value;
531 * default:
532 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
538 * Unconditional assert in debug builds for (assumed) unreachable code paths
539 * that have a safe return without crashing in release builds.
541 #define MOZ_ASSERT_UNREACHABLE(reason) \
542 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
544 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
545 do { \
546 MOZ_ASSERT_UNREACHABLE(reason); \
547 MOZ_ASSUME_UNREACHABLE_MARKER(); \
548 } while (false)
551 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
552 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
553 * debug builds, but intentionally fall through in release builds to handle
554 * unexpected values.
556 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
557 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
558 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
559 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
560 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
561 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
562 * warning stalemate.
564 * // Example before MOZ_FALLTHROUGH_ASSERT:
565 * switch (foo) {
566 * default:
567 * // This case wants to assert in debug builds, fall through in release.
568 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
569 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
570 * case 5:
571 * return 5;
574 * // Example with MOZ_FALLTHROUGH_ASSERT:
575 * switch (foo) {
576 * default:
577 * // This case asserts in debug builds, falls through in release.
578 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
579 * case 5:
580 * return 5;
583 #ifdef DEBUG
584 # define MOZ_FALLTHROUGH_ASSERT(...) \
585 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
586 #else
587 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
588 #endif
591 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
592 * in debug builds and in release builds both. Then, in debug builds and
593 * Nightly and DevEdition release builds, the value of the expression is
594 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
596 #define MOZ_ALWAYS_TRUE(expr) \
597 do { \
598 if (MOZ_LIKELY(expr)) { \
599 /* Silence [[nodiscard]]. */ \
600 } else { \
601 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
603 } while (false)
605 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
606 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
607 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
609 #undef MOZ_DUMP_ASSERTION_STACK
610 #undef MOZ_CRASH_CRASHREPORT
613 * This is only used by Array and nsTArray classes, therefore it is not
614 * required when included from C code.
616 #ifdef __cplusplus
617 namespace mozilla::detail {
618 MFBT_API MOZ_NORETURN MOZ_COLD void InvalidArrayIndex_CRASH(size_t aIndex,
619 size_t aLength);
620 } // namespace mozilla::detail
621 #endif // __cplusplus
623 #endif /* mozilla_Assertions_h */