180. JMP 的间接寻址

为 JMP 添加间接寻址。

180 / 356 · tests/chapter_01_cpu/test_180_indirect_addressing_for_jmp.py

在 emulator/cpu/addressing_modes.py 内创建一个函数:

def indirect(cpu):
    ...

这一步存在的原因

JMP 需要这种特殊的寻址模式,才能从 `JMP ($hhhh)` 所编码的 16 位指针中解析出间接目标地址。

学习提示

这与 indirect_x(cpu) 和 indirect_y(cpu) 不同。

JMP 间接寻址将一个 16 位操作数用作指向内存任意位置的指针

JMP ($0200)

分步说明

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.

重要的硬件缺陷

6502 存在 JMP 间接寻址的跨页边界缺陷。

如果指针以 $FF 结尾,高字节会从同一页中读取,而不是从下一页读取:

JMP ($02FF)

真实 CPU 的读取方式

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

它不会从 $0300 读取高字节。

实现思路参考

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)

运行本课

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