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
16 #include "mozilla/Attributes.h"
17 #include "mozilla/Compiler.h"
18 #include "mozilla/Likely.h"
19 #include "mozilla/MacroArgs.h"
20 #ifdef MOZ_DUMP_ASSERTION_STACK
21 #include "nsTraceRefcnt.h"
29 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
30 * further depends on <windef.h>. We hardcode these few definitions manually
31 * because those headers clutter the global namespace with a significant
32 * number of undesired macros and symbols.
37 __declspec(dllimport
) int __stdcall
38 TerminateProcess(void* hProcess
, unsigned int uExitCode
);
39 __declspec(dllimport
) void* __stdcall
GetCurrentProcess(void);
47 # include <android/log.h>
51 * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C.
52 * In C++11, static_assert is provided by the compiler to the same effect.
53 * This can be useful when you make certain assumptions about what must hold for
54 * optimal, or even correct, behavior. For example, you might assert that the
55 * size of a struct is a multiple of the target architecture's word size:
59 * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
60 * "S should be a multiple of word size for efficiency");
62 * static_assert(sizeof(S) % sizeof(size_t) == 0,
63 * "S should be a multiple of word size for efficiency");
65 * This macro can be used in any location where both an extern declaration and a
66 * typedef could be used.
70 * Some of the definitions below create an otherwise-unused typedef. This
71 * triggers compiler warnings with some versions of gcc, so mark the typedefs
72 * as permissibly-unused to disable the warnings.
74 # if defined(__GNUC__)
75 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
77 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
79 # define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y
80 # define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y)
81 # if defined(__SUNPRO_CC)
83 * The Sun Studio C++ compiler is buggy when declaring, inside a function,
84 * another extern'd function with an array argument whose length contains a
85 * sizeof, triggering the error message "sizeof expression not accepted as
86 * size of array parameter". This bug (6688515, not public yet) would hit
87 * defining moz_static_assert as a function, so we always define an extern
88 * array for Sun Studio.
90 * We include the line number in the symbol name in a best-effort attempt
91 * to avoid conflicts (see below).
93 # define MOZ_STATIC_ASSERT(cond, reason) \
94 extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1]
95 # elif defined(__COUNTER__)
97 * If there was no preferred alternative, use a compiler-agnostic version.
99 * Note that the non-__COUNTER__ version has a bug in C++: it can't be used
100 * in both |extern "C"| and normal C++ in the same translation unit. (Alas
101 * |extern "C"| isn't allowed in a function.) The only affected compiler
102 * we really care about is gcc 4.2. For that compiler and others like it,
103 * we include the line number in the function name to do the best we can to
104 * avoid conflicts. These should be rare: a conflict would require use of
105 * MOZ_STATIC_ASSERT on the same line in separate files in the same
106 * translation unit, *and* the uses would have to be in code with
107 * different linkage, *and* the first observed use must be in C++-linkage
110 # define MOZ_STATIC_ASSERT(cond, reason) \
111 typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
113 # define MOZ_STATIC_ASSERT(cond, reason) \
114 extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
117 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
119 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason)
127 * Prints |aStr| as an assertion failure (using aFilename and aLine as the
128 * location of the assertion) to the standard debug-output channel.
130 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
131 * method is primarily for internal use in this header, and only secondarily
132 * for use in implementing release-build assertions.
134 static MOZ_COLD MOZ_ALWAYS_INLINE
void
135 MOZ_ReportAssertionFailure(const char* aStr
, const char* aFilename
, int aLine
)
136 MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
139 __android_log_print(ANDROID_LOG_FATAL
, "MOZ_Assert",
140 "Assertion failure: %s, at %s:%d\n",
141 aStr
, aFilename
, aLine
);
143 fprintf(stderr
, "Assertion failure: %s, at %s:%d\n", aStr
, aFilename
, aLine
);
144 #if defined (MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API)
145 nsTraceRefcnt::WalkTheStack(stderr
);
151 static MOZ_COLD MOZ_ALWAYS_INLINE
void
152 MOZ_ReportCrash(const char* aStr
, const char* aFilename
, int aLine
)
153 MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
156 __android_log_print(ANDROID_LOG_FATAL
, "MOZ_CRASH",
157 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr
, aFilename
, aLine
);
159 fprintf(stderr
, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr
, aFilename
, aLine
);
160 #if defined(MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API)
161 nsTraceRefcnt::WalkTheStack(stderr
);
168 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
169 * call MOZ_CRASH instead.
171 #if defined(_MSC_VER)
173 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
174 * (not nested in a system function) breakpoint. This distinctively invokes
175 * Breakpad without requiring system library symbols on all stack-processing
176 * machines, as a nested breakpoint would require.
178 * We use TerminateProcess with the exit code aborting would generate
179 * because we don't want to invoke atexit handlers, destructors, library
180 * unload handlers, and so on when our process might be in a compromised
183 * We don't use abort() because it'd cause Windows to annoyingly pop up the
184 * process error dialog multiple times. See bug 345118 and bug 426163.
186 * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the
187 * compiler doesn't hassle us to provide a return statement after a
188 * MOZ_REALLY_CRASH() call.
190 * (Technically these are Windows requirements, not MSVC requirements. But
191 * practically you need MSVC for debugging, and we only ship builds created
192 * by MSVC, so doing it this way reduces complexity.)
195 __declspec(noreturn
) __inline
void MOZ_NoReturn() {}
198 # define MOZ_REALLY_CRASH() \
201 *((volatile int*) NULL) = __LINE__; \
202 ::TerminateProcess(::GetCurrentProcess(), 3); \
206 # define MOZ_REALLY_CRASH() \
209 *((volatile int*) NULL) = __LINE__; \
210 TerminateProcess(GetCurrentProcess(), 3); \
216 # define MOZ_REALLY_CRASH() \
218 *((volatile int*) NULL) = __LINE__; \
222 # define MOZ_REALLY_CRASH() \
224 *((volatile int*) NULL) = __LINE__; \
231 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
232 * Breakpad-compatible way, in both debug and release builds.
234 * MOZ_CRASH is a good solution for "handling" failure cases when you're
235 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
236 * corruption, and so on. It's also a good solution if you need safe behavior
237 * in release builds as well as debug builds. But if the failure is one that
238 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
240 * The optional explanation-string, if provided, must be a string literal
241 * explaining why we're crashing. This argument is intended for use with
242 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
243 * obvious why we're crashing.
245 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
246 * explanation-string, we print the string to stderr. Otherwise, we don't
247 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
248 * builds, and it's hard to print to stderr safely when memory might have been
252 # define MOZ_CRASH(...) MOZ_REALLY_CRASH()
254 # define MOZ_CRASH(...) \
256 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
257 MOZ_REALLY_CRASH(); \
266 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
267 * debug builds. If it is, execution continues. Otherwise, an error message
268 * including the expression and the explanation-string (if provided) is printed,
269 * an attempt is made to invoke any existing debugger, and execution halts.
270 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
271 * which can correctly be falsy.
273 * The optional explanation-string, if provided, must be a string literal
274 * explaining the assertion. It is intended for use with assertions whose
275 * correctness or rationale is non-obvious, and for assertions where the "real"
276 * condition being tested is best described prosaically. Don't provide an
277 * explanation if it's not actually helpful.
279 * // No explanation needed: pointer arguments often must not be NULL.
282 * // An explanation can be helpful to explain exactly how we know an
283 * // assertion is valid.
284 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
285 * "given that <thingA> and <thingB>, we must have...");
287 * // Or it might disambiguate multiple identical (save for their location)
288 * // assertions of the same expression.
289 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
290 * "we already set [[PrimitiveThis]] for this Boolean object");
291 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
292 * "we already set [[PrimitiveThis]] for this String object");
294 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
295 * *only* during debugging, not "in the field". If you want the latter, use
296 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
298 * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and
299 * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare
300 * enough to require real user testing to hit, but is not security-sensitive.
301 * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT
302 * is firing, it should promptly be converted to a MOZ_ASSERT while the failure
303 * is being investigated, rather than letting users suffer.
307 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
308 * accidentally passing something unintended in lieu of an assertion condition.
312 # include "mozilla/TypeTraits.h"
319 static const bool value
= false;
322 template<typename R
, typename
... A
>
323 struct IsFunction
<R(A
...)>
325 static const bool value
= true;
329 struct AssertionConditionType
331 typedef typename RemoveReference
<T
>::Type ValueT
;
332 static_assert(!IsArray
<ValueT
>::value
,
333 "Expected boolean assertion condition, got an array or a "
335 static_assert(!IsFunction
<ValueT
>::value
,
336 "Expected boolean assertion condition, got a function! Did "
337 "you intend to call that function?");
338 static_assert(!IsFloatingPoint
<ValueT
>::value
,
339 "It's often a bad idea to assert that a floating-point number "
340 "is nonzero, because such assertions tend to intermittently "
341 "fail. Shouldn't your code gracefully handle this case instead "
342 "of asserting? Anyway, if you really want to do that, write an "
343 "explicit boolean condition, like !!x or x!=0.");
345 static const bool isValid
= true;
348 } // namespace detail
349 } // namespace mozilla
350 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
351 static_assert(mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
352 "invalid assertion condition")
354 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
357 /* First the single-argument form. */
358 #define MOZ_ASSERT_HELPER1(expr) \
360 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
361 if (MOZ_UNLIKELY(!(expr))) { \
362 MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
363 MOZ_REALLY_CRASH(); \
366 /* Now the two-argument form. */
367 #define MOZ_ASSERT_HELPER2(expr, explain) \
369 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
370 if (MOZ_UNLIKELY(!(expr))) { \
371 MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
372 MOZ_REALLY_CRASH(); \
376 #define MOZ_RELEASE_ASSERT_GLUE(a, b) a b
377 #define MOZ_RELEASE_ASSERT(...) \
378 MOZ_RELEASE_ASSERT_GLUE( \
379 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
383 # define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
385 # define MOZ_ASSERT(...) do { } while (0)
389 # define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT
391 # define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT
395 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
398 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
400 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
401 * designed to catch bugs during debugging, not "in the field".
404 # define MOZ_ASSERT_IF(cond, expr) \
411 # define MOZ_ASSERT_IF(cond, expr) do { } while (0)
415 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
416 * it is undefined behavior for execution to reach this point. No guarantees
417 * are made about what will happen if this is reached at runtime. Most code
418 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
421 #if defined(__clang__) || defined(__GNUC__)
422 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
423 #elif defined(_MSC_VER)
424 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
427 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
429 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
434 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
435 * can assume that the macro call cannot be reached during execution. This lets
436 * the compiler generate better-optimized code under some circumstances, at the
437 * expense of the program's behavior being undefined if control reaches the
438 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
440 * In Gecko, you probably should not use this macro outside of performance- or
441 * size-critical code, because it's unsafe. If you don't care about code size
442 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
444 * SpiderMonkey is a different beast, and there it's acceptable to use
445 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
447 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
448 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
459 * int ptrToInt(ValueType type, void* value) {
461 * // We know for sure that type is either INT or FLOAT, and we want this
462 * // code to run as quickly as possible.
465 * return *(int*) value;
467 * return (int) *(float*) value;
469 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
475 * Unconditional assert in debug builds for (assumed) unreachable code paths
476 * that have a safe return without crashing in release builds.
478 #define MOZ_ASSERT_UNREACHABLE(reason) \
479 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
481 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
483 MOZ_ASSERT_UNREACHABLE(reason); \
484 MOZ_ASSUME_UNREACHABLE_MARKER(); \
488 * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
489 * expression, in debug builds and in release builds both. Then, in debug
490 * builds only, the value of the expression is asserted either true or false
494 # define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr))
495 # define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr))
497 # define MOZ_ALWAYS_TRUE(expr) ((void)(expr))
498 # define MOZ_ALWAYS_FALSE(expr) ((void)(expr))
501 #undef MOZ_DUMP_ASSERTION_STACK
503 #endif /* mozilla_Assertions_h */