diff --git a/lib/libc/stdlib/reallocarray.c b/lib/libc/stdlib/reallocarray.c --- a/lib/libc/stdlib/reallocarray.c +++ b/lib/libc/stdlib/reallocarray.c @@ -17,23 +17,19 @@ #include #include +#include #include #include -/* - * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX - * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW - */ -#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) - void * reallocarray(void *optr, size_t nmemb, size_t size) { + size_t nbytes; - if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && - nmemb > 0 && SIZE_MAX / nmemb < size) { + if (ckd_mul(&nbytes, nmemb, size)) { errno = ENOMEM; return (NULL); } - return (realloc(optr, size * nmemb)); + + return (realloc(optr, nbytes)); } diff --git a/lib/libopenbsd/recallocarray.c b/lib/libopenbsd/recallocarray.c --- a/lib/libopenbsd/recallocarray.c +++ b/lib/libopenbsd/recallocarray.c @@ -16,17 +16,12 @@ */ #include +#include #include #include #include #include -/* - * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX - * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW - */ -#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) - void *recallocarray(void *, size_t, size_t, size_t); void * @@ -38,19 +33,15 @@ if (ptr == NULL) return calloc(newnmemb, size); - if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && - newnmemb > 0 && SIZE_MAX / newnmemb < size) { + if (ckd_mul(&newsize, newnmemb, size)) { errno = ENOMEM; return NULL; } - newsize = newnmemb * size; - if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && - oldnmemb > 0 && SIZE_MAX / oldnmemb < size) { + if (ckd_mul(&oldsize, oldnmemb, size)) { errno = EINVAL; return NULL; } - oldsize = oldnmemb * size; /* * Don't bother too much if we're shrinking just a bit,