diff options
author | Glenn Strauss <gstrauss@gluelogic.com> | 2022-12-10 11:36:03 -0500 |
---|---|---|
committer | Glenn Strauss <gstrauss@gluelogic.com> | 2022-12-10 11:46:20 -0500 |
commit | 0318ef7b64768cc937ee944da445248376793cd3 (patch) | |
tree | 36b543a614a73246e0559a65b4811b8e121ef244 | |
parent | 9e47786e69eb6782a5b8b01f439edaace81bd979 (diff) | |
download | lighttpd-git-0318ef7b64768cc937ee944da445248376793cd3.tar.gz |
[core] ck_calloc() ck_malloc() ck_realloc_u32()
checking functions to wrap calloc(), malloc(), and realloc(),
which ck_assert() that memory allocation succeeds
ck_realloc_u32() additionally checks for integer overflow in args
and that nmemb fits in uint32_t
-rw-r--r-- | src/ck.c | 36 | ||||
-rw-r--r-- | src/ck.h | 21 |
2 files changed, 56 insertions, 1 deletions
@@ -25,7 +25,8 @@ #include "ck.h" -#include <stdlib.h> /* abort() getenv() getenv_s() */ +#include <stdlib.h> /* abort() getenv() getenv_s() + * calloc() malloc() realloc() */ #include <string.h> /* memcpy() memset() memset_s() explicit_bzero() * strerror() strerror_r() strerror_s() strlen() */ @@ -310,6 +311,39 @@ ck_memeq_const_time_fixed_len (const void *a, const void *b, const size_t len) } +void * +ck_malloc (size_t nbytes) +{ + void *ptr = malloc(nbytes); + ck_assert(NULL != ptr); + return ptr; +} + + +void * +ck_calloc (size_t nmemb, size_t elt_sz) +{ + void *ptr = calloc(nmemb, elt_sz); + ck_assert(NULL != ptr); + return ptr; +} + + +void * +ck_realloc_u32 (void **list, size_t n, size_t x, size_t elt_sz) +{ + #ifdef HAVE_REALLOCARRAY /*(not currently detected by build)*/ + ck_assert(x <= UINT32_MAX && n <= UINT32_MAX - x); + void *ptr = reallocarray(*list, n + x, elt_sz); + #else + ck_assert(x <= UINT32_MAX && n <= UINT32_MAX - x && n+x <= SIZE_MAX/elt_sz); + void *ptr = realloc(*list, (n + x) * elt_sz); + #endif + ck_assert(NULL != ptr); + return (*list = ptr); +} + + #include <stdio.h> /* fflush() fprintf() snprintf() */ @@ -65,6 +65,27 @@ __attribute_nonnull__() int ck_memeq_const_time_fixed_len (const void *a, const void *b, size_t len); +/*(ck_malloc() is not from C11 Annex K) + * ck_malloc() performs malloc() on args and aborts if malloc() fails */ +__attribute_malloc__ +__attribute_returns_nonnull__ +void * ck_malloc (size_t nbytes); + +/*(ck_calloc() is not from C11 Annex K) + * ck_calloc() performs calloc() on args and aborts if calloc() fails */ +__attribute_malloc__ +__attribute_returns_nonnull__ +void * ck_calloc (size_t nmemb, size_t elt_sz); + +/*(ck_realloc_u32() is not from C11 Annex K) + * ck_realloc_u32() performs realloc() on *list or aborts + * extends *list with n used elements by x elements of elt_sz + * and ensures n + x <= UINT32_MAX */ +__attribute_nonnull__() +__attribute_returns_nonnull__ +void * ck_realloc_u32 (void **list, size_t n, size_t x, size_t elt_sz); + + /*(ck_bt() is not from C11 Annex K) * ck_bt() prints backtrace to stderr */ __attribute_cold__ |