Skip to content

Truly independent web browser

LibJS: Shift and raise BigInts by huge amounts as the spec says

Shannon Boothebf705370cfb
diff --git a/Libraries/LibJS/Rust/src/bytecode/constant_fold.rs b/Libraries/LibJS/Rust/src/bytecode/constant_fold.rs
index 0c5b2429581..375cd671c7e 100644
--- a/Libraries/LibJS/Rust/src/bytecode/constant_fold.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/constant_fold.rs
@@ -9,8 +9,6 @@
use num_bigint::BigInt;
use num_traits::FromPrimitive;
use num_traits::One;
-use num_traits::Signed;
-use num_traits::ToPrimitive;
use num_traits::Zero;
use libjs_abi::value as nan_box;
@@ -256,15 +254,12 @@ fn try_constant_fold_bigint_binary<G: ConstantPool>(
Some(generator.add_constant_bigint((&a % &b).to_string()))
}
BinaryOp::Exponentiation => {
- if b.is_negative() {
- return None; // Negative exponent throws at runtime.
- }
- let exp = b.to_u32()?;
// Only fold small exponents to avoid huge results.
- if exp > 1000 {
+ if b > BigInt::from(1000) {
return None;
}
- Some(generator.add_constant_bigint(num_traits::pow::pow(a, exp as usize).to_string()))
+ let result = crate::host::bigint_exponentiate(&a, &b)?;
+ Some(generator.add_constant_bigint(result.to_string()))
}
// Comparison operations: produce a Boolean result.
BinaryOp::StrictlyEquals | BinaryOp::LooselyEquals => Some(generator.add_constant_boolean(a == b)),
@@ -277,17 +272,20 @@ fn try_constant_fold_bigint_binary<G: ConstantPool>(
BinaryOp::BitwiseAnd => Some(generator.add_constant_bigint((&a & &b).to_string())),
BinaryOp::BitwiseOr => Some(generator.add_constant_bigint((&a | &b).to_string())),
BinaryOp::BitwiseXor => Some(generator.add_constant_bigint((&a ^ &b).to_string())),
+ // Only fold shifts that grow the value a little, to avoid huge results.
BinaryOp::LeftShift => {
- let shift = b.to_u64()?;
- if shift > 512 {
+ if b > BigInt::from(512) {
return None;
}
- Some(generator.add_constant_bigint((&a << shift as usize).to_string()))
+ let result = crate::host::bigint_left_shift(&a, &b)?;
+ Some(generator.add_constant_bigint(result.to_string()))
}
BinaryOp::RightShift => {
- let shift = b.to_u64()?;
- // BigInt right shift for negative numbers floors toward negative infinity.
- Some(generator.add_constant_bigint((&a >> shift).to_string()))
+ if b < BigInt::from(-512) {
+ return None;
+ }
+ let result = crate::host::bigint_signed_right_shift(&a, &b)?;
+ Some(generator.add_constant_bigint(result.to_string()))
}
// UnsignedRightShift throws TypeError for BigInt.
_ => None,
diff --git a/Libraries/LibJS/Rust/src/frontend_host.rs b/Libraries/LibJS/Rust/src/frontend_host.rs
index db55c75d383..b1bb4977421 100644
--- a/Libraries/LibJS/Rust/src/frontend_host.rs
+++ b/Libraries/LibJS/Rust/src/frontend_host.rs
@@ -10,6 +10,7 @@ use libregex_rust::ast::Flags;
use libregex_rust::regex::Regex;
use num_bigint::BigInt;
+use crate::runtime::big_int_algorithms;
use crate::runtime::regexp_object::parse_regex_pattern;
use crate::runtime::value::number_to_string;
use crate::runtime::value_conversions;
@@ -60,3 +61,18 @@ pub fn string_to_bigint(string: &[u16]) -> Option<BigInt> {
pub fn exponentiate(base: f64, exponent: f64) -> f64 {
value_conversions::exp_double(base, exponent)
}
+
+/// BigInt::exponentiate(base, exponent), which the frontend uses to fold `**`.
+pub fn bigint_exponentiate(base: &BigInt, exponent: &BigInt) -> Option<BigInt> {
+ big_int_algorithms::exponentiate(base, exponent).ok()
+}
+
+/// BigInt::leftShift(x, y), which the frontend uses to fold `<<`.
+pub fn bigint_left_shift(x: &BigInt, y: &BigInt) -> Option<BigInt> {
+ big_int_algorithms::left_shift(x, y).ok()
+}
+
+/// BigInt::signedRightShift(x, y), which the frontend uses to fold `>>`.
+pub fn bigint_signed_right_shift(x: &BigInt, y: &BigInt) -> Option<BigInt> {
+ big_int_algorithms::signed_right_shift(x, y).ok()
+}
diff --git a/Libraries/LibJS/Rust/src/host.rs b/Libraries/LibJS/Rust/src/host.rs
index eaf7699662f..75979ee705c 100644
--- a/Libraries/LibJS/Rust/src/host.rs
+++ b/Libraries/LibJS/Rust/src/host.rs
@@ -44,3 +44,18 @@ pub fn string_to_bigint(string: &[u16]) -> Option<BigInt> {
pub fn exponentiate(base: f64, exponent: f64) -> f64 {
implementation::exponentiate(base, exponent)
}
+
+/// BigInt::exponentiate(base, exponent), which the host implements. Returns None where it throws.
+pub fn bigint_exponentiate(base: &BigInt, exponent: &BigInt) -> Option<BigInt> {
+ implementation::bigint_exponentiate(base, exponent)
+}
+
+/// BigInt::leftShift(x, y), which the host implements. Returns None where it throws.
+pub fn bigint_left_shift(x: &BigInt, y: &BigInt) -> Option<BigInt> {
+ implementation::bigint_left_shift(x, y)
+}
+
+/// BigInt::signedRightShift(x, y), which the host implements. Returns None where it throws.
+pub fn bigint_signed_right_shift(x: &BigInt, y: &BigInt) -> Option<BigInt> {
+ implementation::bigint_signed_right_shift(x, y)
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/big_int_algorithms.rs b/Libraries/LibJS/Rust/src/runtime/big_int_algorithms.rs
index 9ac22d7e08a..64313514bf1 100644
--- a/Libraries/LibJS/Rust/src/runtime/big_int_algorithms.rs
+++ b/Libraries/LibJS/Rust/src/runtime/big_int_algorithms.rs
@@ -30,12 +30,6 @@ const TOMMATH_DIGIT_BIT: u64 = 60;
const DOUBLE_MANTISSA_BITS: u32 = 52;
const DOUBLE_EXPONENT_BIAS: u64 = 1023;
-/// Crypto's pow() passes its u32 exponent to mp_expt_n(), which takes an int. Exponents of 2^31 and above become
-/// negative there, and mp_expt_n() then returns 1 without multiplying, so this returns the exponent actually applied.
-fn exponent_applied_by_crypto_pow(exponent: u32) -> u32 {
- if i32::try_from(exponent).is_ok() { exponent } else { 0 }
-}
-
fn power_of_two_double(exponent: u64) -> f64 {
debug_assert!(exponent < 1024);
f64::from_bits((DOUBLE_EXPONENT_BIAS + exponent) << DOUBLE_MANTISSA_BITS)
@@ -287,21 +281,12 @@ pub fn as_uint_n(bits: u64, bigint: &BigInt) -> Result<BigInt, NumericOperationE
/// 6.1.6.2.9 BigInt::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
pub fn left_shift(x: &BigInt, y: &BigInt) -> Result<BigInt, NumericOperationError> {
- // AD-HOC: Prevent allocating huge amounts of memory.
- let rhs_bigint = y.magnitude();
- if rhs_bigint.bits() > 32 {
- return Err(NumericOperationError::BigIntSizeExceeded);
- }
-
- // x is multiplied or divided by 2^|y| as Crypto's pow() computes it.
- let shift = u64::from(exponent_applied_by_crypto_pow(
- rhs_bigint.to_u32().expect("at most 32 bits"),
- ));
-
// 1. If y < 0ℤ, then
if y.sign() == Sign::Minus {
// a. Return the BigInt value that represents ℝ(x) / 2^-y, rounding down to the nearest integer, including for negative numbers.
// NOTE: Since y is negative we can just do ℝ(x) / 2^|y|
+ // NB: Shifting past the last bit of x leaves nothing of it, however far.
+ let shift = y.magnitude().to_u64().map_or(x.bits(), |shift| shift.min(x.bits()));
let quotient = BigInt::from_biguint(x.sign(), x.magnitude() >> shift);
let remainder_is_zero = x.magnitude().trailing_zeros().is_none_or(|zeros| zeros >= shift);
@@ -314,7 +299,14 @@ pub fn left_shift(x: &BigInt, y: &BigInt) -> Result<BigInt, NumericOperationErro
}
// 2. Return the BigInt value that represents ℝ(x) × 2^y.
- Ok(x << shift)
+ if x.is_zero() {
+ return Ok(BigInt::zero());
+ }
+ // AD-HOC: Prevent allocating huge amounts of memory.
+ let Some(shift) = y.magnitude().to_u32() else {
+ return Err(NumericOperationError::BigIntSizeExceeded);
+ };
+ Ok(x << u64::from(shift))
}
/// 6.1.6.2.10 BigInt::signedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-signedRightShift
@@ -330,13 +322,29 @@ pub fn exponentiate(base: &BigInt, exponent: &BigInt) -> Result<BigInt, NumericO
return Err(NumericOperationError::NegativeExponent);
}
+ // 2. If base is 0ℤ and exponent is 0ℤ, return 1ℤ.
+ // 3. Return the BigInt value that represents ℝ(base) raised to the power ℝ(exponent).
+ // NB: The powers of 0, 1 and -1 are known without computing them, however large the exponent.
+ if base.is_zero() {
+ return Ok(if exponent.is_zero() {
+ BigInt::one()
+ } else {
+ BigInt::zero()
+ });
+ }
+ if base.magnitude().is_one() {
+ return Ok(if exponent.magnitude().bit(0) {
+ base.clone()
+ } else {
+ BigInt::one()
+ });
+ }
// AD-HOC: Prevent allocating huge amounts of memory.
- if exponent.magnitude().bits() > 32 {
+ let Some(exponent) = exponent.magnitude().to_u32() else {
+ return Err(NumericOperationError::BigIntSizeExceeded);
+ };
+ if u64::from(exponent).saturating_mul(base.bits() - 1) > u64::from(u32::MAX) {
return Err(NumericOperationError::BigIntSizeExceeded);
}
-
- // 2. If base is 0ℤ and exponent is 0ℤ, return 1ℤ.
- // 3. Return the BigInt value that represents ℝ(base) raised to the power ℝ(exponent).
- let exponent = exponent_applied_by_crypto_pow(exponent.magnitude().to_u32().expect("at most 32 bits"));
Ok(base.pow(exponent))
}
diff --git a/Libraries/LibJS/Rust/src/test_host.rs b/Libraries/LibJS/Rust/src/test_host.rs
index 934f2d2366b..747f3190830 100644
--- a/Libraries/LibJS/Rust/src/test_host.rs
+++ b/Libraries/LibJS/Rust/src/test_host.rs
@@ -39,6 +39,18 @@ pub fn exponentiate(_base: f64, _exponent: f64) -> f64 {
unimplemented!("no cargo test folds constants")
}
+pub fn bigint_exponentiate(_base: &BigInt, _exponent: &BigInt) -> Option<BigInt> {
+ unimplemented!("no cargo test folds constants")
+}
+
+pub fn bigint_left_shift(_x: &BigInt, _y: &BigInt) -> Option<BigInt> {
+ unimplemented!("no cargo test folds constants")
+}
+
+pub fn bigint_signed_right_shift(_x: &BigInt, _y: &BigInt) -> Option<BigInt> {
+ unimplemented!("no cargo test folds constants")
+}
+
#[unsafe(no_mangle)]
extern "C" fn unicode_code_point_has_space_separator_general_category(code_point: u32) -> bool {
matches!(code_point, 0x1680 | 0x2000..=0x200a | 0x202f | 0x205f | 0x3000)
diff --git a/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js b/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js
index 751c0ed5435..4586a9950c9 100644
--- a/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js
+++ b/Tests/LibJS/Runtime/builtins/BigInt/bigint-basic.js
@@ -203,6 +203,24 @@ test("constant right shift by a huge count", () => {
expect(5n >> 18446744073709551615n).toBe(0n);
});
+test("shifts and powers with huge counts at runtime", () => {
+ const value = x => x;
+ expect(value(5n) >> value(2147483648n)).toBe(0n);
+ expect(value(-5n) >> value(2147483648n)).toBe(-1n);
+ expect(value(5n) << value(-2147483648n)).toBe(0n);
+ expect(value(5n) >> value(4294967296n)).toBe(0n);
+ expect(value(-5n) >> value(2n ** 70n)).toBe(-1n);
+ expect(value(0n) << value(2n ** 40n)).toBe(0n);
+ expect(value(-9n) >> value(1n)).toBe(-5n);
+ expect(value(-1n) ** value(2147483649n)).toBe(-1n);
+ expect(value(-1n) ** value(2n ** 70n)).toBe(1n);
+ expect(value(1n) ** value(4294967296n)).toBe(1n);
+ expect(value(0n) ** value(2147483648n)).toBe(0n);
+ expect(value(0n) ** value(0n)).toBe(1n);
+ expect(() => value(1n) << value(2n ** 33n)).toThrow(RangeError);
+ expect(() => value(2n) ** value(2n ** 33n)).toThrow(RangeError);
+});
+
describe("errors", () => {
test("conversion to number", () => {
expect(() => {