From c5f008a4166bae4350881a74fc04a87d7a5c4ed5 Mon Sep 17 00:00:00 2001 From: Cory Fields Date: Fri, 24 Feb 2017 18:20:03 -0500 Subject: [PATCH 1/2] don't throw std::bad_alloc when out of memory. Instead, terminate immediately --- src/init.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/init.cpp b/src/init.cpp index 196b840cb..22c8974a5 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -797,6 +797,19 @@ ServiceFlags nLocalServices = NODE_NETWORK; } +[[noreturn]] static void new_handler_terminate() +{ + // Rather than throwing std::bad-alloc if allocation fails, terminate + // immediately to (try to) avoid chain corruption. + // Since LogPrintf may itself allocate memory, set the handler directly + // to terminate first. + std::set_new_handler(std::terminate); + LogPrintf("Error: Out of memory. Terminating.\n"); + + // The log was successful, terminate now. + std::terminate(); +}; + bool AppInitBasicSetup() { // ********************************************************* Step 1: setup @@ -849,6 +862,9 @@ bool AppInitBasicSetup() // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #endif + + std::set_new_handler(new_handler_terminate); + return true; } From d4ee7baef729da5e18b5e5c3d6ddb5b97df8d4e4 Mon Sep 17 00:00:00 2001 From: Cory Fields Date: Sat, 25 Feb 2017 01:06:25 -0500 Subject: [PATCH 2/2] prevector: assert successful allocation --- src/prevector.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/prevector.h b/src/prevector.h index 6b2f578f5..cba2e3005 100644 --- a/src/prevector.h +++ b/src/prevector.h @@ -5,6 +5,7 @@ #ifndef _BITCOIN_PREVECTOR_H_ #define _BITCOIN_PREVECTOR_H_ +#include #include #include #include @@ -170,10 +171,15 @@ private: } } else { if (!is_direct()) { + /* FIXME: Because malloc/realloc here won't call new_handler if allocation fails, assert + success. These should instead use an allocator or new/delete so that handlers + are called as necessary, but performance would be slightly degraded by doing so. */ _union.indirect = static_cast(realloc(_union.indirect, ((size_t)sizeof(T)) * new_capacity)); + assert(_union.indirect); _union.capacity = new_capacity; } else { char* new_indirect = static_cast(malloc(((size_t)sizeof(T)) * new_capacity)); + assert(new_indirect); T* src = direct_ptr(0); T* dst = reinterpret_cast(new_indirect); memcpy(dst, src, size() * sizeof(T));