From: Thomas Weißschuh Date: Sat, 4 Apr 2026 11:50:19 +0000 (+0200) Subject: tools/nolibc: check for overflow in calloc() without divisions X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=1e3c374e9fd5ef0bf1ebcb866505b1aad404959e;p=thirdparty%2Fkernel%2Flinux.git tools/nolibc: check for overflow in calloc() without divisions On some architectures without native division instructions the division can generate calls into libgcc/compiler-rt. This library might not be available, so its use should be avoided. Use the compiler builtin to check for overflows without needing a division. The builtin has been available since GCC 3 and clang 3.8. Signed-off-by: Thomas Weißschuh Acked-by: Willy Tarreau Link: https://patch.msgid.link/20260404-nolibc-asprintf-v2-1-17d2d0df9763@weissschuh.net --- diff --git a/tools/include/nolibc/stdlib.h b/tools/include/nolibc/stdlib.h index 2113a8e7695d0..1816c2368b680 100644 --- a/tools/include/nolibc/stdlib.h +++ b/tools/include/nolibc/stdlib.h @@ -145,9 +145,9 @@ void *malloc(size_t len) static __attribute__((unused)) void *calloc(size_t size, size_t nmemb) { - size_t x = size * nmemb; + size_t x; - if (__builtin_expect(size && ((x / size) != nmemb), 0)) { + if (__builtin_expect(__builtin_mul_overflow(size, nmemb, &x), 0)) { SET_ERRNO(ENOMEM); return NULL; }