---
title: "Project: a RISC-V emulator"
heading: Decoding and running machine code in Python
eyebrow: C8 · Lesson 53 · Project
xp: 80
---

::: hook
An emulator is a program that behaves like a processor: it fetches machine-code words, decodes them and carries out each one on registers and memory kept in ordinary variables. Emulators run old game consoles, test firmware before the hardware exists, and check new chip designs instruction by instruction. The board in this course is one, written in JavaScript. In this project you'll write your own in Python, for a subset of RV32I big enough to run loops, arrays and function calls, and run real machine code on it: the words below were produced by the course's assembler from the programs shown.
:::

::: play
- This program adds 1 to 10. Step it and note the machine-code word beside each instruction: those words, and nothing else, are what your emulator will be given.
- The `bne` at address 0x14 is 0xFE629CE3. Its immediate, scattered across the word, decodes to −8: back two instructions, to `loop` at 0x0C.
- When it reaches `ebreak`, a0 = 55. Your emulator must get the same.
:::
:::

```sim cpu
.text
    li a0, 0            # 0x00000513
    li t0, 1            # 0x00100293
    li t1, 11           # 0x00B00313
loop:
    add a0, a0, t0      # 0x00550533
    addi t0, t0, 1      # 0x00128293
    bne t0, t1, loop    # 0xFE629CE3
    ebreak              # 0x00100073
view: datapath
show: a0, t0, t1
speed: 3
```

::: predict
## The branch word 0xFE629CE3 has its sign bit (bit 31) set. What does that tell you before decoding anything else?

- [ ] It's an illegal instruction
- [x] Its offset is negative: it jumps backward
- [ ] It compares signed numbers
- [ ] It's always taken

::: reveal
The offset is negative. Every RISC-V format keeps the immediate's sign in bit 31, so a decoder can sign-extend before it has sorted out where the other immediate bits live. Backward branches are almost always loops.
:::
:::

::: nameit
## What the emulator keeps

- `x`, a list of 32 registers holding signed 32-bit values, with x[0] always 0 (skip any write to it).
- `pc`, starting at 0. Instructions are `words[pc // 4]`.
- `mem`, a dictionary from byte address to a 32-bit word, for word loads and stores only.

## The cycle

Fetch `words[pc // 4]`. Stop at `ebreak` (0x00100073). Otherwise decode, execute, write rd if the instruction has a result and rd isn't 0, and set pc to pc + 4 or the jump target.

## Decoding

| Field | Bits | Python |
|---|---|---|
| opcode | 6:0 | `w & 0x7f` |
| rd | 11:7 | `(w >> 7) & 31` |
| funct3 | 14:12 | `(w >> 12) & 7` |
| rs1 | 19:15 | `(w >> 15) & 31` |
| rs2 | 24:20 | `(w >> 20) & 31` |
| funct7 | 31:25 | `w >> 25` |

Immediates, sign-extended from their top bit:

| Opcode | Format | Immediate |
|---|---|---|
| 0x13, 0x03, 0x67 | I | bits 31:20 (12 bits) |
| 0x23 | S | bits 31:25 then 11:7 (12 bits) |
| 0x63 | B | bit 31 → 12, bit 7 → 11, bits 30:25 → 10:5, bits 11:8 → 4:1, bit 0 is 0 (13 bits) |
| 0x37 | U | bits 31:12 in place, low 12 bits 0 |
| 0x6F | J | bit 31 → 20, bits 19:12 in place, bit 20 → 11, bits 30:21 → 10:1 (21 bits) |

To sign-extend an n-bit value v: if bit n − 1 is set, subtract $2^n$.

## The subset

R-type (0x33): `add`, `sub`, `xor`, `or`, `and`, `slt`. I-type (0x13): `addi`, `xori`, `ori`, `andi`, `slti`, `slli`, `srli`. `lui` (0x37), `lw` (0x03, funct3 2), `sw` (0x23, funct3 2), branches (0x63: `beq` 0, `bne` 1, `blt` 4, `bge` 5), `jal` (0x6F) and `jalr` (0x67). Wrap every result to 32 bits.
:::

::: example
## Decode 0x00812503.

::: solution
1. **Opcode.** 0x03: a load.
2. **Registers and width.** rd = 10 (a0), funct3 = 2 (a word), rs1 = 2 (sp).
3. **The immediate.** The I immediate is bits 31:20 = 8.

