1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
//! `riscy` is a clean and clear implementation of the base 32-bit version of
//! RISC-V instruction set architecture, also known as RV32I.
//!
//! [The oficial specification for RV32I](https://github.com/riscv/riscv-isa-manual/releases/download/Ratified-IMAFDQC/riscv-spec-20191213.pdf).
//!
//! `riscy` does not implement any instrucitons outside of the 42 instructions required by the spec.
//! This makes it rich enough that you can run most simple programs compiled from C on it while
//! keeping it small enough to be used as a tool to learn about RISC-V.
//!
//! Notably absent from the base specification are:
//!
//! * multiplication and division
//! * floating point numbers
//! * atomic memory operations
//! * support for compressed instructions
//! * instructions for operating system support (beyond ecall and ebreak)
//! * instructions for operating on control status registers (CSRs)
//!
//! This crate is a library for building emulators containing a RV32I core.
//! The basic building block for this is the [`RiscV`](RiscV) struct, which
//! roughly corresponds to a RISC-V hart (hardware thread).
//!
//! This crate also comes with a binary (also called `riscy`) which serves as an example of how
//! to use this library. It can run RISC-V ELF binaries, such as those cross-compiled from GCC
//! or Clang. It can also be used to disassemble those binaries.
//!
//! ```
//! $ vim hello.c
//! $ gcc -march=rv32i -mabi=ilp32 hello.c -o hello
//! $ riscy hello
//! Hello, world!
//! $ riscy --dis hello | head
//! PC = 0x00010090
//! _start
//! 0x00010090 97 51 00 00 auipc gp, 20480
//! 0x00010094 93 81 01 db addi gp, gp, -592
//! 0x00010098 13 85 41 04 addi a0, gp, 68
//! 0x0001009c 13 86 c1 09 addi a2, gp, 156
//! 0x000100a0 33 06 a6 40 sub a2, a2, a0
//! 0x000100a4 93 05 00 00 addi a1, zero, 0
//! 0x000100a8 ef 00 c0 20 jal ra, 0x0000020c
//! 0x000100ac 17 05 00 00 auipc a0, 0
//! ```
mod addr;
mod decode;
mod reg;
pub mod memory;
pub use crate::decode::{decode, DecodeError};
pub use crate::memory::Memory;
pub use addr::Addr;
pub use reg::{Reg, RegVal};
use std::convert::TryInto;
use std::fmt;
pub use decode::Instruction;
/// A struct to hold the state of a RiscV core.
pub struct RiscV {
program_counter: Addr,
registers: [RegVal; 32],
instruction_cache: InstructionCache,
}
struct InstructionCache {
base_addr: Addr,
instructions: [Option<Instruction>; 1024]
}
/// A struct to indicate the result of calling .step() or its variants.
///
/// Most instructions return `StepResult::Ok`, indicating that the next
/// instruction was successfully fetched, decoded, and executed.
///
/// A result of StepResult::Call is the result of an ecall instruction.
/// Similarly, a result of StepResult::Break is the result of an ebreak instruction.
#[derive(Debug)]
pub enum StepResult {
Ok,
Call,
Break,
DecodeError(decode::DecodeError),
}
impl RiscV {
/// Create a new RiscV core with all of its registers zeroed out.
pub fn new() -> Self {
RiscV {
program_counter: Addr::new(0x0),
registers: [RegVal::from_u32(0); 32],
instruction_cache: InstructionCache {
base_addr: Addr(0),
instructions: [None; 1024],
},
}
}
/// Fetch, execute, and retire a single instruction.
/// When the core attempts to interact with memory, whether to fetch an instruction,
/// to perform a load or store operation, etc, it makes use of the supplied `memory`.
pub fn step<M: Memory>(&mut self, memory: &mut M) -> StepResult {
self.step_with_retired(memory).0
}
fn flush_instruction_cache<M: Memory>(&mut self, memory: &mut M) {
let pc_u32: u32 = self.program_counter.0;
let base_addr: u32 = pc_u32 & 0xfffff000;
let instructions = [None; 1024];
self.instruction_cache = InstructionCache {
base_addr: Addr(base_addr),
instructions,
};
}
fn fetch_instruction<M: Memory>(&mut self, memory: &mut M) -> Result<Instruction, DecodeError> {
let pc_u32: u32 = self.program_counter.into();
let base_addr = Addr(pc_u32 & 0xfffff000);
if self.instruction_cache.base_addr != base_addr {
self.flush_instruction_cache(memory);
}
let offset: u32 = pc_u32 & 0x00000fff;
// the >> 2 because each instruction is 4 bytes
match self.instruction_cache.instructions[(offset >> 2) as usize] {
None => {
let decoded_instr = decode::decode(memory.load_word(self.program_counter));
let instr = match &decoded_instr {
Ok(instr) => instr,
Err(e) => return decoded_instr,
};
self.instruction_cache.instructions[(offset >> 2) as usize] = Some(instr.clone());
decoded_instr
},
Some(instr) => Ok(instr),
}
}
/// Same as [`step`](crate::RiscV::step), but returns the decoded instruction.
pub fn step_with_retired<M: Memory>(&mut self, memory: &mut M) -> (StepResult, Option<Instruction>) {
let instruction_opt = self.fetch_instruction(memory);
match instruction_opt {
Ok(instruction) => (self.step_instruction(instruction.clone(), memory), Some(instruction)),
Err(invalid_instruction) => (StepResult::DecodeError(invalid_instruction), None),
}
}
fn step_instruction<M: Memory>(&mut self, instruction: Instruction, memory: &mut M) -> StepResult {
match instruction {
Instruction::Beq { rs1, rs2, imm } => {
let v1 = self.reg(rs1);
let v2 = self.reg(rs2);
if v1 == v2 {
self.program_counter += imm.val();
} else {
self.program_counter += 4;
}
StepResult::Ok
}
Instruction::Bne { rs1, rs2, imm } => {
let v1 = self.reg(rs1);
let v2 = self.reg(rs2);
if v1 != v2 {
self.program_counter += imm.val();
} else {
self.program_counter += 4;
}
StepResult::Ok
}
Instruction::Blt { rs1, rs2, imm } => {
let v1 = self.reg(rs1);
let v2 = self.reg(rs2);
if v1.less_than_signed(v2) {
self.program_counter += imm.val();
} else {
self.program_counter += 4;
}
StepResult::Ok
}
Instruction::Bge { rs1, rs2, imm } => {
let v1 = self.reg(rs1);
let v2 = self.reg(rs2);
if v1.greater_than_equal_to_signed(v2) {
self.program_counter += imm.val();
} else {
self.program_counter += 4;
}
StepResult::Ok
}
Instruction::Bltu { rs1, rs2, imm } => {
let v1 = self.reg(rs1);
let v2 = self.reg(rs2);
if v1.less_than_unsigned(v2) {
self.program_counter += imm.val();
} else {
self.program_counter += 4;
}
StepResult::Ok
}
Instruction::Bgeu { rs1, rs2, imm } => {
let v1 = self.reg(rs1);
let v2 = self.reg(rs2);
if v1.greater_than_equal_to_unsigned(v2) {
self.program_counter += imm.val();
} else {
self.program_counter += 4;
}
StepResult::Ok
}
Instruction::Jalr { rd, rs1, imm } => {
let target_addr = (self.reg(rs1).to_addr() + imm.val()).align_to_halfword();
self.set_reg(rd, RegVal::from_addr(self.program_counter + 4));
self.program_counter = target_addr;
StepResult::Ok
}
Instruction::Jal { rd, imm } => {
let target_addr = (self.program_counter + imm.val()).align_to_halfword();
self.set_reg(rd, RegVal::from_addr(self.program_counter + 4));
self.program_counter = target_addr;
StepResult::Ok
}
Instruction::Lui { rd, imm } => {
self.set_reg(rd, imm.val());
self.program_counter += 4;
StepResult::Ok
}
Instruction::Auipc { rd, imm } => {
self.set_reg(rd, RegVal::from_addr(self.program_counter) + imm.val());
self.program_counter += 4;
StepResult::Ok
}
Instruction::Addi { rd, rs1, imm } => {
self.set_reg(rd, self.reg(rs1) + imm.val());
self.program_counter += 4;
StepResult::Ok
}
Instruction::Slti { rd, rs1, imm } => {
if self.reg(rs1).less_than_signed(imm.val()) {
self.set_reg(rd, RegVal::from_u32(1));
} else {
self.set_reg(rd, RegVal::from_u32(0));
}
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sltiu { rd, rs1, imm } => {
if self.reg(rs1).less_than_unsigned(imm.val()) {
self.set_reg(rd, RegVal::from_u32(1));
} else {
self.set_reg(rd, RegVal::from_u32(0));
}
self.program_counter += 4;
StepResult::Ok
}
Instruction::Xori { rd, rs1, imm } => {
self.set_reg(rd, self.reg(rs1) ^ imm.val());
self.program_counter += 4;
StepResult::Ok
}
Instruction::Ori { rd, rs1, imm } => {
self.set_reg(rd, self.reg(rs1) | imm.val());
self.program_counter += 4;
StepResult::Ok
}
Instruction::Andi { rd, rs1, imm } => {
self.set_reg(rd, self.reg(rs1) & imm.val());
self.program_counter += 4;
StepResult::Ok
}
Instruction::Slli { rd, rs1, shamt } => {
self.set_reg(rd, self.reg(rs1).shift_left_logical(shamt.val()));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Srli { rd, rs1, shamt } => {
self.set_reg(rd, self.reg(rs1).shift_right_logical(shamt.val()));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Srai { rd, rs1, shamt } => {
self.set_reg(rd, self.reg(rs1).shift_right_arithmetic(shamt.val()));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Add { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1) + self.reg(rs2));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sub { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1) - self.reg(rs2));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sll { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1).shift_left_logical(self.reg(rs2)));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Slt { rd, rs1, rs2 } => {
if self.reg(rs1).less_than_signed(self.reg(rs2)) {
self.set_reg(rd, RegVal::from_u32(1));
} else {
self.set_reg(rd, RegVal::from_u32(0));
}
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sltu { rd, rs1, rs2 } => {
if self.reg(rs1).less_than_unsigned(self.reg(rs2)) {
self.set_reg(rd, RegVal::from_u32(1));
} else {
self.set_reg(rd, RegVal::from_u32(0));
}
self.program_counter += 4;
StepResult::Ok
}
Instruction::Xor { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1) ^ self.reg(rs2));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Srl { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1).shift_right_logical(self.reg(rs2)));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sra { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1).shift_right_arithmetic(self.reg(rs2)));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Or { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1) | self.reg(rs2));
self.program_counter += 4;
StepResult::Ok
}
Instruction::And { rd, rs1, rs2 } => {
self.set_reg(rd, self.reg(rs1) & self.reg(rs2));
self.program_counter += 4;
StepResult::Ok
}
Instruction::Lb { rd, rs1, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = RegVal::from_i32(memory.load_byte(addr) as i32);
self.set_reg(rd, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Lh { rd, rs1, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = RegVal::from_i32(memory.load_halfword(addr) as i32);
self.set_reg(rd, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Lw { rd, rs1, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = RegVal::from_i32(memory.load_word(addr) as i32);
self.set_reg(rd, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Lbu { rd, rs1, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = RegVal::from_u32(memory.load_byte(addr) as u32);
self.set_reg(rd, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Lhu { rd, rs1, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = RegVal::from_u32(memory.load_halfword(addr) as u32);
self.set_reg(rd, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Lwu { rd, rs1, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = RegVal::from_u32(memory.load_word(addr) as u32);
self.set_reg(rd, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sb { rs1, rs2, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = self.reg(rs2).to_u32() as u8;
memory.store_byte(addr, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sh { rs1, rs2, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = self.reg(rs2).to_u32() as u16;
memory.store_halfword(addr, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Sw { rs1, rs2, imm } => {
let addr = self.reg(rs1).to_addr() + imm.val();
let val = self.reg(rs2).to_u32() as u32;
memory.store_word(addr, val);
self.program_counter += 4;
StepResult::Ok
}
Instruction::Fence { rd } => {
let _ = rd;
unimplemented!()
}
Instruction::FenceI { rd } => {
let _ = rd;
unimplemented!()
}
Instruction::ECall => StepResult::Call,
Instruction::EBreak => StepResult::Break,
}
}
/// Sets the given register to the given value.
/// ```
/// // sets the the stack pointer, `sp`, (also known as `x2`) to the value `0x2000_0000`.
/// riscv.set_reg(2, 0x2000_0000.into());
///```
pub fn set_reg<R: Into<Reg>>(&mut self, reg: R, reg_val: RegVal) {
let Reg(reg_number) = reg.into();
if reg_number != 0 {
self.registers[reg_number as usize] = reg_val;
}
}
/// Gets the value of the given register.
/// ```
/// // gets the value of the return address register, `ra`, (also known as `x1`).
/// riscv.reg(1);
///```
pub fn reg<R: Into<Reg>>(&self, reg: R) -> RegVal {
let Reg(reg_number) = reg.into();
self.registers[reg_number as usize]
}
/// Sets the value of the program counter to the given address.
///
/// This is useful for specifying the entry point to the program when
/// first initializing the machine.
pub fn set_pc(&mut self, addr: Addr) {
self.program_counter = addr;
}
/// Gets the value of the program counter.
pub fn pc(&self) -> Addr {
self.program_counter
}
}
impl fmt::Display for RiscV {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for row in 0..8 {
for col in 0..4 {
let reg = Reg(8 * col + row);
let reg_val = self.reg(reg).to_u32();
write!(f, "{:<3} = {:8x} ", reg.to_string(), reg_val)?;
}
write!(f, "\n")?;
}
Ok(())
}
}