180. Indirect addressing for jmp

Add Indirect addressing for JMP.

Lesson 180 of 356 · tests/chapter_01_cpu/test_180_indirect_addressing_for_jmp.py

Create one function inside emulator/cpu/addressing_modes.py:

def indirect(cpu):
    ...

Why this step exists

JMP needs this special addressing mode to resolve an indirect target from the 16-bit pointer encoded by `JMP ($hhhh)`.

Student guidance

This is different from indirect_x(cpu) and indirect_y(cpu).

JMP indirect uses a 16-bit operand as a pointer anywhere in memory

JMP ($0200)

Step by step

1. Fetch the 16-bit pointer operand from the instruction stream.
   Example bytes: 00 02 -> pointer address $0200.

2. Read the low byte of the target from memory[pointer].
   Example: memory[$0200] = $34.

3. Read the high byte of the target from memory[pointer + 1].
   Example: memory[$0201] = $12.

4. Return the final target address.
   Example: $1234.

Important hardware bug

The 6502 has a JMP indirect page-boundary bug.

If the pointer ends in $FF, the high byte is read from the same page instead of the next page:

JMP ($02FF)

Real CPU reads

low  = memory[$02FF]
high = memory[$0200]

It does NOT read high from $0300.

Useful implementation shape

ptr = cpu.fetch_word()
low = cpu.bus.read(ptr)
high_addr = (ptr & 0xFF00) | ((ptr + 1) & 0x00FF)
high = cpu.bus.read(high_addr)
return low | (high << 8)

Run this lesson

uv run pytest tests/chapter_01_cpu/test_180_indirect_addressing_for_jmp.py -v