From 2f1fc1df5ce6dfaecbde6d161aea3f0be5b74547 Mon Sep 17 00:00:00 2001 From: Anton Korobeynikov Date: Tue, 21 Apr 2020 11:39:57 +0300 Subject: [PATCH] Add xmalloc()-like functionality. xmalloc is a non-standard extension forcing malloc() to abort should the memory allocation failed instead of returning a null pointer. Such functionality is quite useful as it provides one single point of error handling if the caller of malloc() does not check the result (as it often does!) and segfault is ocurring somewhere else. If more fine-grained control is necessary one could register a custom error handler, however, this might not be an option while interposing. --- CMakeLists.txt | 6 ++++++ include/mimalloc-types.h | 1 - src/options.c | 5 +++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e37b508..35e6f81 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,7 @@ option(MI_LOCAL_DYNAMIC_TLS "Use slightly slower, dlopen-compatible TLS mechanis option(MI_BUILD_TESTS "Build test executables" ON) option(MI_CHECK_FULL "Use full internal invariant checking in DEBUG mode (deprecated, use MI_DEBUG_FULL instead)" OFF) option(MI_PADDING "Enable padding to detect heap block overflow (only in debug mode)" ON) +option(MI_XMALLOC "Enable abort() call on memory allocation failure by default" OFF) include("cmake/mimalloc-config-version.cmake") @@ -105,6 +106,11 @@ if(MI_PADDING MATCHES "OFF") list(APPEND mi_defines MI_PADDING=0) endif() +if(MI_XMALLOC MATCHES "ON") + message(STATUS "Enable abort() calls on memory allocation failure (MI_XMALLOC=ON)") + list(APPEND mi_defines MI_XMALLOC=1) +endif() + if(MI_USE_CXX MATCHES "ON") message(STATUS "Use the C++ compiler to compile (MI_USE_CXX=ON)") set_source_files_properties(${mi_sources} PROPERTIES LANGUAGE CXX ) diff --git a/include/mimalloc-types.h b/include/mimalloc-types.h index 7e50a2b..449e2e4 100644 --- a/include/mimalloc-types.h +++ b/include/mimalloc-types.h @@ -61,7 +61,6 @@ terms of the MIT license. A copy of the license can be found in the file #define MI_ENCODE_FREELIST 1 #endif - // ------------------------------------------------------ // Platform specific values // ------------------------------------------------------ diff --git a/src/options.c b/src/options.c index 0af4a48..9fce039 100644 --- a/src/options.c +++ b/src/options.c @@ -348,6 +348,11 @@ static void mi_error_default(int err) { abort(); } #endif +#if defined(MI_XMALLOC) + if (err==ENOMEM || err==EOVERFLOW) { // abort on memory allocation fails in xmalloc mode + abort(); + } +#endif } void mi_register_error(mi_error_fun* fun, void* arg) {