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/. */
6 
7 /* Implementations of runtime and static assertion macros for C and C++. */
8 
9 #ifndef mozilla_Assertions_h
10 #define mozilla_Assertions_h
11 
12 #include "mozilla/Attributes.h"
13 #include "mozilla/Compiler.h"
14 #include "mozilla/Likely.h"
15 
16 #include <stddef.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #ifdef WIN32
20    /*
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.
25     */
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
33    }
34 #  endif
35 #else
36 #  include <signal.h>
37 #endif
38 #ifdef ANDROID
39 #  include <android/log.h>
40 #endif
41 
42 /*
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:
48  *
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");
56  *
57  * This macro can be used in any location where both an extern declaration and a
58  * typedef could be used.
59  */
60 #ifndef __cplusplus
61    /*
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.
65     */
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)
74      /*
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.
81       *
82       * We include the line number in the symbol name in a best-effort attempt
83       * to avoid conflicts (see below).
84       */
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__)
88      /*
89       * If there was no preferred alternative, use a compiler-agnostic version.
90       *
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.
101       */
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
108 
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
113 
114 #ifdef __cplusplus
115 extern "C" {
116 #endif
117 
118 /*
119  * Prints |s| as an assertion failure (using file and ln as the location of the
120  * assertion) to the standard debug-output channel.
121  *
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.
125  */
126 static MOZ_ALWAYS_INLINE void
MOZ_ReportAssertionFailure(const char * s,const char * file,int ln)127 MOZ_ReportAssertionFailure(const char* s, const char* file, int ln)
128 {
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
136 }
137 
138 static MOZ_ALWAYS_INLINE void
MOZ_ReportCrash(const char * s,const char * file,int ln)139 MOZ_ReportCrash(const char* s, const char* file, int ln)
140 {
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
148 }
149 
150 /**
151  * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH().  You should
152  * call MOZ_CRASH instead.
153  */
154 #if defined(_MSC_VER)
155    /*
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.
160     *
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.
165     *
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.
168     *
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.
172     *
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.)
176     */
177 
MOZ_NoReturn()178 __declspec(noreturn) __inline void MOZ_NoReturn() {}
179 
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
212 
213 /*
214  * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
215  * Breakpad-compatible way, in both debug and release builds.
216  *
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.
222  *
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.
227  *
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.
233  */
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
243 
244 #ifdef __cplusplus
245 } /* extern "C" */
246 #endif
247 
248 /*
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.
255  *
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.
261  *
262  *   // No explanation needed: pointer arguments often must not be NULL.
263  *   MOZ_ASSERT(arg);
264  *
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...");
269  *
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");
276  *
277  * MOZ_ASSERT has no effect in non-debug builds.  It is designed to catch bugs
278  * *only* during debugging, not "in the field".
279  */
280 #ifdef DEBUG
281    /* First the single-argument form. */
282 #  define MOZ_ASSERT_HELPER1(expr) \
283      do { \
284        if (MOZ_UNLIKELY(!(expr))) { \
285          MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
286          MOZ_REALLY_CRASH(); \
287        } \
288      } while (0)
289    /* Now the two-argument form. */
290 #  define MOZ_ASSERT_HELPER2(expr, explain) \
291      do { \
292        if (MOZ_UNLIKELY(!(expr))) { \
293          MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
294          MOZ_REALLY_CRASH(); \
295        } \
296      } while (0)
297    /* And now, helper macrology up the wazoo. */
298    /*
299     * Count the number of arguments passed to MOZ_ASSERT, very carefully
300     * tiptoeing around an MSVC bug where it improperly expands __VA_ARGS__ as a
301     * single token in argument lists.  See these URLs for details:
302     *
303     *   http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement
304     *   http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644
305     */
306 #  define MOZ_COUNT_ASSERT_ARGS_IMPL2(_1, _2, count, ...) \
307      count
308 #  define MOZ_COUNT_ASSERT_ARGS_IMPL(args) \
309 	 MOZ_COUNT_ASSERT_ARGS_IMPL2 args
310 #  define MOZ_COUNT_ASSERT_ARGS(...) \
311      MOZ_COUNT_ASSERT_ARGS_IMPL((__VA_ARGS__, 2, 1, 0))
312    /* Pick the right helper macro to invoke. */
313 #  define MOZ_ASSERT_CHOOSE_HELPER2(count) MOZ_ASSERT_HELPER##count
314 #  define MOZ_ASSERT_CHOOSE_HELPER1(count) MOZ_ASSERT_CHOOSE_HELPER2(count)
315 #  define MOZ_ASSERT_CHOOSE_HELPER(count) MOZ_ASSERT_CHOOSE_HELPER1(count)
316    /* The actual macro. */
317 #  define MOZ_ASSERT_GLUE(x, y) x y
318 #  define MOZ_ASSERT(...) \
319      MOZ_ASSERT_GLUE(MOZ_ASSERT_CHOOSE_HELPER(MOZ_COUNT_ASSERT_ARGS(__VA_ARGS__)), \
320                      (__VA_ARGS__))
321 #else
322 #  define MOZ_ASSERT(...) do { } while(0)
323 #endif /* DEBUG */
324 
325 /*
326  * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
327  * true.
328  *
329  *   MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
330  *
331  * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds.  It is
332  * designed to catch bugs during debugging, not "in the field".
333  */
334 #ifdef DEBUG
335 #  define MOZ_ASSERT_IF(cond, expr) \
336      do { \
337        if (cond) \
338          MOZ_ASSERT(expr); \
339      } while (0)
340 #else
341 #  define MOZ_ASSERT_IF(cond, expr)  do { } while (0)
342 #endif
343 
344 /*
345  * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that it is
346  * undefined behavior for execution to reach this point.  No guarantees are made
347  * about what will happen if this is reached at runtime.  Most code should
348  * probably use the higher level MOZ_ASSUME_UNREACHABLE, which uses this when
349  * appropriate.
350  */
351 #if defined(__clang__)
352 #  define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
353 #elif defined(__GNUC__)
354    /*
355     * __builtin_unreachable() was implemented in gcc 4.5.  If we don't have
356     * that, call a noreturn function; abort() will do nicely.  Qualify the call
357     * in C++ in case there's another abort() visible in local scope.
358     */
359 #  if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
360 #    define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
361 #  else
362 #    ifdef __cplusplus
363 #      define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
364 #    else
365 #      define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
366 #    endif
367 #  endif
368 #elif defined(_MSC_VER)
369 #  define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
370 #else
371 #  ifdef __cplusplus
372 #    define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
373 #  else
374 #    define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
375 #  endif
376 #endif
377 
378 /*
379  * MOZ_ASSUME_UNREACHABLE([reason]) tells the compiler that it can assume that
380  * the macro call cannot be reached during execution.  This lets the compiler
381  * generate better-optimized code under some circumstances, at the expense of
382  * the program's behavior being undefined if control reaches the
383  * MOZ_ASSUME_UNREACHABLE.
384  *
385  * In Gecko, you probably should not use this macro outside of performance- or
386  * size-critical code, because it's unsafe.  If you don't care about code size
387  * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
388  *
389  * SpiderMonkey is a different beast, and there it's acceptable to use
390  * MOZ_ASSUME_UNREACHABLE more widely.
391  *
392  * Note that MOZ_ASSUME_UNREACHABLE is noreturn, so it's valid not to return a
393  * value following a MOZ_ASSUME_UNREACHABLE call.
394  *
395  * Example usage:
396  *
397  *   enum ValueType {
398  *     VALUE_STRING,
399  *     VALUE_INT,
400  *     VALUE_FLOAT
401  *   };
402  *
403  *   int ptrToInt(ValueType type, void* value) {
404  *   {
405  *     // We know for sure that type is either INT or FLOAT, and we want this
406  *     // code to run as quickly as possible.
407  *     switch (type) {
408  *     case VALUE_INT:
409  *       return *(int*) value;
410  *     case VALUE_FLOAT:
411  *       return (int) *(float*) value;
412  *     default:
413  *       MOZ_ASSUME_UNREACHABLE("can only handle VALUE_INT and VALUE_FLOAT");
414  *     }
415  *   }
416  */
417 #if defined(DEBUG)
418 #  define MOZ_ASSUME_UNREACHABLE(...) \
419      do { \
420        MOZ_ASSERT(false, "MOZ_ASSUME_UNREACHABLE(" __VA_ARGS__ ")"); \
421        MOZ_ASSUME_UNREACHABLE_MARKER(); \
422      } while (0)
423 #else
424 #  define MOZ_ASSUME_UNREACHABLE(reason)  MOZ_ASSUME_UNREACHABLE_MARKER()
425 #endif
426 
427 /*
428  * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
429  * expression, in debug builds and in release builds both.  Then, in debug
430  * builds only, the value of the expression is asserted either true or false
431  * using MOZ_ASSERT.
432  */
433 #ifdef DEBUG
434 #  define MOZ_ALWAYS_TRUE(expr)      MOZ_ASSERT((expr))
435 #  define MOZ_ALWAYS_FALSE(expr)     MOZ_ASSERT(!(expr))
436 #else
437 #  define MOZ_ALWAYS_TRUE(expr)      ((void)(expr))
438 #  define MOZ_ALWAYS_FALSE(expr)     ((void)(expr))
439 #endif
440 
441 #endif /* mozilla_Assertions_h */
442