From 6dceb328173ed9dc9c7fcdfc250621b4c57ae415 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 8be917e9..7bdd288d 100644 --- a/app/meson.build +++ b/app/meson.build @@ -169,6 +169,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 857623e6..ea44437d 100644 --- a/app/src/compat.h +++ b/app/src/compat.h @@ -67,4 +67,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