Bumping manifests a=b2g-bump
[gecko.git] / mfbt / Assertions.h
bloba463b2768d69b4801b06fe4158d5a80448fac81b
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) = 123; \
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) = 123; \
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) = 123; \
219 ::abort(); \
220 } while (0)
221 # else
222 # define MOZ_REALLY_CRASH() \
223 do { \
224 *((volatile int*) NULL) = 123; \
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.
300 * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
301 * accidentally passing something unintended in lieu of an assertion condition.
304 #ifdef __cplusplus
305 # if defined(__clang__)
306 # define MOZ_SUPPORT_ASSERT_CONDITION_TYPE_VALIDATION
307 # elif defined(__GNUC__)
308 // B2G GCC 4.4 has insufficient decltype support.
309 # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
310 # define MOZ_SUPPORT_ASSERT_CONDITION_TYPE_VALIDATION
311 # endif
312 # elif defined(_MSC_VER)
313 // Disabled for now because of insufficient decltype support. Bug 1004028.
314 # endif
315 #endif
317 #ifdef MOZ_SUPPORT_ASSERT_CONDITION_TYPE_VALIDATION
318 # include "mozilla/TypeTraits.h"
319 namespace mozilla {
320 namespace detail {
322 template<typename T>
323 struct IsFunction
325 static const bool value = false;
328 template<typename R, typename... A>
329 struct IsFunction<R(A...)>
331 static const bool value = true;
334 template<typename T>
335 void ValidateAssertConditionType()
337 typedef typename RemoveReference<T>::Type ValueT;
338 static_assert(!IsArray<ValueT>::value,
339 "Expected boolean assertion condition, got an array or a "
340 "string!");
341 static_assert(!IsFunction<ValueT>::value,
342 "Expected boolean assertion condition, got a function! Did "
343 "you intend to call that function?");
344 static_assert(!IsFloatingPoint<ValueT>::value,
345 "It's often a bad idea to assert that a floating-point number "
346 "is nonzero, because such assertions tend to intermittently "
347 "fail. Shouldn't your code gracefully handle this case instead "
348 "of asserting? Anyway, if you really want to do that, write an "
349 "explicit boolean condition, like !!x or x!=0.");
352 } // namespace detail
353 } // namespace mozilla
354 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
355 mozilla::detail::ValidateAssertConditionType<decltype(x)>()
356 #else
357 # define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
358 #endif
360 /* First the single-argument form. */
361 #define MOZ_ASSERT_HELPER1(expr) \
362 do { \
363 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
364 if (MOZ_UNLIKELY(!(expr))) { \
365 MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
366 MOZ_REALLY_CRASH(); \
368 } while (0)
369 /* Now the two-argument form. */
370 #define MOZ_ASSERT_HELPER2(expr, explain) \
371 do { \
372 MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
373 if (MOZ_UNLIKELY(!(expr))) { \
374 MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
375 MOZ_REALLY_CRASH(); \
377 } while (0)
379 #define MOZ_RELEASE_ASSERT_GLUE(a, b) a b
380 #define MOZ_RELEASE_ASSERT(...) \
381 MOZ_RELEASE_ASSERT_GLUE( \
382 MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
383 (__VA_ARGS__))
385 #ifdef DEBUG
386 # define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
387 #else
388 # define MOZ_ASSERT(...) do { } while (0)
389 #endif /* DEBUG */
392 * MOZ_NIGHTLY_ASSERT is defined for both debug and release builds on the
393 * Nightly channel, but only debug builds on Aurora, Beta, and Release.
395 #if defined(NIGHTLY_BUILD)
396 # define MOZ_NIGHTLY_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
397 #else
398 # define MOZ_NIGHTLY_ASSERT(...) MOZ_ASSERT(__VA_ARGS__)
399 #endif
402 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
403 * true.
405 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
407 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
408 * designed to catch bugs during debugging, not "in the field".
410 #ifdef DEBUG
411 # define MOZ_ASSERT_IF(cond, expr) \
412 do { \
413 if (cond) { \
414 MOZ_ASSERT(expr); \
416 } while (0)
417 #else
418 # define MOZ_ASSERT_IF(cond, expr) do { } while (0)
419 #endif
422 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
423 * it is undefined behavior for execution to reach this point. No guarantees
424 * are made about what will happen if this is reached at runtime. Most code
425 * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
426 * asserts.
428 #if defined(__clang__)
429 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
430 #elif defined(__GNUC__)
432 * __builtin_unreachable() was implemented in gcc 4.5. If we don't have
433 * that, call a noreturn function; abort() will do nicely. Qualify the call
434 * in C++ in case there's another abort() visible in local scope.
436 # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
437 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
438 # else
439 # ifdef __cplusplus
440 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
441 # else
442 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
443 # endif
444 # endif
445 #elif defined(_MSC_VER)
446 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
447 #else
448 # ifdef __cplusplus
449 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
450 # else
451 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
452 # endif
453 #endif
456 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
457 * can assume that the macro call cannot be reached during execution. This lets
458 * the compiler generate better-optimized code under some circumstances, at the
459 * expense of the program's behavior being undefined if control reaches the
460 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
462 * In Gecko, you probably should not use this macro outside of performance- or
463 * size-critical code, because it's unsafe. If you don't care about code size
464 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
466 * SpiderMonkey is a different beast, and there it's acceptable to use
467 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
469 * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
470 * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
471 * call.
473 * Example usage:
475 * enum ValueType {
476 * VALUE_STRING,
477 * VALUE_INT,
478 * VALUE_FLOAT
479 * };
481 * int ptrToInt(ValueType type, void* value) {
483 * // We know for sure that type is either INT or FLOAT, and we want this
484 * // code to run as quickly as possible.
485 * switch (type) {
486 * case VALUE_INT:
487 * return *(int*) value;
488 * case VALUE_FLOAT:
489 * return (int) *(float*) value;
490 * default:
491 * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
497 * Assert in all debug builds plus the Nightly channel's release builds. Take
498 * this extra testing precaution because hitting MOZ_ASSUME_UNREACHABLE_MARKER
499 * could trigger exploitable undefined behavior.
501 #define MOZ_ASSERT_UNREACHABLE(reason) \
502 MOZ_NIGHTLY_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
504 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
505 do { \
506 MOZ_ASSERT_UNREACHABLE(reason); \
507 MOZ_ASSUME_UNREACHABLE_MARKER(); \
508 } while (0)
511 * TODO: Bug 990764: Audit all MOZ_ASSUME_UNREACHABLE calls and replace them
512 * with MOZ_ASSERT_UNREACHABLE, MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE, or
513 * MOZ_CRASH. For now, preserve the macro's same meaning of unreachable.
515 #define MOZ_ASSUME_UNREACHABLE(reason) \
516 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason)
519 * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
520 * expression, in debug builds and in release builds both. Then, in debug
521 * builds only, the value of the expression is asserted either true or false
522 * using MOZ_ASSERT.
524 #ifdef DEBUG
525 # define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr))
526 # define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr))
527 #else
528 # define MOZ_ALWAYS_TRUE(expr) ((void)(expr))
529 # define MOZ_ALWAYS_FALSE(expr) ((void)(expr))
530 #endif
532 #undef MOZ_DUMP_ASSERTION_STACK
534 #endif /* mozilla_Assertions_h */