**Answer:** 0x00812503 is `lw a0, 8(sp)`.
:::
:::

::: example
## Decode the branch 0xFE629CE3's immediate.

::: solution
1. **Bit 31.** Bit 31 = 1 gives imm[12], worth 4096.
2. **Bit 7.** Bit 7 = 1 gives imm[11], worth 2048.
3. **Bits 30:25.** 111111 gives imm[10:5], worth 2016.
4. **Bits 11:8.** 1100 gives imm[4:1], worth 24, and imm[0] is always 0.
5. **Add them.**
   $$\begin{aligned} &4096 + 2048 + 2016 + 24 \\ &= 8184 \end{aligned}$$
6. **Sign-extend.** The top bit of the 13-bit value is set, so it means
   $$8184 - 8192 = -8$$

**Answer:** −8, a branch from the `bne` at 0x14 back to `loop` at 0x0C.
:::
:::

::: check
given: w = 4287956243 | 2147483667 | 4294083219 | 4278255891
answer: floor(w/2^20) - 4096*step(floor(w/2^20) - 2047.5)
tolerance: 0

## What sign-extended I immediate does the `addi` word {w:hex8} hold?

::: right
Right. Bits 31:20, sign-extended: {answer}.
:::

::: misses
- [floor(w/2^20)] Sign-extend: when bit 31 is set the immediate is negative.
- [any] Not yet. Shift right by 20, then subtract 4096 if the top bit is set.
:::
:::

::: check
given: p = 20 | 64 | 200 | 1024
answer: p/4
tolerance: 0

## The emulator's pc is {p:hex4}. Which index of the `words` list holds the instruction to fetch?

::: right
Right. pc // 4 = {answer}.
:::

::: misses
- [p] Instructions are 4 bytes apart, so divide the address by 4.
- [any] Not yet. pc // 4.
:::
:::

::: check
kind: python

## Write `decode(w)`, returning a dictionary with keys `op`, `rd`, `f3`, `rs1`, `rs2`, `f7` and `imm`, where `imm` is the sign-extended immediate for the I, S, B, U and J formats (opcodes above) and 0 for R-type.

```python starter
def decode(w):
    return {'op': w & 0x7f, 'rd': 0, 'f3': 0, 'rs1': 0, 'rs2': 0, 'f7': 0, 'imm': 0}
```

```python solution
def sx(v, bits):
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

def decode(w):
    op, rd, f3 = w & 0x7f, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op in (0x13, 0x03, 0x67):
        imm = sx(w >> 20, 12)
    elif op == 0x23:
        imm = sx(((w >> 25) << 5) | ((w >> 7) & 31), 12)
    elif op == 0x63:
        imm = sx(((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 0x3f) << 5) | (((w >> 8) & 0xf) << 1), 13)
    elif op == 0x37:
        imm = sx(w & 0xfffff000, 32)
    elif op == 0x6f:
        imm = sx(((w >> 31) << 20) | (((w >> 12) & 0xff) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 0x3ff) << 1), 21)
    else:
        imm = 0
    return {'op': op, 'rd': rd, 'f3': f3, 'rs1': rs1, 'rs2': rs2, 'f7': f7, 'imm': imm}
```

```python tests
d = decode(0x00812503)
assert (d['op'], d['rd'], d['f3'], d['rs1'], d['imm']) == (0x03, 10, 2, 2, 8), f"0x00812503 is lw a0, 8(sp); got {d}."
d = decode(0x40a005b3)
assert (d['op'], d['rd'], d['rs1'], d['rs2'], d['f7']) == (0x33, 11, 0, 10, 0x20), f"0x40A005B3 is sub a1, zero, a0; got {d}."
assert decode(0xff950513)['imm'] == -7, "addi a0, a0, -7 has immediate -7: sign-extend the I immediate."
assert decode(0x04a2a023)['imm'] == 64, "sw a0, 64(t0): the S immediate is split between bits 31:25 and 11:7."
assert decode(0xfe629ce3)['imm'] == -8, "The bne in the sum program branches back 8 bytes, from 0x14 to 0x0C."
assert decode(0xfe0316e3)['imm'] == -20, "bnez t1, loop in the array program branches back 20 bytes."
assert decode(0x018000ef)['imm'] == 24, "jal ra, square jumps forward 24 bytes."
assert decode(0xff5ff06f)['imm'] == -12, "j again jumps back 12 bytes: the J immediate."
assert decode(0x12345537)['imm'] == 0x12345000, "lui a0, 0x12345: the U immediate keeps bits 31:12 in place."
```

