From e05fff8bcf29de78d99b8af5a5f04821bb1e0f3f Mon Sep 17 00:00:00 2001 From: Cong-Cong Pan Date: Thu, 5 Sep 2024 19:11:46 +0800 Subject: [PATCH] fix: overflow panic when shifting left value greater then 31 (#7792) --- .../src/utils/eval/eval_binary_expr.rs | 24 ++++++++++++++++--- .../parsing/evaluate-if-binary/index.js | 2 ++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs b/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs index a6f58993b5e7..2702eeb19acb 100644 --- a/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs +++ b/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs @@ -429,7 +429,27 @@ pub fn handle_const_operation( None } } - BinaryOp::BitAnd | BinaryOp::BitXor | BinaryOp::BitOr | BinaryOp::LShift | BinaryOp::RShift => { + BinaryOp::LShift | BinaryOp::RShift => { + if let Some(left_number) = left.as_int() + && let Some(right_number) = right.as_int() + { + // only the lower 5 bits are used when shifting, so don't do anything + // if the shift amount is outside [0,32) + if (0..32).contains(&right_number) { + res.set_number(match expr.op { + BinaryOp::LShift => left_number << right_number, + BinaryOp::RShift => left_number >> right_number, + _ => unreachable!(), + } as f64); + } else { + res.set_number(left_number as f64); + } + Some(res) + } else { + None + } + } + BinaryOp::BitAnd | BinaryOp::BitXor | BinaryOp::BitOr => { if let Some(left_number) = left.as_int() && let Some(right_number) = right.as_int() { @@ -437,8 +457,6 @@ pub fn handle_const_operation( BinaryOp::BitAnd => left_number & right_number, BinaryOp::BitXor => left_number ^ right_number, BinaryOp::BitOr => left_number | right_number, - BinaryOp::LShift => left_number << right_number, - BinaryOp::RShift => left_number >> right_number, _ => unreachable!(), } as f64); Some(res) diff --git a/packages/rspack-test-tools/tests/normalCases/parsing/evaluate-if-binary/index.js b/packages/rspack-test-tools/tests/normalCases/parsing/evaluate-if-binary/index.js index 044c9e800b96..ad94396348e2 100644 --- a/packages/rspack-test-tools/tests/normalCases/parsing/evaluate-if-binary/index.js +++ b/packages/rspack-test-tools/tests/normalCases/parsing/evaluate-if-binary/index.js @@ -18,6 +18,8 @@ it("should handle bit operation", () => { if ((1 ^ 2) !== 3) require("fail"); if ((1 << 1) !== 2) require("fail"); if ((2 >> 1) !== 1) require("fail"); + if ((2 >> 32) !== 2) require("fail"); + if ((2 << 32) !== 2) require("fail"); }); it("should handle number operation", () => {