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 #if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus)
13 #define MOZ_DUMP_ASSERTION_STACK
14 #endif
15 
16 #include "Attributes.h"
17 #include "Compiler.h"
18 #include "Likely.h"
19 #include "MacroArgs.h"
20 #ifdef MOZ_DUMP_ASSERTION_STACK
21 #include "nsTraceRefcnt.h"
22 #endif
23 
24 #include <stddef.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #ifdef _WIN32
28    /*
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.
33     */
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
41 }
42 #  endif
43 #else
44 #  include <signal.h>
45 #endif
46 #ifdef ANDROID
47 #  include <android/log.h>
48 #endif
49 
50 /*
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:
56  *
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");
64  *
65  * This macro can be used in any location where both an extern declaration and a
66  * typedef could be used.
67  */
68 #ifndef __cplusplus
69    /*
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.
73     */
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)
82      /*
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.
89       *
90       * We include the line number in the symbol name in a best-effort attempt
91       * to avoid conflicts (see below).
92       */
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__)
96      /*
97       * If there was no preferred alternative, use a compiler-agnostic version.
98       *
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.
109       */
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
116 
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
121 
122 #ifdef __cplusplus
123 extern "C" {
124 #endif
125 
126 /*
127  * Prints |aStr| as an assertion failure (using aFilename and aLine as the
128  * location of the assertion) to the standard debug-output channel.
129  *
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.
133  */
134 static MOZ_COLD MOZ_ALWAYS_INLINE void
MOZ_ReportAssertionFailure(const char * aStr,const char * aFilename,int aLine)135 MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine)
136   MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
137 {
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 #if defined (MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API)
145   nsTraceRefcnt::WalkTheStack(stderr);
146 #endif
147   fflush(stderr);
148 #endif
149 }
150 
151 static MOZ_COLD MOZ_ALWAYS_INLINE void
MOZ_ReportCrash(const char * aStr,const char * aFilename,int aLine)152 MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine)
153   MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS
154 {
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 #if defined(MOZ_DUMP_ASSERTION_STACK) && !defined(MOZILLA_XPCOMRT_API)
161   nsTraceRefcnt::WalkTheStack(stderr);
162 #endif
163   fflush(stderr);
164 #endif
165 }
166 
167 /**
168  * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH().  You should
169  * call MOZ_CRASH instead.
170  */
171 #if defined(_MSC_VER)
172    /*
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.
177     *
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.
182     *
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.
185     *
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.
189     *
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.)
193     */
194 
MOZ_NoReturn()195 __declspec(noreturn) __inline void MOZ_NoReturn() {}
196 
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
229 
230 /*
231  * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a
232  * Breakpad-compatible way, in both debug and release builds.
233  *
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.
239  *
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.
244  *
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.
250  */
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
260 
261 #ifdef __cplusplus
262 } /* extern "C" */
263 #endif
264 
265 /*
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.
272  *
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.
278  *
279  *   // No explanation needed: pointer arguments often must not be NULL.
280  *   MOZ_ASSERT(arg);
281  *
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...");
286  *
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");
293  *
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.
297  *
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.
304  */
305 
306 /*
307  * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against
308  * accidentally passing something unintended in lieu of an assertion condition.
309  */
310 
311 #ifdef __cplusplus
312 #  include "TypeTraits.h"
313 namespace mozilla {
314 namespace detail {
315 
316 template<typename T>
317 struct IsFunction
318 {
319   static const bool value = false;
320 };
321 
322 template<typename R, typename... A>
323 struct IsFunction<R(A...)>
324 {
325   static const bool value = true;
326 };
327 
328 template<typename T>
329 struct AssertionConditionType
330 {
331   typedef typename RemoveReference<T>::Type ValueT;
332   static_assert(!IsArray<ValueT>::value,
333                 "Expected boolean assertion condition, got an array or a "
334                 "string!");
335   static_assert(!IsFunction<ValueT>::value,
336                 "Expected boolean assertion condition, got a function! Did "
337                 "you intend to call that function?");
338   static_assert(!IsFloatingPoint<ValueT>::value,
339                 "It's often a bad idea to assert that a floating-point number "
340                 "is nonzero, because such assertions tend to intermittently "
341                 "fail. Shouldn't your code gracefully handle this case instead "
342                 "of asserting? Anyway, if you really want to do that, write an "
343                 "explicit boolean condition, like !!x or x!=0.");
344 
345   static const bool isValid = true;
346 };
347 
348 } // namespace detail
349 } // namespace mozilla
350 #  define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \
351      static_assert(mozilla::detail::AssertionConditionType<decltype(x)>::isValid, \
352                    "invalid assertion condition")
353 #else
354 #  define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x)
355 #endif
356 
357 /* First the single-argument form. */
358 #define MOZ_ASSERT_HELPER1(expr) \
359   do { \
360     MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
361     if (MOZ_UNLIKELY(!(expr))) { \
362       MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
363       MOZ_REALLY_CRASH(); \
364     } \
365   } while (0)
366 /* Now the two-argument form. */
367 #define MOZ_ASSERT_HELPER2(expr, explain) \
368   do { \
369     MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \
370     if (MOZ_UNLIKELY(!(expr))) { \
371       MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
372       MOZ_REALLY_CRASH(); \
373     } \
374   } while (0)
375 
376 #define MOZ_RELEASE_ASSERT_GLUE(a, b) a b
377 #define MOZ_RELEASE_ASSERT(...) \
378   MOZ_RELEASE_ASSERT_GLUE( \
379     MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \
380     (__VA_ARGS__))
381 
382 #ifdef DEBUG
383 #  define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__)
384 #else
385 #  define MOZ_ASSERT(...) do { } while (0)
386 #endif /* DEBUG */
387 
388 #ifdef RELEASE_BUILD
389 #  define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT
390 #else
391 #  define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT
392 #endif
393 
394 /*
395  * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
396  * true.
397  *
398  *   MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
399  *
400  * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds.  It is
401  * designed to catch bugs during debugging, not "in the field".
402  */
403 #ifdef DEBUG
404 #  define MOZ_ASSERT_IF(cond, expr) \
405      do { \
406        if (cond) { \
407          MOZ_ASSERT(expr); \
408        } \
409      } while (0)
410 #else
411 #  define MOZ_ASSERT_IF(cond, expr)  do { } while (0)
412 #endif
413 
414 /*
415  * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that
416  * it is undefined behavior for execution to reach this point.  No guarantees
417  * are made about what will happen if this is reached at runtime.  Most code
418  * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra
419  * asserts.
420  */
421 #if defined(__clang__) || defined(__GNUC__)
422 #  define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable()
423 #elif defined(_MSC_VER)
424 #  define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0)
425 #else
426 #  ifdef __cplusplus
427 #    define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort()
428 #  else
429 #    define MOZ_ASSUME_UNREACHABLE_MARKER() abort()
430 #  endif
431 #endif
432 
433 /*
434  * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it
435  * can assume that the macro call cannot be reached during execution.  This lets
436  * the compiler generate better-optimized code under some circumstances, at the
437  * expense of the program's behavior being undefined if control reaches the
438  * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE.
439  *
440  * In Gecko, you probably should not use this macro outside of performance- or
441  * size-critical code, because it's unsafe.  If you don't care about code size
442  * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH.
443  *
444  * SpiderMonkey is a different beast, and there it's acceptable to use
445  * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely.
446  *
447  * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid
448  * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
449  * call.
450  *
451  * Example usage:
452  *
453  *   enum ValueType {
454  *     VALUE_STRING,
455  *     VALUE_INT,
456  *     VALUE_FLOAT
457  *   };
458  *
459  *   int ptrToInt(ValueType type, void* value) {
460  *   {
461  *     // We know for sure that type is either INT or FLOAT, and we want this
462  *     // code to run as quickly as possible.
463  *     switch (type) {
464  *     case VALUE_INT:
465  *       return *(int*) value;
466  *     case VALUE_FLOAT:
467  *       return (int) *(float*) value;
468  *     default:
469  *       MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType");
470  *     }
471  *   }
472  */
473 
474 /*
475  * Unconditional assert in debug builds for (assumed) unreachable code paths
476  * that have a safe return without crashing in release builds.
477  */
478 #define MOZ_ASSERT_UNREACHABLE(reason) \
479    MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason)
480 
481 #define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \
482    do { \
483      MOZ_ASSERT_UNREACHABLE(reason); \
484      MOZ_ASSUME_UNREACHABLE_MARKER(); \
485    } while (0)
486 
487 /*
488  * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
489  * expression, in debug builds and in release builds both.  Then, in debug
490  * builds only, the value of the expression is asserted either true or false
491  * using MOZ_ASSERT.
492  */
493 #ifdef DEBUG
494 #  define MOZ_ALWAYS_TRUE(expr)      MOZ_ASSERT((expr))
495 #  define MOZ_ALWAYS_FALSE(expr)     MOZ_ASSERT(!(expr))
496 #else
497 #  define MOZ_ALWAYS_TRUE(expr)      ((void)(expr))
498 #  define MOZ_ALWAYS_FALSE(expr)     ((void)(expr))
499 #endif
500 
501 #undef MOZ_DUMP_ASSERTION_STACK
502 
503 #endif /* mozilla_Assertions_h */
504