::: right
Right. The scrambled B and J immediates are the fiddly part, and now they're done.
:::
:::

::: check
kind: python

## Write `run(words, limit=10000)` for registers only: the R-type and I-type arithmetic instructions, `lui` and the four branches, stopping at `ebreak` and returning the list of 32 registers. (Include your `decode`, or decode inside `run`.)

```python starter
def run(words, limit=10000):
    return [0] * 32
```

```python solution
def sx(v, bits):
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

def decode(w):
    op, rd, f3 = w & 0x7f, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op == 0x13:
        imm = sx(w >> 20, 12)
    elif op == 0x63:
        imm = sx(((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 0x3f) << 5) | (((w >> 8) & 0xf) << 1), 13)
    elif op == 0x37:
        imm = sx(w & 0xfffff000, 32)
    else:
        imm = 0
    return op, rd, f3, rs1, rs2, f7, imm

def run(words, limit=10000):
    x = [0] * 32
    pc = 0
    for _ in range(limit):
        w = words[pc // 4]
        if w == 0x00100073:
            return x
        op, rd, f3, rs1, rs2, f7, imm = decode(w)
        a, b, nxt, v = x[rs1], x[rs2], pc + 4, None
        if op == 0x33:
            v = {(0, 0): a + b, (0, 0x20): a - b, (4, 0): a ^ b, (6, 0): a | b, (7, 0): a & b, (2, 0): int(a < b)}[(f3, f7)]
        elif op == 0x13:
            v = {0: a + imm, 4: a ^ imm, 6: a | imm, 7: a & imm, 2: int(a < imm), 1: a << (imm & 31), 5: (a & 0xffffffff) >> (imm & 31)}[f3]
        elif op == 0x37:
            v = imm
        elif op == 0x63:
            if {0: a == b, 1: a != b, 4: a < b, 5: a >= b}[f3]:
                nxt = pc + imm
        if v is not None and rd != 0:
            x[rd] = sx(v, 32)
        pc = nxt
    raise RuntimeError('no ebreak within the limit')
```

```python tests
sum_prog = [0x00000513, 0x00100293, 0x00b00313, 0x00550533, 0x00128293, 0xfe629ce3, 0x00100073]
r = run(sum_prog)
assert r[10] == 55, f"The sum program should leave 55 in a0 (x10), got {r[10]}."
count = [0x06400513, 0x00000593, 0xff950513, 0x00158593, 0xfe055ce3, 0x00100073]
r = run(count)
assert (r[10], r[11]) == (-5, 15), f"Subtracting 7 from 100 until it goes negative: a0 = -5 after 15 passes; got a0 = {r[10]}, a1 = {r[11]}."
big = [0x12345537, 0x67850513, 0x40a005b3, 0x00a5a633, 0x00a546b3, 0x00100073]
r = run(big)
assert r[10] == 0x12345678, f"lui then addi should build 0x12345678 in a0, got {hex(r[10])}."
assert r[11] == -0x12345678, f"sub a1, zero, a0 should give -0x12345678, got {r[11]}."
assert (r[12], r[13]) == (1, 0), f"slt a2, a1, a0 should be 1 and xor a3, a0, a0 should be 0; got {r[12]}, {r[13]}."
assert r[0] == 0, "x0 must stay 0."
```

::: right
Right. That's a working processor for straight-line code and loops.
:::
:::

::: check
kind: python

## Write `run(words, mem, limit=10000)` for the whole subset: add `lw`, `sw` (word-aligned, with `mem` a dictionary from byte address to word, missing addresses reading as 0), `jal` and `jalr`. Return the registers; `mem` is changed in place.

```python starter
def run(words, mem, limit=10000):
    return [0] * 32
```

