Bug 1627646 - Avoid creating a Port object when there are no listeners r=mixedpuppy
[gecko.git] / mfbt / Assertions.h
blob0d05bcc315312f5ab9dcfb6295d584c5dc2610d8
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Implementations of runtime and static assertion macros for C and C++. */
9 #ifndef mozilla_Assertions_h
10 #define mozilla_Assertions_h
12 #if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus)
13 # define MOZ_DUMP_ASSERTION_STACK
14 #endif
16 #include "mozilla/Attributes.h"
17 #include "mozilla/Compiler.h"
18 #include "mozilla/Likely.h"
19 #include "mozilla/MacroArgs.h"
20 #include "mozilla/StaticAnalysisFunctions.h"
21 #include "mozilla/Types.h"
22 #ifdef MOZ_DUMP_ASSERTION_STACK
23 # include "nsTraceRefcnt.h"
24 # ifdef ANDROID
25 # include "mozilla/StackWalk.h"
26 # include <algorithm>
27 # endif
28 #endif
31 * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter
32 * if present. It is declared here (and defined in Assertions.cpp) to make it
33 * available to all code, even libraries that don't link with the crash reporter
34 * directly.
36 MOZ_BEGIN_EXTERN_C
37 extern MFBT_DATA const char* gMozCrashReason;
38 MOZ_END_EXTERN_C
40 #if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API)
41 static inline void AnnotateMozCrashReason(const char* reason) {
42 gMozCrashReason = reason;
44 # define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__)
45 #else
46 # define MOZ_CRASH_ANNOTATE(...) \
47 do { /* nothing */ \
48 } while (false)
49 #endif
51 #include <stddef.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #ifdef _MSC_VER
56 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
57 * further depends on <windef.h>. We hardcode these few definitions manually
58 * because those headers clutter the global namespace with a significant
59 * number of undesired macros and symbols.
61 MOZ_BEGIN_EXTERN_C
62 __declspec(dllimport) int __stdcall TerminateProcess(void* hProcess,
63 unsigned int uExitCode);
64 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
65 MOZ_END_EXTERN_C
66 #else
67 # include <signal.h>
68 #endif
69 #ifdef ANDROID
70 # include <android/log.h>
71 #endif
74 * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C.
75 * In C++11, static_assert is provided by the compiler to the same effect.
76 * This can be useful when you make certain assumptions about what must hold for
77 * optimal, or even correct, behavior. For example, you might assert that the
78 * size of a struct is a multiple of the target architecture's word size:
80 * struct S { ... };
81 * // C
82 * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
83 * "S should be a multiple of word size for efficiency");
84 * // C++11
85 * static_assert(sizeof(S) % sizeof(size_t) == 0,
86 * "S should be a multiple of word size for efficiency");
88 * This macro can be used in any location where both an extern declaration and a
89 * typedef could be used.
91 #ifndef __cplusplus
93 * Some of the definitions below create an otherwise-unused typedef. This
94 * triggers compiler warnings with some versions of gcc, so mark the typedefs
95 * as permissibly-unused to disable the warnings.
97 # if defined(__GNUC__)
98 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
99 # else
100 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
101 # endif
102 # define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y
103 # define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y)
104 # if defined(__SUNPRO_CC)
106 * The Sun Studio C++ compiler is buggy when declaring, inside a function,
107 * another extern'd function with an array argument whose length contains a
108 * sizeof, triggering the error message "sizeof expression not accepted as
109 * size of array parameter". This bug (6688515, not public yet) would hit
110 * defining moz_static_assert as a function, so we always define an extern
111 * array for Sun Studio.
113 * We include the line number in the symbol name in a best-effort attempt
114 * to avoid conflicts (see below).
116 # define MOZ_STATIC_ASSERT(cond, reason) \
117 extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, \
118 __LINE__)[(cond) ? 1 : -1]
119 # elif defined(__COUNTER__)
121 * If there was no preferred alternative, use a compiler-agnostic version.
123 * Note that the non-__COUNTER__ version has a bug in C++: it can't be used
124 * in both |extern "C"| and normal C++ in the same translation unit. (Alas
125 * |extern "C"| isn't allowed in a function.) The only affected compiler
126 * we really care about is gcc 4.2. For that compiler and others like it,
127 * we include the line number in the function name to do the best we can to
128 * avoid conflicts. These should be rare: a conflict would require use of
129 * MOZ_STATIC_ASSERT on the same line in separate files in the same
130 * translation unit, *and* the uses would have to be in code with
131 * different linkage, *and* the first observed use must be in C++-linkage
132 * code.
134 # define MOZ_STATIC_ASSERT(cond, reason) \
135 typedef int MOZ_STATIC_ASSERT_GLUE( \
136 moz_static_assert, \
137 __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
138 # else
139 # define MOZ_STATIC_ASSERT(cond, reason) \
140 extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)( \
141 int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
142 # endif
144 # define MOZ_STATIC_ASSERT_IF(cond, expr, reason) \
145 MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
146 #else
147 # define MOZ_STATIC_ASSERT_IF(cond, expr, reason) \
148 static_assert(!(cond) || (expr), reason)
149 #endif
151 MOZ_BEGIN_EXTERN_C
154 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
155 * location of the assertion) to the standard debug-output channel.
157 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
158 * method is primarily for internal use in this header, and only secondarily
159 * for use in implementing release-build assertions.
161 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void
162 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename,
163 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
164 #ifdef ANDROID
165 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
166 "Assertion failure: %s, at %s:%d\n", aStr, aFilename,
167 aLine);
168 # if defined(MOZ_DUMP_ASSERTION_STACK)
169 nsTraceRefcnt::WalkTheStack(
170 [](uint32_t aFrameNumber, void* aPC, void* aSP, void* aClosure) {
171 MozCodeAddressDetails details;
172 static const size_t buflen = 1024;
173 char buf[buflen + 1]; // 1 for trailing '\n'
175 MozDescribeCodeAddress(aPC, &details);
176 MozFormatCodeAddressDetails(buf, buflen, aFrameNumber, aPC, &details);
177 size_t len = std::min(strlen(buf), buflen + 1 - 2);
178 buf[len++] = '\n';
179 buf[len] = '\0';
180 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", "%s", buf);
182 # endif
183 #else
184 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
185 # if defined(MOZ_DUMP_ASSERTION_STACK)
186 nsTraceRefcnt::WalkTheStack(stderr);
187 # endif
188 fflush(stderr);
189 #endif
192 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NEVER_INLINE void MOZ_ReportCrash(
193 const char* aStr, const char* aFilename,
194 int aLine) MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS {
195 #ifdef ANDROID
196 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
197 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
198 #else
199 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
200 # if defined(MOZ_DUMP_ASSERTION_STACK)
201 nsTraceRefcnt::WalkTheStack(stderr);
202 # endif
203 fflush(stderr);
204 #endif
208 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
209 * call MOZ_CRASH instead.
211 #if defined(_MSC_VER)
213 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
214 * (not nested in a system function) breakpoint. This distinctively invokes
215 * Breakpad without requiring system library symbols on all stack-processing
216 * machines, as a nested breakpoint would require.
218 * We use __LINE__ to prevent the compiler from folding multiple crash sites
219 * together, which would make crash reports hard to understand.
221 * We use TerminateProcess with the exit code aborting would generate
222 * because we don't want to invoke atexit handlers, destructors, library
223 * unload handlers, and so on when our process might be in a compromised
224 * state.
226 * We don't use abort() because it'd cause Windows to annoyingly pop up the
227 * process error dialog multiple times. See bug 345118 and bug 426163.
229 * (Technically these are Windows requirements, not MSVC requirements. But
230 * practically you need MSVC for debugging, and we only ship builds created
231 * by MSVC, so doing it this way reduces complexity.)
234 MOZ_MAYBE_UNUSED static MOZ_COLD MOZ_NORETURN MOZ_NEVER_INLINE void
235 MOZ_NoReturn(int aLine) {
236 *((volatile int*)NULL) = aLine;
237 TerminateProcess(GetCurrentProcess(), 3);
240 # define MOZ_REALLY_CRASH(line) \
241 do { \
242 __debugbreak(); \
243 MOZ_NoReturn(line); \
244 } while (false)
245 #else
248 * MOZ_CRASH_WRITE_ADDR is the address to be used when performing a forced
249 * crash. NULL is preferred however if for some reason NULL cannot be used
250 * this makes choosing another value possible.
252 * In the case of UBSan certain checks, bounds specifically, cause the compiler
253 * to emit the 'ud2' instruction when storing to 0x0. This causes forced
254 * crashes to manifest as ILL (at an arbitrary address) instead of the expected
255 * SEGV at 0x0.
257 # ifdef MOZ_UBSAN
258 # define MOZ_CRASH_WRITE_ADDR 0x1
259 # else
260 # define MOZ_CRASH_WRITE_ADDR NULL
261 # endif
263 # ifdef __cplusplus
264 # define MOZ_REALLY_CRASH(line) \
265 do { \
266 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
267 ::abort(); \
268 } while (false)
269 # else
270 # define MOZ_REALLY_CRASH(line) \
271 do { \
272 *((volatile int*)MOZ_CRASH_WRITE_ADDR) = line; /* NOLINT */ \
273 abort(); \
274 } while (false)
275 # endif
276 #endif
279 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
280 * Breakpad-compatible way, in both debug and release builds.
282 * MOZ_CRASH is a good solution for "handling" failure cases when you're
283 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
284 * corruption, and so on. It's also a good solution if you need safe behavior
285 * in release builds as well as debug builds. But if the failure is one that
286 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
288 * The optional explanation-string, if provided, must be a string literal
289 * explaining why we're crashing. This argument is intended for use with
290 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
291 * obvious why we're crashing.
293 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
294 * explanation-string, we print the string to stderr. Otherwise, we don't
295 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
296 * builds, and it's hard to print to stderr safely when memory might have been
297 * corrupted.
299 #ifndef DEBUG
300 # define MOZ_CRASH(...) \
301 do { \
302 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
303 MOZ_REALLY_CRASH(__LINE__); \
304 } while (false)
305 #else
306 # define MOZ_CRASH(...) \
307 do { \
308 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
309 MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \
310 MOZ_REALLY_CRASH(__LINE__); \
311 } while (false)
312 #endif
315 * MOZ_CRASH_UNSAFE(explanation-string) can be used if the explanation string
316 * cannot be a string literal (but no other processing needs to be done on it).
317 * A regular MOZ_CRASH() is preferred wherever possible, as passing arbitrary
318 * strings from a potentially compromised process is not without risk. If the
319 * string being passed is the result of a printf-style function, consider using
320 * MOZ_CRASH_UNSAFE_PRINTF instead.
322 * @note This macro causes data collection because crash strings are annotated
323 * to crash-stats and are publicly visible. Firefox data stewards must do data
324 * review on usages of this macro.
326 static MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_COLD MOZ_NORETURN void MOZ_Crash(
327 const char* aFilename, int aLine, const char* aReason) {
328 #ifdef DEBUG
329 MOZ_ReportCrash(aReason, aFilename, aLine);
330 #endif
331 MOZ_CRASH_ANNOTATE(aReason);
332 MOZ_REALLY_CRASH(aLine);
334 #define MOZ_CRASH_UNSAFE(reason) MOZ_Crash(__FILE__, __LINE__, reason)
336 static const size_t sPrintfMaxArgs = 4;
337 static const size_t sPrintfCrashReasonSize = 1024;
339 MFBT_API MOZ_COLD MOZ_NEVER_INLINE MOZ_FORMAT_PRINTF(1, 2) const
340 char* MOZ_CrashPrintf(const char* aFormat, ...);
343 * MOZ_CRASH_UNSAFE_PRINTF(format, arg1 [, args]) can be used when more
344 * information is desired than a string literal can supply. The caller provides
345 * a printf-style format string, which must be a string literal and between
346 * 1 and 4 additional arguments. A regular MOZ_CRASH() is preferred wherever
347 * possible, as passing arbitrary strings to printf from a potentially
348 * compromised process is not without risk.
350 * @note This macro causes data collection because crash strings are annotated
351 * to crash-stats and are publicly visible. Firefox data stewards must do data
352 * review on usages of this macro.
354 #define MOZ_CRASH_UNSAFE_PRINTF(format, ...) \
355 do { \
356 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) > 0, \
357 "Did you forget arguments to MOZ_CRASH_UNSAFE_PRINTF? " \
358 "Or maybe you want MOZ_CRASH instead?"); \
359 static_assert(MOZ_ARG_COUNT(__VA_ARGS__) <= sPrintfMaxArgs, \
360 "Only up to 4 additional arguments are allowed!"); \
361 static_assert(sizeof(format) <= sPrintfCrashReasonSize, \
362 "The supplied format string is too long!"); \
363 MOZ_Crash(__FILE__, __LINE__, MOZ_CrashPrintf("" format, __VA_ARGS__)); \
364 } while (false)
366 MOZ_END_EXTERN_C
369 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
370 * debug builds. If it is, execution continues. Otherwise, an error message
371 * including the expression and the explanation-string (if provided) is printed,
372 * an attempt is made to invoke any existing debugger, and execution halts.
373 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
374 * which can correctly be falsy.
376 * The optional explanation-string, if provided, must be a string literal
377 * explaining the assertion. It is intended for use with assertions whose
378 * correctness or rationale is non-obvious, and for assertions where the "real"
379 * condition being tested is best described prosaically. Don't provide an
380 * explanation if it's not actually helpful.
382 * // No explanation needed: pointer arguments often must not be NULL.
383 * MOZ_ASSERT(arg);
385 * // An explanation can be helpful to explain exactly how we know an
386 * // assertion is valid.
387 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
388 * "given that <thingA> and <thingB>, we must have...");
390 * // Or it might disambiguate multiple identical (save for their location)
391 * // assertions of the same expression.
392 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
393 * "we already set [[PrimitiveThis]] for this Boolean object");
394 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
395 * "we already set [[PrimitiveThis]] for this String object");
397 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
398 * *only* during debugging, not "in the field". If you want the latter, use
399 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
401 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
402 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
403 * enough to require real user testing to hit, but is not security-sensitive.
404 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
405 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
406 * is being investigated, rather than letting users suffer.
408 * MOZ_DIAGNOSTIC_ASSERT_ENABLED is defined when MOZ_DIAGNOSTIC_ASSERT is like
409 * MOZ_RELEASE_ASSERT rather than MOZ_ASSERT.
413 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
414 * accidentally passing something unintended in lieu of an assertion condition.
417 #ifdef __cplusplus
418 # include <type_traits>
419 namespace mozilla {
420 namespace detail {
422 template <typename T>
423 struct AssertionConditionType {
424 using ValueT = std::remove_reference_t<T>;
425 static_assert(!std::is_array_v<ValueT>,
426 "Expected boolean assertion condition, got an array or a "
427 "string!");
428 static_assert(!std::is_function_v<ValueT>,
429 "Expected boolean assertion condition, got a function! Did "
430 "you intend to call that function?");
431 static_assert(!std::is_floating_point_v<ValueT>,
432 "It's often a bad idea to assert that a floating-point number "
433 "is nonzero, because such assertions tend to intermittently "
434 "fail. Shouldn't your code gracefully handle this case instead "
435 "of asserting? Anyway, if you really want to do that, write an "
436 "explicit boolean condition, like !!x or x!=0.");
438 static const bool isValid = true;
441 } // namespace detail
442 } // namespace mozilla
443 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
444 static_assert( \
445 mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
446 "invalid assertion condition")
447 #else
448 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
449 #endif
451 #if defined(DEBUG) || defined(MOZ_ASAN)
452 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
453 MOZ_ReportAssertionFailure(__VA_ARGS__)
454 #else
455 # define MOZ_REPORT_ASSERTION_FAILURE(...) \
456 do { /* nothing */ \
457 } while (false)
458 #endif
460 /* First the single-argument form. */
461 #define MOZ_ASSERT_HELPER1(kind, expr) \
462 do { \
463 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
464 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
465 MOZ_REPORT_ASSERTION_FAILURE(#expr, __FILE__, __LINE__); \
466 MOZ_CRASH_ANNOTATE(kind "(" #expr ")"); \
467 MOZ_REALLY_CRASH(__LINE__); \
469 } while (false)
470 /* Now the two-argument form. */
471 #define MOZ_ASSERT_HELPER2(kind, expr, explain) \
472 do { \
473 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
474 if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \
475 MOZ_REPORT_ASSERTION_FAILURE(#expr " (" explain ")", __FILE__, \
476 __LINE__); \
477 MOZ_CRASH_ANNOTATE(kind "(" #expr ") (" explain ")"); \
478 MOZ_REALLY_CRASH(__LINE__); \
480 } while (false)
482 #define MOZ_ASSERT_GLUE(a, b) a b
483 #define MOZ_RELEASE_ASSERT(...) \
484 MOZ_ASSERT_GLUE( \
485 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
486 ("MOZ_RELEASE_ASSERT", __VA_ARGS__))
488 #ifdef DEBUG
489 # define MOZ_ASSERT(...) \
490 MOZ_ASSERT_GLUE( \
491 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
492 ("MOZ_ASSERT", __VA_ARGS__))
493 #else
494 # define MOZ_ASSERT(...) \
495 do { \
496 } while (false)
497 #endif /* DEBUG */
499 #if defined(NIGHTLY_BUILD) || defined(MOZ_DEV_EDITION) || defined(DEBUG)
500 # define MOZ_DIAGNOSTIC_ASSERT(...) \
501 MOZ_ASSERT_GLUE( \
502 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
503 ("MOZ_DIAGNOSTIC_ASSERT", __VA_ARGS__))
504 # define MOZ_DIAGNOSTIC_ASSERT_ENABLED 1
505 #else
506 # define MOZ_DIAGNOSTIC_ASSERT(...) \
507 do { \
508 } while (false)
509 #endif
512 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
513 * true.
515 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
517 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
518 * designed to catch bugs during debugging, not "in the field".
520 #ifdef DEBUG
521 # define MOZ_ASSERT_IF(cond, expr) \
522 do { \
523 if (cond) { \
524 MOZ_ASSERT(expr); \
526 } while (false)
527 #else
528 # define MOZ_ASSERT_IF(cond, expr) \
529 do { \
530 } while (false)
531 #endif
534 * MOZ_DIAGNOSTIC_ASSERT_IF is like MOZ_ASSERT_IF, but using
535 * MOZ_DIAGNOSTIC_ASSERT as the underlying assert.
537 * See the block comment for MOZ_DIAGNOSTIC_ASSERT above for more details on how
538 * diagnostic assertions work and how to use them.
540 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
541 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
542 do { \
543 if (cond) { \
544 MOZ_DIAGNOSTIC_ASSERT(expr); \
546 } while (false)
547 #else
548 # define MOZ_DIAGNOSTIC_ASSERT_IF(cond, expr) \
549 do { \
550 } while (false)
551 #endif
554 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
555 * it is undefined behavior for execution to reach this point. No guarantees
556 * are made about what will happen if this is reached at runtime. Most code
557 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
558 * asserts.
560 #if defined(__clang__) || defined(__GNUC__)
561 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
562 #elif defined(_MSC_VER)
563 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
564 #else
565 # ifdef __cplusplus
566 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
567 # else
568 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
569 # endif
570 #endif
573 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
574 * can assume that the macro call cannot be reached during execution. This lets
575 * the compiler generate better-optimized code under some circumstances, at the
576 * expense of the program's behavior being undefined if control reaches the
577 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
579 * In Gecko, you probably should not use this macro outside of performance- or
580 * size-critical code, because it's unsafe. If you don't care about code size
581 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
583 * SpiderMonkey is a different beast, and there it's acceptable to use
584 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
586 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
587 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
588 * call.
590 * Example usage:
592 * enum ValueType {
593 * VALUE_STRING,
594 * VALUE_INT,
595 * VALUE_FLOAT
596 * };
598 * int ptrToInt(ValueType type, void* value) {
600 * // We know for sure that type is either INT or FLOAT, and we want this
601 * // code to run as quickly as possible.
602 * switch (type) {
603 * case VALUE_INT:
604 * return *(int*) value;
605 * case VALUE_FLOAT:
606 * return (int) *(float*) value;
607 * default:
608 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
614 * Unconditional assert in debug builds for (assumed) unreachable code paths
615 * that have a safe return without crashing in release builds.
617 #define MOZ_ASSERT_UNREACHABLE(reason) \
618 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
620 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
621 do { \
622 MOZ_ASSERT_UNREACHABLE(reason); \
623 MOZ_ASSUME_UNREACHABLE_MARKER(); \
624 } while (false)
627 * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about
628 * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in
629 * debug builds, but intentionally fall through in release builds to handle
630 * unexpected values.
632 * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to [[fallthrough]]? In
633 * release builds, the MOZ_ASSERT(false) will expand to `do { } while (false)`,
634 * requiring a [[fallthrough]] annotation to suppress a -Wimplicit-fallthrough
635 * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like
636 * `if (true) { MOZ_CRASH(); }` and the [[fallthrough]] annotation will cause
637 * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this
638 * warning stalemate.
640 * // Example before MOZ_FALLTHROUGH_ASSERT:
641 * switch (foo) {
642 * default:
643 * // This case wants to assert in debug builds, fall through in release.
644 * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds!
645 * [[fallthrough]]; // but -Wunreachable-code warning in debug builds!
646 * case 5:
647 * return 5;
650 * // Example with MOZ_FALLTHROUGH_ASSERT:
651 * switch (foo) {
652 * default:
653 * // This case asserts in debug builds, falls through in release.
654 * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!");
655 * case 5:
656 * return 5;
659 #ifdef DEBUG
660 # define MOZ_FALLTHROUGH_ASSERT(...) \
661 MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " __VA_ARGS__)
662 #else
663 # define MOZ_FALLTHROUGH_ASSERT(...) [[fallthrough]]
664 #endif
667 * MOZ_ALWAYS_TRUE(expr) and friends always evaluate the provided expression,
668 * in debug builds and in release builds both. Then, in debug builds and
669 * Nightly and DevEdition release builds, the value of the expression is
670 * asserted either true or false using MOZ_DIAGNOSTIC_ASSERT.
672 #define MOZ_ALWAYS_TRUE(expr) \
673 do { \
674 if (MOZ_LIKELY(expr)) { \
675 /* Silence MOZ_MUST_USE. */ \
676 } else { \
677 MOZ_DIAGNOSTIC_ASSERT(false, #expr); \
679 } while (false)
681 #define MOZ_ALWAYS_FALSE(expr) MOZ_ALWAYS_TRUE(!(expr))
682 #define MOZ_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE((expr).isOk())
683 #define MOZ_ALWAYS_ERR(expr) MOZ_ALWAYS_TRUE((expr).isErr())
685 #undef MOZ_DUMP_ASSERTION_STACK
686 #undef MOZ_CRASH_CRASHREPORT
688 #endif /* mozilla_Assertions_h */