no bug - Import translations from android-l10n r=release a=l10n CLOSED TREE
[gecko.git] / mfbt / Assertions.h
blob634d340579350673012379ea4e5eda38e3911d85
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_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
150 * it is undefined behavior for execution to reach this point. No guarantees
151 * are made about what will happen if this is reached at runtime. Most code
152 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
153 * asserts.
155 #if defined(__clang__) || defined(__GNUC__)
156 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
157 #elif defined(_MSC_VER)
158 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
159 #else
160 # ifdef __cplusplus
161 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
162 # else
163 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
164 # endif
165 #endif
168 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
169 * call MOZ_CRASH instead.
171 #if defined(_MSC_VER)
173 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
174 * (not nested in a system function) breakpoint. This distinctively invokes
175 * Breakpad without requiring system library symbols on all stack-processing
176 * machines, as a nested breakpoint would require.
178 * We use __LINE__ to prevent the compiler from folding multiple crash sites
179 * together, which would make crash reports hard to understand.
181 * We use TerminateProcess with the exit code aborting would generate
182 * because we don't want to invoke atexit handlers, destructors, library
183 * unload handlers, and so on when our process might be in a compromised
184 * state.
186 * We don't use abort() because it'd cause Windows to annoyingly pop up the
187 * process error dialog multiple times. See bug 345118 and bug 426163.
189 * (Technically these are Windows requirements, not MSVC requirements. But
190 * practically you need MSVC for debugging, and we only ship builds created
191 * by MSVC, so doing it this way reduces complexity.)
194 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
195 MOZ_NoReturn(int aLine) {
196 *((volatile int*)NULL) = aLine;
197 TerminateProcess(GetCurrentProcess(), 3);
198 MOZ_ASSUME_UNREACHABLE_MARKER();
201 # define MOZ_REALLY_CRASH(line) \
202 do { \
203 __debugbreak(); \
204 MOZ_NoReturn(line); \
205 } while (false)
207 #elif __wasi__
209 # define MOZ_REALLY_CRASH(line) __builtin_trap()
211 #else
214 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
215 * crash. NULL is preferred however if for some reason NULL cannot be used
216 * this makes choosing another value possible.
218 * In the case of UBSan certain checks, bounds specifically, cause the compiler
219 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
220 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
221 * SEGV at 0x0.
223 # ifdef MOZ_UBSAN
224 # define MOZ_CRASH_WRITE_ADDR 0x1
225 # else
226 # define MOZ_CRASH_WRITE_ADDR NULL
227 # endif
229 # ifdef __cplusplus
230 # define MOZ_REALLY_CRASH(line) \
231 do { \
232 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
233 MOZ_NOMERGE ::abort(); \
234 } while (false)
235 # else
236 # define MOZ_REALLY_CRASH(line) \
237 do { \
238 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
239 MOZ_NOMERGE abort(); \
240 } while (false)
241 # endif
242 #endif
245 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
246 * Breakpad-compatible way, in both debug and release builds.
248 * MOZ_CRASH is a good solution for "handling" failure cases when you're
249 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
250 * corruption, and so on. It's also a good solution if you need safe behavior
251 * in release builds as well as debug builds. But if the failure is one that
252 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
254 * The optional explanation-string, if provided, must be a string literal
255 * explaining why we're crashing. This argument is intended for use with
256 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
257 * obvious why we're crashing.
259 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
260 * explanation-string, we print the string to stderr. Otherwise, we don't
261 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
262 * builds, and it's hard to print to stderr safely when memory might have been
263 * corrupted.
265 #if !(defined(DEBUG) || defined(FUZZING))
266 # define MOZ_CRASH(...) \
267 do { \
268 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
269 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
270 MOZ_REALLY_CRASH(__LINE__); \
271 } while (false)
272 #else
273 # define MOZ_CRASH(...) \
274 do { \
275 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
276 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
277 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
278 MOZ_REALLY_CRASH(__LINE__); \
279 } while (false)
280 #endif
283 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
284 * cannot be a string literal (but no other processing needs to be done on it).
285 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
286 * strings from a potentially compromised process is not without risk. If the
287 * string being passed is the result of a printf-style function, consider using
288 * MOZ_CRASH_UNSAFE_PRINTF instead.
290 * @note This macro causes data collection because crash strings are annotated
291 * to crash-stats and are publicly visible. Firefox data stewards must do data
292 * review on usages of this macro.
294 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
295 const char* aFilename, int aLine, const char* aReason) {
296 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", aFilename, aLine, aReason);
297 #if defined(DEBUG) || defined(FUZZING)
298 MOZ_ReportCrash(aReason, aFilename, aLine);
299 #endif
300 MOZ_CRASH_ANNOTATE(aReason);
301 MOZ_REALLY_CRASH(aLine);
303 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
305 static const size_t sPrintfMaxArgs = 4;
306 static const size_t sPrintfCrashReasonSize = 1024;
308 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
309 char* MOZ_CrashPrintf(const char* aFormat, ...);
312 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
313 * information is desired than a string literal can supply. The caller provides
314 * a printf-style format string, which must be a string literal and between
315 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
316 * possible, as passing arbitrary strings to printf from a potentially
317 * compromised process is not without risk.
319 * @note This macro causes data collection because crash strings are annotated
320 * to crash-stats and are publicly visible. Firefox data stewards must do data
321 * review on usages of this macro.
323 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
324 do { \
325 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
326 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
327 "Or maybe you want MOZ_CRASH instead?"); \
328 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
329 "Only up to 4 additional arguments are allowed!"); \
330 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
331 "The supplied format string is too long!"); \
332 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
333 } while (false)
335 MOZ_END_EXTERN_C
338 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
339 * debug builds. If it is, execution continues. Otherwise, an error message
340 * including the expression and the explanation-string (if provided) is printed,
341 * an attempt is made to invoke any existing debugger, and execution halts.
342 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
343 * which can correctly be falsy.
345 * The optional explanation-string, if provided, must be a string literal
346 * explaining the assertion. It is intended for use with assertions whose
347 * correctness or rationale is non-obvious, and for assertions where the "real"
348 * condition being tested is best described prosaically. Don't provide an
349 * explanation if it's not actually helpful.
351 * // No explanation needed: pointer arguments often must not be NULL.
352 * MOZ_ASSERT(arg);
354 * // An explanation can be helpful to explain exactly how we know an
355 * // assertion is valid.
356 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
357 * "given that <thingA> and <thingB>, we must have...");
359 * // Or it might disambiguate multiple identical (save for their location)
360 * // assertions of the same expression.
361 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
362 * "we already set [[PrimitiveThis]] for this Boolean object");
363 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
364 * "we already set [[PrimitiveThis]] for this String object");
366 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
367 * *only* during debugging, not "in the field". If you want the latter, use
368 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
370 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly and early beta
371 * and MOZ_ASSERT in late Beta and Release - use this when a condition is
372 * potentially rare enough to require real user testing to hit, but is not
373 * security-sensitive. This can cause user pain, so use it sparingly. If a
374 * MOZ_DIAGNOSTIC_ASSERT is firing, it should promptly be converted to a
375 * MOZ_ASSERT while the failure is being investigated, rather than letting users
376 * suffer.
378 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
379 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
383 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
384 * accidentally passing something unintended in lieu of an assertion condition.
387 #ifdef __cplusplus
388 # include <type_traits>
389 namespace mozilla {
390 namespace detail {
392 template <typename T>
393 struct AssertionConditionType {
394 using ValueT = std::remove_reference_t<T>;
395 static_assert(!std::is_array_v<ValueT>,
396 "Expected boolean assertion condition, got an array or a "
397 "string!");
398 static_assert(!std::is_function_v<ValueT>,
399 "Expected boolean assertion condition, got a function! Did "
400 "you intend to call that function?");
401 static_assert(!std::is_floating_point_v<ValueT>,
402 "It's often a bad idea to assert that a floating-point number "
403 "is nonzero, because such assertions tend to intermittently "
404 "fail. Shouldn't your code gracefully handle this case instead "
405 "of asserting? Anyway, if you really want to do that, write an "
406 "explicit boolean condition, like !!x or x!=0.");
408 static const bool isValid = true;
411 } // namespace detail
412 } // namespace mozilla
413 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
414 static_assert( \
415 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
416 "invalid assertion condition")
417 #else
418 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
419 #endif
421 #if defined(DEBUG) || defined(MOZ_ASAN)
422 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
423 MOZ_ReportAssertionFailure(__VA_ARGS__)
424 #else
425 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
426 do { /* nothing */ \
427 } while (false)
428 #endif
430 /* First the single-argument form. */
431 #define MOZ_ASSERT_HELPER1(kind, expr) \
432 do { \
433 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
434 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
435 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
436 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
437 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
438 MOZ_REALLY_CRASH(__LINE__); \
440 } while (false)
441 /* Now the two-argument form. */
442 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
443 do { \
444 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
445 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
446 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
447 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
448 __LINE__); \
449 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
450 MOZ_REALLY_CRASH(__LINE__); \
452 } while (false)
454 #define MOZ_ASSERT_GLUE(a, b) a b
455 #define MOZ_RELEASE_ASSERT(...) \
456 MOZ_ASSERT_GLUE( \
457 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
458 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
460 #ifdef DEBUG
461 # define MOZ_ASSERT(...) \
462 MOZ_ASSERT_GLUE( \
463 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
464 ("MOZ_ASSERT", __VA_ARGS__))
465 #else
466 # define MOZ_ASSERT(...) \
467 do { \
468 } while (false)
469 #endif /* DEBUG */
471 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
472 # define MOZ_DIAGNOSTIC_ASSERT(...) \
473 MOZ_ASSERT_GLUE( \
474 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
475 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
476 #else
477 # define MOZ_DIAGNOSTIC_ASSERT(...) \
478 do { \
479 } while (false)
480 #endif
483 * MOZ_ASSERT_DEBUG_OR_FUZZING is like a MOZ_ASSERT but also enabled in builds
484 * that are non-DEBUG but FUZZING. This is useful for checks that are too
485 * expensive for Nightly in general but are still indicating potentially
486 * critical bugs.
487 * In fuzzing builds, the assert is rewritten to be a diagnostic assert because
488 * we already use this in other sensitive places and fuzzing automation is
489 * set to act on these under all circumstances.
491 #ifdef FUZZING
492 # define MOZ_ASSERT_DEBUG_OR_FUZZING(...) MOZ_DIAGNOSTIC_ASSERT(__VA_ARGS__)
493 #else
494 # define MOZ_ASSERT_DEBUG_OR_FUZZING(...) MOZ_ASSERT(__VA_ARGS__)
495 #endif
498 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
499 * true.
501 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
503 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
504 * designed to catch bugs during debugging, not "in the field".
506 #ifdef DEBUG
507 # define MOZ_ASSERT_IF(cond, expr) \
508 do { \
509 if (cond) { \
510 MOZ_ASSERT(expr); \
512 } while (false)
513 #else
514 # define MOZ_ASSERT_IF(cond, expr) \
515 do { \
516 } while (false)
517 #endif
520 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
521 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
523 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
524 * diagnostic assertions work and how to use them.
526 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
527 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
528 do { \
529 if (cond) { \
530 MOZ_DIAGNOSTIC_ASSERT(expr); \
532 } while (false)
533 #else
534 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
535 do { \
536 } while (false)
537 #endif
540 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
541 * can assume that the macro call cannot be reached during execution. This lets
542 * the compiler generate better-optimized code under some circumstances, at the
543 * expense of the program's behavior being undefined if control reaches the
544 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
546 * In Gecko, you probably should not use this macro outside of performance- or
547 * size-critical code, because it's unsafe. If you don't care about code size
548 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
550 * SpiderMonkey is a different beast, and there it's acceptable to use
551 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
553 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
554 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
555 * call.
557 * Example usage:
559 * enum ValueType {
560 * VALUE_STRING,
561 * VALUE_INT,
562 * VALUE_FLOAT
563 * };
565 * int ptrToInt(ValueType type, void* value) {
567 * // We know for sure that type is either INT or FLOAT, and we want this
568 * // code to run as quickly as possible.
569 * switch (type) {
570 * case VALUE_INT:
571 * return *(int*) value;
572 * case VALUE_FLOAT:
573 * return (int) *(float*) value;
574 * default:
575 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
581 * Unconditional assert in debug builds for (assumed) unreachable code paths
582 * that have a safe return without crashing in release builds.
584 #define MOZ_ASSERT_UNREACHABLE(reason) \
585 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
587 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
588 do { \
589 MOZ_ASSERT_UNREACHABLE(reason); \
590 MOZ_ASSUME_UNREACHABLE_MARKER(); \
591 } while (false)
594 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
595 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
596 * debug builds, but intentionally fall through in release builds to handle
597 * unexpected values.
599 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
600 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
601 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
602 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
603 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
604 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
605 * warning stalemate.
607 * // Example before MOZ_FALLTHROUGH_ASSERT:
608 * switch (foo) {
609 * default:
610 * // This case wants to assert in debug builds, fall through in release.
611 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
612 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
613 * case 5:
614 * return 5;
617 * // Example with MOZ_FALLTHROUGH_ASSERT:
618 * switch (foo) {
619 * default:
620 * // This case asserts in debug builds, falls through in release.
621 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
622 * case 5:
623 * return 5;
626 #ifdef DEBUG
627 # define MOZ_FALLTHROUGH_ASSERT(...) \
628 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
629 #else
630 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
631 #endif
634 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
635 * in debug builds and in release builds both. Then, in debug builds and
636 * Nightly and early beta builds, the value of the expression is
637 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
639 #define MOZ_ALWAYS_TRUE(expr) \
640 do { \
641 if (MOZ_LIKELY(expr)) { \
642 /* Silence [[nodiscard]]. */ \
643 } else { \
644 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
646 } while (false)
648 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
649 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
650 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
653 * These are disabled when fuzzing
655 #ifdef FUZZING
656 # define MOZ_CRASH_UNLESS_FUZZING(...) \
657 do { \
658 } while (0)
659 # define MOZ_ASSERT_UNLESS_FUZZING(...) \
660 do { \
661 } while (0)
662 #else
663 # define MOZ_CRASH_UNLESS_FUZZING(...) MOZ_CRASH(__VA_ARGS__)
664 # define MOZ_ASSERT_UNLESS_FUZZING(...) MOZ_ASSERT(__VA_ARGS__)
665 #endif
667 #undef MOZ_BUFFER_STDERR
668 #undef MOZ_CRASH_CRASHREPORT
669 #undef MOZ_DUMP_ASSERTION_STACK
672 * This is only used by Array and nsTArray classes, therefore it is not
673 * required when included from C code.
675 #ifdef __cplusplus
676 namespace mozilla::detail {
677 MFBT_API MOZ_NORETURN MOZ_COLD void InvalidArrayIndex_CRASH(size_t aIndex,
678 size_t aLength);
679 } // namespace mozilla::detail
680 #endif // __cplusplus
683 * Provide a fake default value to be used when a value is required but none can
684 * sensibily be provided without adding undefined behavior or security issues.
686 * This function asserts and aborts if it ever executed.
688 * Example usage:
690 * class Trooper {
691 * const Droid& lookFor;
692 * Trooper() : lookFor(MakeCompilerAssumeUnreachableFakeValue<
693 const Droid&>()) {
694 * // The class might be instantiated due to existing caller
695 * // but this never happens in practice.
697 * };
700 #ifdef __cplusplus
701 namespace mozilla {
702 template <typename T>
703 static inline T MakeCompilerAssumeUnreachableFakeValue() {
704 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE();
706 } // namespace mozilla
707 #endif // __cplusplus
709 #endif /* mozilla_Assertions_h */