From 2a3f0b3bb3affaefaef3bcb04eaa8797ba13361b Mon Sep 17 00:00:00 2001 From: Quentin Legot Date: Wed, 9 Nov 2022 17:31:14 +0100 Subject: [PATCH] Fix decode to allow overflow in certains cases, add a case in test for riscv_lui where imm is negative --- src/decode.rs | 8 +++++--- src/print.rs | 2 ++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/decode.rs b/src/decode.rs index 3ef5bdb..68d0e2f 100644 --- a/src/decode.rs +++ b/src/decode.rs @@ -1,3 +1,5 @@ +use core::num::Wrapping; // Permet d'autoriser les overflow pour les opérations voulues + #[allow(non_snake_case)] // supprimer le warning snake case (quand les noms de variables ont des majuscules) #[derive(Debug)] pub struct Instruction { @@ -45,8 +47,8 @@ pub fn decode(val : u32) -> Instruction { let imm12_I = ((val >> 20) & 0xfff) as u16; let imm12_S = (((val >> 20) & 0xfe0) + ((val >> 7) & 0x1f)) as u16; - let imm12_I_signed = if imm12_I >= 2048 { imm12_I - 4096 } else { imm12_I } as i16; - let imm12_S_signed = if imm12_S >= 2048 { imm12_S - 4096 } else { imm12_S } as i16; + let imm12_I_signed = if imm12_I >= 2048 { (Wrapping(imm12_I) - Wrapping(4096)).0 } else { imm12_I } as i16; + let imm12_S_signed = if imm12_S >= 2048 { (Wrapping(imm12_S) - Wrapping(4096)).0 } else { imm12_S } as i16; let imm13 = (((val >> 19) & 0x1000) + ((val >> 20) & 0x7e0) + ((val >> 7) & 0x1e) + ((val << 4) & 0x800)) as i16; @@ -57,7 +59,7 @@ pub fn decode(val : u32) -> Instruction { let imm21_1 = ((val & 0xff000) + ((val >> 9) & 0x800) + ((val >> 20) & 0x7fe) + ((val >> 11) & 0x100000)) as u32; - let imm21_1_signed = if imm21_1 >= 1048576 { imm21_1 - 2097152 } else { imm21_1 } as i32; + let imm21_1_signed = if imm21_1 >= 1048576 { (Wrapping(imm21_1) - Wrapping(2097152)).0 } else { imm21_1 } as i32; let shamt = ((val >> 20) & 0x3f) as u8; diff --git a/src/print.rs b/src/print.rs index 3e4eb00..aac1952 100644 --- a/src/print.rs +++ b/src/print.rs @@ -299,7 +299,9 @@ mod test { #[test] fn test_lui() { let lui = decode::decode(0b01110001000011111000_11100_0110111); + let lui_negatif = decode::decode(0b11110001000011111000_11100_0110111); assert_eq!("lui x28, 0x710F8000", print::print(lui, 0)); + assert_eq!("lui x28, 0xF10F8000", print::print(lui_negatif, 0)); } #[test]