Skip to content

Commit af223d4

Browse files
authored
Merge pull request Tencent#1261 from fmalita/exponent-underflow
Prevent int underflow when parsing exponents
2 parents a091035 + 8269bc2 commit af223d4

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

include/rapidjson/reader.h

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1632,9 +1632,18 @@ class GenericReader {
16321632
if (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
16331633
exp = static_cast<int>(s.Take() - '0');
16341634
if (expMinus) {
1635+
// (exp + expFrac) must not underflow int => we're detecting when -exp gets
1636+
// dangerously close to INT_MIN (a pessimistic next digit 9 would push it into
1637+
// underflow territory):
1638+
//
1639+
// -(exp * 10 + 9) + expFrac >= INT_MIN
1640+
// <=> exp <= (expFrac - INT_MIN - 9) / 10
1641+
RAPIDJSON_ASSERT(expFrac <= 0);
1642+
int maxExp = (expFrac + 2147483639) / 10;
1643+
16351644
while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
16361645
exp = exp * 10 + static_cast<int>(s.Take() - '0');
1637-
if (exp >= 214748364) { // Issue #313: prevent overflow exponent
1646+
if (RAPIDJSON_UNLIKELY(exp > maxExp)) {
16381647
while (RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent
16391648
s.Take();
16401649
}

test/unittest/readertest.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ static void TestParseDouble() {
242242
TEST_DOUBLE(fullPrecision, "1e-214748363", 0.0); // Maximum supported negative exponent
243243
TEST_DOUBLE(fullPrecision, "1e-214748364", 0.0);
244244
TEST_DOUBLE(fullPrecision, "1e-21474836311", 0.0);
245+
TEST_DOUBLE(fullPrecision, "1.00000000001e-2147483638", 0.0);
245246
TEST_DOUBLE(fullPrecision, "0.017976931348623157e+310", 1.7976931348623157e+308); // Max double in another form
246247

247248
// Since

0 commit comments

Comments
 (0)