Skip to content

Commit

Permalink
fastparse: Fix bug in overflow detection (vitessio#13702)
Browse files Browse the repository at this point in the history
Signed-off-by: Dirkjan Bussink <[email protected]>
  • Loading branch information
dbussink authored Aug 3, 2023
1 parent b8ee6c9 commit acd2615
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
28 changes: 28 additions & 0 deletions go/mysql/fastparse/fastparse.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ next:
break next
}

var cutoff uint64
switch base {
case 10:
cutoff = math.MaxUint64/10 + 1
case 16:
cutoff = math.MaxUint64/16 + 1
default:
cutoff = math.MaxUint64/uint64(base) + 1
}
if d >= cutoff {
return math.MaxUint64, fmt.Errorf("cannot parse uint64 from %q: %w", s, ErrOverflow)
}
v := d*uint64(base) + uint64(b)
if v < d {
return math.MaxUint64, fmt.Errorf("cannot parse uint64 from %q: %w", s, ErrOverflow)
Expand Down Expand Up @@ -139,6 +151,22 @@ next:
break next
}

var cutoff uint64
switch base {
case 10:
cutoff = math.MaxInt64/10 + 1
case 16:
cutoff = math.MaxInt64/16 + 1
default:
cutoff = math.MaxInt64/uint64(base) + 1
}
if d >= cutoff {
if minus {
return math.MinInt64, fmt.Errorf("cannot parse int64 from %q: %w", s, ErrOverflow)
}
return math.MaxInt64, fmt.Errorf("cannot parse int64 from %q: %w", s, ErrOverflow)
}

v := d*uint64(base) + uint64(b)
if v < d {
if minus {
Expand Down
12 changes: 12 additions & 0 deletions go/mysql/fastparse/fastparse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@ func TestParseInt64(t *testing.T) {
expected: 9223372036854775807,
err: `cannot parse int64 from "18446744073709551616": overflow`,
},
{
input: "31415926535897932384",
base: 10,
expected: 9223372036854775807,
err: `cannot parse int64 from "31415926535897932384": overflow`,
},
{
input: "1.1",
base: 10,
Expand Down Expand Up @@ -297,6 +303,12 @@ func TestParseUint64(t *testing.T) {
expected: 18446744073709551615,
err: `cannot parse uint64 from "18446744073709551616": overflow`,
},
{
input: "31415926535897932384",
base: 10,
expected: 18446744073709551615,
err: `cannot parse uint64 from "31415926535897932384": overflow`,
},
{
input: "1.1",
base: 10,
Expand Down

0 comments on commit acd2615

Please sign in to comment.