From 8e0264cfd6889b73c241b60736fe96ba1322ee6e Mon Sep 17 00:00:00 2001 From: Michael Grunder Date: Fri, 22 May 2020 09:27:49 -0700 Subject: Allow users to replace allocator and handle OOM everywhere. (#800) * Adds an indirection to every allocation/deallocation to allow users to plug in ones of their choosing (use custom functions, jemalloc, etc). * Gracefully handle OOM everywhere in hiredis. This should make it possible for users of the library to have more flexibility in how they handle such situations. * Changes `redisReaderTask->elements` from an `int` to a `long long` to prevent a possible overflow when transferring the task elements into a `redisReply`. * Adds a configurable `max elements` member to `redisReader` that defaults to 2^32 - 1. This can be set to "unlimited" by setting the value to zero. --- alloc.h | 50 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) (limited to 'alloc.h') diff --git a/alloc.h b/alloc.h index 2c9b04e..b581e56 100644 --- a/alloc.h +++ b/alloc.h @@ -31,23 +31,61 @@ #ifndef HIREDIS_ALLOC_H #define HIREDIS_ALLOC_H -#include /* for size_t */ - -#ifndef HIREDIS_OOM_HANDLER -#define HIREDIS_OOM_HANDLER abort() -#endif +#include /* for size_t */ #ifdef __cplusplus extern "C" { #endif +/* Structure pointing to our actually configured allocators */ +typedef struct hiredisAllocFuncs { + void *(*malloc)(size_t); + void *(*calloc)(size_t,size_t); + void *(*realloc)(void*,size_t); + char *(*strdup)(const char*); + void (*free)(void*); +} hiredisAllocFuncs; + +hiredisAllocFuncs hiredisSetAllocators(hiredisAllocFuncs *ha); +void hiredisResetAllocators(void); + +#ifndef _WIN32 + +/* Hiredis' configured allocator function pointer struct */ +extern hiredisAllocFuncs hiredisAllocFns; + +static inline void *hi_malloc(size_t size) { + return hiredisAllocFns.malloc(size); +} + +static inline void *hi_calloc(size_t nmemb, size_t size) { + return hiredisAllocFns.calloc(nmemb, size); +} + +static inline void *hi_realloc(void *ptr, size_t size) { + return hiredisAllocFns.realloc(ptr, size); +} + +static inline char *hi_strdup(const char *str) { + return hiredisAllocFns.strdup(str); +} + +static inline void hi_free(void *ptr) { + hiredisAllocFns.free(ptr); +} + +#else + void *hi_malloc(size_t size); void *hi_calloc(size_t nmemb, size_t size); void *hi_realloc(void *ptr, size_t size); char *hi_strdup(const char *str); +void hi_free(void *ptr); + +#endif #ifdef __cplusplus } #endif -#endif /* HIREDIS_ALLOC_H */ +#endif /* HIREDIS_ALLOC_H */ -- cgit v1.2.3