Skip to content

Commit 9ab6bf2

Browse files
committed
[cherry-pick] target/riscv: fix ub during instruction decode
A left shift operation caused an implicit integer promotion, triggering the following UBSan error: ``` left shift of 254 by 24 places cannot be represented in type 'int' ``` NOTE: it seems that this code won't work correctly with BE targets, however this is a general problem of the whole implementation anyway. See: riscv-collab/riscv-openocd#1299 Signed-off-by: Anatoly Parshintsev <[email protected]>
1 parent f5f712e commit 9ab6bf2

File tree

1 file changed

+3
-9
lines changed

1 file changed

+3
-9
lines changed

src/target/riscv/riscv.c

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2390,23 +2390,17 @@ int riscv_hit_watchpoint(struct target *target, struct watchpoint **hit_watchpoi
23902390
riscv_reg_t dpc;
23912391
if (riscv_reg_get(target, &dpc, GDB_REGNO_DPC) != ERROR_OK)
23922392
return ERROR_FAIL;
2393-
const uint8_t length = 4;
23942393
LOG_TARGET_DEBUG(target, "dpc is 0x%" PRIx64, dpc);
23952394

23962395
/* fetch the instruction at dpc */
2397-
uint8_t buffer[length];
2398-
if (target_read_buffer(target, dpc, length, buffer) != ERROR_OK) {
2396+
uint8_t buffer[4];
2397+
if (target_read_buffer(target, dpc, sizeof(buffer), buffer) != ERROR_OK) {
23992398
LOG_TARGET_ERROR(target, "Failed to read instruction at dpc 0x%" PRIx64,
24002399
dpc);
24012400
return ERROR_FAIL;
24022401
}
24032402

2404-
riscv_insn_t instruction = 0;
2405-
2406-
for (int i = 0; i < length; i++) {
2407-
LOG_TARGET_DEBUG(target, "Next byte is %x", buffer[i]);
2408-
instruction += (buffer[i] << 8 * i);
2409-
}
2403+
riscv_insn_t instruction = le_to_h_u32(buffer);
24102404
LOG_TARGET_DEBUG(target, "Full instruction is %x", instruction);
24112405

24122406
int rs;

0 commit comments

Comments
 (0)