Porting Pokémon FireRed to PC, and Proving It Still Matches the GBA

How a native Linux and Windows port of Pokémon FireRed was built from the pret decompilation on a clean-room virtual GBA, and verified frame by frame against the real GBA build over the whole game. Directed by me, implemented with Claude Code.

18 min read · c · game-porting · gba · differential-testing · claude-code

In short: FireRed's decompiled C code now runs natively on Linux and Windows, with no CPU emulation. It is played from New Game to the post-game by recorded input and matches the GBA build of the same code at every step: frames, random numbers, sound output and save files. Claude Code wrote almost all of the code; I set the direction and made the calls. For the overview and the key decisions, see the case study. This article is the engineering.

The pret project decompiled Pokémon FireRed into C that builds a byte-for-byte copy of the original ROM. Emerald, its sibling, already has several native PC ports. FireRed had none that was playable. I wanted one, as a faithful base for Nuzlocke runs, a randomizer and, later, Soul Link online with friends.

Getting the game to run turned out to be the easy half. Getting it to run correctly, and knowing that it does, was the project.

Three ways to get a port that only looks right

Before any code, the planning phase measured the tree. 277 of the 283 C files compiled for x86-64 unchanged; the rest were ARM inline assembly and one save-size assert. The game is single-threaded and blocks in exactly one place per frame. On paper, it's a very portable codebase.

Three things make it treacherous anyway, and each produces a binary that appears to work:

  1. 32-bit data on a 64-bit machine. The game stores pointers in 4-byte words all over its data and scripts, and casts between pointers and integers in 543 places.
  2. Frame timing. The GBA sometimes runs late, and the random number generator is called from the frame interrupt. Get the timing slightly wrong and the game still plays, just not the same game.
  3. The graphics and sound hardware. Mid-frame register changes, windows, blending, affine sprites and a sound mixer written in ARM assembly all have to be reproduced exactly.

So the rule from day one was that nothing counts as working until it matches the real GBA build.

The shape of the port

The game's C code is compiled natively with -DPORTABLE. It keeps doing what it does on the GBA: writing hardware registers, video memory, sprite tables and palettes. Natively those are plain arrays, and behind them sits a small virtual GBA written from the GBATEK hardware documentation:

  • a scanline renderer (windows, colour effects, affine and double-size sprites, the OBJ window, mosaic, affine backgrounds, the per-line sprite cycle budget);
  • DMA, timers and interrupts;
  • the twelve BIOS calls FireRed uses;
  • a flash chip backed by a 128 KiB file;
  • the sound hardware (more below).

A rule kept this layer clean: platform/core/ never includes an SDL or OS header. The game talks to it only through the GBA-shaped interface it already uses. The front-ends, an SDL3 window and a headless test runner, own everything else.

The frame driver is the heart of it. The GBA game loop runs its logic, then waits for the vertical blank. Natively, that wait is where the hardware gets to run:

  1. Game logic runs as if inside VBlank, at scanline 161.
  2. When the game waits for the next frame, the driver steps scanlines 162–227 and then 0–159. It renders each line with the registers as they are at that moment, and runs the HBlank DMAs and interrupts in between.
  3. At line 160 it runs the VBlank DMAs and the game's own VBlank handler, advances the timers, and hands the frame to the front-end.
One frame of 228 lines, to scale: lines 0 to 159 are visible and drawn one at a time, lines 160 to 227 are VBlank. Zoomed in: at line 160 the VBlank DMAs, the game's VBlank handler and the timers run and the frame goes to the screen; at line 161 the game's logic runs and then waits; the driver then steps lines 162 to 227 and 0 to 159, drawing each visible line.0160227visible lines 0–159VBlank 160–227line 160VBlank DMAs and handler,timers, frame to the screen→line 161the game's logic runs,then waits for VBlank→lines 162–227, 0–159stepped by the driver;visible lines drawn one by one
Fig. 1 · One frame in the port's frame driver: the full 228 lines to scale, and the start of VBlank zoomed in. Registers are read line by line, so mid-frame effects come out right.

The core of it is short. This is the frame loop from platform/core/frame.c, trimmed, with a few comments added:

