Bug 1577282 - Part 2: Move functions outside of the Spectrum prototype. r=Maliha
[gecko.git] / mfbt / Assertions.h
blob68210ed4b9bed08a145e43bc9540d73cfae93ec2
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 #endif
27 * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter
28 * if present. It is declared here (and defined in Assertions.cpp) to make it
29 * available to all code, even libraries that don't link with the crash reporter
30 * directly.
32 MOZ_BEGIN_EXTERN_C
33 extern MFBT_DATA const char* gMozCrashReason;
34 MOZ_END_EXTERN_C
36 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
37 static inline void AnnotateMozCrashReason(const char* reason) {
38 gMozCrashReason = reason;
40 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
41 #else
42 # define MOZ_CRASH_ANNOTATE(...) \
43 do { /* nothing */ \
44 } while (false)
45 #endif
47 #include <stddef.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #ifdef _MSC_VER
52 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
53 * further depends on <windef.h>. We hardcode these few definitions manually
54 * because those headers clutter the global namespace with a significant
55 * number of undesired macros and symbols.
57 MOZ_BEGIN_EXTERN_C
58 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
59 unsigned int uExitCode);
60 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
61 MOZ_END_EXTERN_C
62 #else
63 # include <signal.h>
64 #endif
65 #ifdef ANDROID
66 # include <android/log.h>
67 #endif
70 * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C.
71 * In C++11, static_assert is provided by the compiler to the same effect.
72 * This can be useful when you make certain assumptions about what must hold for
73 * optimal, or even correct, behavior. For example, you might assert that the
74 * size of a struct is a multiple of the target architecture's word size:
76 * struct S { ... };
77 * // C
78 * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
79 * "S should be a multiple of word size for efficiency");
80 * // C++11
81 * static_assert(sizeof(S) % sizeof(size_t) == 0,
82 * "S should be a multiple of word size for efficiency");
84 * This macro can be used in any location where both an extern declaration and a
85 * typedef could be used.
87 #ifndef __cplusplus
89 * Some of the definitions below create an otherwise-unused typedef. This
90 * triggers compiler warnings with some versions of gcc, so mark the typedefs
91 * as permissibly-unused to disable the warnings.
93 # if defined(__GNUC__)
94 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
95 # else
96 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
97 # endif
98 # define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y
99 # define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y)
100 # if defined(__SUNPRO_CC)
102 * The Sun Studio C++ compiler is buggy when declaring, inside a function,
103 * another extern'd function with an array argument whose length contains a
104 * sizeof, triggering the error message "sizeof expression not accepted as
105 * size of array parameter". This bug (6688515, not public yet) would hit
106 * defining moz_static_assert as a function, so we always define an extern
107 * array for Sun Studio.
109 * We include the line number in the symbol name in a best-effort attempt
110 * to avoid conflicts (see below).
112 # define MOZ_STATIC_ASSERT(cond, reason) \
113 extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, \
114 __LINE__)[(cond) ? 1 : -1]
115 # elif defined(__COUNTER__)
117 * If there was no preferred alternative, use a compiler-agnostic version.
119 * Note that the non-__COUNTER__ version has a bug in C++: it can't be used
120 * in both |extern "C"| and normal C++ in the same translation unit. (Alas
121 * |extern "C"| isn't allowed in a function.) The only affected compiler
122 * we really care about is gcc 4.2. For that compiler and others like it,
123 * we include the line number in the function name to do the best we can to
124 * avoid conflicts. These should be rare: a conflict would require use of
125 * MOZ_STATIC_ASSERT on the same line in separate files in the same
126 * translation unit, *and* the uses would have to be in code with
127 * different linkage, *and* the first observed use must be in C++-linkage
128 * code.
130 # define MOZ_STATIC_ASSERT(cond, reason) \
131 typedef int MOZ_STATIC_ASSERT_GLUE( \
132 moz_static_assert, \
133 __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
134 # else
135 # define MOZ_STATIC_ASSERT(cond, reason) \
136 extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)( \
137 int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
138 # endif
140 # define MOZ_STATIC_ASSERT_IF(cond, expr, reason) \
141 MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
142 #else
143 # define MOZ_STATIC_ASSERT_IF(cond, expr, reason) \
144 static_assert(!(cond) || (expr), reason)
145 #endif
147 MOZ_BEGIN_EXTERN_C
150 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
151 * location of the assertion) to the standard debug-output channel.
153 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
154 * method is primarily for internal use in this header, and only secondarily
155 * for use in implementing release-build assertions.
157 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
158 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
159 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
160 #ifdef ANDROID
161 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
162 "Assertion failure: %s, at %s:%d\n", aStr, aFilename,
163 aLine);
164 #else
165 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
166 # if defined(MOZ_DUMP_ASSERTION_STACK)
167 nsTraceRefcnt::WalkTheStack(stderr);
168 # endif
169 fflush(stderr);
170 #endif
173 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
174 const char* aStr, const char* aFilename,
175 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
176 #ifdef ANDROID
177 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
178 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
179 #else
180 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
181 # if defined(MOZ_DUMP_ASSERTION_STACK)
182 nsTraceRefcnt::WalkTheStack(stderr);
183 # endif
184 fflush(stderr);
185 #endif
189 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
190 * call MOZ_CRASH instead.
192 #if defined(_MSC_VER)
194 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
195 * (not nested in a system function) breakpoint. This distinctively invokes
196 * Breakpad without requiring system library symbols on all stack-processing
197 * machines, as a nested breakpoint would require.
199 * We use __LINE__ to prevent the compiler from folding multiple crash sites
200 * together, which would make crash reports hard to understand.
202 * We use TerminateProcess with the exit code aborting would generate
203 * because we don't want to invoke atexit handlers, destructors, library
204 * unload handlers, and so on when our process might be in a compromised
205 * state.
207 * We don't use abort() because it'd cause Windows to annoyingly pop up the
208 * process error dialog multiple times. See bug 345118 and bug 426163.
210 * (Technically these are Windows requirements, not MSVC requirements. But
211 * practically you need MSVC for debugging, and we only ship builds created
212 * by MSVC, so doing it this way reduces complexity.)
215 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
216 MOZ_NoReturn(int aLine) {
217 *((volatile int*)NULL) = aLine;
218 TerminateProcess(GetCurrentProcess(), 3);
221 # define MOZ_REALLY_CRASH(line) \
222 do { \
223 __debugbreak(); \
224 MOZ_NoReturn(line); \
225 } while (false)
226 #else
229 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
230 * crash. NULL is preferred however if for some reason NULL cannot be used
231 * this makes choosing another value possible.
233 * In the case of UBSan certain checks, bounds specifically, cause the compiler
234 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
235 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
236 * SEGV at 0x0.
238 # ifdef MOZ_UBSAN
239 # define MOZ_CRASH_WRITE_ADDR 0x1
240 # else
241 # define MOZ_CRASH_WRITE_ADDR NULL
242 # endif
244 # ifdef __cplusplus
245 # define MOZ_REALLY_CRASH(line) \
246 do { \
247 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
248 ::abort(); \
249 } while (false)
250 # else
251 # define MOZ_REALLY_CRASH(line) \
252 do { \
253 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
254 abort(); \
255 } while (false)
256 # endif
257 #endif
260 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
261 * Breakpad-compatible way, in both debug and release builds.
263 * MOZ_CRASH is a good solution for "handling" failure cases when you're
264 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
265 * corruption, and so on. It's also a good solution if you need safe behavior
266 * in release builds as well as debug builds. But if the failure is one that
267 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
269 * The optional explanation-string, if provided, must be a string literal
270 * explaining why we're crashing. This argument is intended for use with
271 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
272 * obvious why we're crashing.
274 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
275 * explanation-string, we print the string to stderr. Otherwise, we don't
276 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
277 * builds, and it's hard to print to stderr safely when memory might have been
278 * corrupted.
280 #ifndef DEBUG
281 # define MOZ_CRASH(...) \
282 do { \
283 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
284 MOZ_REALLY_CRASH(__LINE__); \
285 } while (false)
286 #else
287 # define MOZ_CRASH(...) \
288 do { \
289 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
290 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
291 MOZ_REALLY_CRASH(__LINE__); \
292 } while (false)
293 #endif
296 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
297 * cannot be a string literal (but no other processing needs to be done on it).
298 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
299 * strings from a potentially compromised process is not without risk. If the
300 * string being passed is the result of a printf-style function, consider using
301 * MOZ_CRASH_UNSAFE_PRINTF instead.
303 * @note This macro causes data collection because crash strings are annotated
304 * to crash-stats and are publicly visible. Firefox data stewards must do data
305 * review on usages of this macro.
307 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
308 const char* aFilename, int aLine, const char* aReason) {
309 #ifdef DEBUG
310 MOZ_ReportCrash(aReason, aFilename, aLine);
311 #endif
312 MOZ_CRASH_ANNOTATE(aReason);
313 MOZ_REALLY_CRASH(aLine);
315 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
317 static const size_t sPrintfMaxArgs = 4;
318 static const size_t sPrintfCrashReasonSize = 1024;
320 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
321 char* MOZ_CrashPrintf(const char* aFormat, ...);
324 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
325 * information is desired than a string literal can supply. The caller provides
326 * a printf-style format string, which must be a string literal and between
327 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
328 * possible, as passing arbitrary strings to printf from a potentially
329 * compromised process is not without risk.
331 * @note This macro causes data collection because crash strings are annotated
332 * to crash-stats and are publicly visible. Firefox data stewards must do data
333 * review on usages of this macro.
335 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
336 do { \
337 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
338 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
339 "Or maybe you want MOZ_CRASH instead?"); \
340 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
341 "Only up to 4 additional arguments are allowed!"); \
342 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
343 "The supplied format string is too long!"); \
344 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
345 } while (false)
347 MOZ_END_EXTERN_C
350 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
351 * debug builds. If it is, execution continues. Otherwise, an error message
352 * including the expression and the explanation-string (if provided) is printed,
353 * an attempt is made to invoke any existing debugger, and execution halts.
354 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
355 * which can correctly be falsy.
357 * The optional explanation-string, if provided, must be a string literal
358 * explaining the assertion. It is intended for use with assertions whose
359 * correctness or rationale is non-obvious, and for assertions where the "real"
360 * condition being tested is best described prosaically. Don't provide an
361 * explanation if it's not actually helpful.
363 * // No explanation needed: pointer arguments often must not be NULL.
364 * MOZ_ASSERT(arg);
366 * // An explanation can be helpful to explain exactly how we know an
367 * // assertion is valid.
368 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
369 * "given that <thingA> and <thingB>, we must have...");
371 * // Or it might disambiguate multiple identical (save for their location)
372 * // assertions of the same expression.
373 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
374 * "we already set [[PrimitiveThis]] for this Boolean object");
375 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
376 * "we already set [[PrimitiveThis]] for this String object");
378 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
379 * *only* during debugging, not "in the field". If you want the latter, use
380 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
382 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
383 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
384 * enough to require real user testing to hit, but is not security-sensitive.
385 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
386 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
387 * is being investigated, rather than letting users suffer.
389 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
390 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
394 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
395 * accidentally passing something unintended in lieu of an assertion condition.
398 #ifdef __cplusplus
399 # include "mozilla/TypeTraits.h"
400 namespace mozilla {
401 namespace detail {
403 template <typename T>
404 struct AssertionConditionType {
405 typedef typename RemoveReference<T>::Type ValueT;
406 static_assert(!IsArray<ValueT>::value,
407 "Expected boolean assertion condition, got an array or a "
408 "string!");
409 static_assert(!IsFunction<ValueT>::value,
410 "Expected boolean assertion condition, got a function! Did "
411 "you intend to call that function?");
412 static_assert(!IsFloatingPoint<ValueT>::value,
413 "It's often a bad idea to assert that a floating-point number "
414 "is nonzero, because such assertions tend to intermittently "
415 "fail. Shouldn't your code gracefully handle this case instead "
416 "of asserting? Anyway, if you really want to do that, write an "
417 "explicit boolean condition, like !!x or x!=0.");
419 static const bool isValid = true;
422 } // namespace detail
423 } // namespace mozilla
424 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
425 static_assert( \
426 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
427 "invalid assertion condition")
428 #else
429 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
430 #endif
432 #if defined(DEBUG) || defined(MOZ_ASAN)
433 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
434 MOZ_ReportAssertionFailure(__VA_ARGS__)
435 #else
436 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
437 do { /* nothing */ \
438 } while (false)
439 #endif
441 /* First the single-argument form. */
442 #define MOZ_ASSERT_HELPER1(kind, expr) \
443 do { \
444 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
445 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
446 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
447 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
448 MOZ_REALLY_CRASH(__LINE__); \
450 } while (false)
451 /* Now the two-argument form. */
452 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
453 do { \
454 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
455 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
456 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
457 __LINE__); \
458 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
459 MOZ_REALLY_CRASH(__LINE__); \
461 } while (false)
463 #define MOZ_ASSERT_GLUE(a, b) a b
464 #define MOZ_RELEASE_ASSERT(...) \
465 MOZ_ASSERT_GLUE( \
466 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
467 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
469 #ifdef DEBUG
470 # define MOZ_ASSERT(...) \
471 MOZ_ASSERT_GLUE( \
472 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
473 ("MOZ_ASSERT", __VA_ARGS__))
474 #else
475 # define MOZ_ASSERT(...) \
476 do { \
477 } while (false)
478 #endif /* DEBUG */
480 #if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION) || defined(DEBUG)
481 # define MOZ_DIAGNOSTIC_ASSERT(...) \
482 MOZ_ASSERT_GLUE( \
483 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
484 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
485 # define MOZ_DIAGNOSTIC_ASSERT_ENABLED 1
486 #else
487 # define MOZ_DIAGNOSTIC_ASSERT(...) \
488 do { \
489 } while (false)
490 #endif
493 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
494 * true.
496 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
498 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
499 * designed to catch bugs during debugging, not "in the field".
501 #ifdef DEBUG
502 # define MOZ_ASSERT_IF(cond, expr) \
503 do { \
504 if (cond) { \
505 MOZ_ASSERT(expr); \
507 } while (false)
508 #else
509 # define MOZ_ASSERT_IF(cond, expr) \
510 do { \
511 } while (false)
512 #endif
515 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
516 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
518 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
519 * diagnostic assertions work and how to use them.
521 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
522 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
523 do { \
524 if (cond) { \
525 MOZ_DIAGNOSTIC_ASSERT(expr); \
527 } while (false)
528 #else
529 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
530 do { \
531 } while (false)
532 #endif
535 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
536 * it is undefined behavior for execution to reach this point. No guarantees
537 * are made about what will happen if this is reached at runtime. Most code
538 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
539 * asserts.
541 #if defined(__clang__) || defined(__GNUC__)
542 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
543 #elif defined(_MSC_VER)
544 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
545 #else
546 # ifdef __cplusplus
547 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
548 # else
549 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
550 # endif
551 #endif
554 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
555 * can assume that the macro call cannot be reached during execution. This lets
556 * the compiler generate better-optimized code under some circumstances, at the
557 * expense of the program's behavior being undefined if control reaches the
558 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
560 * In Gecko, you probably should not use this macro outside of performance- or
561 * size-critical code, because it's unsafe. If you don't care about code size
562 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
564 * SpiderMonkey is a different beast, and there it's acceptable to use
565 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
567 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
568 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
569 * call.
571 * Example usage:
573 * enum ValueType {
574 * VALUE_STRING,
575 * VALUE_INT,
576 * VALUE_FLOAT
577 * };
579 * int ptrToInt(ValueType type, void* value) {
581 * // We know for sure that type is either INT or FLOAT, and we want this
582 * // code to run as quickly as possible.
583 * switch (type) {
584 * case VALUE_INT:
585 * return *(int*) value;
586 * case VALUE_FLOAT:
587 * return (int) *(float*) value;
588 * default:
589 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
595 * Unconditional assert in debug builds for (assumed) unreachable code paths
596 * that have a safe return without crashing in release builds.
598 #define MOZ_ASSERT_UNREACHABLE(reason) \
599 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
601 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
602 do { \
603 MOZ_ASSERT_UNREACHABLE(reason); \
604 MOZ_ASSUME_UNREACHABLE_MARKER(); \
605 } while (false)
608 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
609 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
610 * debug builds, but intentionally fall through in release builds to handle
611 * unexpected values.
613 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to MOZ_FALLTHROUGH? In
614 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
615 * requiring a MOZ_FALLTHROUGH annotation to suppress a -Wimplicit-fallthrough
616 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
617 * `if (true) { MOZ_CRASH(); }` and the MOZ_FALLTHROUGH annotation will cause
618 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
619 * warning stalemate.
621 * // Example before MOZ_FALLTHROUGH_ASSERT:
622 * switch (foo) {
623 * default:
624 * // This case wants to assert in debug builds, fall through in release.
625 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
626 * MOZ_FALLTHROUGH; // but -Wunreachable-code warning in debug builds!
627 * case 5:
628 * return 5;
631 * // Example with MOZ_FALLTHROUGH_ASSERT:
632 * switch (foo) {
633 * default:
634 * // This case asserts in debug builds, falls through in release.
635 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
636 * case 5:
637 * return 5;
640 #ifdef DEBUG
641 # define MOZ_FALLTHROUGH_ASSERT(...) \
642 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
643 #else
644 # define MOZ_FALLTHROUGH_ASSERT(...) MOZ_FALLTHROUGH
645 #endif
648 * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
649 * expression, in debug builds and in release builds both. Then, in debug
650 * builds only, the value of the expression is asserted either true or false
651 * using MOZ_ASSERT.
653 #ifdef DEBUG
654 # define MOZ_ALWAYS_TRUE(expr) \
655 do { \
656 if ((expr)) { \
657 /* Do nothing. */ \
658 } else { \
659 MOZ_ASSERT(false, #expr); \
661 } while (false)
662 # define MOZ_ALWAYS_FALSE(expr) \
663 do { \
664 if ((expr)) { \
665 MOZ_ASSERT(false, #expr); \
666 } else { \
667 /* Do nothing. */ \
669 } while (false)
670 # define MOZ_ALWAYS_OK(expr) MOZ_ASSERT((expr).isOk())
671 # define MOZ_ALWAYS_ERR(expr) MOZ_ASSERT((expr).isErr())
672 #else
673 # define MOZ_ALWAYS_TRUE(expr) \
674 do { \
675 if ((expr)) { \
676 /* Silence MOZ_MUST_USE. */ \
678 } while (false)
679 # define MOZ_ALWAYS_FALSE(expr) \
680 do { \
681 if ((expr)) { \
682 /* Silence MOZ_MUST_USE. */ \
684 } while (false)
685 # define MOZ_ALWAYS_OK(expr) \
686 do { \
687 if ((expr).isOk()) { \
688 /* Silence MOZ_MUST_USE. */ \
690 } while (false)
691 # define MOZ_ALWAYS_ERR(expr) \
692 do { \
693 if ((expr).isErr()) { \
694 /* Silence MOZ_MUST_USE. */ \
696 } while (false)
697 #endif
700 * MOZ_DIAGNOSTIC_ALWAYS_TRUE is like MOZ_ALWAYS_TRUE, but using
701 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
703 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
704 * diagnostic assertions work and how to use them.
706 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
707 # define MOZ_DIAGNOSTIC_ALWAYS_TRUE(expr) \
708 do { \
709 if ((expr)) { \
710 /* Do nothing. */ \
711 } else { \
712 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
714 } while (false)
715 #else
716 # define MOZ_DIAGNOSTIC_ALWAYS_TRUE(expr) \
717 do { \
718 if ((expr)) { \
719 /* Silence MOZ_MUST_USE. */ \
721 } while (false)
722 #endif
724 #undef MOZ_DUMP_ASSERTION_STACK
725 #undef MOZ_CRASH_CRASHREPORT
727 #endif /* mozilla_Assertions_h */