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

@ -65,8 +65,10 @@ void* mi_valloc(size_t size) mi_attr_noexcept {
void* mi_pvalloc(size_t size) mi_attr_noexcept {
size_t psize = _mi_os_page_size();
if (size >= SIZE_MAX - psize) return NULL; // overflow
size_t asize = ((size + psize - 1) / psize) * psize;
size_t asize;
if (mi_unlikely(mi_add_overflow(size, psize, &asize)))
return NULL; // overflow
asize = ((asize - 1) / psize) * psize; // TODO: use _mi_align_down
return mi_malloc_aligned(asize, psize);
}

View file

@ -302,8 +302,9 @@ static void* mi_os_mem_alloc_aligned(size_t size, size_t alignment, bool commit,
// if not aligned, free it, overallocate, and unmap around it
if (((uintptr_t)p % alignment != 0)) {
mi_os_mem_free(p, size, stats);
if (size >= (SIZE_MAX - alignment)) return NULL; // overflow
size_t over_size = size + alignment;
size_t over_size;
if (mi_unlikely(mi_add_overflow(size, alignment, &over_size)))
return NULL; // overflow
#if _WIN32
// over-allocate and than re-allocate exactly at an aligned address in there.