Bug 1838484 - Don't create module loader for template contents owner document r=smaug
[gecko.git] / mfbt / Assertions.h
blobcd3239eedd944100a7c96fd0ea02bead6a0608a4
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;
41 // See bug 1681846, on 32-bit Android ARM the compiler removes the store to
42 // gMozCrashReason if this barrier is not present.
43 asm volatile("" ::: "memory");
45 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
46 #else
47 # define MOZ_CRASH_ANNOTATE(...) \
48 do { /* nothing */ \
49 } while (false)
50 #endif
52 #include <stddef.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #ifdef _MSC_VER
57 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
58 * further depends on <windef.h>. We hardcode these few definitions manually
59 * because those headers clutter the global namespace with a significant
60 * number of undesired macros and symbols.
62 MOZ_BEGIN_EXTERN_C
63 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
64 unsigned int uExitCode);
65 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
66 MOZ_END_EXTERN_C
67 #elif defined(__wasi__)
69 * On Wasm/WASI platforms, we just call __builtin_trap().
71 #else
72 # include <signal.h>
73 #endif
74 #ifdef ANDROID
75 # include <android/log.h>
76 #endif
78 MOZ_BEGIN_EXTERN_C
80 #if defined(ANDROID) && defined(MOZ_DUMP_ASSERTION_STACK)
81 MOZ_MAYBE_UNUSED static void MOZ_ReportAssertionFailurePrintFrame(
82 const char* aBuf) {
83 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", "%s\n", aBuf);
85 #endif
88 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
89 * location of the assertion) to the standard debug-output channel.
91 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
92 * method is primarily for internal use in this header, and only secondarily
93 * for use in implementing release-build assertions.
95 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
96 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
97 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
98 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_ASSERT", aFilename, aLine, aStr);
99 #ifdef ANDROID
100 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
101 "Assertion failure: %s, at %s:%d\n", aStr, aFilename,
102 aLine);
103 # if defined(MOZ_DUMP_ASSERTION_STACK)
104 MozWalkTheStackWithWriter(MOZ_ReportAssertionFailurePrintFrame, CallerPC(),
105 /* aMaxFrames */ 0);
106 # endif
107 #else
108 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
109 # if defined(MOZ_DUMP_ASSERTION_STACK)
110 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
111 # endif
112 fflush(stderr);
113 #endif
116 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
117 const char* aStr, const char* aFilename,
118 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
119 #ifdef ANDROID
120 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
121 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
122 #else
123 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
124 # if defined(MOZ_DUMP_ASSERTION_STACK)
125 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
126 # endif
127 fflush(stderr);
128 #endif
132 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
133 * call MOZ_CRASH instead.
135 #if defined(_MSC_VER)
137 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
138 * (not nested in a system function) breakpoint. This distinctively invokes
139 * Breakpad without requiring system library symbols on all stack-processing
140 * machines, as a nested breakpoint would require.
142 * We use __LINE__ to prevent the compiler from folding multiple crash sites
143 * together, which would make crash reports hard to understand.
145 * We use TerminateProcess with the exit code aborting would generate
146 * because we don't want to invoke atexit handlers, destructors, library
147 * unload handlers, and so on when our process might be in a compromised
148 * state.
150 * We don't use abort() because it'd cause Windows to annoyingly pop up the
151 * process error dialog multiple times. See bug 345118 and bug 426163.
153 * (Technically these are Windows requirements, not MSVC requirements. But
154 * practically you need MSVC for debugging, and we only ship builds created
155 * by MSVC, so doing it this way reduces complexity.)
158 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
159 MOZ_NoReturn(int aLine) {
160 *((volatile int*)NULL) = aLine;
161 TerminateProcess(GetCurrentProcess(), 3);
164 # define MOZ_REALLY_CRASH(line) \
165 do { \
166 __debugbreak(); \
167 MOZ_NoReturn(line); \
168 } while (false)
170 #elif __wasi__
172 # define MOZ_REALLY_CRASH(line) __builtin_trap()
174 #else
177 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
178 * crash. NULL is preferred however if for some reason NULL cannot be used
179 * this makes choosing another value possible.
181 * In the case of UBSan certain checks, bounds specifically, cause the compiler
182 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
183 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
184 * SEGV at 0x0.
186 # ifdef MOZ_UBSAN
187 # define MOZ_CRASH_WRITE_ADDR 0x1
188 # else
189 # define MOZ_CRASH_WRITE_ADDR NULL
190 # endif
192 # ifdef __cplusplus
193 # define MOZ_REALLY_CRASH(line) \
194 do { \
195 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
196 ::abort(); \
197 } while (false)
198 # else
199 # define MOZ_REALLY_CRASH(line) \
200 do { \
201 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
202 abort(); \
203 } while (false)
204 # endif
205 #endif
208 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
209 * Breakpad-compatible way, in both debug and release builds.
211 * MOZ_CRASH is a good solution for "handling" failure cases when you're
212 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
213 * corruption, and so on. It's also a good solution if you need safe behavior
214 * in release builds as well as debug builds. But if the failure is one that
215 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
217 * The optional explanation-string, if provided, must be a string literal
218 * explaining why we're crashing. This argument is intended for use with
219 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
220 * obvious why we're crashing.
222 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
223 * explanation-string, we print the string to stderr. Otherwise, we don't
224 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
225 * builds, and it's hard to print to stderr safely when memory might have been
226 * corrupted.
228 #if !(defined(DEBUG) || defined(FUZZING))
229 # define MOZ_CRASH(...) \
230 do { \
231 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
232 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
233 MOZ_REALLY_CRASH(__LINE__); \
234 } while (false)
235 #else
236 # define MOZ_CRASH(...) \
237 do { \
238 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
239 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
240 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
241 MOZ_REALLY_CRASH(__LINE__); \
242 } while (false)
243 #endif
246 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
247 * cannot be a string literal (but no other processing needs to be done on it).
248 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
249 * strings from a potentially compromised process is not without risk. If the
250 * string being passed is the result of a printf-style function, consider using
251 * MOZ_CRASH_UNSAFE_PRINTF instead.
253 * @note This macro causes data collection because crash strings are annotated
254 * to crash-stats and are publicly visible. Firefox data stewards must do data
255 * review on usages of this macro.
257 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
258 const char* aFilename, int aLine, const char* aReason) {
259 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", aFilename, aLine, aReason);
260 #if defined(DEBUG) || defined(FUZZING)
261 MOZ_ReportCrash(aReason, aFilename, aLine);
262 #endif
263 MOZ_CRASH_ANNOTATE(aReason);
264 MOZ_REALLY_CRASH(aLine);
266 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
268 static const size_t sPrintfMaxArgs = 4;
269 static const size_t sPrintfCrashReasonSize = 1024;
271 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
272 char* MOZ_CrashPrintf(const char* aFormat, ...);
275 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
276 * information is desired than a string literal can supply. The caller provides
277 * a printf-style format string, which must be a string literal and between
278 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
279 * possible, as passing arbitrary strings to printf from a potentially
280 * compromised process is not without risk.
282 * @note This macro causes data collection because crash strings are annotated
283 * to crash-stats and are publicly visible. Firefox data stewards must do data
284 * review on usages of this macro.
286 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
287 do { \
288 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
289 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
290 "Or maybe you want MOZ_CRASH instead?"); \
291 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
292 "Only up to 4 additional arguments are allowed!"); \
293 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
294 "The supplied format string is too long!"); \
295 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
296 } while (false)
298 MOZ_END_EXTERN_C
301 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
302 * debug builds. If it is, execution continues. Otherwise, an error message
303 * including the expression and the explanation-string (if provided) is printed,
304 * an attempt is made to invoke any existing debugger, and execution halts.
305 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
306 * which can correctly be falsy.
308 * The optional explanation-string, if provided, must be a string literal
309 * explaining the assertion. It is intended for use with assertions whose
310 * correctness or rationale is non-obvious, and for assertions where the "real"
311 * condition being tested is best described prosaically. Don't provide an
312 * explanation if it's not actually helpful.
314 * // No explanation needed: pointer arguments often must not be NULL.
315 * MOZ_ASSERT(arg);
317 * // An explanation can be helpful to explain exactly how we know an
318 * // assertion is valid.
319 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
320 * "given that <thingA> and <thingB>, we must have...");
322 * // Or it might disambiguate multiple identical (save for their location)
323 * // assertions of the same expression.
324 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
325 * "we already set [[PrimitiveThis]] for this Boolean object");
326 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
327 * "we already set [[PrimitiveThis]] for this String object");
329 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
330 * *only* during debugging, not "in the field". If you want the latter, use
331 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
333 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
334 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
335 * enough to require real user testing to hit, but is not security-sensitive.
336 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
337 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
338 * is being investigated, rather than letting users suffer.
340 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
341 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
345 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
346 * accidentally passing something unintended in lieu of an assertion condition.
349 #ifdef __cplusplus
350 # include <type_traits>
351 namespace mozilla {
352 namespace detail {
354 template <typename T>
355 struct AssertionConditionType {
356 using ValueT = std::remove_reference_t<T>;
357 static_assert(!std::is_array_v<ValueT>,
358 "Expected boolean assertion condition, got an array or a "
359 "string!");
360 static_assert(!std::is_function_v<ValueT>,
361 "Expected boolean assertion condition, got a function! Did "
362 "you intend to call that function?");
363 static_assert(!std::is_floating_point_v<ValueT>,
364 "It's often a bad idea to assert that a floating-point number "
365 "is nonzero, because such assertions tend to intermittently "
366 "fail. Shouldn't your code gracefully handle this case instead "
367 "of asserting? Anyway, if you really want to do that, write an "
368 "explicit boolean condition, like !!x or x!=0.");
370 static const bool isValid = true;
373 } // namespace detail
374 } // namespace mozilla
375 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
376 static_assert( \
377 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
378 "invalid assertion condition")
379 #else
380 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
381 #endif
383 #if defined(DEBUG) || defined(MOZ_ASAN)
384 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
385 MOZ_ReportAssertionFailure(__VA_ARGS__)
386 #else
387 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
388 do { /* nothing */ \
389 } while (false)
390 #endif
392 /* First the single-argument form. */
393 #define MOZ_ASSERT_HELPER1(kind, expr) \
394 do { \
395 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
396 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
397 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
398 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
399 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
400 MOZ_REALLY_CRASH(__LINE__); \
402 } while (false)
403 /* Now the two-argument form. */
404 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
405 do { \
406 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
407 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
408 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
409 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
410 __LINE__); \
411 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
412 MOZ_REALLY_CRASH(__LINE__); \
414 } while (false)
416 #define MOZ_ASSERT_GLUE(a, b) a b
417 #define MOZ_RELEASE_ASSERT(...) \
418 MOZ_ASSERT_GLUE( \
419 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
420 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
422 #ifdef DEBUG
423 # define MOZ_ASSERT(...) \
424 MOZ_ASSERT_GLUE( \
425 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
426 ("MOZ_ASSERT", __VA_ARGS__))
427 #else
428 # define MOZ_ASSERT(...) \
429 do { \
430 } while (false)
431 #endif /* DEBUG */
433 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
434 # define MOZ_DIAGNOSTIC_ASSERT(...) \
435 MOZ_ASSERT_GLUE( \
436 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
437 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
438 #else
439 # define MOZ_DIAGNOSTIC_ASSERT(...) \
440 do { \
441 } while (false)
442 #endif
445 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
446 * true.
448 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
450 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
451 * designed to catch bugs during debugging, not "in the field".
453 #ifdef DEBUG
454 # define MOZ_ASSERT_IF(cond, expr) \
455 do { \
456 if (cond) { \
457 MOZ_ASSERT(expr); \
459 } while (false)
460 #else
461 # define MOZ_ASSERT_IF(cond, expr) \
462 do { \
463 } while (false)
464 #endif
467 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
468 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
470 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
471 * diagnostic assertions work and how to use them.
473 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
474 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
475 do { \
476 if (cond) { \
477 MOZ_DIAGNOSTIC_ASSERT(expr); \
479 } while (false)
480 #else
481 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
482 do { \
483 } while (false)
484 #endif
487 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
488 * it is undefined behavior for execution to reach this point. No guarantees
489 * are made about what will happen if this is reached at runtime. Most code
490 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
491 * asserts.
493 #if defined(__clang__) || defined(__GNUC__)
494 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
495 #elif defined(_MSC_VER)
496 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
497 #else
498 # ifdef __cplusplus
499 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
500 # else
501 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
502 # endif
503 #endif
506 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
507 * can assume that the macro call cannot be reached during execution. This lets
508 * the compiler generate better-optimized code under some circumstances, at the
509 * expense of the program's behavior being undefined if control reaches the
510 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
512 * In Gecko, you probably should not use this macro outside of performance- or
513 * size-critical code, because it's unsafe. If you don't care about code size
514 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
516 * SpiderMonkey is a different beast, and there it's acceptable to use
517 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
519 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
520 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
521 * call.
523 * Example usage:
525 * enum ValueType {
526 * VALUE_STRING,
527 * VALUE_INT,
528 * VALUE_FLOAT
529 * };
531 * int ptrToInt(ValueType type, void* value) {
533 * // We know for sure that type is either INT or FLOAT, and we want this
534 * // code to run as quickly as possible.
535 * switch (type) {
536 * case VALUE_INT:
537 * return *(int*) value;
538 * case VALUE_FLOAT:
539 * return (int) *(float*) value;
540 * default:
541 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
547 * Unconditional assert in debug builds for (assumed) unreachable code paths
548 * that have a safe return without crashing in release builds.
550 #define MOZ_ASSERT_UNREACHABLE(reason) \
551 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
553 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
554 do { \
555 MOZ_ASSERT_UNREACHABLE(reason); \
556 MOZ_ASSUME_UNREACHABLE_MARKER(); \
557 } while (false)
560 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
561 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
562 * debug builds, but intentionally fall through in release builds to handle
563 * unexpected values.
565 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
566 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
567 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
568 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
569 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
570 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
571 * warning stalemate.
573 * // Example before MOZ_FALLTHROUGH_ASSERT:
574 * switch (foo) {
575 * default:
576 * // This case wants to assert in debug builds, fall through in release.
577 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
578 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
579 * case 5:
580 * return 5;
583 * // Example with MOZ_FALLTHROUGH_ASSERT:
584 * switch (foo) {
585 * default:
586 * // This case asserts in debug builds, falls through in release.
587 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
588 * case 5:
589 * return 5;
592 #ifdef DEBUG
593 # define MOZ_FALLTHROUGH_ASSERT(...) \
594 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
595 #else
596 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
597 #endif
600 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
601 * in debug builds and in release builds both. Then, in debug builds and
602 * Nightly and DevEdition release builds, the value of the expression is
603 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
605 #define MOZ_ALWAYS_TRUE(expr) \
606 do { \
607 if (MOZ_LIKELY(expr)) { \
608 /* Silence [[nodiscard]]. */ \
609 } else { \
610 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
612 } while (false)
614 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
615 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
616 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
619 * These are disabled when fuzzing
621 #ifdef FUZZING
622 # define MOZ_CRASH_UNLESS_FUZZING(...) \
623 do { \
624 } while (0)
625 # define MOZ_ASSERT_UNLESS_FUZZING(...) \
626 do { \
627 } while (0)
628 #else
629 # define MOZ_CRASH_UNLESS_FUZZING(...) MOZ_CRASH(__VA_ARGS__)
630 # define MOZ_ASSERT_UNLESS_FUZZING(...) MOZ_ASSERT(__VA_ARGS__)
631 #endif
633 #undef MOZ_DUMP_ASSERTION_STACK
634 #undef MOZ_CRASH_CRASHREPORT
637 * This is only used by Array and nsTArray classes, therefore it is not
638 * required when included from C code.
640 #ifdef __cplusplus
641 namespace mozilla::detail {
642 MFBT_API MOZ_NORETURN MOZ_COLD void InvalidArrayIndex_CRASH(size_t aIndex,
643 size_t aLength);
644 } // namespace mozilla::detail
645 #endif // __cplusplus
648 * Provide a fake default value to be used when a value is required but none can
649 * sensibily be provided without adding undefined behavior or security issues.
651 * This function asserts and aborts if it ever executed.
653 * Example usage:
655 * class Trooper {
656 * const Droid& lookFor;
657 * Trooper() : lookFor(MakeCompilerAssumeUnreachableFakeValue<
658 const Droid&>()) {
659 * // The class might be instantiated due to existing caller
660 * // but this never happens in practice.
662 * };
665 #ifdef __cplusplus
666 namespace mozilla {
667 template <typename T>
668 static inline T MakeCompilerAssumeUnreachableFakeValue() {
669 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE();
671 } // namespace mozilla
672 #endif // __cplusplus
674 #endif /* mozilla_Assertions_h */