static void RunFrame(void)
{
    int line = sNextLine;

    for (;;)
    {
        if (line == VBLANK_LINE)
        {
            // VBlank DMAs start with VBlank, before the IRQ handler runs.
            REG_VCOUNT = line;
            Platform_RunDmas(DMA_START_VBLANK);
            BeginLine(line);   // sets VCOUNT/DISPSTAT, raises the VBlank IRQ
            HBlank(line);
            break;
        }
        RunLine(line);         // BeginLine, PPU_RenderLine if visible, HBlank
        line = (line + 1) % PLATFORM_TOTAL_LINES;
    }

    gPlatformFrameCount++;
    BeginLine(LOGIC_LINE);     // the game's logic runs "during" line 161
    sNextLine = LOGIC_LINE + 1;
    Platform_AdvanceTimers(PLATFORM_CYCLES_PER_FRAME);
    host_frame_hook(gPlatformFramebuffer);
    Platform_UpdateKeypad();
}

Because register state is sampled per scanline, effects that change registers mid-frame (the intro, battle transitions) come out right without the game knowing it isn't on hardware.

The plan was to change as little game code as possible. Every edit to a pret file sits behind #ifdef PORTABLE, has a row in a ledger of upstream modifications, and is checked by a guard that rebuilds the GBA ROM and compares the hashes of all 649 object files. The GBA build has stayed byte-identical through the whole project.

32-bit addresses on a 64-bit machine

The first trap shows up before anything runs. In the GNU assembler, .word means 4 bytes on ARM and 2 bytes on x86. Assembled tables that C reads as structs silently change shape: a MapHeader is 28 bytes on the GBA and 48 natively. The assembler even parses macro arguments differently, so five lines in the Celadon Game Corner's coin scripts failed with "too many positional arguments" until they got parentheses:

goto_if_ge VAR_TEMP_1, ((MAX_COINS + 1) - 500), CeladonCity_GameCorner_EventScript_ClerkNoRoomForCoins

The bigger question was what to do about pointers. The Emerald ports took different routes. One widened the script bytecode to 8-byte pointers and needed 766 hand edits to the offsets, with regressions to match. The port takes a different line:

  • Keep 32-bit addresses valid. The executable is linked non-PIE and loaded below 4 GiB, so a pointer still fits in the game's 4-byte words. A relocation checker fails the build on any 8- or 16-bit relocation. On Windows the image is linked at 0x10000000 with a fixed base, and a startup check refuses to run if it ends up higher.
  • Bytecode stays 4 bytes. Map scripts, battle scripts and animation scripts are unchanged.
  • Only tables that C reads as structs widen, through a ptr macro in the assembler macros. It is .4byte on the GBA and .8byte natively, so the GBA objects don't change:
	.macro ptr values:vararg
	.ifdef PORTABLE
	.8byte \values
	.else
	.4byte \values
	.endif
	.endm
  • Every pointer/integer cast is checked. This came from pokeemerald-wasm, which I had Claude add to the research survey. At build time a clang-AST pass rewrites each cast in the preprocessed game code into PortPtrToWord or PortWordToPtr. The first fails if an address doesn't fit in 32 bits, the second unless the word is zero or points inside the image. A failure aborts with the frame and the caller. In normal play none has fired; the fuzzer tripped one, in a battle animation that rebuilds an address from two 16-bit halves. The checks cost nothing measurable, so they stay on in every build.
  • Layouts are checked, not trusted. A layout checker reads the C types from DWARF debug info, walks every C-declared symbol defined in the assembled data, follows pointer fields through relocations, and fails on any wrong stride, size or pointer slot.

The rewriter means the game's central pointer macros didn't need hand edits at all: after preprocessing they are just casts, and the pass wraps them.

The helpers themselves are a compare and an unlikely branch:

static inline void *PortWordToPtr(uint32_t word)
{
    uintptr_t v = word;

    if (PORT_PTRWORD_CHECKS && v != 0
     && __builtin_expect(v < (uintptr_t)PORT_IMAGE_START || v >= (uintptr_t)PORT_IMAGE_END, 0))
        Platform_PtrWordFail("word is not an address in the image", v);
    return (void *)v;
}

One of the rewriter's test cases shows why the checks earn their keep. Some task code stores a pointer as two 16-bit halves and joins them later. The pass turns this:

d[0] = (u32)p; d[1] = (u32)p >> 16;
return (void *)(d[0] | (d[1] << 16));

into this:

d[0] = (u32)PortPtrToWord(p); d[1] = (u32)PortPtrToWord(p) >> 16;
return (void *)PortWordToPtr((d[0] | (d[1] << 16)));

