Skip to content

Commit d1c1d7d

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 ed4fe8f commit d1c1d7d

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

riscv.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -594,8 +594,11 @@ static uint32_t op_mul(uint32_t insn, uint32_t a, uint32_t b)
594594
{
595595
/* TODO: Test ifunc7 zeros */
596596
switch (decode_func3(insn)) {
597-
case 0b000: /* MUL */
598-
return a * b;
597+
case 0b000: { /* MUL */
598+
const int64_t _a = (int32_t) a;
599+
const int64_t _b = (int32_t) b;
600+
return ((uint64_t) (_a * _b)) & ((1ULL << 32) - 1);
601+
}
599602
case 0b001: { /* MULH */
600603
const int64_t _a = (int32_t) a;
601604
const int64_t _b = (int32_t) b;

0 commit comments

Comments
 (0)