diff mbox series

[4/6] tools/nolibc: fix integer overflow in i{64,}toa_r() and

Message ID 20250416-nolibc-ubsan-v1-4-c4704bb23da7@weissschuh.net
State New
Headers show
Series tools/nolibc: fix some undefined behaviour and enable UBSAN | expand

Commit Message

Thomas Weißschuh April 16, 2025, 6:40 p.m. UTC
In twos complement the most negative number can not be negated.

Fixes: b1c21e7d99cd ("tools/nolibc/stdlib: add i64toa() and u64toa()")
Fixes: 66c397c4d2e1 ("tools/nolibc/stdlib: replace the ltoa() function with more efficient ones")
Signed-off-by: Thomas Weißschuh <linux@weissschuh.net>
---
 tools/include/nolibc/stdlib.h | 24 ++++++++----------------
 1 file changed, 8 insertions(+), 16 deletions(-)
diff mbox series

Patch

diff --git a/tools/include/nolibc/stdlib.h b/tools/include/nolibc/stdlib.h
index 86ad378ab1ea220559d5ab1adc4bb9972977ba9e..5e4b97810d49ac1b1bd79d6f779f6a748f188a39 100644
--- a/tools/include/nolibc/stdlib.h
+++ b/tools/include/nolibc/stdlib.h
@@ -271,16 +271,12 @@  int utoa_r(unsigned long in, char *buffer)
 static __attribute__((unused))
 int itoa_r(long in, char *buffer)
 {
-	char *ptr = buffer;
-	int len = 0;
-
 	if (in < 0) {
-		in = -in;
-		*(ptr++) = '-';
-		len++;
+		*(buffer++) = '-';
+		return 1 + utoa_r(-(unsigned long)in, buffer);
 	}
-	len += utoa_r(in, ptr);
-	return len;
+
+	return utoa_r(in, buffer);
 }
 
 /* for historical compatibility, same as above but returns the pointer to the
@@ -407,16 +403,12 @@  int u64toa_r(uint64_t in, char *buffer)
 static __attribute__((unused))
 int i64toa_r(int64_t in, char *buffer)
 {
-	char *ptr = buffer;
-	int len = 0;
-
 	if (in < 0) {
-		in = -in;
-		*(ptr++) = '-';
-		len++;
+		*(buffer++) = '-';
+		return 1 + u64toa_r(-(unsigned long long)in, buffer);
 	}
-	len += u64toa_r(in, ptr);
-	return len;
+
+	return u64toa_r(in, buffer);
 }
 
 /* converts int64_t <in> to a string using the static itoa_buffer and returns