1
0
mirror of https://github.com/golang/go synced 2024-11-26 11:08:38 -07:00

math/big: check for excessive exponents in Rat.SetString

Found by oss-fuzz https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=33284

Fixes #45910.

Change-Id: I61e7b04dbd80343420b57eede439e361c0f7b79c
Reviewed-on: https://go-review.googlesource.com/c/go/+/316149
Trust: Robert Griesemer <gri@golang.org>
Trust: Katie Hockman <katie@golang.org>
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Katie Hockman <katie@golang.org>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
This commit is contained in:
Robert Griesemer 2021-05-02 11:27:03 -07:00
parent 54e20b505d
commit 6c591f79b0
2 changed files with 33 additions and 7 deletions

View File

@ -51,7 +51,8 @@ func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
// An optional base-10 ``e'' or base-2 ``p'' (or their upper-case variants)
// exponent may be provided as well, except for hexadecimal floats which
// only accept an (optional) ``p'' exponent (because an ``e'' or ``E'' cannot
// be distinguished from a mantissa digit).
// be distinguished from a mantissa digit). If the exponent's absolute value
// is too large, the operation may fail.
// The entire string, not just a prefix, must be valid for success. If the
// operation failed, the value of z is undefined but the returned value is nil.
func (z *Rat) SetString(s string) (*Rat, bool) {
@ -169,6 +170,9 @@ func (z *Rat) SetString(s string) (*Rat, bool) {
if n < 0 {
n = -n
}
if n > 1e6 {
return nil, false // avoid excessively large exponents
}
pow5 := z.b.abs.expNN(natFive, nat(nil).setWord(Word(n)), nil) // use underlying array of z.b.abs
if exp5 > 0 {
z.a.abs = z.a.abs.mul(z.a.abs, pow5)
@ -181,15 +185,12 @@ func (z *Rat) SetString(s string) (*Rat, bool) {
}
// apply exp2 contributions
if exp2 < -1e7 || exp2 > 1e7 {
return nil, false // avoid excessively large exponents
}
if exp2 > 0 {
if int64(uint(exp2)) != exp2 {
panic("exponent too large")
}
z.a.abs = z.a.abs.shl(z.a.abs, uint(exp2))
} else if exp2 < 0 {
if int64(uint(-exp2)) != -exp2 {
panic("exponent too large")
}
z.b.abs = z.b.abs.shl(z.b.abs, uint(-exp2))
}

View File

@ -589,3 +589,28 @@ func TestIssue31184(t *testing.T) {
}
}
}
func TestIssue45910(t *testing.T) {
var x Rat
for _, test := range []struct {
input string
want bool
}{
{"1e-1000001", false},
{"1e-1000000", true},
{"1e+1000000", true},
{"1e+1000001", false},
{"0p1000000000000", true},
{"1p-10000001", false},
{"1p-10000000", true},
{"1p+10000000", true},
{"1p+10000001", false},
{"1.770p02041010010011001001", false}, // test case from issue
} {
_, got := x.SetString(test.input)
if got != test.want {
t.Errorf("SetString(%s) got ok = %v; want %v", test.input, got, test.want)
}
}
}