If a half is a signed s16, the join sign-extends and produces an address outside the image. Natively that is an abort with the frame number, not a mystery crash three screens later. That is the class of bug the fuzzer found, in a battle animation.

The oracle

Every claim of correctness in this project comes from one comparison. The oracle is the GBA ROM built from the same commit and flags as the native build, run headless in libmgba, the mGBA emulator's core library. A same-source oracle separates porting bugs from pret's intentional bug fixes, which a retail ROM would mix in.

Both sides take the same recorded input and report on it:

  • Golden checkpoints compare frames pixel for pixel in the GBA's 15-bit colour at named moments. 1,295 of them cover the full-game run.
  • Semantic checkpoints compare game state by memory: party, bag, money, flags, location, PC boxes, the RNG. The oracle reads by symbol name and DWARF offset, so differences in struct layout don't matter.
  • Iteration traces compare every game-loop iteration: frame counters, the RNG value, how many times key functions were called.

The oracle is only ever compared against. The project rule was clean room: hardware behaviour comes from GBATEK, never from reading emulator source. When GBATEK is silent, the oracle is measured and the port matches it. That's how the renderer learned that darkening rounds red differently from green and blue, and that ObjAffineSet rounds negative products toward zero. That detail was measured on 33 of 33 matrices, and it's why the Poké Ball's rotation in battle came out right.

Lag: where the random numbers go

The GBA doesn't always finish its logic within one frame. Over the first three minutes of play it runs late on 0.87 % of frames, all of them during scene loads. When it does, the VBlank interrupt fires in the middle of the logic, and the game's VBlank handler calls Random().

Natively, the logic never runs late. So after the first slow map load, the port's RNG was a few calls behind, and wandering NPCs walked somewhere else. The game was fine. It just wasn't the same game.

One long game-logic iteration with four Random() calls. On the GBA the VBlank interrupt, which also calls Random(), fires between the second and third call. Natively without a trace it runs after the logic, so the random numbers come out in a different order. With the lag trace it runs just before the third call, as on the GBA.GBAR1R2R3R4VBlankNative, no traceR1R2R3R4VBlankNative, lag traceR1R2R3R4VBlank
Fig. 2 · One logic iteration with four Random() calls (R1–R4). The VBlank handler calls Random() too, so where it lands decides every number after it.

The fix is a lag trace. The oracle records, for every lag VBlank, how far the logic had got when it fired, counted in "marker" calls. Natively, the frame driver runs that VBlank just before the matching marker call. The trace grew a version at a time, as each new case appeared:

  • Markers: Random() first, then SetVBlankCallback() (a battle installs a callback that calls Random() between two lag VBlanks), then BIOS calls, then song starts.
  • A lag VBlank inside Random() itself, between its load and its store of the RNG state. The store then undoes the handler's calls. It happened at iteration 26,090 of the rival battle replay, and the trace now flags it.
  • Deferred register writes. On the GBA, some register writes from logic that overruns VBlank wait for the next one. The trace records which writes deferred and at which scanline, and the native replay applies them the same way. It fails loudly if the number of calls differs.
  • mGBA's own breakpoint quirk. It stops twice at a breakpoint when an interrupt lands exactly there. The oracle had to undo the double count.

No game file had to change for the markers. The native build links with --wrap=Random, so every call in the game lands in the port's wrapper first:

u16 __wrap_Random(void)
{
    if (!Platform_InIrq())
    {
        u32 rngValue;

        Platform_BeforeLogicMarker(PLATFORM_MARKER_RANDOM);  // run any lag VBlank due here
        gPlatformLogicRandomCalls++;
        rngValue = gRngValue;
        Platform_InsideLogicRandom();  // the rare VBlank between load and store
        gRngValue = rngValue;
    }
    return __real_Random();
}

With the lag trace, every replay matches the GBA iteration for iteration. The SDL build, which has no trace to follow, still has two known timing differences. One is visible: a single frame of graphics under the wrong palette when you enter a cave. Fixing them means modelling how long the game's logic takes inside a frame, a design change I've left open.

Sound

FireRed's sound engine, m4a, is half C and half ARM assembly. The C half compiles natively with a few guarded edits. The sequencer and mixer were translated from m4a_1.s into integer-exact C, about 1,200 lines. Under them is a from-scratch model of the GBA's sound hardware: the two FIFO channels fed by DMA on timer overflow, and the four PSG channels (square with sweep and envelope, wave RAM with two banks, the noise LFSR).

