SkyTemple / py-desmume

Python Library and GUI for DeSmuME, the Nintendo DS emulator
GNU General Public License v3.0
24 stars 5 forks source link

`emulator.memory.get_next_instruction()` function return value not what is expected #28

Closed mike8699 closed 2 years ago

mike8699 commented 2 years ago

The desmume.emulator.memory.get_next_instruction() function doesn't seem to behave the way the docs specify it should. The docs say that it "(r)eturns the next instruction to be executed by the ARM9 processor", but that doesn't appear to the case. Here's a sample program demonstrating this:

from desmume.emulator import DeSmuME

e = DeSmuME()
e.open('base/out/out.nds')

def callback(address: int, size: int):
    print(f'get_next_instruction(): {hex(e.memory.get_next_instruction())}')
    print(f'register_arm9.pc: {hex(e.memory.register_arm9.pc)}')

e.memory.register_exec(0x2058954, callback)

for _ in range(500):
    e.cycle()

Output:

get_next_instruction(): 0x2058958
register_arm9.pc: 0x205895c

I've also printed out the contents of the program counter register to compare. As you can see, the value returned by get_next_instruction is 4 bytes less than that of the program counter. So, it seems that the get_next_instruction function actually returns the memory address of the most recently executed instruction.

I'm happy to contribute a PR that corrects this behavior if that would help. From what I can tell, the solution is to either a) Change get_next_instruction() to a name more appropriate for its actual functionality, or b) Modify get_next_instruction() to actually return the bytecode for the next ARM instruction.

Any thoughts @theCapypara? The ROM used in that sample code is Zelda: Phantom Hourglass US, if you'd like to confirm for yourself.

theCapypara commented 2 years ago

No, this is correct. The PC is always (?) 4 bytes ahead on the next instruction that is being executed. I don't know/remember the details but this is a weird ARM quirk

theCapypara commented 2 years ago

https://stackoverflow.com/questions/24091566/why-does-the-arm-pc-register-point-to-the-instruction-after-the-next-one-to-be-e

mike8699 commented 2 years ago

Wow, interesting. TIL