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