Skip to content

fix: signed overflow when parsing long numbers - #41

Merged
MaJerle merged 1 commit into
MaJerle:developfrom
emincan2000:fix-number-overflow
Oct 26, 2026
Merged

MaJerle merged 1 commit into
MaJerle:developfrom
emincan2000:fix-number-overflow

Conversation

@emincan2000

Copy link
Copy Markdown
Contributor

#33 was closed, but on current develop (bbcf520) prv_parse_number() still accumulates the integer, fraction and exponent digits in lwjson_int_t without a range check. Besides the UBSan reports, it gives wrong values in a normal -O2 build:

[20000000000000000000.5]      -> 1.55e18 (real part was taken from the overflowed integer)
[0.12345678901234567890123]   -> 4.8e-05
[9223372036854775808]         -> -9223372036854775808 as int

Changes, all inside prv_parse_number():

  • The integer part is accumulated as a negative value, so -9223372036854775808 fits. If the number doesn't fit lwjson_int_t it is returned as LWJSON_TYPE_NUM_REAL instead of wrapping. The real value is accumulated alongside, so a long integer part before . or e is right too.
  • Fraction digits stop being added once dec_num would overflow. Those digits are below double precision anyway (with a 32-bit lwjson_int_t this keeps 9 fraction digits, before it wrapped).
  • The exponent saturates instead of overflowing, the result is 0 or infinity either way.
  • LWJSON_INT_MAX is computed from sizeof(lwjson_int_t), since the int type is configurable.

For numbers that already fit, the output is unchanged: I parsed 60k random numbers (various integer/fraction/exponent lengths, signs, -0 cases) with the old and new code, with both float and double as LWJSON_CFG_REAL_TYPE, and got identical results. I also ran a differential test against Python's json with random documents under ASan/UBSan; the number related reports are gone. With LWJSON_CFG_INT_TYPE int the limits behave the same way.

I added a few number cases to test_json_parse_basic (they fail before this change). All tests in tests/ pass with ASan/UBSan, I built them with gcc directly rather than through test.py.

Integer, fraction and exponent digits were accumulated in lwjson_int_t
without a range check. This is undefined behavior and gives wrong values,
e.g. 20000000000000000000.5 parsed as 1.55e18, and the valid minimum
-9223372036854775808 overflowed before negation.

- Integer part is accumulated as a negative value so the minimum fits.
  If it does not fit lwjson_int_t, the number is returned as real.
- Fraction digits that do not fit are ignored, they are below real
  precision anyway.
- Exponent saturates, the result is already 0 or infinity.
@MaJerle
MaJerle merged commit 9c4d476 into MaJerle:develop Oct 26, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants