bug 818009 - canActivate: only click-to-play-type plugins are valid r=jaws
[gecko.git] / mfbt / Assertions.h
blob407fb24e98d19d76a087eef5dcf9c669c1d199e0
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 /* Implementations of runtime and static assertion macros for C and C++. */
8 #ifndef mozilla_Assertions_h_
9 #define mozilla_Assertions_h_
11 #include "mozilla/Attributes.h"
13 #include <stddef.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #ifdef WIN32
18 * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
19 * further depends on <windef.h>. We hardcode these few definitions manually
20 * because those headers clutter the global namespace with a significant
21 * number of undesired macros and symbols.
23 # ifdef __cplusplus
24 extern "C" {
25 # endif
26 __declspec(dllimport) int __stdcall
27 TerminateProcess(void* hProcess, unsigned int uExitCode);
28 __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
29 # ifdef __cplusplus
31 # endif
32 #else
33 # include <signal.h>
34 #endif
35 #ifdef ANDROID
36 # include <android/log.h>
37 #endif
40 * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time*. This
41 * can be useful when you make certain assumptions about what must hold for
42 * optimal, or even correct, behavior. For example, you might assert that the
43 * size of a struct is a multiple of the target architecture's word size:
45 * struct S { ... };
46 * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
47 * "S should be a multiple of word size for efficiency");
49 * This macro can be used in any location where both an extern declaration and a
50 * typedef could be used.
52 * Be aware of the gcc 4.2 concerns noted further down when writing patches that
53 * use this macro, particularly if a patch only bounces on OS X.
55 #ifdef __cplusplus
56 # if defined(__clang__)
57 # ifndef __has_extension
58 # define __has_extension __has_feature /* compatibility, for older versions of clang */
59 # endif
60 # if __has_extension(cxx_static_assert)
61 # define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
62 # endif
63 # elif defined(__GNUC__)
64 # if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \
65 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
66 # define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
67 # endif
68 # elif defined(_MSC_VER)
69 # if _MSC_VER >= 1600 /* MSVC 10 */
70 # define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
71 # endif
72 # elif defined(__HP_aCC)
73 # if __HP_aCC >= 62500 && defined(_HP_CXX0x_SOURCE)
74 # define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
75 # endif
76 # endif
77 #endif
78 #ifndef MOZ_STATIC_ASSERT
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]
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])
115 # endif
116 #endif
118 #define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
120 #ifdef __cplusplus
121 extern "C" {
122 #endif
125 * MOZ_CRASH crashes the program, plain and simple, in a Breakpad-compatible
126 * way, in both debug and release builds.
128 * MOZ_CRASH is a good solution for "handling" failure cases when you're
129 * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
130 * corruption, and so on. It's also a good solution if you need safe behavior
131 * in release builds as well as debug builds. But if the failure is one that
132 * should be debugged and fixed, MOZ_ASSERT is generally preferable.
134 #if defined(_MSC_VER)
136 * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
137 * (not nested in a system function) breakpoint. This distinctively invokes
138 * Breakpad without requiring system library symbols on all stack-processing
139 * machines, as a nested breakpoint would require. We use TerminateProcess
140 * with the exit code aborting would generate because we don't want to invoke
141 * atexit handlers, destructors, library unload handlers, and so on when our
142 * process might be in a compromised state. We don't use abort() because
143 * it'd cause Windows to annoyingly pop up the process error dialog multiple
144 * times. See bug 345118 and bug 426163.
146 * (Technically these are Windows requirements, not MSVC requirements. But
147 * practically you need MSVC for debugging, and we only ship builds created
148 * by MSVC, so doing it this way reduces complexity.)
150 # ifdef __cplusplus
151 # define MOZ_CRASH() \
152 do { \
153 __debugbreak(); \
154 *((volatile int*) NULL) = 123; \
155 ::TerminateProcess(::GetCurrentProcess(), 3); \
156 } while (0)
157 # else
158 # define MOZ_CRASH() \
159 do { \
160 __debugbreak(); \
161 *((volatile int*) NULL) = 123; \
162 TerminateProcess(GetCurrentProcess(), 3); \
163 } while (0)
164 # endif
165 #else
166 # ifdef __cplusplus
167 # define MOZ_CRASH() \
168 do { \
169 *((volatile int*) NULL) = 123; \
170 ::abort(); \
171 } while (0)
172 # else
173 # define MOZ_CRASH() \
174 do { \
175 *((volatile int*) NULL) = 123; \
176 abort(); \
177 } while (0)
178 # endif
179 #endif
182 * Prints |s| as an assertion failure (using file and ln as the location of the
183 * assertion) to the standard debug-output channel.
185 * Usually you should use MOZ_ASSERT instead of this method. This method is
186 * primarily for internal use in this header, and only secondarily for use in
187 * implementing release-build assertions.
189 static MOZ_ALWAYS_INLINE void
190 MOZ_ReportAssertionFailure(const char* s, const char* file, int ln)
192 #ifdef ANDROID
193 __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
194 "Assertion failure: %s, at %s:%d\n", s, file, ln);
195 #else
196 fprintf(stderr, "Assertion failure: %s, at %s:%d\n", s, file, ln);
197 fflush(stderr);
198 #endif
201 #ifdef __cplusplus
202 } /* extern "C" */
203 #endif
206 * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
207 * debug builds. If it is, execution continues. Otherwise, an error message
208 * including the expression and the explanation-string (if provided) is printed,
209 * an attempt is made to invoke any existing debugger, and execution halts.
210 * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
211 * which can correctly be falsy.
213 * The optional explanation-string, if provided, must be a string literal
214 * explaining the assertion. It is intended for use with assertions whose
215 * correctness or rationale is non-obvious, and for assertions where the "real"
216 * condition being tested is best described prosaically. Don't provide an
217 * explanation if it's not actually helpful.
219 * // No explanation needed: pointer arguments often must not be NULL.
220 * MOZ_ASSERT(arg);
222 * // An explanation can be helpful to explain exactly how we know an
223 * // assertion is valid.
224 * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
225 * "given that <thingA> and <thingB>, we must have...");
227 * // Or it might disambiguate multiple identical (save for their location)
228 * // assertions of the same expression.
229 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
230 * "we already set [[PrimitiveThis]] for this Boolean object");
231 * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
232 * "we already set [[PrimitiveThis]] for this String object");
234 * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
235 * *only* during debugging, not "in the field".
237 #ifdef DEBUG
238 /* First the single-argument form. */
239 # define MOZ_ASSERT_HELPER1(expr) \
240 do { \
241 if (!(expr)) { \
242 MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
243 MOZ_CRASH(); \
245 } while (0)
246 /* Now the two-argument form. */
247 # define MOZ_ASSERT_HELPER2(expr, explain) \
248 do { \
249 if (!(expr)) { \
250 MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
251 MOZ_CRASH(); \
253 } while (0)
254 /* And now, helper macrology up the wazoo. */
256 * Count the number of arguments passed to MOZ_ASSERT, very carefully
257 * tiptoeing around an MSVC bug where it improperly expands __VA_ARGS__ as a
258 * single token in argument lists. See these URLs for details:
260 * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement
261 * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644
263 # define MOZ_COUNT_ASSERT_ARGS_IMPL2(_1, _2, count, ...) \
264 count
265 # define MOZ_COUNT_ASSERT_ARGS_IMPL(args) \
266 MOZ_COUNT_ASSERT_ARGS_IMPL2 args
267 # define MOZ_COUNT_ASSERT_ARGS(...) \
268 MOZ_COUNT_ASSERT_ARGS_IMPL((__VA_ARGS__, 2, 1, 0))
269 /* Pick the right helper macro to invoke. */
270 # define MOZ_ASSERT_CHOOSE_HELPER2(count) MOZ_ASSERT_HELPER##count
271 # define MOZ_ASSERT_CHOOSE_HELPER1(count) MOZ_ASSERT_CHOOSE_HELPER2(count)
272 # define MOZ_ASSERT_CHOOSE_HELPER(count) MOZ_ASSERT_CHOOSE_HELPER1(count)
273 /* The actual macro. */
274 # define MOZ_ASSERT_GLUE(x, y) x y
275 # define MOZ_ASSERT(...) \
276 MOZ_ASSERT_GLUE(MOZ_ASSERT_CHOOSE_HELPER(MOZ_COUNT_ASSERT_ARGS(__VA_ARGS__)), \
277 (__VA_ARGS__))
278 #else
279 # define MOZ_ASSERT(...) do { } while(0)
280 #endif /* DEBUG */
283 * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
284 * true.
286 * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
288 * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
289 * designed to catch bugs during debugging, not "in the field".
291 #ifdef DEBUG
292 # define MOZ_ASSERT_IF(cond, expr) \
293 do { \
294 if (cond) \
295 MOZ_ASSERT(expr); \
296 } while (0)
297 #else
298 # define MOZ_ASSERT_IF(cond, expr) do { } while (0)
299 #endif
302 * MOZ_NOT_REACHED_MARKER() expands to an expression which states that it is
303 * undefined behavior for execution to reach this point. No guarantees are made
304 * about what will happen if this is reached at runtime. Most code should
305 * probably use the higher level MOZ_NOT_REACHED, which uses this when
306 * appropriate.
308 #if defined(__clang__)
309 # define MOZ_NOT_REACHED_MARKER() __builtin_unreachable()
310 #elif defined(__GNUC__)
312 * __builtin_unreachable() was implemented in gcc 4.5. If we don't have
313 * that, call a noreturn function; abort() will do nicely. Qualify the call
314 * in C++ in case there's another abort() visible in local scope.
316 # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
317 # define MOZ_NOT_REACHED_MARKER() __builtin_unreachable()
318 # else
319 # ifdef __cplusplus
320 # define MOZ_NOT_REACHED_MARKER() ::abort()
321 # else
322 # define MOZ_NOT_REACHED_MARKER() abort()
323 # endif
324 # endif
325 #elif defined(_MSC_VER)
326 # define MOZ_NOT_REACHED_MARKER() __assume(0)
327 #else
328 # ifdef __cplusplus
329 # define MOZ_NOT_REACHED_MARKER() ::abort()
330 # else
331 # define MOZ_NOT_REACHED_MARKER() abort()
332 # endif
333 #endif
336 * MOZ_NOT_REACHED(reason) indicates that the given point can't be reached
337 * during execution: simply reaching that point in execution is a bug. It takes
338 * as an argument an error message indicating the reason why that point should
339 * not have been reachable.
341 * // ...in a language parser...
342 * void handle(BooleanLiteralNode node)
344 * if (node.isTrue())
345 * handleTrueLiteral();
346 * else if (node.isFalse())
347 * handleFalseLiteral();
348 * else
349 * MOZ_NOT_REACHED("boolean literal that's not true or false?");
352 #if defined(DEBUG)
353 # define MOZ_NOT_REACHED(reason) \
354 do { \
355 MOZ_ASSERT(false, reason); \
356 MOZ_NOT_REACHED_MARKER(); \
357 } while (0)
358 #else
359 # define MOZ_NOT_REACHED(reason) MOZ_NOT_REACHED_MARKER()
360 #endif
363 * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
364 * expression, in debug builds and in release builds both. Then, in debug
365 * builds only, the value of the expression is asserted either true or false
366 * using MOZ_ASSERT.
368 #ifdef DEBUG
369 # define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr))
370 # define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr))
371 #else
372 # define MOZ_ALWAYS_TRUE(expr) ((void)(expr))
373 # define MOZ_ALWAYS_FALSE(expr) ((void)(expr))
374 #endif
376 #endif /* mozilla_Assertions_h_ */