Skip to content

Fix BigInt error handling in pow and string comparisons - #1977

Open
NicolasBonet wants to merge 1 commit into
quickjs-ng:masterfrom
NicolasBonet:fix-bigint-error-paths
Open

NicolasBonet wants to merge 1 commit into
quickjs-ng:masterfrom
NicolasBonet:fix-bigint-error-paths

Conversation

@NicolasBonet

@NicolasBonet NicolasBonet commented Dec 4, 2026 •

Copy link
Copy Markdown

This fixes two bugs in BigInt error paths.

1. js_bigint_pow leaks memory when a multiplication fails

The square-and-multiply loop keeps the partial result in r. On each step it multiplies into a new r1, then frees r. When js_bigint_mul fails (for example under a memory limit), the function returned NULL without freeing r. The fix frees r before returning.

2. Comparing a string with a BigInt hides exceptions

To compare a string with a BigInt (==, !=, <, <=, >, >=), js_eq_slow and js_relational_slow first convert the string with JS_StringToBigInt. That call returns one of three things:

  • a BigInt, and the comparison goes ahead
  • NaN when the string isn't a valid BigInt literal, and the comparison is false as the spec requires
  • JS_EXCEPTION when the conversion fails, for example on out-of-memory or when the number is too large

Both functions only checked whether the result was a BigInt, so JS_EXCEPTION took the "invalid literal" path. The comparison returned false and the exception was left pending on the context:

'1'.repeat(1e6) == 1n    // false, with a RangeError still pending
BigInt('1'.repeat(1e6))  // RangeError: BigInt is too large to allocate

The fix checks for JS_EXCEPTION after each conversion and propagates it, so the comparison throws the same RangeError as BigInt().

Tests

New api-test.c cases cover both bugs and fail without the fix: bigint_pow_oom reports the leak through JS_ABORT_ON_LEAKS, and bigint_string_compare_exception checks that each comparison throws. tests.conf and the test262 BigInt, comparison and exponentiation directories pass.

js_bigint_pow leaked its partial result when a multiplication failed.

js_relational_slow and js_eq_slow treated an exception from
JS_StringToBigInt as an invalid BigInt literal. The comparison returned
false and left the exception pending, e.g. '1'.repeat(1e6) == 1n.

This branch has not been deployed

No deployments
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.

1 participant