Bug 1673965 [wpt PR 26319] - Update interfaces/resize-observer.idl, a=testonly
[gecko.git] / mfbt / Assertions.h
blobd4aef43fe9e5777e9e995ae47d202fec85d05a6b
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Implementations of runtime and static assertion macros for C and C++. */
9 #ifndef mozilla_Assertions_h
10 #define mozilla_Assertions_h
12 #if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus)
13 # define MOZ_DUMP_ASSERTION_STACK
14 #endif
16 #include "mozilla/Attributes.h"
17 #include "mozilla/Compiler.h"
18 #include "mozilla/Likely.h"
19 #include "mozilla/MacroArgs.h"
20 #include "mozilla/StaticAnalysisFunctions.h"
21 #include "mozilla/Types.h"
22 #ifdef MOZ_DUMP_ASSERTION_STACK
23 # include "nsTraceRefcnt.h"
24 # ifdef ANDROID
25 # include "mozilla/StackWalk.h"
26 # include <algorithm>
27 # endif
28 #endif
31 * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter
32 * if present. It is declared here (and defined in Assertions.cpp) to make it
33 * available to all code, even libraries that don't link with the crash reporter
34 * directly.
36 MOZ_BEGIN_EXTERN_C
37 extern MFBT_DATA const char* gMozCrashReason;
38 MOZ_END_EXTERN_C
40 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
41 static inline void AnnotateMozCrashReason(const char* reason) {
42 gMozCrashReason = reason;
44 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
45 #else
46 # define MOZ_CRASH_ANNOTATE(...) \
47 do { /* nothing */ \
48 } while (false)
49 #endif
51 #include <stddef.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #ifdef _MSC_VER
56 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
57 * further depends on <windef.h>. We hardcode these few definitions manually
58 * because those headers clutter the global namespace with a significant
59 * number of undesired macros and symbols.
61 MOZ_BEGIN_EXTERN_C
62 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
63 unsigned int uExitCode);
64 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
65 MOZ_END_EXTERN_C
66 #else
67 # include <signal.h>
68 #endif
69 #ifdef ANDROID
70 # include <android/log.h>
71 #endif
73 MOZ_BEGIN_EXTERN_C
76 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
77 * location of the assertion) to the standard debug-output channel.
79 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
80 * method is primarily for internal use in this header, and only secondarily
81 * for use in implementing release-build assertions.
83 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
84 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
85 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
86 #ifdef ANDROID
87 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
88 "Assertion failure: %s, at %s:%d\n", aStr, aFilename,
89 aLine);
90 # if defined(MOZ_DUMP_ASSERTION_STACK)
91 nsTraceRefcnt::WalkTheStack(
92 [](uint32_t aFrameNumber, void* aPC, void* aSP, void* aClosure) {
93 MozCodeAddressDetails details;
94 static const size_t buflen = 1024;
95 char buf[buflen + 1]; // 1 for trailing '\n'
97 MozDescribeCodeAddress(aPC, &details);
98 MozFormatCodeAddressDetails(buf, buflen, aFrameNumber, aPC, &details);
99 size_t len = std::min(strlen(buf), buflen + 1 - 2);
100 buf[len++] = '\n';
101 buf[len] = '\0';
102 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", "%s", buf);
104 # endif
105 #else
106 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
107 # if defined(MOZ_DUMP_ASSERTION_STACK)
108 nsTraceRefcnt::WalkTheStack(stderr);
109 # endif
110 fflush(stderr);
111 #endif
114 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
115 const char* aStr, const char* aFilename,
116 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
117 #ifdef ANDROID
118 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
119 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
120 #else
121 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
122 # if defined(MOZ_DUMP_ASSERTION_STACK)
123 nsTraceRefcnt::WalkTheStack(stderr);
124 # endif
125 fflush(stderr);
126 #endif
130 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
131 * call MOZ_CRASH instead.
133 #if defined(_MSC_VER)
135 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
136 * (not nested in a system function) breakpoint. This distinctively invokes
137 * Breakpad without requiring system library symbols on all stack-processing
138 * machines, as a nested breakpoint would require.
140 * We use __LINE__ to prevent the compiler from folding multiple crash sites
141 * together, which would make crash reports hard to understand.
143 * We use TerminateProcess with the exit code aborting would generate
144 * because we don't want to invoke atexit handlers, destructors, library
145 * unload handlers, and so on when our process might be in a compromised
146 * state.
148 * We don't use abort() because it'd cause Windows to annoyingly pop up the
149 * process error dialog multiple times. See bug 345118 and bug 426163.
151 * (Technically these are Windows requirements, not MSVC requirements. But
152 * practically you need MSVC for debugging, and we only ship builds created
153 * by MSVC, so doing it this way reduces complexity.)
156 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
157 MOZ_NoReturn(int aLine) {
158 *((volatile int*)NULL) = aLine;
159 TerminateProcess(GetCurrentProcess(), 3);
162 # define MOZ_REALLY_CRASH(line) \
163 do { \
164 __debugbreak(); \
165 MOZ_NoReturn(line); \
166 } while (false)
167 #else
170 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
171 * crash. NULL is preferred however if for some reason NULL cannot be used
172 * this makes choosing another value possible.
174 * In the case of UBSan certain checks, bounds specifically, cause the compiler
175 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
176 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
177 * SEGV at 0x0.
179 # ifdef MOZ_UBSAN
180 # define MOZ_CRASH_WRITE_ADDR 0x1
181 # else
182 # define MOZ_CRASH_WRITE_ADDR NULL
183 # endif
185 # ifdef __cplusplus
186 # define MOZ_REALLY_CRASH(line) \
187 do { \
188 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
189 ::abort(); \
190 } while (false)
191 # else
192 # define MOZ_REALLY_CRASH(line) \
193 do { \
194 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
195 abort(); \
196 } while (false)
197 # endif
198 #endif
201 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
202 * Breakpad-compatible way, in both debug and release builds.
204 * MOZ_CRASH is a good solution for "handling" failure cases when you're
205 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
206 * corruption, and so on. It's also a good solution if you need safe behavior
207 * in release builds as well as debug builds. But if the failure is one that
208 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
210 * The optional explanation-string, if provided, must be a string literal
211 * explaining why we're crashing. This argument is intended for use with
212 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
213 * obvious why we're crashing.
215 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
216 * explanation-string, we print the string to stderr. Otherwise, we don't
217 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
218 * builds, and it's hard to print to stderr safely when memory might have been
219 * corrupted.
221 #ifndef DEBUG
222 # define MOZ_CRASH(...) \
223 do { \
224 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
225 MOZ_REALLY_CRASH(__LINE__); \
226 } while (false)
227 #else
228 # define MOZ_CRASH(...) \
229 do { \
230 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
231 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
232 MOZ_REALLY_CRASH(__LINE__); \
233 } while (false)
234 #endif
237 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
238 * cannot be a string literal (but no other processing needs to be done on it).
239 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
240 * strings from a potentially compromised process is not without risk. If the
241 * string being passed is the result of a printf-style function, consider using
242 * MOZ_CRASH_UNSAFE_PRINTF instead.
244 * @note This macro causes data collection because crash strings are annotated
245 * to crash-stats and are publicly visible. Firefox data stewards must do data
246 * review on usages of this macro.
248 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
249 const char* aFilename, int aLine, const char* aReason) {
250 #ifdef DEBUG
251 MOZ_ReportCrash(aReason, aFilename, aLine);
252 #endif
253 MOZ_CRASH_ANNOTATE(aReason);
254 MOZ_REALLY_CRASH(aLine);
256 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
258 static const size_t sPrintfMaxArgs = 4;
259 static const size_t sPrintfCrashReasonSize = 1024;
261 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
262 char* MOZ_CrashPrintf(const char* aFormat, ...);
265 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
266 * information is desired than a string literal can supply. The caller provides
267 * a printf-style format string, which must be a string literal and between
268 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
269 * possible, as passing arbitrary strings to printf from a potentially
270 * compromised process is not without risk.
272 * @note This macro causes data collection because crash strings are annotated
273 * to crash-stats and are publicly visible. Firefox data stewards must do data
274 * review on usages of this macro.
276 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
277 do { \
278 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
279 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
280 "Or maybe you want MOZ_CRASH instead?"); \
281 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
282 "Only up to 4 additional arguments are allowed!"); \
283 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
284 "The supplied format string is too long!"); \
285 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
286 } while (false)
288 MOZ_END_EXTERN_C
291 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
292 * debug builds. If it is, execution continues. Otherwise, an error message
293 * including the expression and the explanation-string (if provided) is printed,
294 * an attempt is made to invoke any existing debugger, and execution halts.
295 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
296 * which can correctly be falsy.
298 * The optional explanation-string, if provided, must be a string literal
299 * explaining the assertion. It is intended for use with assertions whose
300 * correctness or rationale is non-obvious, and for assertions where the "real"
301 * condition being tested is best described prosaically. Don't provide an
302 * explanation if it's not actually helpful.
304 * // No explanation needed: pointer arguments often must not be NULL.
305 * MOZ_ASSERT(arg);
307 * // An explanation can be helpful to explain exactly how we know an
308 * // assertion is valid.
309 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
310 * "given that <thingA> and <thingB>, we must have...");
312 * // Or it might disambiguate multiple identical (save for their location)
313 * // assertions of the same expression.
314 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
315 * "we already set [[PrimitiveThis]] for this Boolean object");
316 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
317 * "we already set [[PrimitiveThis]] for this String object");
319 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
320 * *only* during debugging, not "in the field". If you want the latter, use
321 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
323 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
324 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
325 * enough to require real user testing to hit, but is not security-sensitive.
326 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
327 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
328 * is being investigated, rather than letting users suffer.
330 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
331 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
335 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
336 * accidentally passing something unintended in lieu of an assertion condition.
339 #ifdef __cplusplus
340 # include <type_traits>
341 namespace mozilla {
342 namespace detail {
344 template <typename T>
345 struct AssertionConditionType {
346 using ValueT = std::remove_reference_t<T>;
347 static_assert(!std::is_array_v<ValueT>,
348 "Expected boolean assertion condition, got an array or a "
349 "string!");
350 static_assert(!std::is_function_v<ValueT>,
351 "Expected boolean assertion condition, got a function! Did "
352 "you intend to call that function?");
353 static_assert(!std::is_floating_point_v<ValueT>,
354 "It's often a bad idea to assert that a floating-point number "
355 "is nonzero, because such assertions tend to intermittently "
356 "fail. Shouldn't your code gracefully handle this case instead "
357 "of asserting? Anyway, if you really want to do that, write an "
358 "explicit boolean condition, like !!x or x!=0.");
360 static const bool isValid = true;
363 } // namespace detail
364 } // namespace mozilla
365 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
366 static_assert( \
367 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
368 "invalid assertion condition")
369 #else
370 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
371 #endif
373 #if defined(DEBUG) || defined(MOZ_ASAN)
374 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
375 MOZ_ReportAssertionFailure(__VA_ARGS__)
376 #else
377 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
378 do { /* nothing */ \
379 } while (false)
380 #endif
382 /* First the single-argument form. */
383 #define MOZ_ASSERT_HELPER1(kind, expr) \
384 do { \
385 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
386 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
387 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
388 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
389 MOZ_REALLY_CRASH(__LINE__); \
391 } while (false)
392 /* Now the two-argument form. */
393 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
394 do { \
395 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
396 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
397 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
398 __LINE__); \
399 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
400 MOZ_REALLY_CRASH(__LINE__); \
402 } while (false)
404 #define MOZ_ASSERT_GLUE(a, b) a b
405 #define MOZ_RELEASE_ASSERT(...) \
406 MOZ_ASSERT_GLUE( \
407 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
408 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
410 #ifdef DEBUG
411 # define MOZ_ASSERT(...) \
412 MOZ_ASSERT_GLUE( \
413 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
414 ("MOZ_ASSERT", __VA_ARGS__))
415 #else
416 # define MOZ_ASSERT(...) \
417 do { \
418 } while (false)
419 #endif /* DEBUG */
421 #if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION) || defined(DEBUG)
422 # define MOZ_DIAGNOSTIC_ASSERT(...) \
423 MOZ_ASSERT_GLUE( \
424 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
425 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
426 # define MOZ_DIAGNOSTIC_ASSERT_ENABLED 1
427 #else
428 # define MOZ_DIAGNOSTIC_ASSERT(...) \
429 do { \
430 } while (false)
431 #endif
434 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
435 * true.
437 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
439 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
440 * designed to catch bugs during debugging, not "in the field".
442 #ifdef DEBUG
443 # define MOZ_ASSERT_IF(cond, expr) \
444 do { \
445 if (cond) { \
446 MOZ_ASSERT(expr); \
448 } while (false)
449 #else
450 # define MOZ_ASSERT_IF(cond, expr) \
451 do { \
452 } while (false)
453 #endif
456 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
457 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
459 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
460 * diagnostic assertions work and how to use them.
462 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
463 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
464 do { \
465 if (cond) { \
466 MOZ_DIAGNOSTIC_ASSERT(expr); \
468 } while (false)
469 #else
470 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
471 do { \
472 } while (false)
473 #endif
476 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
477 * it is undefined behavior for execution to reach this point. No guarantees
478 * are made about what will happen if this is reached at runtime. Most code
479 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
480 * asserts.
482 #if defined(__clang__) || defined(__GNUC__)
483 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
484 #elif defined(_MSC_VER)
485 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
486 #else
487 # ifdef __cplusplus
488 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
489 # else
490 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
491 # endif
492 #endif
495 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
496 * can assume that the macro call cannot be reached during execution. This lets
497 * the compiler generate better-optimized code under some circumstances, at the
498 * expense of the program's behavior being undefined if control reaches the
499 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
501 * In Gecko, you probably should not use this macro outside of performance- or
502 * size-critical code, because it's unsafe. If you don't care about code size
503 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
505 * SpiderMonkey is a different beast, and there it's acceptable to use
506 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
508 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
509 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
510 * call.
512 * Example usage:
514 * enum ValueType {
515 * VALUE_STRING,
516 * VALUE_INT,
517 * VALUE_FLOAT
518 * };
520 * int ptrToInt(ValueType type, void* value) {
522 * // We know for sure that type is either INT or FLOAT, and we want this
523 * // code to run as quickly as possible.
524 * switch (type) {
525 * case VALUE_INT:
526 * return *(int*) value;
527 * case VALUE_FLOAT:
528 * return (int) *(float*) value;
529 * default:
530 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
536 * Unconditional assert in debug builds for (assumed) unreachable code paths
537 * that have a safe return without crashing in release builds.
539 #define MOZ_ASSERT_UNREACHABLE(reason) \
540 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
542 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
543 do { \
544 MOZ_ASSERT_UNREACHABLE(reason); \
545 MOZ_ASSUME_UNREACHABLE_MARKER(); \
546 } while (false)
549 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
550 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
551 * debug builds, but intentionally fall through in release builds to handle
552 * unexpected values.
554 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
555 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
556 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
557 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
558 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
559 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
560 * warning stalemate.
562 * // Example before MOZ_FALLTHROUGH_ASSERT:
563 * switch (foo) {
564 * default:
565 * // This case wants to assert in debug builds, fall through in release.
566 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
567 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
568 * case 5:
569 * return 5;
572 * // Example with MOZ_FALLTHROUGH_ASSERT:
573 * switch (foo) {
574 * default:
575 * // This case asserts in debug builds, falls through in release.
576 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
577 * case 5:
578 * return 5;
581 #ifdef DEBUG
582 # define MOZ_FALLTHROUGH_ASSERT(...) \
583 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
584 #else
585 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
586 #endif
589 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
590 * in debug builds and in release builds both. Then, in debug builds and
591 * Nightly and DevEdition release builds, the value of the expression is
592 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
594 #define MOZ_ALWAYS_TRUE(expr) \
595 do { \
596 if (MOZ_LIKELY(expr)) { \
597 /* Silence MOZ_MUST_USE. */ \
598 } else { \
599 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
601 } while (false)
603 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
604 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
605 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
607 #undef MOZ_DUMP_ASSERTION_STACK
608 #undef MOZ_CRASH_CRASHREPORT
610 #endif /* mozilla_Assertions_h */