Skip to content

Commit

Permalink
Fix signed integer overflow in RV32M
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
visitorckw committed Jan 8, 2024
1 parent ed4fe8f commit d1c1d7d
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions riscv.c
Original file line number Diff line number Diff line change
Expand Up @@ -594,8 +594,11 @@ static uint32_t op_mul(uint32_t insn, uint32_t a, uint32_t b)
{
/* TODO: Test ifunc7 zeros */
switch (decode_func3(insn)) {
case 0b000: /* MUL */
return a * b;
case 0b000: { /* MUL */
const int64_t _a = (int32_t) a;
const int64_t _b = (int32_t) b;
return ((uint64_t) (_a * _b)) & ((1ULL << 32) - 1);
}
case 0b001: { /* MULH */
const int64_t _a = (int32_t) a;
const int64_t _b = (int32_t) b;
Expand Down

0 comments on commit d1c1d7d

Please sign in to comment.