|
5 | 5 | #ifndef BITCOIN_UTIL_CHECK_H |
6 | 6 | #define BITCOIN_UTIL_CHECK_H |
7 | 7 |
|
| 8 | +#include <config/bitcoin-config.h> |
8 | 9 | #include <tinyformat.h> |
9 | 10 |
|
10 | 11 | #include <stdexcept> |
@@ -38,4 +39,56 @@ class NonFatalCheckError : public std::runtime_error |
38 | 39 | } \ |
39 | 40 | } while (false) |
40 | 41 |
|
| 42 | +/** |
| 43 | + * ASSUME(expression) |
| 44 | + * |
| 45 | + * ASSUME(...) is used to document assumptions. |
| 46 | + * |
| 47 | + * Bitcoin Core is always compiled with assertions enabled. assert(...) |
| 48 | + * is thus only appropriate for documenting critical assumptions |
| 49 | + * where a failed assumption should lead to immediate abortion also |
| 50 | + * in production environments. |
| 51 | + * |
| 52 | + * ASSUME(...) works like assert(...) if -DABORT_ON_FAILED_ASSUME |
| 53 | + * and is side-effect safe. |
| 54 | + * |
| 55 | + * More specifically: |
| 56 | + * |
| 57 | + * * If compiled with -DABORT_ON_FAILED_ASSUME (set by --enable-debug |
| 58 | + * and --enable-fuzz): Evaluate expression and abort if expression is |
| 59 | + * false. |
| 60 | + * |
| 61 | + * * Otherwise: |
| 62 | + * Evaluate expression and continue execution. |
| 63 | + * |
| 64 | + * ABORT_ON_FAILED_ASSUME should not be set in production environments. |
| 65 | + * |
| 66 | + * Example |
| 67 | + * ======= |
| 68 | + * int main(void) { |
| 69 | + * ASSUME(IsFoo()); |
| 70 | + * ... |
| 71 | + * } |
| 72 | + * |
| 73 | + * If !IsFoo() and -DABORT_ON_FAILED_ASSUME, then: |
| 74 | + * filename.cpp:123: main: ASSUME(IsFoo()) failed. |
| 75 | + * Aborted |
| 76 | + * Otherwise the execution continues. |
| 77 | + */ |
| 78 | + |
| 79 | +#ifdef ABORT_ON_FAILED_ASSUME |
| 80 | +#define ACTION_ON_FAILED_ASSUME std::abort(); |
| 81 | +#else |
| 82 | +#define ACTION_ON_FAILED_ASSUME |
| 83 | +#endif |
| 84 | + |
| 85 | +#define ASSUME(expression) \ |
| 86 | + do { \ |
| 87 | + if (!(expression)) { \ |
| 88 | + tfm::format(std::cerr, "%s:%d: %s: ASSUME(%s) failed. You may report this issue here: %s\n", \ |
| 89 | + __FILE__, __LINE__, __func__, #expression, PACKAGE_BUGREPORT); \ |
| 90 | + ACTION_ON_FAILED_ASSUME \ |
| 91 | + } \ |
| 92 | + } while (false) |
| 93 | + |
41 | 94 | #endif // BITCOIN_UTIL_CHECK_H |
0 commit comments