Bug 1837620 - Part 2: Remove baseline ICs that guard objects when the objects becomes...
[gecko.git] / mfbt / Assertions.h
blob45e1b830cf581c080a5f6b8825b082c76e3d9f53
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
16 #if defined(XP_WIN) && (defined(DEBUG) || defined(FUZZING))
17 # define MOZ_BUFFER_STDERR
18 #endif
20 #include "mozilla/Attributes.h"
21 #include "mozilla/Compiler.h"
22 #include "mozilla/Fuzzing.h"
23 #include "mozilla/Likely.h"
24 #include "mozilla/MacroArgs.h"
25 #include "mozilla/StaticAnalysisFunctions.h"
26 #include "mozilla/Types.h"
27 #ifdef MOZ_DUMP_ASSERTION_STACK
28 # include "mozilla/StackWalk.h"
29 #endif
32 * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter
33 * if present. It is declared here (and defined in Assertions.cpp) to make it
34 * available to all code, even libraries that don't link with the crash reporter
35 * directly.
37 MOZ_BEGIN_EXTERN_C
38 extern MFBT_DATA const char* gMozCrashReason;
39 MOZ_END_EXTERN_C
41 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
42 static inline void AnnotateMozCrashReason(const char* reason) {
43 gMozCrashReason = reason;
44 // See bug 1681846, on 32-bit Android ARM the compiler removes the store to
45 // gMozCrashReason if this barrier is not present.
46 asm volatile("" ::: "memory");
48 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
49 #else
50 # define MOZ_CRASH_ANNOTATE(...) \
51 do { /* nothing */ \
52 } while (false)
53 #endif
55 #include <stddef.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #ifdef _MSC_VER
60 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
61 * further depends on <windef.h>. We hardcode these few definitions manually
62 * because those headers clutter the global namespace with a significant
63 * number of undesired macros and symbols.
65 MOZ_BEGIN_EXTERN_C
66 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
67 unsigned int uExitCode);
68 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
69 MOZ_END_EXTERN_C
70 #elif defined(__wasi__)
72 * On Wasm/WASI platforms, we just call __builtin_trap().
74 #else
75 # include <signal.h>
76 #endif
77 #ifdef ANDROID
78 # include <android/log.h>
79 #endif
81 MOZ_BEGIN_EXTERN_C
83 #if defined(ANDROID) && defined(MOZ_DUMP_ASSERTION_STACK)
84 MOZ_MAYBE_UNUSED static void MOZ_ReportAssertionFailurePrintFrame(
85 const char* aBuf) {
86 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", "%s\n", aBuf);
88 #endif
91 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
92 * location of the assertion) to the standard debug-output channel.
94 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
95 * method is primarily for internal use in this header, and only secondarily
96 * for use in implementing release-build assertions.
98 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
99 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
100 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
101 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_ASSERT", aFilename, aLine, aStr);
102 #ifdef ANDROID
103 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
104 "Assertion failure: %s, at %s:%d\n", aStr, aFilename,
105 aLine);
106 # if defined(MOZ_DUMP_ASSERTION_STACK)
107 MozWalkTheStackWithWriter(MOZ_ReportAssertionFailurePrintFrame, CallerPC(),
108 /* aMaxFrames */ 0);
109 # endif
110 #else
111 # if defined(MOZ_BUFFER_STDERR)
112 char msg[1024] = "";
113 snprintf(msg, sizeof(msg) - 1, "Assertion failure: %s, at %s:%d\n", aStr,
114 aFilename, aLine);
115 fputs(msg, stderr);
116 # else
117 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
118 # endif
119 # if defined(MOZ_DUMP_ASSERTION_STACK)
120 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
121 # endif
122 fflush(stderr);
123 #endif
126 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
127 const char* aStr, const char* aFilename,
128 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
129 #ifdef ANDROID
130 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
131 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
132 #else
133 # if defined(MOZ_BUFFER_STDERR)
134 char msg[1024] = "";
135 snprintf(msg, sizeof(msg) - 1, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr,
136 aFilename, aLine);
137 fputs(msg, stderr);
138 # else
139 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
140 # endif
141 # if defined(MOZ_DUMP_ASSERTION_STACK)
142 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
143 # endif
144 fflush(stderr);
145 #endif
149 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
150 * call MOZ_CRASH instead.
152 #if defined(_MSC_VER)
154 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
155 * (not nested in a system function) breakpoint. This distinctively invokes
156 * Breakpad without requiring system library symbols on all stack-processing
157 * machines, as a nested breakpoint would require.
159 * We use __LINE__ to prevent the compiler from folding multiple crash sites
160 * together, which would make crash reports hard to understand.
162 * We use TerminateProcess with the exit code aborting would generate
163 * because we don't want to invoke atexit handlers, destructors, library
164 * unload handlers, and so on when our process might be in a compromised
165 * state.
167 * We don't use abort() because it'd cause Windows to annoyingly pop up the
168 * process error dialog multiple times. See bug 345118 and bug 426163.
170 * (Technically these are Windows requirements, not MSVC requirements. But
171 * practically you need MSVC for debugging, and we only ship builds created
172 * by MSVC, so doing it this way reduces complexity.)
175 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
176 MOZ_NoReturn(int aLine) {
177 *((volatile int*)NULL) = aLine;
178 TerminateProcess(GetCurrentProcess(), 3);
181 # define MOZ_REALLY_CRASH(line) \
182 do { \
183 __debugbreak(); \
184 MOZ_NoReturn(line); \
185 } while (false)
187 #elif __wasi__
189 # define MOZ_REALLY_CRASH(line) __builtin_trap()
191 #else
194 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
195 * crash. NULL is preferred however if for some reason NULL cannot be used
196 * this makes choosing another value possible.
198 * In the case of UBSan certain checks, bounds specifically, cause the compiler
199 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
200 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
201 * SEGV at 0x0.
203 # ifdef MOZ_UBSAN
204 # define MOZ_CRASH_WRITE_ADDR 0x1
205 # else
206 # define MOZ_CRASH_WRITE_ADDR NULL
207 # endif
209 # ifdef __cplusplus
210 # define MOZ_REALLY_CRASH(line) \
211 do { \
212 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
213 ::abort(); \
214 } while (false)
215 # else
216 # define MOZ_REALLY_CRASH(line) \
217 do { \
218 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
219 abort(); \
220 } while (false)
221 # endif
222 #endif
225 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
226 * Breakpad-compatible way, in both debug and release builds.
228 * MOZ_CRASH is a good solution for "handling" failure cases when you're
229 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
230 * corruption, and so on. It's also a good solution if you need safe behavior
231 * in release builds as well as debug builds. But if the failure is one that
232 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
234 * The optional explanation-string, if provided, must be a string literal
235 * explaining why we're crashing. This argument is intended for use with
236 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
237 * obvious why we're crashing.
239 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
240 * explanation-string, we print the string to stderr. Otherwise, we don't
241 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
242 * builds, and it's hard to print to stderr safely when memory might have been
243 * corrupted.
245 #if !(defined(DEBUG) || defined(FUZZING))
246 # define MOZ_CRASH(...) \
247 do { \
248 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
249 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
250 MOZ_REALLY_CRASH(__LINE__); \
251 } while (false)
252 #else
253 # define MOZ_CRASH(...) \
254 do { \
255 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
256 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
257 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
258 MOZ_REALLY_CRASH(__LINE__); \
259 } while (false)
260 #endif
263 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
264 * cannot be a string literal (but no other processing needs to be done on it).
265 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
266 * strings from a potentially compromised process is not without risk. If the
267 * string being passed is the result of a printf-style function, consider using
268 * MOZ_CRASH_UNSAFE_PRINTF instead.
270 * @note This macro causes data collection because crash strings are annotated
271 * to crash-stats and are publicly visible. Firefox data stewards must do data
272 * review on usages of this macro.
274 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
275 const char* aFilename, int aLine, const char* aReason) {
276 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", aFilename, aLine, aReason);
277 #if defined(DEBUG) || defined(FUZZING)
278 MOZ_ReportCrash(aReason, aFilename, aLine);
279 #endif
280 MOZ_CRASH_ANNOTATE(aReason);
281 MOZ_REALLY_CRASH(aLine);
283 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
285 static const size_t sPrintfMaxArgs = 4;
286 static const size_t sPrintfCrashReasonSize = 1024;
288 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
289 char* MOZ_CrashPrintf(const char* aFormat, ...);
292 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
293 * information is desired than a string literal can supply. The caller provides
294 * a printf-style format string, which must be a string literal and between
295 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
296 * possible, as passing arbitrary strings to printf from a potentially
297 * compromised process is not without risk.
299 * @note This macro causes data collection because crash strings are annotated
300 * to crash-stats and are publicly visible. Firefox data stewards must do data
301 * review on usages of this macro.
303 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
304 do { \
305 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
306 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
307 "Or maybe you want MOZ_CRASH instead?"); \
308 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
309 "Only up to 4 additional arguments are allowed!"); \
310 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
311 "The supplied format string is too long!"); \
312 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
313 } while (false)
315 MOZ_END_EXTERN_C
318 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
319 * debug builds. If it is, execution continues. Otherwise, an error message
320 * including the expression and the explanation-string (if provided) is printed,
321 * an attempt is made to invoke any existing debugger, and execution halts.
322 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
323 * which can correctly be falsy.
325 * The optional explanation-string, if provided, must be a string literal
326 * explaining the assertion. It is intended for use with assertions whose
327 * correctness or rationale is non-obvious, and for assertions where the "real"
328 * condition being tested is best described prosaically. Don't provide an
329 * explanation if it's not actually helpful.
331 * // No explanation needed: pointer arguments often must not be NULL.
332 * MOZ_ASSERT(arg);
334 * // An explanation can be helpful to explain exactly how we know an
335 * // assertion is valid.
336 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
337 * "given that <thingA> and <thingB>, we must have...");
339 * // Or it might disambiguate multiple identical (save for their location)
340 * // assertions of the same expression.
341 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
342 * "we already set [[PrimitiveThis]] for this Boolean object");
343 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
344 * "we already set [[PrimitiveThis]] for this String object");
346 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
347 * *only* during debugging, not "in the field". If you want the latter, use
348 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
350 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly and early beta
351 * and MOZ_ASSERT in late Beta and Release - use this when a condition is
352 * potentially rare enough to require real user testing to hit, but is not
353 * security-sensitive. This can cause user pain, so use it sparingly. If a
354 * MOZ_DIAGNOSTIC_ASSERT is firing, it should promptly be converted to a
355 * MOZ_ASSERT while the failure is being investigated, rather than letting users
356 * suffer.
358 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
359 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
363 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
364 * accidentally passing something unintended in lieu of an assertion condition.
367 #ifdef __cplusplus
368 # include <type_traits>
369 namespace mozilla {
370 namespace detail {
372 template <typename T>
373 struct AssertionConditionType {
374 using ValueT = std::remove_reference_t<T>;
375 static_assert(!std::is_array_v<ValueT>,
376 "Expected boolean assertion condition, got an array or a "
377 "string!");
378 static_assert(!std::is_function_v<ValueT>,
379 "Expected boolean assertion condition, got a function! Did "
380 "you intend to call that function?");
381 static_assert(!std::is_floating_point_v<ValueT>,
382 "It's often a bad idea to assert that a floating-point number "
383 "is nonzero, because such assertions tend to intermittently "
384 "fail. Shouldn't your code gracefully handle this case instead "
385 "of asserting? Anyway, if you really want to do that, write an "
386 "explicit boolean condition, like !!x or x!=0.");
388 static const bool isValid = true;
391 } // namespace detail
392 } // namespace mozilla
393 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
394 static_assert( \
395 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
396 "invalid assertion condition")
397 #else
398 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
399 #endif
401 #if defined(DEBUG) || defined(MOZ_ASAN)
402 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
403 MOZ_ReportAssertionFailure(__VA_ARGS__)
404 #else
405 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
406 do { /* nothing */ \
407 } while (false)
408 #endif
410 /* First the single-argument form. */
411 #define MOZ_ASSERT_HELPER1(kind, expr) \
412 do { \
413 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
414 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
415 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
416 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
417 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
418 MOZ_REALLY_CRASH(__LINE__); \
420 } while (false)
421 /* Now the two-argument form. */
422 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
423 do { \
424 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
425 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
426 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
427 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
428 __LINE__); \
429 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
430 MOZ_REALLY_CRASH(__LINE__); \
432 } while (false)
434 #define MOZ_ASSERT_GLUE(a, b) a b
435 #define MOZ_RELEASE_ASSERT(...) \
436 MOZ_ASSERT_GLUE( \
437 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
438 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
440 #ifdef DEBUG
441 # define MOZ_ASSERT(...) \
442 MOZ_ASSERT_GLUE( \
443 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
444 ("MOZ_ASSERT", __VA_ARGS__))
445 #else
446 # define MOZ_ASSERT(...) \
447 do { \
448 } while (false)
449 #endif /* DEBUG */
451 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
452 # define MOZ_DIAGNOSTIC_ASSERT(...) \
453 MOZ_ASSERT_GLUE( \
454 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
455 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
456 #else
457 # define MOZ_DIAGNOSTIC_ASSERT(...) \
458 do { \
459 } while (false)
460 #endif
463 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
464 * true.
466 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
468 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
469 * designed to catch bugs during debugging, not "in the field".
471 #ifdef DEBUG
472 # define MOZ_ASSERT_IF(cond, expr) \
473 do { \
474 if (cond) { \
475 MOZ_ASSERT(expr); \
477 } while (false)
478 #else
479 # define MOZ_ASSERT_IF(cond, expr) \
480 do { \
481 } while (false)
482 #endif
485 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
486 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
488 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
489 * diagnostic assertions work and how to use them.
491 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
492 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
493 do { \
494 if (cond) { \
495 MOZ_DIAGNOSTIC_ASSERT(expr); \
497 } while (false)
498 #else
499 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
500 do { \
501 } while (false)
502 #endif
505 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
506 * it is undefined behavior for execution to reach this point. No guarantees
507 * are made about what will happen if this is reached at runtime. Most code
508 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
509 * asserts.
511 #if defined(__clang__) || defined(__GNUC__)
512 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
513 #elif defined(_MSC_VER)
514 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
515 #else
516 # ifdef __cplusplus
517 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
518 # else
519 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
520 # endif
521 #endif
524 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
525 * can assume that the macro call cannot be reached during execution. This lets
526 * the compiler generate better-optimized code under some circumstances, at the
527 * expense of the program's behavior being undefined if control reaches the
528 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
530 * In Gecko, you probably should not use this macro outside of performance- or
531 * size-critical code, because it's unsafe. If you don't care about code size
532 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
534 * SpiderMonkey is a different beast, and there it's acceptable to use
535 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
537 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
538 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
539 * call.
541 * Example usage:
543 * enum ValueType {
544 * VALUE_STRING,
545 * VALUE_INT,
546 * VALUE_FLOAT
547 * };
549 * int ptrToInt(ValueType type, void* value) {
551 * // We know for sure that type is either INT or FLOAT, and we want this
552 * // code to run as quickly as possible.
553 * switch (type) {
554 * case VALUE_INT:
555 * return *(int*) value;
556 * case VALUE_FLOAT:
557 * return (int) *(float*) value;
558 * default:
559 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
565 * Unconditional assert in debug builds for (assumed) unreachable code paths
566 * that have a safe return without crashing in release builds.
568 #define MOZ_ASSERT_UNREACHABLE(reason) \
569 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
571 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
572 do { \
573 MOZ_ASSERT_UNREACHABLE(reason); \
574 MOZ_ASSUME_UNREACHABLE_MARKER(); \
575 } while (false)
578 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
579 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
580 * debug builds, but intentionally fall through in release builds to handle
581 * unexpected values.
583 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
584 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
585 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
586 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
587 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
588 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
589 * warning stalemate.
591 * // Example before MOZ_FALLTHROUGH_ASSERT:
592 * switch (foo) {
593 * default:
594 * // This case wants to assert in debug builds, fall through in release.
595 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
596 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
597 * case 5:
598 * return 5;
601 * // Example with MOZ_FALLTHROUGH_ASSERT:
602 * switch (foo) {
603 * default:
604 * // This case asserts in debug builds, falls through in release.
605 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
606 * case 5:
607 * return 5;
610 #ifdef DEBUG
611 # define MOZ_FALLTHROUGH_ASSERT(...) \
612 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
613 #else
614 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
615 #endif
618 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
619 * in debug builds and in release builds both. Then, in debug builds and
620 * Nightly and early beta builds, the value of the expression is
621 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
623 #define MOZ_ALWAYS_TRUE(expr) \
624 do { \
625 if (MOZ_LIKELY(expr)) { \
626 /* Silence [[nodiscard]]. */ \
627 } else { \
628 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
630 } while (false)
632 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
633 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
634 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
637 * These are disabled when fuzzing
639 #ifdef FUZZING
640 # define MOZ_CRASH_UNLESS_FUZZING(...) \
641 do { \
642 } while (0)
643 # define MOZ_ASSERT_UNLESS_FUZZING(...) \
644 do { \
645 } while (0)
646 #else
647 # define MOZ_CRASH_UNLESS_FUZZING(...) MOZ_CRASH(__VA_ARGS__)
648 # define MOZ_ASSERT_UNLESS_FUZZING(...) MOZ_ASSERT(__VA_ARGS__)
649 #endif
651 #undef MOZ_BUFFER_STDERR
652 #undef MOZ_CRASH_CRASHREPORT
653 #undef MOZ_DUMP_ASSERTION_STACK
656 * This is only used by Array and nsTArray classes, therefore it is not
657 * required when included from C code.
659 #ifdef __cplusplus
660 namespace mozilla::detail {
661 MFBT_API MOZ_NORETURN MOZ_COLD void InvalidArrayIndex_CRASH(size_t aIndex,
662 size_t aLength);
663 } // namespace mozilla::detail
664 #endif // __cplusplus
667 * Provide a fake default value to be used when a value is required but none can
668 * sensibily be provided without adding undefined behavior or security issues.
670 * This function asserts and aborts if it ever executed.
672 * Example usage:
674 * class Trooper {
675 * const Droid& lookFor;
676 * Trooper() : lookFor(MakeCompilerAssumeUnreachableFakeValue<
677 const Droid&>()) {
678 * // The class might be instantiated due to existing caller
679 * // but this never happens in practice.
681 * };
684 #ifdef __cplusplus
685 namespace mozilla {
686 template <typename T>
687 static inline T MakeCompilerAssumeUnreachableFakeValue() {
688 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE();
690 } // namespace mozilla
691 #endif // __cplusplus
693 #endif /* mozilla_Assertions_h */