diff options
author | Justin M. Keyes <justinkz@gmail.com> | 2019-01-08 00:22:57 +0100 |
---|---|---|
committer | Justin M. Keyes <justinkz@gmail.com> | 2019-01-09 10:41:17 +0100 |
commit | 6b6a4d63ec585badcd69890608bc144ef4d89af7 (patch) | |
tree | 058ab0764ff3d09c8b138ec7d9132ed724290c40 /src | |
parent | eaabec459ac1a85448caa79d0c8b0820d63cd342 (diff) | |
download | rneovim-6b6a4d63ec585badcd69890608bc144ef4d89af7.tar.gz rneovim-6b6a4d63ec585badcd69890608bc144ef4d89af7.tar.bz2 rneovim-6b6a4d63ec585badcd69890608bc144ef4d89af7.zip |
assert.h: Check overflow with STRICT_ADD, STRICT_SUB
Diffstat (limited to 'src')
-rw-r--r-- | src/nvim/assert.h | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/nvim/assert.h b/src/nvim/assert.h index 761636305e..48c5363d5a 100644 --- a/src/nvim/assert.h +++ b/src/nvim/assert.h @@ -15,6 +15,10 @@ # define __has_extension __has_feature #endif +#ifndef __has_builtin +# define __has_builtin __has_feature +#endif + /// @def STATIC_ASSERT /// @brief Assert at compile time if condition is not satisfied. /// @@ -121,4 +125,31 @@ ((enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) }) 0) #endif +/// @def STRICT_ADD +/// +/// Requires GCC 5+ and Clang 3.8+ +/// https://clang.llvm.org/docs/LanguageExtensions.html +/// https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html +/// +/// Alternative for compilers without __builtin_xx_overflow ? +/// https://stackoverflow.com/a/44830670/152142 +/// +/// @param MAX Maximum value of the narrowest type of operand. +/// Not used if compiler supports __builtin_add_overflow. +#if __has_builtin(__builtin_add_overflow) +# define STRICT_ADD(a, b, c) \ + do { if (__builtin_add_overflow(a, b, c)) { abort(); } } while (0) +#else +# define STRICT_ADD(a, b, c) \ + do { *c = a + b; } while (0) +#endif + +#if __has_builtin(__builtin_sub_overflow) +# define STRICT_SUB(a, b, c) \ + do { if (__builtin_sub_overflow(a, b, c)) { abort(); } } while (0) +#else +# define STRICT_SUB(a, b, c) \ + do { *c = a - b; } while (0) +#endif + #endif // NVIM_ASSERT_H |