From cd99f1b6431539f56158cb90e102be7ab9518ed5 Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Tue, 28 Feb 2023 21:43:19 +0100 Subject: [PATCH] Add compat for reallocarray() This function fails safely in the case where the multiplication would overflow. --- app/meson.build | 1 + app/src/compat.c | 15 ++++++++++++++- app/src/compat.h | 4 ++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/app/meson.build b/app/meson.build index 85ded6ef..acb238cf 100644 --- a/app/meson.build +++ b/app/meson.build @@ -173,6 +173,7 @@ check_functions = [ 'vasprintf', 'nrand48', 'jrand48', + 'reallocarray', ] foreach f : check_functions diff --git a/app/src/compat.c b/app/src/compat.c index bb0152aa..785f843c 100644 --- a/app/src/compat.c +++ b/app/src/compat.c @@ -3,6 +3,9 @@ #include "config.h" #include +#ifndef HAVE_REALLOCARRAY +# include +#endif #include #include #include @@ -93,5 +96,15 @@ long jrand48(unsigned short xsubi[3]) { return v.i; } #endif - +#endif + +#ifndef HAVE_REALLOCARRAY +void *reallocarray(void *ptr, size_t nmemb, size_t size) { + size_t bytes; + if (__builtin_mul_overflow(nmemb, size, &bytes)) { + errno = ENOMEM; + return NULL; + } + return realloc(ptr, bytes); +} #endif diff --git a/app/src/compat.h b/app/src/compat.h index c720ddfe..22563421 100644 --- a/app/src/compat.h +++ b/app/src/compat.h @@ -74,4 +74,8 @@ long nrand48(unsigned short xsubi[3]); long jrand48(unsigned short xsubi[3]); #endif +#ifndef HAVE_REALLOCARRAY +void *reallocarray(void *ptr, size_t nmemb, size_t size); +#endif + #endif