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)) && \
14 # define MOZ_DUMP_ASSERTION_STACK
17 #include "mozilla/Attributes.h"
18 #include "mozilla/Compiler.h"
19 #include "mozilla/Likely.h"
20 #include "mozilla/MacroArgs.h"
21 #include "mozilla/StaticAnalysisFunctions.h"
22 #include "mozilla/Types.h"
23 #ifdef MOZ_DUMP_ASSERTION_STACK
24 # include "mozilla/StackWalk.h"
28 * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter
29 * if present. It is declared here (and defined in Assertions.cpp) to make it
30 * available to all code, even libraries that don't link with the crash reporter
34 extern MFBT_DATA
const char* gMozCrashReason
;
37 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
38 static inline void AnnotateMozCrashReason(const char* reason
) {
39 gMozCrashReason
= reason
;
41 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
43 # define MOZ_CRASH_ANNOTATE(...) \
53 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
54 * further depends on <windef.h>. We hardcode these few definitions manually
55 * because those headers clutter the global namespace with a significant
56 * number of undesired macros and symbols.
59 __declspec(dllimport
) int __stdcall
TerminateProcess(void* hProcess
,
60 unsigned int uExitCode
);
61 __declspec(dllimport
) void* __stdcall
GetCurrentProcess(void);
63 #elif defined(__wasi__)
65 * On Wasm/WASI platforms, we just call __builtin_trap().
71 # include <android/log.h>
76 #if defined(ANDROID) && defined(MOZ_DUMP_ASSERTION_STACK)
77 MOZ_MAYBE_UNUSED
static void MOZ_ReportAssertionFailurePrintFrame(
79 __android_log_print(ANDROID_LOG_FATAL
, "MOZ_Assert", "%s\n", aBuf
);
84 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
85 * location of the assertion) to the standard debug-output channel.
87 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
88 * method is primarily for internal use in this header, and only secondarily
89 * for use in implementing release-build assertions.
91 MOZ_MAYBE_UNUSED
static MOZ_COLD MOZ_NEVER_INLINE
void
92 MOZ_ReportAssertionFailure(const char* aStr
, const char* aFilename
,
93 int aLine
) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
{
95 __android_log_print(ANDROID_LOG_FATAL
, "MOZ_Assert",
96 "Assertion failure: %s, at %s:%d\n", aStr
, aFilename
,
98 # if defined(MOZ_DUMP_ASSERTION_STACK)
99 MozWalkTheStackWithWriter(MOZ_ReportAssertionFailurePrintFrame
, CallerPC(),
103 fprintf(stderr
, "Assertion failure: %s, at %s:%d\n", aStr
, aFilename
, aLine
);
104 # if defined(MOZ_DUMP_ASSERTION_STACK)
105 MozWalkTheStack(stderr
, CallerPC(), /* aMaxFrames */ 0);
111 MOZ_MAYBE_UNUSED
static MOZ_COLD MOZ_NEVER_INLINE
void MOZ_ReportCrash(
112 const char* aStr
, const char* aFilename
,
113 int aLine
) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
{
115 __android_log_print(ANDROID_LOG_FATAL
, "MOZ_CRASH",
116 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr
, aFilename
, aLine
);
118 fprintf(stderr
, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr
, aFilename
, aLine
);
119 # if defined(MOZ_DUMP_ASSERTION_STACK)
120 MozWalkTheStack(stderr
, CallerPC(), /* aMaxFrames */ 0);
127 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
128 * call MOZ_CRASH instead.
130 #if defined(_MSC_VER)
132 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
133 * (not nested in a system function) breakpoint. This distinctively invokes
134 * Breakpad without requiring system library symbols on all stack-processing
135 * machines, as a nested breakpoint would require.
137 * We use __LINE__ to prevent the compiler from folding multiple crash sites
138 * together, which would make crash reports hard to understand.
140 * We use TerminateProcess with the exit code aborting would generate
141 * because we don't want to invoke atexit handlers, destructors, library
142 * unload handlers, and so on when our process might be in a compromised
145 * We don't use abort() because it'd cause Windows to annoyingly pop up the
146 * process error dialog multiple times. See bug 345118 and bug 426163.
148 * (Technically these are Windows requirements, not MSVC requirements. But
149 * practically you need MSVC for debugging, and we only ship builds created
150 * by MSVC, so doing it this way reduces complexity.)
153 MOZ_MAYBE_UNUSED
static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE
void
154 MOZ_NoReturn(int aLine
) {
155 *((volatile int*)NULL
) = aLine
;
156 TerminateProcess(GetCurrentProcess(), 3);
159 # define MOZ_REALLY_CRASH(line) \
162 MOZ_NoReturn(line); \
167 # define MOZ_REALLY_CRASH(line) __builtin_trap()
172 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
173 * crash. NULL is preferred however if for some reason NULL cannot be used
174 * this makes choosing another value possible.
176 * In the case of UBSan certain checks, bounds specifically, cause the compiler
177 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
178 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
182 # define MOZ_CRASH_WRITE_ADDR 0x1
184 # define MOZ_CRASH_WRITE_ADDR NULL
188 # define MOZ_REALLY_CRASH(line) \
190 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
194 # define MOZ_REALLY_CRASH(line) \
196 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
203 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
204 * Breakpad-compatible way, in both debug and release builds.
206 * MOZ_CRASH is a good solution for "handling" failure cases when you're
207 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
208 * corruption, and so on. It's also a good solution if you need safe behavior
209 * in release builds as well as debug builds. But if the failure is one that
210 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
212 * The optional explanation-string, if provided, must be a string literal
213 * explaining why we're crashing. This argument is intended for use with
214 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
215 * obvious why we're crashing.
217 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
218 * explanation-string, we print the string to stderr. Otherwise, we don't
219 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
220 * builds, and it's hard to print to stderr safely when memory might have been
224 # define MOZ_CRASH(...) \
226 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
227 MOZ_REALLY_CRASH(__LINE__); \
230 # define MOZ_CRASH(...) \
232 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
233 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
234 MOZ_REALLY_CRASH(__LINE__); \
239 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
240 * cannot be a string literal (but no other processing needs to be done on it).
241 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
242 * strings from a potentially compromised process is not without risk. If the
243 * string being passed is the result of a printf-style function, consider using
244 * MOZ_CRASH_UNSAFE_PRINTF instead.
246 * @note This macro causes data collection because crash strings are annotated
247 * to crash-stats and are publicly visible. Firefox data stewards must do data
248 * review on usages of this macro.
250 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN
void MOZ_Crash(
251 const char* aFilename
, int aLine
, const char* aReason
) {
253 MOZ_ReportCrash(aReason
, aFilename
, aLine
);
255 MOZ_CRASH_ANNOTATE(aReason
);
256 MOZ_REALLY_CRASH(aLine
);
258 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
260 static const size_t sPrintfMaxArgs
= 4;
261 static const size_t sPrintfCrashReasonSize
= 1024;
263 MFBT_API MOZ_COLD MOZ_NEVER_INLINE
MOZ_FORMAT_PRINTF(1, 2) const
264 char* MOZ_CrashPrintf(const char* aFormat
, ...);
267 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
268 * information is desired than a string literal can supply. The caller provides
269 * a printf-style format string, which must be a string literal and between
270 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
271 * possible, as passing arbitrary strings to printf from a potentially
272 * compromised process is not without risk.
274 * @note This macro causes data collection because crash strings are annotated
275 * to crash-stats and are publicly visible. Firefox data stewards must do data
276 * review on usages of this macro.
278 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
280 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
281 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
282 "Or maybe you want MOZ_CRASH instead?"); \
283 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
284 "Only up to 4 additional arguments are allowed!"); \
285 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
286 "The supplied format string is too long!"); \
287 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
293 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
294 * debug builds. If it is, execution continues. Otherwise, an error message
295 * including the expression and the explanation-string (if provided) is printed,
296 * an attempt is made to invoke any existing debugger, and execution halts.
297 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
298 * which can correctly be falsy.
300 * The optional explanation-string, if provided, must be a string literal
301 * explaining the assertion. It is intended for use with assertions whose
302 * correctness or rationale is non-obvious, and for assertions where the "real"
303 * condition being tested is best described prosaically. Don't provide an
304 * explanation if it's not actually helpful.
306 * // No explanation needed: pointer arguments often must not be NULL.
309 * // An explanation can be helpful to explain exactly how we know an
310 * // assertion is valid.
311 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
312 * "given that <thingA> and <thingB>, we must have...");
314 * // Or it might disambiguate multiple identical (save for their location)
315 * // assertions of the same expression.
316 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
317 * "we already set [[PrimitiveThis]] for this Boolean object");
318 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
319 * "we already set [[PrimitiveThis]] for this String object");
321 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
322 * *only* during debugging, not "in the field". If you want the latter, use
323 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
325 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
326 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
327 * enough to require real user testing to hit, but is not security-sensitive.
328 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
329 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
330 * is being investigated, rather than letting users suffer.
332 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
333 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
337 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
338 * accidentally passing something unintended in lieu of an assertion condition.
342 # include <type_traits>
346 template <typename T
>
347 struct AssertionConditionType
{
348 using ValueT
= std::remove_reference_t
<T
>;
349 static_assert(!std::is_array_v
<ValueT
>,
350 "Expected boolean assertion condition, got an array or a "
352 static_assert(!std::is_function_v
<ValueT
>,
353 "Expected boolean assertion condition, got a function! Did "
354 "you intend to call that function?");
355 static_assert(!std::is_floating_point_v
<ValueT
>,
356 "It's often a bad idea to assert that a floating-point number "
357 "is nonzero, because such assertions tend to intermittently "
358 "fail. Shouldn't your code gracefully handle this case instead "
359 "of asserting? Anyway, if you really want to do that, write an "
360 "explicit boolean condition, like !!x or x!=0.");
362 static const bool isValid
= true;
365 } // namespace detail
366 } // namespace mozilla
367 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
369 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
370 "invalid assertion condition")
372 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
375 #if defined(DEBUG) || defined(MOZ_ASAN)
376 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
377 MOZ_ReportAssertionFailure(__VA_ARGS__)
379 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
384 /* First the single-argument form. */
385 #define MOZ_ASSERT_HELPER1(kind, expr) \
387 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
388 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
389 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
390 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
391 MOZ_REALLY_CRASH(__LINE__); \
394 /* Now the two-argument form. */
395 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
397 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
398 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
399 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
401 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
402 MOZ_REALLY_CRASH(__LINE__); \
406 #define MOZ_ASSERT_GLUE(a, b) a b
407 #define MOZ_RELEASE_ASSERT(...) \
409 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
410 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
413 # define MOZ_ASSERT(...) \
415 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
416 ("MOZ_ASSERT", __VA_ARGS__))
418 # define MOZ_ASSERT(...) \
423 #if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION) || defined(DEBUG)
424 # define MOZ_DIAGNOSTIC_ASSERT(...) \
426 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
427 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
428 # define MOZ_DIAGNOSTIC_ASSERT_ENABLED 1
430 # define MOZ_DIAGNOSTIC_ASSERT(...) \
436 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
439 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
441 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
442 * designed to catch bugs during debugging, not "in the field".
445 # define MOZ_ASSERT_IF(cond, expr) \
452 # define MOZ_ASSERT_IF(cond, expr) \
458 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
459 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
461 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
462 * diagnostic assertions work and how to use them.
464 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
465 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
468 MOZ_DIAGNOSTIC_ASSERT(expr); \
472 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
478 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
479 * it is undefined behavior for execution to reach this point. No guarantees
480 * are made about what will happen if this is reached at runtime. Most code
481 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
484 #if defined(__clang__) || defined(__GNUC__)
485 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
486 #elif defined(_MSC_VER)
487 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
490 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
492 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
497 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
498 * can assume that the macro call cannot be reached during execution. This lets
499 * the compiler generate better-optimized code under some circumstances, at the
500 * expense of the program's behavior being undefined if control reaches the
501 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
503 * In Gecko, you probably should not use this macro outside of performance- or
504 * size-critical code, because it's unsafe. If you don't care about code size
505 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
507 * SpiderMonkey is a different beast, and there it's acceptable to use
508 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
510 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
511 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
522 * int ptrToInt(ValueType type, void* value) {
524 * // We know for sure that type is either INT or FLOAT, and we want this
525 * // code to run as quickly as possible.
528 * return *(int*) value;
530 * return (int) *(float*) value;
532 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
538 * Unconditional assert in debug builds for (assumed) unreachable code paths
539 * that have a safe return without crashing in release builds.
541 #define MOZ_ASSERT_UNREACHABLE(reason) \
542 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
544 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
546 MOZ_ASSERT_UNREACHABLE(reason); \
547 MOZ_ASSUME_UNREACHABLE_MARKER(); \
551 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
552 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
553 * debug builds, but intentionally fall through in release builds to handle
556 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
557 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
558 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
559 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
560 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
561 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
564 * // Example before MOZ_FALLTHROUGH_ASSERT:
567 * // This case wants to assert in debug builds, fall through in release.
568 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
569 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
574 * // Example with MOZ_FALLTHROUGH_ASSERT:
577 * // This case asserts in debug builds, falls through in release.
578 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
584 # define MOZ_FALLTHROUGH_ASSERT(...) \
585 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
587 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
591 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
592 * in debug builds and in release builds both. Then, in debug builds and
593 * Nightly and DevEdition release builds, the value of the expression is
594 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
596 #define MOZ_ALWAYS_TRUE(expr) \
598 if (MOZ_LIKELY(expr)) { \
599 /* Silence [[nodiscard]]. */ \
601 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
605 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
606 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
607 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
609 #undef MOZ_DUMP_ASSERTION_STACK
610 #undef MOZ_CRASH_CRASHREPORT
612 #endif /* mozilla_Assertions_h */