Bumping manifests a=b2g-bump
[gecko.git] / mfbt / Assertions.h
blob0b0640e9c37894d08acaafb58372672b548c9be4
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 #ifdef MOZ_DUMP_ASSERTION_STACK
21 #include "nsTraceRefcnt.h"
22 #endif
24 #include <stddef.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #ifdef WIN32
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.
34 # ifdef __cplusplus
35 extern "C" {
36 # endif
37 __declspec(dllimport) int __stdcall
38 TerminateProcess(void* hProcess, unsigned int uExitCode);
39 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
40 # ifdef __cplusplus
42 # endif
43 #else
44 # include <signal.h>
45 #endif
46 #ifdef ANDROID
47 # include <android/log.h>
48 #endif
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:
57 * struct S { ... };
58 * // C
59 * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
60 * "S should be a multiple of word size for efficiency");
61 * // C++11
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.
68 #ifndef __cplusplus
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))
76 # else
77 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
78 # endif
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
108 * code.
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
112 # else
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
115 # endif
117 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
118 #else
119 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason)
120 #endif
122 #ifdef __cplusplus
123 extern "C" {
124 #endif
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_ALWAYS_INLINE void
135 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine)
136 MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
138 #ifdef ANDROID
139 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
140 "Assertion failure: %s, at %s:%d\n",
141 aStr, aFilename, aLine);
142 #else
143 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine);
144 #ifdef MOZ_DUMP_ASSERTION_STACK
145 nsTraceRefcnt::WalkTheStack(stderr);
146 #endif
147 fflush(stderr);
148 #endif
151 static MOZ_ALWAYS_INLINE void
152 MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine)
153 MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
155 #ifdef ANDROID
156 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
157 "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
158 #else
159 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine);
160 #ifdef MOZ_DUMP_ASSERTION_STACK
161 nsTraceRefcnt::WalkTheStack(stderr);
162 #endif
163 fflush(stderr);
164 #endif
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
181 * state.
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() {}
197 # ifdef __cplusplus
198 # define MOZ_REALLY_CRASH() \
199 do { \
200 ::__debugbreak(); \
201 *((volatile int*) NULL) = __LINE__; \
202 ::TerminateProcess(::GetCurrentProcess(), 3); \
203 ::MOZ_NoReturn(); \
204 } while (0)
205 # else
206 # define MOZ_REALLY_CRASH() \
207 do { \
208 __debugbreak(); \
209 *((volatile int*) NULL) = __LINE__; \
210 TerminateProcess(GetCurrentProcess(), 3); \
211 MOZ_NoReturn(); \
212 } while (0)
213 # endif
214 #else
215 # ifdef __cplusplus
216 # define MOZ_REALLY_CRASH() \
217 do { \
218 *((volatile int*) NULL) = __LINE__; \
219 ::abort(); \
220 } while (0)
221 # else
222 # define MOZ_REALLY_CRASH() \
223 do { \
224 *((volatile int*) NULL) = __LINE__; \
225 abort(); \
226 } while (0)
227 # endif
228 #endif
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
249 * corrupted.
251 #ifndef DEBUG
252 # define MOZ_CRASH(...) MOZ_REALLY_CRASH()
253 #else
254 # define MOZ_CRASH(...) \
255 do { \
256 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
257 MOZ_REALLY_CRASH(); \
258 } while (0)
259 #endif
261 #ifdef __cplusplus
262 } /* extern "C" */
263 #endif
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.
280 * MOZ_ASSERT(arg);
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.
311 #ifdef __cplusplus
312 # if defined(__clang__)
313 # define MOZ_SUPPORT_ASSERT_CONDITION_TYPE_VALIDATION
314 # elif defined(__GNUC__)
315 // B2G GCC 4.4 has insufficient decltype support.
316 # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
317 # define MOZ_SUPPORT_ASSERT_CONDITION_TYPE_VALIDATION
318 # endif
319 # elif defined(_MSC_VER)
320 // Disabled for now because of insufficient decltype support. Bug 1004028.
321 # endif
322 #endif
324 #ifdef MOZ_SUPPORT_ASSERT_CONDITION_TYPE_VALIDATION
325 # include "mozilla/TypeTraits.h"
326 namespace mozilla {
327 namespace detail {
329 template<typename T>
330 struct IsFunction
332 static const bool value = false;
335 template<typename R, typename... A>
336 struct IsFunction<R(A...)>
338 static const bool value = true;
341 template<typename T>
342 struct AssertionConditionType
344 typedef typename RemoveReference<T>::Type ValueT;
345 static_assert(!IsArray<ValueT>::value,
346 "Expected boolean assertion condition, got an array or a "
347 "string!");
348 static_assert(!IsFunction<ValueT>::value,
349 "Expected boolean assertion condition, got a function! Did "
350 "you intend to call that function?");
351 static_assert(!IsFloatingPoint<ValueT>::value,
352 "It's often a bad idea to assert that a floating-point number "
353 "is nonzero, because such assertions tend to intermittently "
354 "fail. Shouldn't your code gracefully handle this case instead "
355 "of asserting? Anyway, if you really want to do that, write an "
356 "explicit boolean condition, like !!x or x!=0.");
358 static const bool isValid = true;
361 } // namespace detail
362 } // namespace mozilla
363 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
364 static_assert(mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
365 "invalid assertion condition")
366 #else
367 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
368 #endif
370 /* First the single-argument form. */
371 #define MOZ_ASSERT_HELPER1(expr) \
372 do { \
373 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
374 if (MOZ_UNLIKELY(!(expr))) { \
375 MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
376 MOZ_REALLY_CRASH(); \
378 } while (0)
379 /* Now the two-argument form. */
380 #define MOZ_ASSERT_HELPER2(expr, explain) \
381 do { \
382 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
383 if (MOZ_UNLIKELY(!(expr))) { \
384 MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
385 MOZ_REALLY_CRASH(); \
387 } while (0)
389 #define MOZ_RELEASE_ASSERT_GLUE(a, b) a b
390 #define MOZ_RELEASE_ASSERT(...) \
391 MOZ_RELEASE_ASSERT_GLUE( \
392 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
393 (__VA_ARGS__))
395 #ifdef DEBUG
396 # define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
397 #else
398 # define MOZ_ASSERT(...) do { } while (0)
399 #endif /* DEBUG */
401 #ifdef RELEASE_BUILD
402 # define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT
403 #else
404 # define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT
405 #endif
408 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
409 * true.
411 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
413 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
414 * designed to catch bugs during debugging, not "in the field".
416 #ifdef DEBUG
417 # define MOZ_ASSERT_IF(cond, expr) \
418 do { \
419 if (cond) { \
420 MOZ_ASSERT(expr); \
422 } while (0)
423 #else
424 # define MOZ_ASSERT_IF(cond, expr) do { } while (0)
425 #endif
428 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
429 * it is undefined behavior for execution to reach this point. No guarantees
430 * are made about what will happen if this is reached at runtime. Most code
431 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
432 * asserts.
434 #if defined(__clang__)
435 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
436 #elif defined(__GNUC__)
438 * __builtin_unreachable() was implemented in gcc 4.5. If we don't have
439 * that, call a noreturn function; abort() will do nicely. Qualify the call
440 * in C++ in case there's another abort() visible in local scope.
442 # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
443 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
444 # else
445 # ifdef __cplusplus
446 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
447 # else
448 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
449 # endif
450 # endif
451 #elif defined(_MSC_VER)
452 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
453 #else
454 # ifdef __cplusplus
455 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
456 # else
457 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
458 # endif
459 #endif
462 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
463 * can assume that the macro call cannot be reached during execution. This lets
464 * the compiler generate better-optimized code under some circumstances, at the
465 * expense of the program's behavior being undefined if control reaches the
466 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
468 * In Gecko, you probably should not use this macro outside of performance- or
469 * size-critical code, because it's unsafe. If you don't care about code size
470 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
472 * SpiderMonkey is a different beast, and there it's acceptable to use
473 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
475 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
476 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
477 * call.
479 * Example usage:
481 * enum ValueType {
482 * VALUE_STRING,
483 * VALUE_INT,
484 * VALUE_FLOAT
485 * };
487 * int ptrToInt(ValueType type, void* value) {
489 * // We know for sure that type is either INT or FLOAT, and we want this
490 * // code to run as quickly as possible.
491 * switch (type) {
492 * case VALUE_INT:
493 * return *(int*) value;
494 * case VALUE_FLOAT:
495 * return (int) *(float*) value;
496 * default:
497 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
503 * Unconditional assert in debug builds for (assumed) unreachable code paths
504 * that have a safe return without crashing in release builds.
506 #define MOZ_ASSERT_UNREACHABLE(reason) \
507 MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
509 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
510 do { \
511 MOZ_ASSERT_UNREACHABLE(reason); \
512 MOZ_ASSUME_UNREACHABLE_MARKER(); \
513 } while (0)
516 * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
517 * expression, in debug builds and in release builds both. Then, in debug
518 * builds only, the value of the expression is asserted either true or false
519 * using MOZ_ASSERT.
521 #ifdef DEBUG
522 # define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr))
523 # define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr))
524 #else
525 # define MOZ_ALWAYS_TRUE(expr) ((void)(expr))
526 # define MOZ_ALWAYS_FALSE(expr) ((void)(expr))
527 #endif
529 #undef MOZ_DUMP_ASSERTION_STACK
531 #endif /* mozilla_Assertions_h */