r/ReverseEngineering • • 13h ago

Solved compiling NES Games as CPP and Running them natively. Statically converts 6502 to CPP using static analysis and then compiles code, watches the trace as the user plays the game, and dynamically adds instructions as they are discovered which are then recompiled the next pass.

https://github.com/jasonbrianhall/nes2cpp
36 Upvotes

6 comments sorted by

5

u/walmartbonerpills 12h ago

Interesting. How does it handle all the different mappers

4

u/jasonbrianhall 12h ago

It has full mapper logic for each supported mapper and correctly handles bank switching. On the first compile it does static analysis of the PRG banks and generates native C++ for the code it can reach, while falling back to a built-in 6502 interpreter for anything it hasn’t discovered yet. When the game performs a bank switch or an indirect jump into unknown code, the interpreter logs those paths to a trace file so the next rebuild can translate them into native code, which then becomes native code, instead of interpreted. It currently only supports a limited set of mappers but that covers like 90% of all NES games. I put a video of it compiling Contra and running it.

5

u/tetyys 8h ago

watches the trace as the user plays the game, and dynamically adds instructions as they are discovered which are then recompiled the next pass.

thats called JIT compilation

-2

u/jasonbrianhall 3h ago edited 3h ago

No it's not. JIT recompiles as its ran. This writes the instructions to a trace file and then when it's recompiled, those become permanently static. Their is no jit engine. It's not Java. The next pass is GCC, not internally like Java. I never once said it was a JIT, I said it statically recompiled dynamically discovered 6502 code. When I said adds instructions as they are discovered, it was to a trace file so that it knows which ones are are code and which ones are data.

3

u/nothingtoseehr 1h ago

Uuuh that's not what determines a JIT. It has nothing to do with Java or GCC. You're perfectly describing a JIT, QEMU works the exact same way you're describing

Fully static decompilation of a 6502 is impossible, because compiling a "trace file" is by definition not static. It's a JIT on unknown/untranslated code, and that's perfectly OK, it's a perfectly valid technique

2

u/AlAccountNamesRTaken 43m ago

I think the sticking point is that the asm generation isn't live like it is on a typical JIT, it's closer to AOT with a dynamic pass on it.