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