Re: [PATCH v1 1/2] tools/nolibc/stdlib: Support overflow checking for older compiler versions

From: Willy Tarreau
Date: Fri May 20 2022 - 00:19:39 EST


Hi Ammar,

On Fri, May 20, 2022 at 12:21:15AM +0700, Ammar Faizi wrote:
> diff --git a/tools/include/nolibc/stdlib.h b/tools/include/nolibc/stdlib.h
> index 8fd32eaf8037..92378c4b9660 100644
> --- a/tools/include/nolibc/stdlib.h
> +++ b/tools/include/nolibc/stdlib.h
> @@ -128,10 +128,9 @@ void *malloc(size_t len)
> static __attribute__((unused))
> void *calloc(size_t size, size_t nmemb)
> {
> - void *orig;
> - size_t res = 0;
> + size_t x = size * nmemb;
>
> - if (__builtin_expect(__builtin_mul_overflow(nmemb, size, &res), 0)) {
> + if (__builtin_expect(size && ((x / size) != nmemb), 0)) {

Ah, that approach is even better than mine, I'm seeing that on x86 the
compiler simply checks the overflow flag after the multiply, that's
perfect!

Acked-by: Willy Tarreau <w@xxxxxx>

Willy