Testing is the same idea as the graphics. Both sides write a per-frame trace of the mixer's PCM buffer and every sound register, wave RAM included. They are identical on every frame of 732 sound tests (every song, fanfare, sound effect and cry), over the full replays, and over two 30-minute runs.

Output goes to SDL3 at 32,768 Hz stereo. The game produces audio at the GBA's 59.7275 frames per second while displays run at 60 or more, so a PI controller adjusts the resampling rate within ±0.5 % to hold the queue at 2.5 frames. Over a 30-minute soak there were no underruns.

Saves that load in an emulator

Native structs aren't GBA structs: pointers are 8 bytes and padding differs. But I wanted saves to stay compatible with emulator .sav files. The port does that with a generated boundary:

  • A tool reads the DWARF debug info of both builds and flattens every save block to its leaves: 487 fields in SaveBlock2, 3,744 in SaveBlock1, 4,203 in the PC storage.
  • From that it generates a table of 341 copy spans and 438 _Static_asserts on the native offsets and sizes. The game saves into GBA-layout staging buffers through that table, and loads back through it.
  • The check fails if a struct ever changes in a way the table doesn't know about.

The result loads both ways: a native save plays in mGBA, and an mGBA save plays natively. On disk the write is an atomic four-step commit with a .bak. A kill -9 at any step leaves a loadable file, and a save cut off between sectors leaves the old file alone.

What the GBA forgives

ASan and UBSan ran over the replays, and the most interesting bugs are things the GBA quietly survives:

  • Reads through null land on the BIOS. On the GBA, address 0 is the BIOS region: reads return harmless bytes and writes vanish. Natively they segfault. It happened in the summary screen, the PC storage system and MOVE ITEMS. Each fix was measured on the oracle first, to do exactly what the GBA does (usually nothing).
  • Brock's defeat text expands to 377 bytes. On the GBA it runs past its buffer into an unused array, which the decomp even comments on. Natively it overwrote the pointer to the script that runs after the battle. The buffer now gets the 448 bytes the GBA's layout leaves it.
  • sizeof(...) - 8 in the wireless library assumed two 4-byte pointers. Natively it also cleared a callback, so leaving a Pokémon Center skipped nine frames of polling. Only the iteration trace noticed.
  • Erased flash. On a fresh save the game indexes an array with sector id 0xFFFF, about 1 MiB out of bounds. The GBA can't fault and moves on.
  • Busy-waits on interrupts. Several loading loops spin until the VBlank interrupt has copied data. Natively, interrupts only come with frames, so they hung, until a guarded call steps the hardware to the next VBlank.
  • A stack-use-after-return in the summary screen's sprite templates, caught at frame 78,834 of the Viridian Forest replay.
  • Division by zero returns a value on the GBA and traps on x86. Only a dev warp into a battle with an empty party reaches it.

The fixes are small and fenced off from the GBA build. The PC storage one, in full:

void SetMovingMonPriority(u8 priority)
{
#ifdef PORTABLE
    // Called with no mon held (the cursor on the party or buttons while
    // depositing, M6 S6): the GBA writes into the BIOS region, a no-op.
    if (gStorage->movingMonSprite == NULL)
        return;
#endif
    gStorage->movingMonSprite->oam.priority = priority;
}

And Brock's, which keeps the overflow but gives it somewhere harmless to go:

#ifdef PORTABLE
// Room for what the GBA layout absorbs: the strings that overflow 300 bytes
// (Brock's defeat text, 377) run into the buffers and sFlickerArray below,
// 448 bytes before gBattleTypeFlags. Natively the variables are in another
// order, so the overflow hit battle_setup.c's script pointers (M6 S7).
EWRAM_DATA u8 gDisplayedStringBattle[300 + 3 * TEXT_BUFF_ARRAY_COUNT + 25 * sizeof(u32)] = {0};
#else
EWRAM_DATA u8 gDisplayedStringBattle[300] = {0};
#endif

The Pokédude's tutorial reading past its input table, a palette copy that picks up neighbouring tiles, the map preview turning one palette wrong on 861 frames. M9 alone added 55 rows to the modification ledger (native-only fixes and lag-replay hooks), all under PORTABLE, all measured against the oracle.

