]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
tools/nolibc: check for overflow in calloc() without divisions
authorThomas Weißschuh <linux@weissschuh.net>
Sat, 4 Apr 2026 11:50:19 +0000 (13:50 +0200)
committerThomas Weißschuh <linux@weissschuh.net>
Mon, 6 Apr 2026 17:46:52 +0000 (19:46 +0200)
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 <linux@weissschuh.net>
Acked-by: Willy Tarreau <w@1wt.eu>
Link: https://patch.msgid.link/20260404-nolibc-asprintf-v2-1-17d2d0df9763@weissschuh.net
tools/include/nolibc/stdlib.h

index 2113a8e7695d0aba3b7262e30b0c1378ee79da48..1816c2368b6803b725384c9285760076bbe5e4c3 100644 (file)
@@ -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;
        }