[LTP] [PATCH 06/15] ujson: reader: Check for signed integer overflow
Cyril Hrubis
chrubis@suse.cz
Fri Oct 9 13:59:09 CEST 2026
Hi!
> static int get_int(ujson_reader *buf, struct ujson_val *res)
> {
> - long val = 0;
> + unsigned long val = 0;
> int sign = 1;
>
> if (eatb(buf, '-')) {
> @@ -325,17 +326,25 @@ static int get_int(ujson_reader *buf, struct ujson_val *res)
> return 1;
> }
>
> + unsigned long max = (sign < 0) ? (unsigned long)LONG_MAX + 1UL : (unsigned long)LONG_MAX;
> +
> while (is_digit(peekb(buf))) {
> - val *= 10;
> - val += getb(buf) - '0';
> - //TODO: overflow?
> + unsigned int d = getb(buf) - '0';
> +
> + if (val > (max - d) / 10) {
> + ujson_err(buf, "Integer overflow");
> + return 1;
> + }
> +
> + val = val * 10 + d;
> }
>
> if (sign < 0)
> - val = -val;
> + res->val_int = (long)(0UL - val);
This would be better res->val_int = -(long)val;
And I do not like the code that much, but I think that we cannot do much
better without having separate functions for possitive and negative
numbers.
--
Cyril Hrubis
chrubis@suse.cz
More information about the ltp
mailing list