diff --git a/src/sds.c b/src/sds.c index f1e4f94..aeb9bc5 100644 --- a/src/sds.c +++ b/src/sds.c @@ -88,6 +88,7 @@ sds sdsnewlen(const void *init, size_t initlen) { int hdrlen = sdsHdrSize(type); unsigned char *fp; /* flags pointer. */ + assert(initlen + hdrlen + 1 > initlen); /* Catch size_t overflow */ sh = s_malloc(hdrlen+initlen+1); if (!init) memset(sh, 0, hdrlen+initlen+1); @@ -204,6 +205,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) { len = sdslen(s); sh = (char*)s-sdsHdrSize(oldtype); newlen = (len+addlen); + assert(newlen > len); /* Catch size_t overflow */ if (newlen < SDS_MAX_PREALLOC) newlen *= 2; else @@ -217,6 +219,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) { if (type == SDS_TYPE_5) type = SDS_TYPE_8; hdrlen = sdsHdrSize(type); + assert(hdrlen + newlen + 1 > len); /* Catch size_t overflow */ if (oldtype==type) { newsh = s_realloc(sh, hdrlen+newlen+1); if (newsh == NULL) return NULL; diff --git a/src/zmalloc.c b/src/zmalloc.c index 4dbef83..dca90c2 100644 --- a/src/zmalloc.c +++ b/src/zmalloc.c @@ -55,6 +55,12 @@ void zlibc_free(void *ptr) { #endif #endif +#if PREFIX_SIZE > 0 +#define ASSERT_NO_SIZE_OVERFLOW(sz) assert((sz) + PREFIX_SIZE > (sz)) +#else +#define ASSERT_NO_SIZE_OVERFLOW(sz) +#endif + /* Explicitly override malloc/free etc when using tcmalloc. */ #if defined(USE_TCMALLOC) #define malloc(size) tc_malloc(size) @@ -102,6 +108,7 @@ static void zmalloc_default_oom(size_t size) { static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom; void *zmalloc(size_t size) { + ASSERT_NO_SIZE_OVERFLOW(size); void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); @@ -116,6 +123,7 @@ void *zmalloc(size_t size) { } void *zcalloc(size_t size) { + ASSERT_NO_SIZE_OVERFLOW(size); void *ptr = calloc(1, size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); @@ -130,6 +138,7 @@ void *zcalloc(size_t size) { } void *zrealloc(void *ptr, size_t size) { + ASSERT_NO_SIZE_OVERFLOW(size); #ifndef HAVE_MALLOC_SIZE void *realptr; #endif