Use builtin addition overflow checker

This adds wrappers for the __builtin add overflow checkers present
in gcc 5+ and recent clang as well as fallback implementation for
other compilers.
This commit is contained in:
Jim Huang 2019-07-18 13:15:05 +08:00 committed by Jim Huang
parent 60e9d3f69d
commit 37da06298d
3 changed files with 21 additions and 4 deletions

View file

@ -109,6 +109,9 @@ bool _mi_page_is_valid(mi_page_t* page);
#define mi_likely(x) (x)
#endif
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#if defined(_MSC_VER)
#define mi_decl_noinline __declspec(noinline)
@ -146,6 +149,17 @@ static inline bool mi_mul_overflow(size_t size, size_t count, size_t* total) {
&& size > 0 && (SIZE_MAX / size) < count);
}
// Overflow detecting addition
static inline bool mi_add_overflow(size_t a, size_t b, size_t* total) {
#if __has_builtin(__builtin_add_overflow) || __GNUC__ >= 5
return __builtin_add_overflow(a, b, total);
#else
if (a >= (SIZE_MAX - b)) return true; // overflow
*total = a + b;
return false;
#endif
}
// Align a byte size to a size in _machine words_,
// i.e. byte size == `wsize*sizeof(void*)`.
static inline size_t _mi_wsize_from_size(size_t size) {