From 97cb57d52157d76b117a607b45fec03ea41c2dcf Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 17 Dec 2022 14:42:56 +0100 Subject: [PATCH] Check for overflow/underflow in parse_signed_integer --- luna/src/NumberParsing.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/luna/src/NumberParsing.cpp b/luna/src/NumberParsing.cpp index 1f4c7680..0938c06b 100644 --- a/luna/src/NumberParsing.cpp +++ b/luna/src/NumberParsing.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -47,6 +48,9 @@ usize parse_unsigned_integer(const char* str, const char** endptr, int base) return val; } +#define SSIZE_MAX LONG_MAX +#define SSIZE_MIN (-SSIZE_MAX - (isize)1) + isize parse_signed_integer(const char* str, const char** endptr, int base) { bool negative = false; @@ -59,9 +63,9 @@ isize parse_signed_integer(const char* str, const char** endptr, int base) str++; } - usize rc = parse_unsigned_integer( - str, endptr, - base); // FIXME: Check for overflow (the unsigned usize value might not fit into a signed isize) + usize rc = parse_unsigned_integer(str, endptr, base); + + if (rc > SSIZE_MAX) { return negative ? SSIZE_MIN : SSIZE_MAX; } return negative ? -(isize)rc : (isize)rc; }