Files
Basys3RiscV/tools/rv32emu.py
T
brad ArantandClaude Opus 5.5 bda9bb67b6 Add a 640x480 two-colour graphics mode; start in white
The graphics memory doubles as 640x480 at a bit a pixel (port 38), four
pixels to an entry, plotted by read-modify-write, in two colours from
port 39 (0 transparent). BASIC gets SCREEN 0 / SCREEN 1 [,set[,clear]];
a plain fill (as every game does) returns to 320x240 and BASIC follows.
The text now starts in white (SW5:4 = 00; 10 is green). The README is
rewritten to stand on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:06:30 -08:00

606 lines
21 KiB
Python

#!/usr/bin/env python3
"""RV32IMF emulator of the Basys 3 RISC-V computer, for testing programs on the
PC and as a reference for rtl/rv32_cpu.v.
The same machine as rtl/rv32_cpu.v and rtl/rv32_system.v: RV32IMF (floating
point from tools/f32.py, bit for bit as rtl/rv32_fpu.v), machine
mode, the CSRs the core has (no triggers), the resumable NMI, 80 KB of RAM
(writes below rom_top ignored), the monitor's 32 KB ROM at 20000h and 8 KB of
RAM at 28000h, the I/O ports at FFFFFF00h + N (io_in / io_out, to be
overridden) and the 32-bit registers at FFFFFE00h + N.
python3 tools/rv32emu.py image.bin [--input FILE] [--max N] [--trace FILE]
runs a raw image from address 0 with the console on ports 0/1: text from
--input is typed, output goes to stdout. --trace writes "pc instruction" for
each instruction run. The emulator also counts the clocks rv32_cpu would take
(cycles; see cost()).
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import f32 # noqa: E402
M32 = 0xFFFFFFFF
RAM_END = 0x14000
MON_BASE, MON_RAM, MON_END = 0x20000, 0x28000, 0x2A000
MEM_SIZE = MON_END
class Trap(Exception):
def __init__(self, cause, tval=0):
self.cause, self.tval = cause, tval
def sx(v, bits):
v &= (1 << bits) - 1
return v - (1 << bits) if v >> (bits - 1) else v
def s32(v):
return v - (1 << 32) if v & 0x80000000 else v
class RV32:
def __init__(self, mem=b"", rom_top=0, inp=b"", out=None):
self.m = bytearray(MEM_SIZE)
self.m[:len(mem)] = mem
self.rom_top = rom_top # writes below are ignored
self.x = [0] * 32
self.f = [0] * 32 # float registers (bit patterns)
self.fs = 1 # mstatus.FS: Initial
self.fflags = 0
self.frm = 0
self.pc = 0
self.cache = {}
self.csr = {0x300: 0, 0x304: 0, 0x305: 0, 0x340: 0, 0x341: 0, 0x342: 0, 0x343: 0,
0x740: 0, 0x741: 0, 0x742: 0}
self.nmie = True
self.count = 0 # instructions completed
self.cycles = 0 # clocks rv32_cpu would take (see cost())
self.inp = bytearray(inp)
self.out = out if out is not None else bytearray()
self.step_arm = False # nmi after the next instruction (port 60)
self.stepped = False
self.nmi_pending = False
self.why = 0
self.bp = [0, 0]
self.bp_on = 0
self.g_hires = 0 # port 38: 640x480 graphics mode
@property
def sp(self):
return self.x[2]
@sp.setter
def sp(self, v):
self.x[2] = v & M32
# ---------------------------------------------------------------- memory
def rd8(self, a):
if a < MEM_SIZE:
return self.m[a]
if a >= 0xFFFFFF00:
return self.io_in(a & 0xFF) & 0xFF
if a >= 0xFFFFFE00:
return self.word_in(a & 0xFC) >> (8 * (a & 3)) & 0xFF
return 0
def rd16(self, a):
if a < MEM_SIZE - 1:
return self.m[a] | self.m[a + 1] << 8
return self.rd8(a) | self.rd8(a + 1) << 8
def rd32(self, a):
if a < MEM_SIZE - 3:
return int.from_bytes(self.m[a:a + 4], "little")
if a >= 0xFFFFFF00:
return self.io_in(a & 0xFF) & 0xFF
if a >= 0xFFFFFE00:
return self.word_in(a & 0xFC) & M32
return 0
def writable(self, a):
return self.rom_top <= a < RAM_END or MON_RAM <= a < MON_END
def wr8(self, a, v):
if a < MEM_SIZE:
if self.writable(a):
self.m[a] = v & 0xFF
if a & ~3 in self.cache:
del self.cache[a & ~3]
elif a >= 0xFFFFFF00:
self.port_out(a & 0xFF, v & 0xFF)
elif a >= 0xFFFFFE00 and not a & 3:
self.word_out(a & 0xFC, v & 0xFF)
def wr16(self, a, v):
self.wr8(a, v)
self.wr8(a + 1, v >> 8)
def wr32(self, a, v):
if a >= 0xFFFFFF00:
self.port_out(a & 0xFF, v & 0xFF)
elif a >= 0xFFFFFE00:
self.word_out(a & 0xFC, v & M32)
else:
for i in range(4):
self.wr8(a + i, v >> 8 * i)
# -------------------------------------------------------------- devices
def io_in(self, port):
"""A port read; override. The console is ports 0 and 1."""
if port == 0:
return (1 if self.inp else 0) | 2
if port == 1:
return self.inp.pop(0) if self.inp else 0
if port == 0x60:
return self.why
if port == 0x34:
return 0 # graphics fill: done at once
if port == 0x38:
return self.g_hires
return 0xFF
def io_out(self, port, v):
"""A port write; override."""
if port == 1:
self.out.append(v)
def port_out(self, port, v):
if port == 0x60:
self.step_arm = bool(v & 2)
elif port == 0x61:
if not self.nmi_pending and not self.in_monitor():
self.nmi_pending, self.why_r = True, 2
elif port == 0x67:
self.bp_on = v & 3
elif port == 0x38:
self.g_hires = v & 1
elif port == 0x34 and not v & 0x80:
self.g_hires = 0
self.io_out(port, v)
def millis(self):
return self.count // 30000 # about 30 instructions a microsecond
def word_in(self, a):
if a == 0x00:
return self.millis() & M32
if a == 0x04:
return (self.count // 30) & M32
if a == 0x10:
return self.bp[0]
if a == 0x14:
return self.bp[1]
return 0
def word_out(self, a, v):
if a == 0x10:
self.bp[0] = v
elif a == 0x14:
self.bp[1] = v
def in_monitor(self):
return MON_BASE <= self.pc < MON_RAM
# ------------------------------------------------------------------ CSRs
def csr_read(self, n):
if n == 0x300:
return self.csr[0x300] | 0x1800 | self.fs << 13 | (0x80000000 if self.fs == 3 else 0)
if n == 0x301:
return 0x40001120
if n in (1, 2, 3):
if not self.fs:
raise Trap(2)
return [0, self.fflags, self.frm, self.frm << 5 | self.fflags][n]
if n == 0x344:
return 0
if n == 0x744:
return 0x1800 | (8 if self.nmie else 0)
if n in (0xB00, 0xC00, 0xC01, 0xB02, 0xC02):
return self.count & M32
if n in (0xB80, 0xC80, 0xC81, 0xB82, 0xC82):
return self.count >> 32 & M32
if n in (0xF11, 0xF12, 0xF13, 0xF14, 0xF15, 0x310, 0x7A0, 0x7A1, 0x7A2):
return 0 # (no triggers: tselect stays 0, tdata1 type 0)
if n in self.csr:
return self.csr[n]
raise Trap(2)
def csr_write(self, n, v):
if n >> 10 == 3:
raise Trap(2)
if n == 0x300:
self.csr[0x300] = v & 0x88
self.fs = v >> 13 & 3
elif n in (1, 2, 3):
if not self.fs:
raise Trap(2)
if n == 1:
self.fflags = v & 31
elif n == 2:
self.frm = v & 7
else:
self.fflags, self.frm = v & 31, v >> 5 & 7
self.fs = 3
elif n == 0x304:
self.csr[0x304] = v & 0xFFFF0888
elif n in (0x305, 0x341, 0x741):
self.csr[n] = v & ~3 & M32
elif n == 0x744:
self.nmie = bool(v & 8)
elif n in self.csr:
self.csr[n] = v & M32
elif n in (0x301, 0x344, 0x310, 0x7A0, 0x7A1, 0x7A2):
pass
elif n in (0xB00, 0xB02): # the count after this instruction is v
self.count = (self.count & ~M32 | v) - 1
elif n in (0xB80, 0xB82):
self.count = (self.count & M32 | v << 32) - 1
else:
raise Trap(2)
# --------------------------------------------------------------- decode
def decode(self, pc):
ins = self.rd32(pc)
opc, rd, f3 = ins & 0x7F, ins >> 7 & 31, ins >> 12 & 7
rs1, rs2, f7 = ins >> 15 & 31, ins >> 20 & 31, ins >> 25
x = self.x
nxt = (pc + 4) & M32
immi = sx(ins >> 20, 12)
ill = Trap(2, ins)
def illegal():
raise ill
if opc == 0x37 or opc == 0x17: # lui, auipc
v = (ins & 0xFFFFF000) + (pc if opc == 0x17 else 0) & M32
if rd == 0:
return lambda: nxt
def f():
x[rd] = v
return nxt
return f
if opc == 0x6F: # jal
t = (pc + sx((ins >> 31) << 20 | (ins >> 12 & 0xFF) << 12 | (ins >> 20 & 1) << 11 |
(ins >> 21 & 0x3FF) << 1, 21)) & M32
def f():
if t & 3:
raise Trap(0, t)
if rd:
x[rd] = nxt
return t
return f
if opc == 0x67 and f3 == 0: # jalr
def f():
t = (x[rs1] + immi) & 0xFFFFFFFE
if t & 3:
raise Trap(0, t)
if rd:
x[rd] = nxt
return t
return f
if opc == 0x63 and f3 not in (2, 3): # branches
t = (pc + sx((ins >> 31) << 12 | (ins >> 7 & 1) << 11 | (ins >> 25 & 0x3F) << 5 |
(ins >> 8 & 15) << 1, 13)) & M32
cmp = [lambda a, b: a == b, lambda a, b: a != b, None, None,
lambda a, b: s32(a) < s32(b), lambda a, b: s32(a) >= s32(b),
lambda a, b: a < b, lambda a, b: a >= b][f3]
def f():
if cmp(x[rs1], x[rs2]):
if t & 3:
raise Trap(0, t)
return t
return nxt
return f
if opc == 0x03 and f3 in (0, 1, 2, 4, 5): # loads
def f():
a = (x[rs1] + immi) & M32
if f3 == 2:
if a & 3:
raise Trap(4, a)
v = self.rd32(a)
elif f3 & 3 == 1:
if a & 1:
raise Trap(4, a)
v = self.rd16(a)
if f3 == 1 and v & 0x8000:
v |= 0xFFFF0000
else:
v = self.rd8(a)
if f3 == 0 and v & 0x80:
v |= 0xFFFFFF00
if rd:
x[rd] = v
return nxt
return f
if opc == 0x23 and f3 in (0, 1, 2): # stores
imms = sx((ins >> 25) << 5 | (ins >> 7 & 31), 12)
def f():
a = (x[rs1] + imms) & M32
v = x[rs2]
if f3 == 2:
if a & 3:
raise Trap(6, a)
self.wr32(a, v)
elif f3 == 1:
if a & 1:
raise Trap(6, a)
if a >= 0xFFFFFE00:
self.wr32(a, v & 0xFFFF)
else:
self.wr16(a, v)
else:
self.wr8(a, v)
return nxt
return f
if opc == 0x13: # op-imm
sh = rs2
if (f3 == 1 and f7 != 0) or (f3 == 5 and f7 not in (0, 0x20)):
return illegal
ops = {
0: lambda a: (a + immi) & M32,
2: lambda a: int(s32(a) < immi),
3: lambda a: int(a < (immi & M32)),
4: lambda a: (a ^ immi) & M32,
6: lambda a: (a | immi) & M32,
7: lambda a: (a & immi) & M32,
1: lambda a: (a << sh) & M32,
5: (lambda a: (s32(a) >> sh) & M32) if f7 else (lambda a: a >> sh),
}
op = ops[f3]
if rd == 0:
return lambda: nxt
def f():
x[rd] = op(x[rs1])
return nxt
return f
if opc == 0x33 and f7 in (0, 0x20, 1): # op, mul/div
if f7 == 1:
op = [
lambda a, b: (a * b) & M32,
lambda a, b: (s32(a) * s32(b)) >> 32 & M32,
lambda a, b: (s32(a) * b) >> 32 & M32,
lambda a, b: (a * b) >> 32,
lambda a, b: M32 if b == 0 else (a if (a == 0x80000000 and b == M32) else
int(s32(a) / s32(b)) & M32),
lambda a, b: M32 if b == 0 else a // b,
lambda a, b: a if b == 0 else (0 if (a == 0x80000000 and b == M32) else
(s32(a) - int(s32(a) / s32(b)) * s32(b)) & M32),
lambda a, b: a if b == 0 else a % b,
][f3]
else:
if f7 == 0x20 and f3 not in (0, 5):
return illegal
op = {
(0, 0): lambda a, b: (a + b) & M32,
(0, 0x20): lambda a, b: (a - b) & M32,
(1, 0): lambda a, b: (a << (b & 31)) & M32,
(2, 0): lambda a, b: int(s32(a) < s32(b)),
(3, 0): lambda a, b: int(a < b),
(4, 0): lambda a, b: a ^ b,
(5, 0): lambda a, b: a >> (b & 31),
(5, 0x20): lambda a, b: (s32(a) >> (b & 31)) & M32,
(6, 0): lambda a, b: a | b,
(7, 0): lambda a, b: a & b,
}[(f3, f7)]
if rd == 0:
return lambda: nxt
def f():
x[rd] = op(x[rs1], x[rs2])
return nxt
return f
if opc in (0x07, 0x27, 0x43, 0x47, 0x4B, 0x4F, 0x53):
return self.decode_f(ins, pc)
if opc == 0x0F and f3 in (0, 1): # fence, fence.i
return lambda: nxt
if opc == 0x73:
if ins == 0x00000073:
def f():
raise Trap(11)
return f
if ins == 0x00100073:
def f():
raise Trap(3, pc)
return f
if ins == 0x30200073: # mret
def f():
st = self.csr[0x300]
self.csr[0x300] = (st & ~8) | (8 if st & 0x80 else 0) | 0x80
return self.csr[0x341]
return f
if ins == 0x70200073: # mnret
def f():
self.nmie = True
return self.csr[0x741]
return f
if ins == 0x10500073: # wfi
return lambda: nxt
if f3 in (1, 2, 3, 5, 6, 7):
n = ins >> 20
uimm = rs1
def f():
src = uimm if f3 & 4 else x[rs1]
write = f3 & 3 == 1 or rs1 != 0
old = self.csr_read(n)
if write:
v = src if f3 & 3 == 1 else (old | src if f3 & 3 == 2 else old & ~src)
self.csr_write(n, v & M32)
if rd:
x[rd] = old
return nxt
return f
return illegal
def decode_f(self, ins, pc):
"""The F extension: as rv32_cpu decodes it (illegal while mstatus.FS
is Off, or with a reserved rounding mode)."""
opc, rd, f3 = ins & 0x7F, ins >> 7 & 31, ins >> 12 & 7
rs1, rs2, rs3 = ins >> 15 & 31, ins >> 20 & 31, ins >> 27
x, fr = self.x, self.f
nxt = (pc + 4) & M32
ill = Trap(2, ins)
def illegal():
raise ill
if opc == 0x07 and f3 == 2: # flw
immi = sx(ins >> 20, 12)
def f():
if not self.fs:
raise ill
a = (x[rs1] + immi) & M32
if a & 3:
raise Trap(4, a)
fr[rd] = self.rd32(a)
self.fs = 3
return nxt
return f
if opc == 0x27 and f3 == 2: # fsw
imms = sx((ins >> 25) << 5 | (ins >> 7 & 31), 12)
def f():
if not self.fs:
raise ill
a = (x[rs1] + imms) & M32
if a & 3:
raise Trap(6, a)
self.wr32(a, fr[rs2])
return nxt
return f
if opc in (0x07, 0x27) or (ins >> 25) & 3:
return illegal
f5 = ins >> 27
uses_rm = opc != 0x53 or f5 in (0, 1, 2, 3, 0x0B, 0x18, 0x1A)
if opc == 0x53:
ok = (f5 <= 3 or (f5 == 0x0B and rs2 == 0) or (f5 == 4 and f3 <= 2) or
(f5 == 5 and f3 <= 1) or (f5 == 0x14 and f3 <= 2) or
(f5 in (0x18, 0x1A) and rs2 <= 1) or (f5 == 0x1C and rs2 == 0 and f3 <= 1) or
(f5 == 0x1E and rs2 == 0 and f3 == 0))
if not ok:
return illegal
to_int = opc == 0x53 and f5 in (0x18, 0x1C, 0x14)
from_int = opc == 0x53 and f5 in (0x1A, 0x1E)
def f():
if not self.fs:
raise ill
rm = self.frm if f3 == 7 else f3
if uses_rm and rm > 4:
raise ill
a = x[rs1] if from_int else fr[rs1]
r, fl, _ = f32.execute(ins, rm, a, fr[rs2], fr[rs3])
self.fflags |= fl
self.fs = 3
if to_int:
if rd:
x[rd] = r
else:
fr[rd] = r
return nxt
return f
# ------------------------------------------------------------------ run
def trap(self, cause, tval):
self.csr[0x341] = self.pc
self.csr[0x342] = cause
self.csr[0x343] = tval & M32
st = self.csr[0x300]
self.csr[0x300] = (st & ~0x88) | (0x80 if st & 8 else 0)
self.pc = self.csr[0x305]
def enter_nmi(self):
self.csr[0x741] = self.pc
self.csr[0x742] = 0x80000000
self.nmie = False
self.stepped = False
self.pc = MON_BASE
def step(self):
"""One instruction (or the NMI before it)."""
if self.nmie:
hit = self.bp_on & 1 and self.pc == self.bp[0] and 4 or \
self.bp_on & 2 and self.pc == self.bp[1] and 5
if self.nmi_pending or hit or (self.step_arm and self.stepped):
self.why = self.why_r if self.nmi_pending else hit or 3
self.nmi_pending = self.step_arm = False
self.enter_nmi()
return
f = self.cache.get(self.pc)
if f is None:
f = self.cache[self.pc] = self.decode(self.pc)
pc = self.pc
try:
self.pc = f()
except Trap as t:
self.trap(t.cause, t.tval)
self.cycles += 3
return
self.count += 1
self.cycles += self.cost(pc)
if self.nmie:
self.stepped = True
def cost(self, pc):
"""Clocks rv32_cpu takes for the instruction at pc, just run: 2, or 3
for a load, store, jump or taken branch (4 for I/O), 4 for a multiply,
35 for a divide; floating point as listed in rv32_cpu.v (the shortcut
for infinite, NaN and zero operands isn't counted)."""
ins = self.rd32(pc)
op = ins & 0x7F
if op in (0x07, 0x27):
return 3
if op in (0x43, 0x47, 0x4B, 0x4F):
return 12
if op == 0x53:
f5 = ins >> 27
return {0: 12, 1: 12, 2: 12, 3: 36, 0x0B: 36, 0x18: 5, 0x1A: 8}.get(f5, 4)
if op in (0x03, 0x23):
a = (self.x[ins >> 15 & 31] + sx(ins >> 20 if op == 3 else (ins >> 25) << 5 | (ins >> 7 & 31), 12)) & M32
return 4 if a >= 0xFFFFFE00 or MON_RAM <= a < MON_END else 3
if op in (0x6F, 0x67) or (op == 0x63 and self.pc != (pc + 4) & M32):
return 3
if op == 0x33 and ins >> 25 == 1:
return 35 if ins >> 14 & 1 else 4
if op == 0x0F and ins >> 12 & 7 == 1:
return 3
return 2
def nmi(self, why=1):
"""The Pause key."""
if not self.nmi_pending and not self.in_monitor():
self.nmi_pending, self.why_r = True, why
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("image")
ap.add_argument("--input", default=None)
ap.add_argument("--max", type=int, default=10_000_000)
ap.add_argument("--trace", default=None)
a = ap.parse_args()
inp = open(a.input, "rb").read() if a.input else b""
cpu = RV32(open(a.image, "rb").read(), inp=inp)
tr = open(a.trace, "w") if a.trace else None
for _ in range(a.max):
if tr:
tr.write("%08x %08x\n" % (cpu.pc, cpu.rd32(cpu.pc)))
cpu.step()
if cpu.out:
sys.stdout.buffer.write(bytes(cpu.out))
cpu.out.clear()
sys.stdout.flush()
if __name__ == "__main__":
main()