Skip to content

Commit 32895fb

Browse files
committed
Fix signed integer overflow in RV32M
The current implementation of the mul instruction does not guard against integer overflow, potentially leading to undefined behavior. Cast the operands to int64_t before performing the multiplication to ensure that the result can be accommodated without overflow. The lower 32 bits of the product are then extracted, preserving the correct uint32_t type.
1 parent 2a58885 commit 32895fb

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

src/rv32_constopt.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,8 +408,9 @@ CONSTOPT(csrrci, { info->is_constant[ir->rd] = false; })
408408
CONSTOPT(mul, {
409409
if (info->is_constant[ir->rs1] && info->is_constant[ir->rs2]) {
410410
info->is_constant[ir->rd] = true;
411-
ir->imm = (int32_t) info->const_val[ir->rs1] *
412-
(int32_t) info->const_val[ir->rs2];
411+
const int64_t multiplicand = (int32_t) info->const_val[ir->rs1];
412+
const int64_t multiplier = (int32_t) info->const_val[ir->rs2];
413+
ir->imm = ((uint64_t) (multiplicand * multiplier)) & ((1ULL << 32) - 1);
413414
info->const_val[ir->rd] = ir->imm;
414415
ir->opcode = rv_insn_lui;
415416
ir->impl = dispatch_table[ir->opcode];

src/rv32_template.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1047,7 +1047,12 @@ RVOP(
10471047
/* MUL: Multiply */
10481048
RVOP(
10491049
mul,
1050-
{ rv->X[ir->rd] = (int32_t) rv->X[ir->rs1] * (int32_t) rv->X[ir->rs2]; },
1050+
{
1051+
const int64_t multiplicand = (int32_t) rv->X[ir->rs1];
1052+
const int64_t multiplier = (int32_t) rv->X[ir->rs2];
1053+
rv->X[ir->rd] =
1054+
((uint64_t) (multiplicand * multiplier)) & ((1ULL << 32) - 1);
1055+
},
10511056
GEN({
10521057
ld, S32, TMP0, X, rs1;
10531058
ld, S32, TMP1, X, rs2;

0 commit comments

Comments
 (0)