From 1fc877fd9473c50a51bc616118250a9fc64d3da0 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Wed, 30 Jun 2021 10:34:14 +0200 Subject: [PATCH] std: Catch and handle overflow in json parser When a floating-point value with no fractional part is shoved into an integer type we must check whether it fits or not before calling `@floatToInt` as the builtin panics in case of overflow. Catch the error and bubble it up to the caller. --- lib/std/json.zig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/std/json.zig b/lib/std/json.zig index 7cce202634..842a6dc3f2 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1555,6 +1555,7 @@ fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options: return try std.fmt.parseInt(T, numberToken.slice(tokens.slice, tokens.i - 1), 10); const float = try std.fmt.parseFloat(f128, numberToken.slice(tokens.slice, tokens.i - 1)); if (std.math.round(float) != float) return error.InvalidNumber; + if (float > std.math.maxInt(T) or float < std.math.minInt(T)) return error.Overflow; return @floatToInt(T, float); }, .Optional => |optionalInfo| { @@ -2617,6 +2618,7 @@ test "parse exponential into int" { const r = try parse(T, &TokenStream.init("{ \"int\": 4.2e2 }"), ParseOptions{}); try testing.expectEqual(@as(i64, 420), r.int); try testing.expectError(error.InvalidNumber, parse(T, &TokenStream.init("{ \"int\": 0.042e2 }"), ParseOptions{})); + try testing.expectError(error.Overflow, parse(T, &TokenStream.init("{ \"int\": 18446744073709551616.0 }"), ParseOptions{})); } test "escaped characters" {