Merge b2g-inbound to m-c.
[gecko.git] / mfbt / Assertions.h
blob8a5fa205f9c9ea339a04881c2e7b2edec07315b9
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 #include "mozilla/Attributes.h"
13 #include "mozilla/Compiler.h"
14 #include "mozilla/Likely.h"
16 #include <stddef.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #ifdef WIN32
21 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
22 * further depends on <windef.h>. We hardcode these few definitions manually
23 * because those headers clutter the global namespace with a significant
24 * number of undesired macros and symbols.
26 # ifdef __cplusplus
27 extern "C" {
28 # endif
29 __declspec(dllimport) int __stdcall
30 TerminateProcess(void* hProcess, unsigned int uExitCode);
31 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
32 # ifdef __cplusplus
34 # endif
35 #else
36 # include <signal.h>
37 #endif
38 #ifdef ANDROID
39 # include <android/log.h>
40 #endif
43 * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C.
44 * In C++11, static_assert is provided by the compiler to the same effect.
45 * This can be useful when you make certain assumptions about what must hold for
46 * optimal, or even correct, behavior. For example, you might assert that the
47 * size of a struct is a multiple of the target architecture's word size:
49 * struct S { ... };
50 * // C
51 * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
52 * "S should be a multiple of word size for efficiency");
53 * // C++11
54 * static_assert(sizeof(S) % sizeof(size_t) == 0,
55 * "S should be a multiple of word size for efficiency");
57 * This macro can be used in any location where both an extern declaration and a
58 * typedef could be used.
60 #ifndef __cplusplus
62 * Some of the definitions below create an otherwise-unused typedef. This
63 * triggers compiler warnings with some versions of gcc, so mark the typedefs
64 * as permissibly-unused to disable the warnings.
66 # if defined(__GNUC__)
67 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
68 # else
69 # define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
70 # endif
71 # define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y
72 # define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y)
73 # if defined(__SUNPRO_CC)
75 * The Sun Studio C++ compiler is buggy when declaring, inside a function,
76 * another extern'd function with an array argument whose length contains a
77 * sizeof, triggering the error message "sizeof expression not accepted as
78 * size of array parameter". This bug (6688515, not public yet) would hit
79 * defining moz_static_assert as a function, so we always define an extern
80 * array for Sun Studio.
82 * We include the line number in the symbol name in a best-effort attempt
83 * to avoid conflicts (see below).
85 # define MOZ_STATIC_ASSERT(cond, reason) \
86 extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1]
87 # elif defined(__COUNTER__)
89 * If there was no preferred alternative, use a compiler-agnostic version.
91 * Note that the non-__COUNTER__ version has a bug in C++: it can't be used
92 * in both |extern "C"| and normal C++ in the same translation unit. (Alas
93 * |extern "C"| isn't allowed in a function.) The only affected compiler
94 * we really care about is gcc 4.2. For that compiler and others like it,
95 * we include the line number in the function name to do the best we can to
96 * avoid conflicts. These should be rare: a conflict would require use of
97 * MOZ_STATIC_ASSERT on the same line in separate files in the same
98 * translation unit, *and* the uses would have to be in code with
99 * different linkage, *and* the first observed use must be in C++-linkage
100 * code.
102 # define MOZ_STATIC_ASSERT(cond, reason) \
103 typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
104 # else
105 # define MOZ_STATIC_ASSERT(cond, reason) \
106 extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
107 # endif
109 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
110 #else
111 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason)
112 #endif
114 #ifdef __cplusplus
115 extern "C" {
116 #endif
119 * Prints |s| as an assertion failure (using file and ln as the location of the
120 * assertion) to the standard debug-output channel.
122 * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This
123 * method is primarily for internal use in this header, and only secondarily
124 * for use in implementing release-build assertions.
126 static MOZ_ALWAYS_INLINE void
127 MOZ_ReportAssertionFailure(const char* s, const char* file, int ln)
129 #ifdef ANDROID
130 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
131 "Assertion failure: %s, at %s:%d\n", s, file, ln);
132 #else
133 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", s, file, ln);
134 fflush(stderr);
135 #endif
138 static MOZ_ALWAYS_INLINE void
139 MOZ_ReportCrash(const char* s, const char* file, int ln)
141 #ifdef ANDROID
142 __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH",
143 "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln);
144 #else
145 fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", s, file, ln);
146 fflush(stderr);
147 #endif
151 * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should
152 * call MOZ_CRASH instead.
154 #if defined(_MSC_VER)
156 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
157 * (not nested in a system function) breakpoint. This distinctively invokes
158 * Breakpad without requiring system library symbols on all stack-processing
159 * machines, as a nested breakpoint would require.
161 * We use TerminateProcess with the exit code aborting would generate
162 * because we don't want to invoke atexit handlers, destructors, library
163 * unload handlers, and so on when our process might be in a compromised
164 * state.
166 * We don't use abort() because it'd cause Windows to annoyingly pop up the
167 * process error dialog multiple times. See bug 345118 and bug 426163.
169 * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the
170 * compiler doesn't hassle us to provide a return statement after a
171 * MOZ_REALLY_CRASH() call.
173 * (Technically these are Windows requirements, not MSVC requirements. But
174 * practically you need MSVC for debugging, and we only ship builds created
175 * by MSVC, so doing it this way reduces complexity.)
178 __declspec(noreturn) __inline void MOZ_NoReturn() {}
180 # ifdef __cplusplus
181 # define MOZ_REALLY_CRASH() \
182 do { \
183 ::__debugbreak(); \
184 *((volatile int*) NULL) = 123; \
185 ::TerminateProcess(::GetCurrentProcess(), 3); \
186 ::MOZ_NoReturn(); \
187 } while (0)
188 # else
189 # define MOZ_REALLY_CRASH() \
190 do { \
191 __debugbreak(); \
192 *((volatile int*) NULL) = 123; \
193 TerminateProcess(GetCurrentProcess(), 3); \
194 MOZ_NoReturn(); \
195 } while (0)
196 # endif
197 #else
198 # ifdef __cplusplus
199 # define MOZ_REALLY_CRASH() \
200 do { \
201 *((volatile int*) NULL) = 123; \
202 ::abort(); \
203 } while (0)
204 # else
205 # define MOZ_REALLY_CRASH() \
206 do { \
207 *((volatile int*) NULL) = 123; \
208 abort(); \
209 } while (0)
210 # endif
211 #endif
214 * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
215 * Breakpad-compatible way, in both debug and release builds.
217 * MOZ_CRASH is a good solution for "handling" failure cases when you're
218 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
219 * corruption, and so on. It's also a good solution if you need safe behavior
220 * in release builds as well as debug builds. But if the failure is one that
221 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
223 * The optional explanation-string, if provided, must be a string literal
224 * explaining why we're crashing. This argument is intended for use with
225 * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's
226 * obvious why we're crashing.
228 * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an
229 * explanation-string, we print the string to stderr. Otherwise, we don't
230 * print anything; this is because we want MOZ_CRASH to be 100% safe in release
231 * builds, and it's hard to print to stderr safely when memory might have been
232 * corrupted.
234 #ifndef DEBUG
235 # define MOZ_CRASH(...) MOZ_REALLY_CRASH()
236 #else
237 # define MOZ_CRASH(...) \
238 do { \
239 MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \
240 MOZ_REALLY_CRASH(); \
241 } while(0)
242 #endif
244 #ifdef __cplusplus
245 } /* extern "C" */
246 #endif
249 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
250 * debug builds. If it is, execution continues. Otherwise, an error message
251 * including the expression and the explanation-string (if provided) is printed,
252 * an attempt is made to invoke any existing debugger, and execution halts.
253 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
254 * which can correctly be falsy.
256 * The optional explanation-string, if provided, must be a string literal
257 * explaining the assertion. It is intended for use with assertions whose
258 * correctness or rationale is non-obvious, and for assertions where the "real"
259 * condition being tested is best described prosaically. Don't provide an
260 * explanation if it's not actually helpful.
262 * // No explanation needed: pointer arguments often must not be NULL.
263 * MOZ_ASSERT(arg);
265 * // An explanation can be helpful to explain exactly how we know an
266 * // assertion is valid.
267 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
268 * "given that <thingA> and <thingB>, we must have...");
270 * // Or it might disambiguate multiple identical (save for their location)
271 * // assertions of the same expression.
272 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
273 * "we already set [[PrimitiveThis]] for this Boolean object");
274 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
275 * "we already set [[PrimitiveThis]] for this String object");
277 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
278 * *only* during debugging, not "in the field". If you want the latter, use
279 * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well.
282 /* First the single-argument form. */
283 #define MOZ_ASSERT_HELPER1(expr) \
284 do { \
285 if (MOZ_UNLIKELY(!(expr))) { \
286 MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
287 MOZ_REALLY_CRASH(); \
289 } while (0)
290 /* Now the two-argument form. */
291 #define MOZ_ASSERT_HELPER2(expr, explain) \
292 do { \
293 if (MOZ_UNLIKELY(!(expr))) { \
294 MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
295 MOZ_REALLY_CRASH(); \
297 } while (0)
298 /* And now, helper macrology up the wazoo. */
300 * Count the number of arguments passed to MOZ_ASSERT, very carefully
301 * tiptoeing around an MSVC bug where it improperly expands __VA_ARGS__ as a
302 * single token in argument lists. See these URLs for details:
304 * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement
305 * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644
307 #define MOZ_COUNT_ASSERT_ARGS_IMPL2(_1, _2, count, ...) \
308 count
309 #define MOZ_COUNT_ASSERT_ARGS_IMPL(args) \
310 MOZ_COUNT_ASSERT_ARGS_IMPL2 args
311 #define MOZ_COUNT_ASSERT_ARGS(...) \
312 MOZ_COUNT_ASSERT_ARGS_IMPL((__VA_ARGS__, 2, 1, 0))
313 /* Pick the right helper macro to invoke. */
314 #define MOZ_ASSERT_CHOOSE_HELPER2(count) MOZ_ASSERT_HELPER##count
315 #define MOZ_ASSERT_CHOOSE_HELPER1(count) MOZ_ASSERT_CHOOSE_HELPER2(count)
316 #define MOZ_ASSERT_CHOOSE_HELPER(count) MOZ_ASSERT_CHOOSE_HELPER1(count)
317 /* The actual macros. */
318 #define MOZ_ASSERT_GLUE(x, y) x y
319 #define MOZ_RELEASE_ASSERT(...) \
320 MOZ_ASSERT_GLUE(MOZ_ASSERT_CHOOSE_HELPER(MOZ_COUNT_ASSERT_ARGS(__VA_ARGS__)), \
321 (__VA_ARGS__))
322 #ifdef DEBUG
323 # define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
324 #else
325 # define MOZ_ASSERT(...) do { } while(0)
326 #endif /* DEBUG */
329 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
330 * true.
332 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
334 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
335 * designed to catch bugs during debugging, not "in the field".
337 #ifdef DEBUG
338 # define MOZ_ASSERT_IF(cond, expr) \
339 do { \
340 if (cond) \
341 MOZ_ASSERT(expr); \
342 } while (0)
343 #else
344 # define MOZ_ASSERT_IF(cond, expr) do { } while (0)
345 #endif
348 * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that it is
349 * undefined behavior for execution to reach this point. No guarantees are made
350 * about what will happen if this is reached at runtime. Most code should
351 * probably use the higher level MOZ_ASSUME_UNREACHABLE, which uses this when
352 * appropriate.
354 #if defined(__clang__)
355 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
356 #elif defined(__GNUC__)
358 * __builtin_unreachable() was implemented in gcc 4.5. If we don't have
359 * that, call a noreturn function; abort() will do nicely. Qualify the call
360 * in C++ in case there's another abort() visible in local scope.
362 # if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
363 # define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
364 # else
365 # ifdef __cplusplus
366 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
367 # else
368 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
369 # endif
370 # endif
371 #elif defined(_MSC_VER)
372 # define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
373 #else
374 # ifdef __cplusplus
375 # define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
376 # else
377 # define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
378 # endif
379 #endif
382 * MOZ_ASSUME_UNREACHABLE([reason]) tells the compiler that it can assume that
383 * the macro call cannot be reached during execution. This lets the compiler
384 * generate better-optimized code under some circumstances, at the expense of
385 * the program's behavior being undefined if control reaches the
386 * MOZ_ASSUME_UNREACHABLE.
388 * In Gecko, you probably should not use this macro outside of performance- or
389 * size-critical code, because it's unsafe. If you don't care about code size
390 * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
392 * SpiderMonkey is a different beast, and there it's acceptable to use
393 * MOZ_ASSUME_UNREACHABLE more widely.
395 * Note that MOZ_ASSUME_UNREACHABLE is noreturn, so it's valid not to return a
396 * value following a MOZ_ASSUME_UNREACHABLE call.
398 * Example usage:
400 * enum ValueType {
401 * VALUE_STRING,
402 * VALUE_INT,
403 * VALUE_FLOAT
404 * };
406 * int ptrToInt(ValueType type, void* value) {
408 * // We know for sure that type is either INT or FLOAT, and we want this
409 * // code to run as quickly as possible.
410 * switch (type) {
411 * case VALUE_INT:
412 * return *(int*) value;
413 * case VALUE_FLOAT:
414 * return (int) *(float*) value;
415 * default:
416 * MOZ_ASSUME_UNREACHABLE("can only handle VALUE_INT and VALUE_FLOAT");
420 #if defined(DEBUG)
421 # define MOZ_ASSUME_UNREACHABLE(...) \
422 do { \
423 MOZ_ASSERT(false, "MOZ_ASSUME_UNREACHABLE(" __VA_ARGS__ ")"); \
424 MOZ_ASSUME_UNREACHABLE_MARKER(); \
425 } while (0)
426 #else
427 # define MOZ_ASSUME_UNREACHABLE(reason) MOZ_ASSUME_UNREACHABLE_MARKER()
428 #endif
431 * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
432 * expression, in debug builds and in release builds both. Then, in debug
433 * builds only, the value of the expression is asserted either true or false
434 * using MOZ_ASSERT.
436 #ifdef DEBUG
437 # define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr))
438 # define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr))
439 #else
440 # define MOZ_ALWAYS_TRUE(expr) ((void)(expr))
441 # define MOZ_ALWAYS_FALSE(expr) ((void)(expr))
442 #endif
444 #endif /* mozilla_Assertions_h */