Playing the whole game as a test

The final proof is a playthrough. The full game is a chain of 20 chapters of recorded input, joined by in-game saves: from Pewter City through the eight gyms, the Elite Four and the Champion, the Hall of Fame and the credits, the National Pokédex, the Sevii Islands' post-game story and a Trainer Tower challenge. That's 1,804,901 frames, 8 hours 21 minutes of game time.

  • Each chapter starts at power-on from the previous chapter's GBA save, plays CONTINUE through the quest log's recap, and ends with a SAVE whose native file must equal the GBA's.
  • A chain beats one long replay: each chapter reruns and bisects on its own, and SAVE and CONTINUE get tested twenty times.
  • Battles were searched, not ground. A tool searched each turn's input timing on the oracle for the crits, misses and AI moves a route needed.
  • Features that input can't reasonably reach (the roaming legendary, a failed save screen, Seafoam's currents) got labelled, injected test scenarios. The main chain stays input-only.

Around that run:

  • Every map. A dev warp on both sides reaches all 425 maps, and all of them are pixel-exact 300 frames after the warp. The first sweep took 35–42 minutes; starting both sides from a saved snapshot and forking a child process per map brought it to 146 seconds with byte-identical results.
  • Fuzzing. Play-shaped random input from forked snapshots, an AFL-style coverage map, a shrinker, and a triage step that retimes each finding to the GBA's lag so it can be replayed on the oracle. It found crashes in the PC storage system, Easy Chat and Teachy TV, and a divide by zero in a battle animation.
  • Platforms. Every build gives the same 600-frame hash: three Linux containers, an Arch package, the Windows zip under Wine, and a real Windows CI runner. Wine and Linux give identical frames, audio and save files over every chapter.

All of it runs from one script, check.sh, with stages from a 40-second quick check to the 38-minute all-chapters run. A content-keyed cache of oracle runs (2.6 GiB when full) is what keeps the rerun loop fast.

How I worked with Claude Code

Claude Code (Claude Opus 5.5) did the research, wrote the plans and almost all of the code, and ran the checks. Every one of the 245 commits carries its co-author line. My job was direction and judgement.

It started with research, not code. I wrote the brief: a real source port of the decompiled code, with no embedded emulator, starting from the existing Emerald ports. Claude cloned and read twelve projects, measured the tree, and wrote a feasibility study, an architecture and a roadmap of eleven milestones, from M0 (the oracle) to M10 (release quality). pokeemerald-wasm was a late addition I asked for. Its cast-rewriting idea became the checked-cast pass above.

Every milestone ran the same way. A written plan with a step table, one commit per step, a report at the end, and a STATUS.md that any fresh session could resume from. Nothing merged into the main branch until I agreed. Some tracks ran in parallel in separate git worktrees, such as the battle slice and the battle-scenario harness.

The calls were mine. A sample from the logs:

  • how the full-game run splits and reorders into chapters, as the game required (one request needs the National Pokédex first; a scientist blocks a tile until a later scene);
  • which features get injected scenarios instead of played input;
  • which of three designs the last lag-trace version used;
  • that 26 unreached script sites in the quest log are acceptable;
  • keeping the 6-minute map sweep out of the main check;
  • no v1.0 tag until real testers have played it, and no public code or binaries until a legal review.

The oracle made the reviewing possible. I couldn't read every line of a 76,000-line change. I could read a report that said "iteration-exact, 1,295 checkpoints at offset 0, clean under ASan/UBSan" and know it meant something, because "looks right" was never an accepted result.

The planning phase estimated six to fifteen months of full-time work for one experienced C developer to reach "fully playable". The full-game milestone closed seven days after the first port commit.

What it doesn't do (yet)

  • No external testers yet, so there's no v1.0. The tester round is planned and waiting for testers.
  • No public release. The decompilation is unlicensed and treated as Nintendo's and Game Freak's copyright, so the code stays private and build-from-source for personal use until a legal review.
  • No link features. Trades, link battles and the wireless adapter are stubbed. Online play is planned through the game's own link layer, so the game's own trades and battles can be reused.
  • Extras are just starting. Instant text, fast-forward, colour correction, display filters and a settings screen in the game's own font are in, all off by default, and with all of them off the game is unchanged. An enforced Nuzlocke mode and a seeded randomizer are next.