Debian Codegraph @

mfbt/Assertions.h

raw
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/. */
6
7 /* Implementations of runtime and static assertion macros for C and C++. */
8
9 #ifndef mozilla_Assertions_h
10 #define mozilla_Assertions_h
11
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
19
20 // It appears that this is sometimes compiled without XP_WIN
21 #if defined(_WIN32)
22 # include <process.h>
23 # define MOZ_GET_PID() _getpid()
24 #elif !defined(__wasi__)
25 # include <unistd.h>
26 # define MOZ_GET_PID() getpid()
27 #else
28 // Prevent compiler warning
29 # define MOZ_GET_PID() -1
30 #endif
31
32 #include "mozilla/Attributes.h"
33 #include "mozilla/Compiler.h"
34 #include "mozilla/Fuzzing.h"
35 #include "mozilla/Likely.h"
36 #include "mozilla/MacroArgs.h"
37 #include "mozilla/StaticAnalysisFunctions.h"
38 #include "mozilla/Types.h"
39 #ifdef MOZ_DUMP_ASSERTION_STACK
40 # include "mozilla/StackWalk.h"
41 #endif
42
43 /*
44 * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter
45 * if present. It is declared here (and defined in Assertions.cpp) to make it
46 * available to all code, even libraries that don't link with the crash reporter
47 * directly.
48 */
49 MOZ_BEGIN_EXTERN_C
50 extern MFBT_DATA const char* gMozCrashReason;
51 MOZ_END_EXTERN_C
52
53 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
54 static inline void AnnotateMozCrashReason(const char* reason) {
55 gMozCrashReason = reason;
56 // The following assembly fakes a memory read/write to the compiler, which
57 // prevents the removal of gMozCrashReason store. See bug 1681846 and 1945507.
58 # if defined(__clang__)
59 asm volatile("" : "+r,m"(gMozCrashReason) : : "memory");
60 # else
61 asm volatile("" : "+m,r"(gMozCrashReason) : : "memory");
62 # endif
63 }
64 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
65 #else
66 # define MOZ_CRASH_ANNOTATE(...) \
67 do { /* nothing */ \
68 } while (false)
69 #endif
70
71 #include <stddef.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #ifdef _MSC_VER
75 /*
76 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
77 * further depends on <windef.h>. We hardcode these few definitions manually
78 * because those headers clutter the global namespace with a significant
79 * number of undesired macros and symbols.
80 */
81 MOZ_BEGIN_EXTERN_C
82 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
83 unsigned int uExitCode);
84 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
85 MOZ_END_EXTERN_C
86 #elif defined(__wasi__)
87 /*
88 * On Wasm/WASI platforms, we just call __builtin_trap().
89 */
90 #else
91 # include <signal.h>
92 #endif
93 #ifdef ANDROID
94 # include <android/log.h>
95 #endif
96
97 MOZ_BEGIN_EXTERN_C
98
99 #if defined(ANDROID) && defined(MOZ_DUMP_ASSERTION_STACK)
100 MOZ_MAYBE_UNUSED static void MOZ_ReportAssertionFailurePrintFrame(
101 const char* aBuf) {
102 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", "%s", aBuf);
103 }
104 MOZ_MAYBE_UNUSED static void MOZ_CrashPrintFrame(const char* aBuf) {
105 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Crash", "%s", aBuf);
106 }
107 #endif
108
109 /*
110 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
111 * location of the assertion) to the standard debug-output channel.
112 *
113 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
114 * method is primarily for internal use in this header, and only secondarily
115 * for use in implementing release-build assertions.
116 */
117
118 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
119 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
120 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
121 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_ASSERT", aFilename, aLine, aStr);
122 #ifdef ANDROID
123 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
124 "[%d] Assertion failure: %s, at %s:%d\n", MOZ_GET_PID(),
125 aStr, aFilename, aLine);
126 # if defined(MOZ_DUMP_ASSERTION_STACK)
127 MozWalkTheStackWithWriter(MOZ_ReportAssertionFailurePrintFrame, CallerPC(),
128 /* aMaxFrames */ 0);
129 # endif
130 #else
131 # if defined(MOZ_BUFFER_STDERR)
132 char msg[1024] = "";
133 snprintf(msg, sizeof(msg) - 1, "[%d] Assertion failure: %s, at %s:%d\n",
134 MOZ_GET_PID(), aStr, aFilename, aLine);
135 fputs(msg, stderr);
136 # else
137 fprintf(stderr, "[%d] Assertion failure: %s, at %s:%d\n", MOZ_GET_PID(), aStr,
138 aFilename, aLine);
139 # endif
140 # if defined(MOZ_DUMP_ASSERTION_STACK)
141 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
142 # endif
143 fflush(stderr);
144 #endif
145 }
146
147 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
148 const char* aStr, const char* aFilename,
149 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
150 #ifdef ANDROID
151 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
152 "[%d] Hit MOZ_CRASH(%s) at %s:%d\n", MOZ_GET_PID(), aStr,
153 aFilename, aLine);
154 # if defined(MOZ_DUMP_ASSERTION_STACK)
155 MozWalkTheStackWithWriter(MOZ_CrashPrintFrame, CallerPC(),
156 /* aMaxFrames */ 0);
157 # endif
158 #else
159 # if defined(MOZ_BUFFER_STDERR)
160 char msg[1024] = "";
161 snprintf(msg, sizeof(msg) - 1, "[%d] Hit MOZ_CRASH(%s) at %s:%d\n",
162 MOZ_GET_PID(), aStr, aFilename, aLine);
163 fputs(msg, stderr);
164 # else
165 fprintf(stderr, "[%d] Hit MOZ_CRASH(%s) at %s:%d\n", MOZ_GET_PID(), aStr,
166 aFilename, aLine);
167 # endif
168 # if defined(MOZ_DUMP_ASSERTION_STACK)
169 MozWalkTheStack(stderr, CallerPC(), /* aMaxFrames */ 0);
170 # endif
171 fflush(stderr);
172 #endif
173 }
174
175 /*
176 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
177 * it is undefined behavior for execution to reach this point. No guarantees
178 * are made about what will happen if this is reached at runtime. Most code
179 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
180 * asserts.
181 */
182 #if defined(__clang__) || defined(__GNUC__)
183 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
184 #elif defined(_MSC_VER)
185 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
186 #else
187 # ifdef __cplusplus
188 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
189 # else
190 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
191 # endif
192 #endif
193
194 /**
195 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
196 * call MOZ_CRASH instead.
197 */
198 #if defined(_MSC_VER)
199 /*
200 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
201 * (not nested in a system function) breakpoint. This distinctively invokes
202 * Breakpad without requiring system library symbols on all stack-processing
203 * machines, as a nested breakpoint would require.
204 *
205 * We use __LINE__ to prevent the compiler from folding multiple crash sites
206 * together, which would make crash reports hard to understand.
207 *
208 * We use TerminateProcess with the exit code aborting would generate
209 * because we don't want to invoke atexit handlers, destructors, library
210 * unload handlers, and so on when our process might be in a compromised
211 * state.
212 *
213 * We don't use abort() because it'd cause Windows to annoyingly pop up the
214 * process error dialog multiple times. See bug 345118 and bug 426163.
215 *
216 * (Technically these are Windows requirements, not MSVC requirements. But
217 * practically you need MSVC for debugging, and we only ship builds created
218 * by MSVC, so doing it this way reduces complexity.)
219 */
220
221 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
222 MOZ_NoReturn(int aLine) {
223 *((volatile int*)NULL) = aLine;
224 TerminateProcess(GetCurrentProcess(), 3);
225 MOZ_ASSUME_UNREACHABLE_MARKER();
226 }
227
228 # define MOZ_REALLY_CRASH(line) \
229 do { \
230 MOZ_NOMERGE __debugbreak(); \
231 MOZ_NoReturn(line); \
232 } while (false)
233
234 #elif __wasi__
235
236 # define MOZ_REALLY_CRASH(line) __builtin_trap()
237
238 #else
239
240 /*
241 * MOZ_CrashSequence() executes a sequence that causes the process to crash by
242 * writing the line number specified in the `aLine` parameter to the address
243 * provide by `aAddress`. The store is implemented as volatile assembly code to
244 * ensure it's always included in the output and always executed.
245 */
246 static inline void MOZ_CrashSequence(void* aAddress, intptr_t aLine) {
247 # if defined(__i386__) || defined(__x86_64__)
248 asm volatile(
249 "mov %1, (%0);\n" // Write the line number to the crashing address
250 : // no output registers
251 : "r"(aAddress), "r"(aLine));
252 # elif defined(__arm__) || defined(__aarch64__)
253 asm volatile(
254 "str %1,[%0];\n" // Write the line number to the crashing address
255 : // no output registers
256 : "r"(aAddress), "r"(aLine));
257 # elif defined(__riscv) && (__riscv_xlen == 64)
258 asm volatile(
259 "sd %1,0(%0);\n" // Write the line number to the crashing address
260 : // no output registers
261 : "r"(aAddress), "r"(aLine));
262 # elif defined(__sparc__) && defined(__arch64__)
263 asm volatile(
264 "stx %1,[%0];\n" // Write the line number to the crashing address
265 : // no output registers
266 : "r"(aAddress), "r"(aLine));
267 # elif defined(__loongarch64)
268 asm volatile(
269 "st.d %1,%0,0;\n" // Write the line number to the crashing address
270 : // no output registers
271 : "r"(aAddress), "r"(aLine));
272 # else
273 # warning \
274 "Unsupported architecture, replace the code below with assembly suitable to crash the process"
275 asm volatile("" ::: "memory");
276 *((volatile int*)aAddress) = aLine; /* NOLINT */
277 # endif
278 }
279
280 /*
281 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
282 * crash. NULL is preferred however if for some reason NULL cannot be used
283 * this makes choosing another value possible.
284 *
285 * In the case of UBSan certain checks, bounds specifically, cause the compiler
286 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
287 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
288 * SEGV at 0x0.
289 */
290 # ifdef MOZ_UBSAN
291 # define MOZ_CRASH_WRITE_ADDR ((void*)0x1)
292 # else
293 # define MOZ_CRASH_WRITE_ADDR NULL
294 # endif
295
296 # ifdef __cplusplus
297 # define MOZ_REALLY_CRASH(line) \
298 do { \
299 MOZ_CrashSequence(MOZ_CRASH_WRITE_ADDR, line); \
300 MOZ_NOMERGE ::abort(); \
301 } while (false)
302 # else
303 # define MOZ_REALLY_CRASH(line) \
304 do { \
305 MOZ_CrashSequence(MOZ_CRASH_WRITE_ADDR, line); \
306 MOZ_NOMERGE abort(); \
307 } while (false)
308 # endif
309 #endif
310
311 /*
312 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
313 * Breakpad-compatible way, in both debug and release builds.
314 *
315 * MOZ_CRASH is a good solution for "handling" failure cases when you're
316 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
317 * corruption, and so on. It's also a good solution if you need safe behavior
318 * in release builds as well as debug builds. But if the failure is one that
319 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
320 *
321 * The optional explanation-string, if provided, must be a string literal
322 * explaining why we're crashing. This argument is intended for use with
323 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
324 * obvious why we're crashing.
325 *
326 * If we're a DEBUG, ASAN or FUZZING build and we crash at a MOZ_CRASH which
327 * provides an explanation-string, we print the string to stderr. Otherwise,
328 * we don't print anything; this is because we want MOZ_CRASH to be 100% safe
329 * in release builds, and it's hard to print to stderr safely when memory might
330 * have been corrupted.
331 */
332 #if !(defined(DEBUG) || defined(MOZ_ASAN) || defined(FUZZING))
333 # define MOZ_CRASH(...) \
334 do { \
335 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
336 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
337 MOZ_REALLY_CRASH(__LINE__); \
338 } while (false)
339 #else
340 # define MOZ_CRASH(...) \
341 do { \
342 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", __FILE__, __LINE__, NULL); \
343 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
344 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
345 MOZ_REALLY_CRASH(__LINE__); \
346 } while (false)
347 #endif
348
349 /*
350 * MOZ_DIAGNOSTIC_CRASH acts like MOZ_CRASH in a MOZ_DIAGNOSTIC_ASSERT_ENABLED
351 * build, and does nothing otherwise. See the comment later in this file for a
352 * description of when MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined.
353 */
354 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
355 # define MOZ_DIAGNOSTIC_CRASH(...) MOZ_CRASH(__VA_ARGS__)
356 #else
357 # define MOZ_DIAGNOSTIC_CRASH(...) \
358 do { /* nothing */ \
359 } while (false)
360 #endif
361
362 /*
363 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
364 * cannot be a string literal (but no other processing needs to be done on it).
365 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
366 * strings from a potentially compromised process is not without risk. If the
367 * string being passed is the result of a printf-style function, consider using
368 * MOZ_CRASH_UNSAFE_PRINTF instead.
369 *
370 * @note This macro causes data collection because crash strings are annotated
371 * to crash-stats and are publicly visible. Firefox data stewards must do data
372 * review on usages of this macro.
373 */
374 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
375 const char* aFilename, int aLine, const char* aReason) {
376 MOZ_FUZZING_HANDLE_CRASH_EVENT4("MOZ_CRASH", aFilename, aLine, aReason);
377 #if defined(DEBUG) || defined(MOZ_ASAN) || defined(FUZZING)
378 MOZ_ReportCrash(aReason, aFilename, aLine);
379 #endif
380 MOZ_CRASH_ANNOTATE(aReason);
381 MOZ_REALLY_CRASH(aLine);
382 }
383 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
384
385 static const size_t sPrintfMaxArgs = 4;
386 static const size_t sPrintfCrashReasonSize = 1024;
387
388 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
389 char* MOZ_CrashPrintf(const char* aFormat, ...);
390
391 /*
392 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
393 * information is desired than a string literal can supply. The caller provides
394 * a printf-style format string, which must be a string literal and between
395 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
396 * possible, as passing arbitrary strings to printf from a potentially
397 * compromised process is not without risk.
398 *
399 * @note This macro causes data collection because crash strings are annotated
400 * to crash-stats and are publicly visible. Firefox data stewards must do data
401 * review on usages of this macro.
402 */
403 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
404 do { \
405 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
406 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
407 "Or maybe you want MOZ_CRASH instead?"); \
408 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
409 "Only up to 4 additional arguments are allowed!"); \
410 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
411 "The supplied format string is too long!"); \
412 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
413 } while (false)
414
415 MOZ_END_EXTERN_C
416
417 /*
418 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
419 * debug builds. If it is, execution continues. Otherwise, an error message
420 * including the expression and the explanation-string (if provided) is printed,
421 * an attempt is made to invoke any existing debugger, and execution halts.
422 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
423 * which can correctly be falsy.
424 *
425 * The optional explanation-string, if provided, must be a string literal
426 * explaining the assertion. It is intended for use with assertions whose
427 * correctness or rationale is non-obvious, and for assertions where the "real"
428 * condition being tested is best described prosaically. Don't provide an
429 * explanation if it's not actually helpful.
430 *
431 * // No explanation needed: pointer arguments often must not be NULL.
432 * MOZ_ASSERT(arg);
433 *
434 * // An explanation can be helpful to explain exactly how we know an
435 * // assertion is valid.
436 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
437 * "given that <thingA> and <thingB>, we must have...");
438 *
439 * // Or it might disambiguate multiple identical (save for their location)
440 * // assertions of the same expression.
441 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
442 * "we already set [[PrimitiveThis]] for this Boolean object");
443 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
444 * "we already set [[PrimitiveThis]] for this String object");
445 *
446 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
447 * *only* during debugging, not "in the field". If you want the latter, use
448 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
449 *
450 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly and early beta
451 * and MOZ_ASSERT in late Beta and Release - use this when a condition is
452 * potentially rare enough to require real user testing to hit, but is not
453 * security-sensitive. This can cause user pain, so use it sparingly. If a
454 * MOZ_DIAGNOSTIC_ASSERT is firing, it should promptly be converted to a
455 * MOZ_ASSERT while the failure is being investigated, rather than letting users
456 * suffer.
457 *
458 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
459 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
460 */
461
462 /*
463 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
464 * accidentally passing something unintended in lieu of an assertion condition.
465 */
466
467 #ifdef __cplusplus
468 # include <type_traits>
469 namespace mozilla {
470 namespace detail {
471
472 template <typename T>
473 struct AssertionConditionType {
474 using ValueT = std::remove_reference_t<T>;
475 static_assert(!std::is_array_v<ValueT>,
476 "Expected boolean assertion condition, got an array or a "
477 "string!");
478 static_assert(!std::is_function_v<ValueT>,
479 "Expected boolean assertion condition, got a function! Did "
480 "you intend to call that function?");
481 static_assert(!std::is_floating_point_v<ValueT>,
482 "It's often a bad idea to assert that a floating-point number "
483 "is nonzero, because such assertions tend to intermittently "
484 "fail. Shouldn't your code gracefully handle this case instead "
485 "of asserting? Anyway, if you really want to do that, write an "
486 "explicit boolean condition, like !!x or x!=0.");
487
488 static const bool isValid = true;
489 };
490
491 } // namespace detail
492 } // namespace mozilla
493 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
494 static_assert( \
495 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
496 "invalid assertion condition")
497 #else
498 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
499 #endif
500
501 #if defined(DEBUG) || defined(MOZ_ASAN)
502 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
503 MOZ_ReportAssertionFailure(__VA_ARGS__)
504 #else
505 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
506 do { /* nothing */ \
507 } while (false)
508 #endif
509
510 /* First the single-argument form. */
511 #define MOZ_ASSERT_HELPER1(kind, expr) \
512 do { \
513 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
514 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
515 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
516 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
517 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
518 MOZ_REALLY_CRASH(__LINE__); \
519 } \
520 } while (false)
521 /* Now the two-argument form. */
522 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
523 do { \
524 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
525 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
526 MOZ_FUZZING_HANDLE_CRASH_EVENT2(kind, #expr); \
527 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
528 __LINE__); \
529 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
530 MOZ_REALLY_CRASH(__LINE__); \
531 } \
532 } while (false)
533
534 #define MOZ_ASSERT_GLUE(a, b) a b
535 #define MOZ_RELEASE_ASSERT(...) \
536 MOZ_ASSERT_GLUE( \
537 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
538 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
539
540 #ifdef DEBUG
541 # define MOZ_ASSERT(...) \
542 MOZ_ASSERT_GLUE( \
543 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
544 ("MOZ_ASSERT", __VA_ARGS__))
545 #else
546 # define MOZ_ASSERT(...) \
547 do { /* nothing */ \
548 } while (false)
549 #endif /* DEBUG */
550
551 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
552 # define MOZ_DIAGNOSTIC_ASSERT(...) \
553 MOZ_ASSERT_GLUE( \
554 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
555 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
556 #else
557 # define MOZ_DIAGNOSTIC_ASSERT(...) \
558 do { /* nothing */ \
559 } while (false)
560 #endif
561
562 /*
563 * MOZ_ASSERT_DEBUG_OR_FUZZING is like a MOZ_ASSERT but also enabled in builds
564 * that are non-DEBUG but FUZZING. This is useful for checks that are too
565 * expensive for Nightly in general but are still indicating potentially
566 * critical bugs.
567 * In fuzzing builds, the assert is rewritten to be a diagnostic assert because
568 * we already use this in other sensitive places and fuzzing automation is
569 * set to act on these under all circumstances.
570 */
571 #ifdef FUZZING
572 # define MOZ_ASSERT_DEBUG_OR_FUZZING(...) MOZ_DIAGNOSTIC_ASSERT(__VA_ARGS__)
573 #else
574 # define MOZ_ASSERT_DEBUG_OR_FUZZING(...) MOZ_ASSERT(__VA_ARGS__)
575 #endif
576
577 /*
578 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
579 * true.
580 *
581 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
582 *
583 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
584 * designed to catch bugs during debugging, not "in the field".
585 */
586 #ifdef DEBUG
587 # define MOZ_ASSERT_IF(cond, expr) \
588 do { \
589 if (cond) { \
590 MOZ_ASSERT(expr); \
591 } \
592 } while (false)
593 #else
594 # define MOZ_ASSERT_IF(cond, expr) \
595 do { /* nothing */ \
596 } while (false)
597 #endif
598
599 /*
600 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
601 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
602 *
603 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
604 * diagnostic assertions work and how to use them.
605 */
606 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
607 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
608 do { \
609 if (cond) { \
610 MOZ_DIAGNOSTIC_ASSERT(expr); \
611 } \
612 } while (false)
613 #else
614 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
615 do { /* nothing */ \
616 } while (false)
617 #endif
618
619 /*
620 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
621 * can assume that the macro call cannot be reached during execution. This lets
622 * the compiler generate better-optimized code under some circumstances, at the
623 * expense of the program's behavior being undefined if control reaches the
624 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
625 *
626 * In Gecko, you probably should not use this macro outside of performance- or
627 * size-critical code, because it's unsafe. If you don't care about code size
628 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
629 *
630 * SpiderMonkey is a different beast, and there it's acceptable to use
631 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
632 *
633 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
634 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
635 * call.
636 *
637 * Example usage:
638 *
639 * enum ValueType {
640 * VALUE_STRING,
641 * VALUE_INT,
642 * VALUE_FLOAT
643 * };
644 *
645 * int ptrToInt(ValueType type, void* value) {
646 * {
647 * // We know for sure that type is either INT or FLOAT, and we want this
648 * // code to run as quickly as possible.
649 * switch (type) {
650 * case VALUE_INT:
651 * return *(int*) value;
652 * case VALUE_FLOAT:
653 * return (int) *(float*) value;
654 * default:
655 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
656 * }
657 * }
658 */
659
660 /*
661 * Unconditional assert in debug builds for (assumed) unreachable code paths
662 * that have a safe return without crashing in release builds.
663 */
664 #define MOZ_ASSERT_UNREACHABLE(reason) \
665 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
666
667 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
668 do { \
669 MOZ_ASSERT_UNREACHABLE(reason); \
670 MOZ_ASSUME_UNREACHABLE_MARKER(); \
671 } while (false)
672
673 /**
674 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
675 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
676 * debug builds, but intentionally fall through in release builds to handle
677 * unexpected values.
678 *
679 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
680 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
681 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
682 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
683 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
684 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
685 * warning stalemate.
686 *
687 * // Example before MOZ_FALLTHROUGH_ASSERT:
688 * switch (foo) {
689 * default:
690 * // This case wants to assert in debug builds, fall through in release.
691 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
692 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
693 * case 5:
694 * return 5;
695 * }
696 *
697 * // Example with MOZ_FALLTHROUGH_ASSERT:
698 * switch (foo) {
699 * default:
700 * // This case asserts in debug builds, falls through in release.
701 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
702 * case 5:
703 * return 5;
704 * }
705 */
706 #ifdef DEBUG
707 # define MOZ_FALLTHROUGH_ASSERT(...) \
708 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
709 #else
710 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
711 #endif
712
713 /*
714 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression, in
715 * both debug and release builds. Then, in debug builds and Nightly and early
716 * beta builds, we crash using the string value of the expression as the message
717 * using MOZ_DIAGNOSTIC_CRASH.
718 */
719 #define MOZ_ALWAYS_TRUE(expr) \
720 do { \
721 if (MOZ_LIKELY(expr)) { \
722 /* Silence [[nodiscard]]. */ \
723 } else { \
724 MOZ_DIAGNOSTIC_CRASH(#expr); \
725 } \
726 } while (false)
727
728 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
729 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
730 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
731
732 /*
733 * These are disabled when fuzzing
734 */
735 #ifdef FUZZING
736 # define MOZ_CRASH_UNLESS_FUZZING(...) \
737 do { /* nothing */ \
738 } while (0)
739 # define MOZ_ASSERT_UNLESS_FUZZING(...) \
740 do { /* nothing */ \
741 } while (0)
742 #else
743 # define MOZ_CRASH_UNLESS_FUZZING(...) MOZ_CRASH(__VA_ARGS__)
744 # define MOZ_ASSERT_UNLESS_FUZZING(...) MOZ_ASSERT(__VA_ARGS__)
745 #endif
746
747 #undef MOZ_BUFFER_STDERR
748 #undef MOZ_CRASH_CRASHREPORT
749 #undef MOZ_DUMP_ASSERTION_STACK
750
751 /*
752 * This is only used by Array and nsTArray classes, therefore it is not
753 * required when included from C code.
754 */
755 #ifdef __cplusplus
756 namespace mozilla::detail {
757 MFBT_API MOZ_NORETURN MOZ_COLD void InvalidArrayIndex_CRASH(size_t aIndex,
758 size_t aLength);
759 } // namespace mozilla::detail
760 #endif // __cplusplus
761
762 /*
763 * Provide a fake default value to be used when a value is required but none can
764 * sensibily be provided without adding undefined behavior or security issues.
765 *
766 * This function asserts and aborts if it ever executed.
767 *
768 * Example usage:
769 *
770 * class Trooper {
771 * const Droid& lookFor;
772 * Trooper() : lookFor(MakeCompilerAssumeUnreachableFakeValue<
773 const Droid&>()) {
774 * // The class might be instantiated due to existing caller
775 * // but this never happens in practice.
776 * }
777 * };
778 *
779 */
780 #ifdef __cplusplus
781 namespace mozilla {
782 template <typename T>
783 static inline T MakeCompilerAssumeUnreachableFakeValue() {
784 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE();
785 }
786 } // namespace mozilla
787 #endif // __cplusplus
788
789 #endif /* mozilla_Assertions_h */