```python solution
def sx(v, bits):
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

def decode(w):
    op, rd, f3 = w & 0x7f, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op in (0x13, 0x03, 0x67):
        imm = sx(w >> 20, 12)
    elif op == 0x23:
        imm = sx(((w >> 25) << 5) | ((w >> 7) & 31), 12)
    elif op == 0x63:
        imm = sx(((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 0x3f) << 5) | (((w >> 8) & 0xf) << 1), 13)
    elif op == 0x37:
        imm = sx(w & 0xfffff000, 32)
    elif op == 0x6f:
        imm = sx(((w >> 31) << 20) | (((w >> 12) & 0xff) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 0x3ff) << 1), 21)
    else:
        imm = 0
    return op, rd, f3, rs1, rs2, f7, imm

def run(words, mem, limit=10000):
    x = [0] * 32
    pc = 0
    for _ in range(limit):
        w = words[pc // 4]
        if w == 0x00100073:
            return x
        op, rd, f3, rs1, rs2, f7, imm = decode(w)
        a, b, nxt, v = x[rs1], x[rs2], pc + 4, None
        if op == 0x33:
            v = {(0, 0): a + b, (0, 0x20): a - b, (4, 0): a ^ b, (6, 0): a | b, (7, 0): a & b, (2, 0): int(a < b)}[(f3, f7)]
        elif op == 0x13:
            v = {0: a + imm, 4: a ^ imm, 6: a | imm, 7: a & imm, 2: int(a < imm), 1: a << (imm & 31), 5: (a & 0xffffffff) >> (imm & 31)}[f3]
        elif op == 0x37:
            v = imm
        elif op == 0x03:
            v = mem.get(a + imm, 0)
        elif op == 0x23:
            mem[a + imm] = b
        elif op == 0x63:
            if {0: a == b, 1: a != b, 4: a < b, 5: a >= b}[f3]:
                nxt = pc + imm
        elif op == 0x6f:
            v, nxt = pc + 4, pc + imm
        elif op == 0x67:
            v, nxt = pc + 4, (a + imm) & ~1
        if v is not None and rd != 0:
            x[rd] = sx(v, 32)
        pc = nxt
    raise RuntimeError('no ebreak within the limit')
```

```python tests
arr = [0x10000293, 0x00400313, 0x00000513, 0x0002a383, 0x00750533, 0x04a2a023, 0x00428293, 0xfff30313, 0xfe0316e3, 0x00100073]
m = {0x100: 5, 0x104: 10, 0x108: -3, 0x10c: 20}
r = run(arr, m)
assert r[10] == 32, f"The array program sums 5, 10, -3 and 20 into a0: 32, got {r[10]}."
assert [m.get(0x140 + 4 * k) for k in range(4)] == [5, 15, 12, 32], f"It stores the running sums at 0x140 to 0x14C; got {[m.get(0x140 + 4 * k) for k in range(4)]}."
call = [0x00600513, 0x018000ef, 0x00050413, 0x00900513, 0x00c000ef, 0x00850533, 0x00100073, 0x00050293,
        0x00000313, 0x00000393, 0x00538863, 0x00a30333, 0x00138393, 0xff5ff06f, 0x00030513, 0x00008067]
r = run(call, {})
assert (r[10], r[8]) == (117, 36), f"Calling square(6) and square(9) and adding should give a0 = 117 with s0 = 36; got a0 = {r[10]}, s0 = {r[8]}."
assert r[1] == 0x14, f"ra should hold 0x14, the return address of the second call; got {hex(r[1])}."
```

::: right
Right. Loops, memory and function calls all run on your emulator, from nothing but the machine code.
:::
:::

::: explain
## How does `jal` followed later by `jalr zero, 0(ra)` make a function call and return work, in terms of what the emulator does?

::: model
`jal ra, square` does two things in one instruction: it writes pc + 4, the address of the instruction after the call, into ra, and it sets the pc to the function's address. The function runs, and its last instruction, `jalr zero, 0(ra)`, sets the pc to the value in ra (plus 0), while writing its own return address into x0, where it's thrown away. So the pc comes back to just after the call. Because the return address lives in a register, a function that calls another must save ra first, or the second `jal` overwrites it.
:::
:::

::: practice

::: check
given: v = 2048 | 4095 | 3000 | 100
answer: v - 4096*step(v - 2047.5)
tolerance: 0

## Sign-extend the 12-bit field value {v}.

::: misses
- [any] Subtract 4096 if bit 11 is set.
:::
:::

::: check
given: p = 8 | 40 | 200
answer: p + 4
base: 16
width: 4

## A `jal ra, f` at address {p:hex4} runs. What does ra hold?

::: misses
- [any] pc + 4.
:::
:::

::: check
given: w = 1048851 | 5244179 | 10486419
answer: floor(w/128) - 32*floor(w/4096)
tolerance: 0

## What does `(w >> 7) & 31` give for {w:hex8}?

::: misses
- [any] The rd field, bits 11:7.
:::
:::
:::
