I Wrote a Game Boy Advance Emulator in Rust
2026-11-24
I had already written emulators for the Famicom (NES) and the Game Boy, so the Game Boy Advance (GBA from here on) seemed like the obvious next step, and judging by the commit log I started around 2018. I abandoned it many times along the way, and before I knew it about eight years had passed, but with some help from AI at the end it now runs reasonably well, so I decided to publish it.
The Famicom and the Game Boy had 8-bit CPUs, but the GBA has a 32-bit ARM7TDMI. In this post I mainly want to write about that ARM7TDMI. The CPU is without a doubt where I sank the most time while writing the GBA emulator; graphics and sound went much more smoothly by comparison.
Table of Contents
Output
It also runs in the browser, so you can try it below. There is a debugger too, with disassembly, breakpoints, and register and memory views.
https://bokuweb.github.io/rgba/
It bundles about 40 freely distributable homebrew games (plus 7 test ROMs). By default it boots Flappy Enaga, a Flappy Bird-style game starring a Shima-enaga (a long-tailed tit).
References
Let me introduce the references first. For GBA hardware there is GBATEK, compiled by Martin Korth (the author of no$gba). CPU instructions, the memory map, I/O registers, BIOS functions, graphics, sound, and even timing are all on a single page, and it covers almost everything you need to write an emulator. Most of what's in this post is written in GBATEK as well.
https://problemkaputt.de/gbatek.htm
The other one I referred to a lot is Tonc, a GBA programming tutorial by Jasper Vijn. It's written from the perspective of someone making games, so it does a good job of explaining why things work the way they do and how they're actually used.
https://www.coranac.com/tonc/text/
GBA Basic Specs
| Item | Overview |
|---|---|
| CPU | ARM7TDMI 16.78MHz 32bit |
| WRAM | 32KB (on-chip) + 256KB (external) |
| VRAM | 96KB |
| ROM | Up to 32MB |
| Display | 240×160 dots, 32768 colors |
| Sprites | Up to 128 on screen, rotation and scaling supported |
| Background | Up to 4 layers, video modes 0-5 (tile / rotation-scaling / bitmap) |
| Sound | Game Boy-compatible 4ch + DirectSound (8bit PCM) 2ch |
| DMA | 4ch |
| Timers | 4ch (cascadable) |
| Interrupts | VBlank, HBlank, VCount, timer, serial, DMA, keypad, cartridge |
There is also an LR35902-equivalent CPU on board for Game Boy compatibility, but in GBA mode only the ARM7TDMI runs.
GBA Memory Map
The GBA memory map looks like this.
| Address | Region | Size | Bus width | Wait |
|---|---|---|---|---|
0x00000000-0x00003FFF | BIOS | 16KB | 32bit | 0 |
0x02000000-0x0203FFFF | EWRAM (external WRAM) | 256KB | 16bit | 2 |
0x03000000-0x03007FFF | IWRAM (on-chip WRAM) | 32KB | 32bit | 0 |
0x04000000-0x040003FE | I/O registers | 32bit | 0 | |
0x05000000-0x050003FF | Palette RAM | 1KB | 16bit | 0 |
0x06000000-0x06017FFF | VRAM | 96KB | 16bit | 0 |
0x07000000-0x070003FF | OAM (sprite attributes) | 1KB | 32bit | 0 |
0x08000000-0x09FFFFFF | ROM (wait state 0) | 32MB | 16bit | Set by WAITCNT |
0x0A000000-0x0BFFFFFF | ROM (wait state 1) | 32MB | 16bit | Set by WAITCNT |
0x0C000000-0x0DFFFFFF | ROM (wait state 2) | 32MB | 16bit | Set by WAITCNT |
0x0E000000-0x0E00FFFF | SRAM (for saves) | 64KB | 8bit | Set by WAITCNT |
The region is determined by the top 8 bits of the address, which keeps things clear. The emulator just needs to dispatch on addr >> 24. rgba also uses this value as a page number and looks up the access cycles for each region in a table.
I'll explain Seq and NonSeq later.
fn compute_cycle(&self, addr: Word, access_type: AccessType) -> Cycle {
let page = (addr >> 24) as usize;
if page > 0xF {
return 1;
}
match access_type {
AccessType::NonSeq(AccessWidth::Byte | AccessWidth::HalfWord) => self.cycle_lut.n16[page],
AccessType::NonSeq(AccessWidth::Word) => self.cycle_lut.n32[page],
AccessType::Seq(AccessWidth::Byte | AccessWidth::HalfWord) => self.cycle_lut.s16[page],
AccessType::Seq(AccessWidth::Word) => self.cycle_lut.s32[page],
}
}
The Famicom and the Game Boy only have a 16-bit (64KB) address space, so using a large ROM required switching banks with a mapper (MBC) on the cartridge.
The emulator also has to implement a mapper for each cartridge type. The GBA has a 32-bit address space, so a 32MB ROM is visible as-is starting at 0x08000000.
Quirks of Each Region
There were a few things that tripped me up while writing it.
- Bus width differs per region: IWRAM is 32-bit with no wait states, but EWRAM and ROM are 16-bit. A 32-bit access to ROM becomes two 16-bit accesses, so running ARM instructions from ROM is slow. That's why the standard practice on the GBA is to copy ARM code that needs to be fast into IWRAM and run it there. It's also why writing in Thumb (described later) is the default
- There are mirrors: IWRAM repeats every 32KB across
0x03000000-0x03FFFFFF, and EWRAM repeats every 256KB. VRAM has an awkward size of 96KB, so it's mirrored in 128KB units, and the last 32KB is a mirror of the 32KB right before it, which is a confusing spec - The end of IWRAM is used by the BIOS: Around
0x03007F00is the stack,0x03007FF8holds the interrupt flags thatIntrWaitchecks, and0x03007FFCholds the address of theIRQhandler. The0x03FFFFFCthat gba.js's BIOS (described later) reads is a mirror, so it's actually this0x03007FFC - Behavior depends on write width: An 8-bit write to the BG area of VRAM writes the same value to both the upper and lower bytes. 8-bit writes to OAM or the OBJ area of VRAM are ignored. SRAM, conversely, can only be accessed in 8-bit units
- The BIOS can't be read: The BIOS region can only be read while
PCis inside the BIOS. Reading it from outside returns the last instruction the BIOS fetched. Apparently this is protection against dumping the BIOS - Reading unmapped regions gives open bus: Reading an unused region returns not 0 but the most recently fetched instruction. Because of the pipeline, fetching has already run two instructions ahead, so here too you need to keep the pipeline in mind to know which value you'll see
The DISPCNT (0x04000000) that shows up in the Hello World later is at the start of the I/O registers, the 0x06000000 where we write the dot is the start of VRAM, and the 0x08000000 where the linker script places the program is the start of ROM. They're all in this table.
The ARM7TDMI Spread Explosively Around the World
The ARM7TDMI isn't a CPU made specifically for the GBA; it was in all kinds of embedded devices around the world at the time. The first few generations of the iPod, the sub-CPU of the Nintendo DS, feature phones of that era... I think almost everyone has touched one at some point without realizing it.
The TDMI in the name means the following.
- T: Supports the Thumb instruction set (16-bit instructions)
- D: Debug features
- M: Multiply with a 64-bit result (Long Multiply)
- I: EmbeddedICE
ARM's business model is licensing IP rather than making chips itself, so lots of manufacturers put out microcontrollers with an ARM7TDMI core. As for how widespread it was: widespread enough that ARM7 microcontroller boards were often bundled as freebies with Interface magazine (a Japanese electronics/embedded magazine).
Differences from the Famicom and the Game Boy
The Famicom's 6502 runs at 1.79MHz and the Game Boy's LR35902 at 4.19MHz, both 8-bit. The GBA is 32-bit at 16.78MHz, so on clock speed alone it's 4x the Game Boy and over 9x the Famicom. Including the bit width, it feels like a jump of several generations at once.
From the perspective of writing an emulator, these are the things that felt very different.
Far More Instructions and Variations
The 6502 and LR35902 instructions are almost uniquely determined by a 1-byte opcode, so you could make a 256-entry table and fill it in one by one.
ARM packs 32-bit instructions full of bit fields, and even a single data processing instruction has a lot of branching. Is the operand an immediate or a register? If it's a register, is it shifted? Where is the shift amount specified? Does it update the flags? ...and it keeps branching. On top of that there's a separate instruction set called Thumb, so it feels like you're effectively implementing two CPUs.
Lots of Registers, and They're Banked per Mode
The 6502 only had about A, X, and Y, but ARM has 16 registers, r0-r15. r13 is treated as SP, r14 as LR, and r15 as PC.
On top of that there are 7 operating modes: User, FIQ, IRQ, Supervisor, Abort, Undefined, and System, and depending on the mode, r13 and r14 (r8-r14 for FIQ) switch to different registers. These are the so-called banked registers. When you enter an interrupt, SP becomes a different register on its own.
The BIOS Has System Calls (BIOS Functions)
The Game Boy had a boot ROM too, but it just showed the logo. The GBA BIOS has system calls (division, square root, memory copy, waiting for VBlank, etc.) that can be invoked with the SWI instruction.
I didn't know this, so when I ran a test ROM and saw svc being called, I was puzzled: "Why is there a software interrupt here?" More on this later.
BIOS Functions via SWI
Let me write a bit more about the system calls (BIOS functions).
Overview
The GBA BIOS is a 16KB ROM located at 0x00000000-0x00003FFF. Besides showing the logo at boot and handling multiboot, it contains about 40 functions that games can call. Roughly grouped, they look like this.
| Category | SWI number | Functions |
|---|---|---|
| Reset | 0x00-0x01 | SoftReset, RegisterRamReset |
| Power saving / interrupt wait | 0x02-0x05 | Halt, Stop, IntrWait, VBlankIntrWait |
| Arithmetic | 0x06-0x0A | Div, DivArm, Sqrt, ArcTan, ArcTan2 |
| Memory copy | 0x0B-0x0C | CpuSet, CpuFastSet |
| Rotation/scaling | 0x0E-0x0F | BgAffineSet, ObjAffineSet |
| Decompression | 0x10-0x18 | BitUnPack, LZ77UnComp, HuffUnComp, RLUnComp, Diff*Unfilter |
| Sound | 0x19-0x24, 0x28-0x2A | SoundBias, SoundDriverInit, MidiKey2Freq, etc. |
| Other | 0x0D, 0x25-0x27 | GetBiosChecksum, MultiBoot, HardReset, CustomHalt |
What's interesting is that division is in there. The ARM7TDMI has no divide instruction, so division has to be done in software. There's no FPU either, so the BIOS provides things like square root. It also feels very game-console-like that there are BgAffineSet and ObjAffineSet, which compute the matrices for rotating and scaling (affine transforming) BGs and sprites from an angle and scale factor, and decompression functions to save ROM space.
How to Call Them
You call them with the swi instruction (later renamed svc in ARM's Unified Assembler Language (UAL)) plus an SWI number. Arguments are passed in r0-r3, and the return value comes back mainly in r0. For example, Div computes r0 / r1 and returns the quotient in r0, the remainder in r1, and the absolute value of the quotient in r3.
@ Thumb
mov r0, #100
mov r1, #7
swi 0x06 @ Div → r0 = 14, r1 = 2
The CpuFastSet in the test ROM I mentioned earlier was exactly a function that just wraps this.
08000c90 <CpuFastSet>:
8000c90: 0c df svc #12
8000c92: 70 47 bx lr
The confusing part is that when calling from ARM state, you have to specify not swi 0x06 but swi 0x060000, the value shifted left by 16 bits. The ARM swi instruction uses its lower 24 bits as the number field, but the GBA BIOS only looks at the upper 8 bits of that.
How It Works
When swi is executed, the CPU does the following. This isn't GBA-specific; it's just ARM's exception mechanism.
- Save
CPSRtoSPSR_svc - Put the return address (the instruction after
swi) into LR_svc - Switch to
Supervisormode, switch to ARM state, and disable interrupts - Set
PCto0x00000008(the SWI vector)
At 0x08 there's a branch to the BIOS's SWI handler, so BIOS code runs from there. The handler reads the caller's swi instruction, extracts the SWI number, and jumps to each function via a table. When done, movs pc, lr restores SPSR into CPSR and returns to the caller. Since CPSR is restored, if it was called from Thumb it properly goes back to Thumb.
In gba.js's BIOS (described later), extracting the SWI number is done in a single instruction: ldrb r0, [lr, #-2].
- Thumb's
swiis 2 bytes, and the lower 8 bits are the number.LRpoints to the instruction afterswi, soLR-2is the start of theswi. Since it's little-endian, the first byte is the number - ARM's
swiis 4 bytes, andLR-4is the start of theswi.LR-2is its third byte, i.e. bits 16-23
So whether it's called from ARM or Thumb, reading the single byte at [lr, #-2] gives you the SWI number. "So that's why you have to shift by 16 bits when calling from ARM!" — it finally clicked. Very well designed.
The real BIOS goes further: it pushes SPSR, R11, R12, and R14 onto the supervisor stack, then switches to System mode before running the function. That way, if interrupts were enabled at the caller, interrupts can also come in during the function, and subsequent stack operations use the user stack.
BIOS functions are handy but not fast. They seem to have been built prioritizing size over speed; according to Tonc, each call has at least 60 cycles of overhead (a normal function call is about 30 cycles), so it's better to avoid using them heavily.
Implementation in the Emulator
If you use the real BIOS (or a compatible BIOS), the CPU emulation simply executes the BIOS's machine code one instruction at a time. The emulator only needs to implement swi according to the exception mechanism above. The BIOS code does all the rest.
The other approach is HLE (High Level Emulation): instead of running the BIOS code, the emulator reproduces only the behavior, "calling this function produces this result." Concretely, when swi is executed, you look at the SWI number and call an emulator-side function directly. For Div, for example, instead of running the BIOS's division routine, you just compute r0 / r1 in Rust and put the results in registers. By the way, the former approach, faithfully running the hardware instruction by instruction, is called LLE (Low Level Emulation).
rgba uses HLE; it doesn't jump to 0x08 but dispatches to functions written in Rust.
match swi_number {
0x00 => Self::soft_reset(bus, gpr, 0),
0x01 => Self::register_ram_reset(bus, gpr),
0x02 => Self::halt(bus, gpr),
0x04 => Self::intr_wait(bus, gpr),
0x05 => Self::vblank_intr_wait(bus, gpr),
0x06 => Self::div(bus, gpr),
// ...
0x11 => Self::lz77_uncomp(bus, gpr, false),
// ...
_ => {}
}
The nice things about HLE are that it's fast and works without the BIOS contents. In exchange, the cycle counts and the BIOS's subtle side effects aren't reproduced. The sound driver functions are currently implemented to do nothing.
The most annoying one was IntrWait. This function "waits until the specified interrupt arrives," so it doesn't finish in one go. You have to Halt the CPU, check whether it's the interrupt you're waiting for each time an interrupt wakes it up, and Halt again if it isn't. And what it checks isn't the hardware IF register but the flags the game's interrupt handler writes to 0x03007FF8. rgba implements this by making it execute the same swi again each time an interrupt wakes it up. To do that it rewinds PC to the position of the swi, but here again, because PC has run ahead, you have to subtract 8 for ARM and 4 for Thumb. There's no escaping the pipeline.
The BIOS Is Copyrighted, So There Are Open BIOSes
The problem here is that the GBA BIOS is Nintendo's program, so naturally it's copyrighted. You can't bundle it with an emulator and distribute it.
But you can't just go without a BIOS either. There are the system calls mentioned above, and when an interrupt occurs the CPU jumps to the IRQ vector at 0x00000018, so without some code there you can't even handle interrupts.
So the options are roughly these.
- Have users provide a BIOS dumped from real hardware
- Implement SWI on the emulator side (the HLE mentioned above)
- Use a compatible BIOS, a so-called Open BIOS
Real-world emulators are often built to use a dumped BIOS if available, and fall back to HLE or a compatible BIOS otherwise.
Open BIOSes
Looking into it, there are people writing freely distributable BIOSes.
- Normmatt's open source BIOS: included in the ReGBA repository
- Cult-of-GBA/BIOS: an MIT-licensed compatible BIOS
- gba.js's BIOS: a minimal BIOS of only 220 bytes included in gba.js (BSD-2-Clause)
- mGBA's HLE BIOS: mGBA's own BIOS, used when there's no dumped BIOS
rgba maps gba.js's BIOS at 0x00000000 and HLEs SWI on the emulator side. This BIOS is only 220 bytes, so you can disassemble and read the whole thing.
0: ea000006 b 0x20 ; Reset
4: eafffffe b 0x4 ; Undefined
8: ea000005 b 0x24 ; SWI
c: eafffffe b 0xc ; Prefetch Abort
10: eafffffe b 0x10 ; Data Abort
14: e1a00000 nop
18: ea00000c b 0x50 ; IRQ
1c: eafffffe b 0x1c ; FIQ
20: e3a0f302 mov pc, #134217728 ; 0x8000000
24: e35d0000 cmp sp, #0
...
34: e55e0002 ldrb r0, [lr, #-2]
38: e3500004 cmp r0, #4
3c: 0b000009 bleq 0x68
40: e3500005 cmp r0, #5
44: 0b000007 bleq 0x68
...
50: e92d500f push {r0, r1, r2, r3, ip, lr}
54: e3a00301 mov r0, #67108864 ; 0x4000000
58: e28fe000 add lr, pc, #0
5c: e510f004 ldr pc, [r0, #-4]
60: e8bd500f pop {r0, r1, r2, r3, ip, lr}
64: e25ef004 subs pc, lr, #4
It's fun to read.
- The first
0x00-0x1Care the exception vectors.UndefinedandAbortare jumps to themselves, i.e. infinite loops - On reset,
mov pc, #0x8000000jumps straight to the cartridge. No logo, no initialization at all - The SWI handler reads the SWI number from the caller's
swiinstruction withldrb r0, [lr, #-2]. And the only ones it handles are 4 (IntrWait) and 5 (VBlankIntrWait) - The
IRQhandler jumps vialdr pc, [r0, #-4]to the address written at0x03FFFFFC. The GBA convention is that the game writes the address of its own interrupt handler there.0x03FFFFFCis a mirror of WRAM, so it's actually0x03007FFC subs pc, lr, #4returns from the interrupt. The -4 here is also because of the pipeline mentioned earlier
It shows that this is all a minimal BIOS needs, and it's also just right for understanding what a BIOS does.
Also, if you skip the BIOS and start executing directly from the cartridge, you need to reproduce the register values as they are when the BIOS finishes. You can mostly figure these out by looking at the skipBios code in VisualBoyAdvance-M.
The Pipeline
The ARM7TDMI has a 3-stage pipeline: fetch, decode, and execute. The troublesome part is that its effects are directly visible to the programmer as part of the spec.
PC Points Two Instructions Ahead
While an instruction is executing, PC points not to that instruction but to the address of the instruction two ahead of it. That is, +8 in ARM state and +4 in Thumb state.
ldr pc, [pc, #-4]
I wanted to read "the address of the instruction after the current one," but it said #-4 and I couldn't make sense of it. Once you realize PC is +8, it adds up: +8-4 = +4. It's this way because fetching has already advanced two instructions ahead.
It started with the 3-stage pipeline of the very first ARM (ARM1), where the address being fetched was visible as PC as-is. That then got fixed as part of the architecture spec. Even as the pipeline got deeper with ARM9 (5 stages) and ARM11 (8 stages), they apparently went out of their way to make it still look like +8 for compatibility. Only with AArch64 was this history finally thrown away, and PC now points to the address of the current instruction.
ARMのLDR疑似命令みてるけど、よくわからぬ。PCが現在の命令の+8になっているんだけど、これはパイプラインの挙動の所為なんだろうか。。現在の命令の次のアドレス示すのにLDR PC, [PC], #-4みたいなことになっててわけわからん。
— bokuweb (@bokuweb17) March 15, 2018
Adjusting PC Is a Pain
For an emulator, I figured you don't really need to implement all three pipeline stages faithfully; in the end, don't you only need to implement the execute stage? But in that case there are a bunch of exceptions here and there, which is a pain in its own way.
- When you branch, you have to flush the pipeline and refetch two instructions from the branch target
- For data processing instructions that specify the shift amount in a register,
PCappears as +12 (because it takes one extra cycle) - Storing
PCwithSTRorSTMalso gives +12 - Thumb's
PC-relative loads drop the lower 2 bits ofPCbefore computing the address - When an interrupt comes in,
LRhas to be set to a value that lets you return with the samesubs pc, lr, #4from both ARM and Thumb. Relative to the emulator's internalPC(+8/+4), the offset differs, so be careful - When an interrupt comes in, the instruction in the execute stage is completed and the remaining instructions in the pipeline are discarded
This becomes a process of passing test ROMs one at a time and squashing things with "oh, this is off by 4 too." Fix one, and something else shifts somewhere. Painful.
Conditional Execution
Every ARM instruction has a condition field in its top 4 bits. In other words, every instruction can be conditionally executed.
| cond | Meaning |
|---|---|
| 0000 | EQ (Z=1) |
| 0001 | NE (Z=0) |
| ... | ... |
| 1011 | LT (N!=V) |
| 1100 | GT |
| 1101 | LE |
| 1110 | AL (always) |
You can attach a condition to anything, like moveq, addne, or ldmgt, so short ifs can be written without branch instructions. Branching flushes the pipeline, so I think the design intent is probably to avoid that.
The condition check itself is just a combination of N, Z, C, and V, so it's done with a single table. What's hard is less the conditions and more how each instruction updates which flags. The C flag in particular is complicated because its meaning changes by instruction: it might be the carry out of the shifter, or the inverse of the borrow from a subtraction.
That said, if you disassemble real code, most instructions are AL (1110). For example, gba.js's BIOS from earlier contains a few conditional instructions.
0: ea000006 b 0x20
20: e3a0f302 mov pc, #134217728 ; 0x8000000
24: e35d0000 cmp sp, #0
28: 03a0d301 moveq sp, #67108864 ; 0x4000000
2c: 024dd020 subeq sp, sp, #32
30: e92d4000 stmfd sp!, {lr}
...
b8: 10211000 eorne r1, r1, r0
bc: 114410b8 strhne r1, [r4, #-8]
Looking at a hex dump, it's almost entirely e, and when you occasionally see a 0 or 1 mixed in you go, "oh, a conditional." For spending 4 bits every time, it's almost always E, which feels a bit wasteful. In fact, Thumb dropped the condition field except for conditional branches (it came back in Thumb-2 in the form of the IT instruction), and AArch64 has almost no conditional execution, so maybe ARM itself thought so too.
Switching to Thumb Is Scary
The ARM7TDMI has two instruction sets, ARM (32-bit instructions) and Thumb (16-bit instructions), and you can switch between them at runtime. The GBA's cartridge ROM has a 16-bit bus, so a 32-bit ARM instruction needs two accesses to fetch. So the standard practice for GBA games is apparently to write mostly in Thumb, and write only the speed-critical parts in ARM and put them in IWRAM.
And the way you switch is scary. When jumping with the BX instruction, if the lowest bit of the target address is 1, i.e. you jump to an odd address, you enter Thumb state.
add r0, pc, #1 @ make it odd
bx r0 @ Thumb from here
Instructions are aligned to 2 or 4 bytes, so the lowest bit is normally unused. The mechanism stuffs the state into it. I understand the logic, but having the entire instruction set change based on one bit of an address is pretty scary.
In fact, while writing the emulator, I hit the bug of decoding ARM instructions as Thumb and charging ahead many times. Even with the wrong instruction set, things still decode into plausible-looking instructions, so it doesn't crash; it runs for a while and then goes wrong. Tracking down where the state went wrong was really painful.
Even more confusing is when you write an odd value directly to PC with something like Thumb's MOV. In that case the state does not switch; the lowest bit is simply discarded. I was jumping to odd addresses here, and fixed it with a 0xFFFFFFFE mask. I spent quite a while looking for where this was documented.
I recall this was also mentioned on Turing Complete FM (a Japanese tech podcast).
Shifts Behave in Baffling Ways
ARM can pass the second operand of a data processing instruction through the barrel shifter, so you can write an add and a shift in one instruction, like add r0, r1, r2, lsl #2. It's very convenient, but from the emulator writer's side there are way too many edge cases.
A Shift Amount of 0 Changes Meaning
When the shift amount is an immediate, a 5-bit field holds 0-31. But a shift amount of 0 for anything other than LSL #0 turns into something else.
| Encoding | Actual meaning |
|---|---|
LSL #0 | No shift (as-is) |
LSR #0 | LSR #32 (result is 0, C is bit31) |
ASR #0 | ASR #32 (all bits filled with the sign, C is bit31) |
ROR #0 | RRX (rotate right by 1 bit through the C flag) |
LSR #0 and ROR #0 are the same as "do nothing," so there's no point distinguishing them from LSL #0, and giving them another meaning is an efficient use of the encoding. In fact, if you write LSR #0 in assembly it gets converted to LSL #0, and LSR #32 is encoded as LSR #0. But if you don't know this, of course you'll get stuck. I got stuck because I didn't know ROR #0 becomes RRX.
Specifying the Shift Amount in a Register Changes It Again
When the shift amount comes from a register, the lower 8 bits are used, so you can shift by 0-255. In this case, 0 really does nothing, and for 32 or more, the result and carry are determined by separate rules for each shift. For example, ROR rotates by the shift amount modulo 32, but when the remainder is 0, C becomes bit31, and so on.
The same ROR behaves completely differently depending on whether it's an immediate or a register, so a lot of tests failed here when I ran test ROMs.
LDR Rotates
This was the most baffling one. When LDR reads from an address not aligned to 4 bytes, the address is rounded down to a multiple of 4, and then the loaded data is rotated right according to the lower 2 bits.
The loaded data is rotated right by 1, 2, or 3 bytes
according to bits [1:0] of the address.
At first I suspected a bug, but it was the spec. ARMv4 doesn't support misaligned access, so it's an access you're not supposed to do, but apparently this is how it actually behaves. Also, on ARMv4, LDRH on an odd address rotates by 8 bits.
So why is it specified like this? For example, if 11 22 33 44 is laid out starting at 0x1000 and you do LDR r0, [0x1001], you get this.
1. Drop the lower 2 bits and read 4 bytes from 0x1000 → 0x44332211
2. Rotate right by addr[1:0] × 8 bits → 0x11443322
After the rotation, the byte at the specified address (0x22) lands exactly in bits 0-7. That's the trick: it's the same mechanism as LDRB.
The ARM7's data bus is 32 bits wide, and with LDRB the target byte arrives at a position determined by the lower 2 bits of the address. It's rotated so it lands in the lower 8 bits, and the upper 24 bits are masked off. A misaligned LDR goes through this same circuit, just without the final mask.
Properly supporting misaligned access would require a circuit that hits the bus twice and stitches the results together. At the time they wanted to cut transistor count, so they left that out, and instead of leaving the behavior undefined, they wrote "this is what happens as a result of reusing the LDRB circuit" into the spec, apparently. It's not a bug, but it's closer to a side effect than a deliberately designed feature.
However, once it's written into the spec, code starts relying on it. One example is a hack that does an LDR at offset +2 to get the value with its upper and lower 16 bits swapped in a single instruction. Even when ARMv6 introduced proper misaligned access, a mode that reverts to the old rotate behavior was kept around for a while for compatibility. Code running on real hardware may rely on this behavior, and test ROMs check it too, so an emulator can't get away without implementing it.
By the way, on x86 a misaligned read just works, and on MIPS it raises an exception (instead there are dedicated instructions LWL/LWR). ARMv4 doesn't raise an exception and returns a rotated value, which is the most trap-like of all.
Test ROMs test this kind of behavior thoroughly too, and I lost several days because Thumb's LDR wouldn't pass.
Immediates Are Made with Rotation Too
Speaking of rotation, immediates use it too. ARM instructions are a fixed 32 bits, so they can't hold a 32-bit immediate as-is. The immediate in a data processing instruction is 12 bits, made of an 8-bit value and a 4-bit rotate amount. It can only represent an 8-bit value rotated right by an even number of bits.
I didn't know this, so when I wrote mov r0, #1234 and assembled it, my emulator reported unsupported instruction.
40: e30004d2 movw r0, #1234 ; 0x4d2
Disassembling it showed movw. 1234 (0x4D2) doesn't fit in 8 bits, so it can't be expressed with a normal mov, and the assembler had used movw, which was added in ARMv6T2 (ARMv7 and so on). ARMv4 has no such instruction, so of course it didn't work. If you specify the target correctly, you get an assembly error instead, so you need to write ldr r0, =1234 and have it read from a literal pool.
LDM/STM Are Something Too
LDM/STM, which load/store multiple registers at once, also have many edge cases.
First, there are four addressing modes: IA (Increment After), IB, DA, and DB, and on top of that you can choose whether to write back. Including LDR, I kept getting confused about pre-index vs. post-index and write-back vs. no write-back.
offset => LDR R0, [R1, R2] address is R1 + R2, R1 is unchanged
preindex => LDR R0, [R1, R2]! address is R1 + R2, R1 = R1 + R2
postindex => LDR R0, [R1], R2 address is R1, R1 = R1 + R2
Post-index writes back even though the W bit is 0, so if you implement it by looking only at the W bit, you'll get stuck.
Even more mysterious is the ^ you put after the register list. It has two meanings.
ldmdb sp, {r0, r1, r2, pc}^
ldmdb sp, {r0, r1, r2, lr}^
When the register list includes pc, as in the first one, it means copying the current mode's SPSR to CPSR at the same time as the load. In other words, returning from an exception. When pc isn't included, as in the second one, it means loading into the "user mode" registers rather than the current mode's registers. They look almost the same but do completely different things.
There's other weird behavior too: passing an empty register list transfers r15 and adds +0x40 to the base; when the base register is in the register list and write-back is on, the value written depends on whether it's first in the list; and so on. GBATEK describes these as "on ARMv4" and "on ARMv5," and you end up implementing them one by one.
Graphics and Sound
So far it's been all about the CPU, but graphics and sound have also evolved quite a bit from the Famicom and the Game Boy.
Graphics: BGs and Sprites
First, a rough comparison.
| Item | Famicom | Game Boy | GBA |
|---|---|---|---|
| Resolution | 256×240 | 160×144 | 240×160 |
| Colors | Pick from a fixed set of ~54 | 4 shades | Freely made from 15bit (32768 colors) |
| BG | 1 | 1 + window | Up to 4 |
| Sprites | 64 (up to 8 per line) | 40 (up to 10 per line) | 128, up to 64×64, rotation and scaling supported |
| Bitmap | None | None | Yes (modes 3-5) |
On the Famicom and the Game Boy, the screen could only be built from a combination of a BG made of 8×8 tiles and sprites. The GBA is basically the same, and modes 0-2 are tile modes. The difference is the number of BGs and colors: in mode 0 you can stack 4 BGs, and tiles can be either 16 colors (choosing from 16 palettes) or 256 colors. In modes 1 and 2, BGs can be rotated and scaled, and things like the so-called pseudo-3D ground are made with this.
On top of that, the GBA has bitmap modes, which the Famicom and the Game Boy didn't. These use VRAM as a framebuffer, so you can write any color you like pixel by pixel.
| Mode | Resolution | Colors | Frames |
|---|---|---|---|
| 3 | 240×160 | 32768 colors (2 bytes per pixel) | 1 |
| 4 | 240×160 | 256 colors (palette, 1 byte) | 2 |
| 5 | 160×128 | 32768 colors | 2 |
The Hello World mentioned earlier uses mode 3; writing a color into VRAM at 0x06000000 makes it show up on screen directly. But 240×160×2 bytes uses 75KB, so there's no room for a back buffer. Modes 4 and 5 have two frames, and you can switch the displayed frame with bit4 of DISPCNT, so you can double buffer by drawing in the back and then flipping. In exchange, in bitmap modes the tile area for sprites shrinks from 32KB to 16KB. Since you can put an image on screen without laying out tiles, these modes suit simple programs like Hello World and things like software-rendered 3D. However, the CPU ends up drawing every pixel, which is heavy, so most commercial games use the tile modes.
Sprites are also enhanced: up to 128 can be displayed in sizes from 8×8 to 64×64, and they can be rotated and scaled using 32 sets of matrices. The Famicom's limit was a count, "up to 8 per line," but on the GBA the limit is determined by the number of rendering cycles available per line (up to 1210 cycles). With small sprites you can put 128 on one line, and large or rotated ones reduce the count accordingly.
There's also hardware support for alpha blending to overlay BGs and sprites semi-transparently, brightness adjustment for fade-in/out, windows that change what's displayed in only part of the screen, mosaic, and more.
From the emulator side, this compositing was the most annoying part. For each pixel, you have to compare the priorities of the 4 BGs and sprites, switch the displayed layers inside and outside windows, and then pick the first and second layers from the top and blend them. Also, games rewrite things like scroll values per line using HBlank interrupts and HBlank DMA (raster scrolling), so you can't reproduce it unless you render one line at a time rather than a whole frame at once. For rotated/scaled BGs, you also need to reproduce the mechanism where the reference coordinates are internally incremented every line and reloaded at VBlank.
You can check how the layers actually stack using rgba's debugger. Open https://bokuweb.github.io/rgba/ and Flappy Enaga will be running; check isolate at the bottom of the screen and try toggling the checkboxes for BG0-BG3 and OBJ. Only the checked layers are displayed.

Breaking down Flappy Enaga's title screen gives this. Top left is the composited screen, top right is BG0 (the ground), bottom left is BG1 (the sky and mountains), and bottom right is OBJ (the logo, the enaga, and the PRESS A button). BG2 and BG3 aren't used. The ground and sky are on separate BGs so that they can scroll at different speeds to create depth. BG0HOFS is incremented by 1 each frame and BG1HOFS gets 1/4 of that, so the sky moves at 1/4 the speed of the ground.

Sound: PSG + DirectSound
| Item | Famicom | Game Boy | GBA |
|---|---|---|---|
| Channels | 2 square, 1 triangle, 1 noise, 1 DPCM | 2 square, 1 wave memory, 1 noise | Game Boy-compatible 4ch + DirectSound 2ch |
GBA sound consists of the same 4 channels as the Game Boy (two square waves, wave memory, and noise), plus two added channels called DirectSound that can play 8-bit PCM. The Game Boy-compatible 4 channels are nearly identical to the Game Boy (Color) sound hardware, so if you've written a Game Boy emulator you can reuse it. However, the register addresses have changed, and the wave memory has grown to 2 banks, so you can play 64-sample waveforms or rewrite the back bank while playing.
The new part is DirectSound, a channel for streaming waveform data produced by the CPU as-is. It works like this.
- Put 8-bit samples into a 32-byte FIFO
- Each time a timer overflows, take one sample from the FIFO and play it (the timer period directly becomes the sampling rate)
- When the FIFO is down to 16 bytes, DMA automatically refills 16 bytes from memory
In other words, sound only comes out when the timer, DMA, and FIFO all work together. For an emulator, if any one of their timings is off, the sound cuts out or the speed changes.
On the Famicom and the Game Boy, the basic approach was to drive the hardware sound generators directly, but many commercial GBA games use the sound driver included in Nintendo's SDK (MusicPlayer2000, a.k.a. m4a or Sappy) to mix multiple instruments on the CPU and then stream the result to DirectSound. A similar driver is also in the BIOS as SoundDriverInit and so on, but real games rarely use it; each game builds the driver into its ROM. Rather than playing through a sound chip, it's closer to the modern approach of streaming CPU-generated audio to a DAC. The final output is resampled to 32.768kHz, 9-bit by default.
By the way, Flappy Enaga, the default ROM, used to produce no sound. When I looked into it, I was handling registers wrong while the sound master was off. While the master is off, only writes to the Game Boy-compatible 4-channel registers are ignored; DirectSound settings and such can still be written. I was ignoring all of them, so games that configure DirectSound before turning the master on had no sound.
Timers
The GBA has four 16-bit timers (TM0-TM3). The Famicom has no timer like this, and the Game Boy had only one.
| Register | Address | Contents |
|---|---|---|
TMxCNT_L | 0x04000100 + 4×x | Read: current counter; write: reload value |
TMxCNT_H | 0x04000102 + 4×x | bit0-1: prescaler (1/64/256/1024), bit2: count-up, bit6: interrupt, bit7: enable |
The behavior is simple: when enabled, it starts counting from the reload value and increments by 1 on every prescaled clock (1/1, 1/64, 1/256, or 1/1024 of 16.78MHz). When it goes past 0xFFFF it overflows, goes back to the reload value, and starts counting again. It can also raise an interrupt on overflow.
The interesting part is count-up (cascade): a timer with bit2 set counts not clock ticks but "the number of times the previous timer overflowed." Chaining TM0 and TM1 lets you use them as a 32-bit timer. TM0 has no previous timer, so this bit is ignored for it.
The biggest use, as mentioned above, is setting the DirectSound sampling rate. One sample is taken from the FIFO on each overflow of TM0 or TM1, so the timer period directly becomes the sampling rate. Other uses include measuring processing time, random seeds, and periodic interrupts.
Here are the key points when writing it for an emulator.
- Reads and writes mean different things at the same address: Writing
TMxCNT_Lsets the reload value, and reading it gives the current counter. The written value doesn't go into the counter immediately; it goes in when the timer is enabled and when it overflows - Don't count one cycle at a time: Each time one CPU instruction executes, advance the timers by the elapsed cycles all at once. rgba keeps the prescaler clock boundaries as absolute time and counts how many boundaries fall within the elapsed time. Just dividing the elapsed cycles by the prescaler ratio can't reproduce the phase offset caused by when the timer was enabled
- There's a small delay right after enabling: On real hardware, counting doesn't start immediately when a timer is enabled. rgba delays the first count by 2 cycles
- Process cascades in order: Advance in order
TM0→TM3, passing the previous timer's overflow count to the next timer
That said, in the mGBA test suite only 373 of 936 count-up tests and 28 of 90 timer interrupt tests pass. The tests do things like enabling a timer and reading the counter a few instructions later, so if instruction cycle counts are off, the results are off by the same amount. This needs to be fixed together with the timing accuracy discussed later.
Interrupts
The GBA has 14 kinds of interrupts: VBlank, HBlank, VCount, timer ×4, serial, DMA ×4, keypad, and cartridge. They're controlled by three registers.
| Register | Address | Contents |
|---|---|---|
IE | 0x04000200 | Which interrupts are enabled (1 bit per kind) |
IF | 0x04000202 | Which interrupts have occurred. Writing 1 clears that bit |
IME | 0x04000208 | Master switch for all interrupts |
When an interrupt occurs, the corresponding bit in IF is set. If IME is 1, some bit is set in both IE and IF, and interrupts aren't disabled by the I flag in the CPU's CPSR, the CPU enters IRQ mode and jumps to the IRQ vector at 0x00000018. From there it's the BIOS's job: as described above, it saves registers and calls the game's interrupt handler written at 0x03007FFC.
The hardware only goes as far as jumping to the IRQ vector; figuring out which interrupt came in is the job of the game's interrupt handler. The handler looks at IF, dispatches, and writes the bits of the handled interrupts to IF to clear them. If you use the IntrWait mentioned earlier, you also need to set the same bits at 0x03007FF8. Forget any of these and the same interrupt fires repeatedly, or IntrWait never returns.
These are the things that tripped me up when writing it for the emulator.
IFis cleared by writing 1: If you store the written value as-is like a normal register, interrupts get set again every time the handler clearsIF- Judge interrupts by "state": rgba originally remembered on the CPU side, as a flag, that an interrupt had occurred, and processed it once interrupts were allowed. But with that, when the handler cleared
IFand then re-enabled interrupts, it would enter an interrupt that no longer existed. Now it re-checksIME,IE, andIFafter every instruction and decides based on whether the conditions are met at that moment 0x03007FF8isn't something the hardware writes: I was also setting the bit at0x03007FF8on the emulator side when an interrupt occurred, which madeIntrWaitwake up even for interrupts disabled inIE, and it failed the test ROM item "disabled interrupts don't occur." The one that writes there is strictly the game's interrupt handler- Waking from
Halt: AHalted CPU wakes up when some bit is set in bothIEandIF.IMEand the I flag don't matter here; the CPU wakes up even if interrupts are disabled (it doesn't jump to the handler, and continues from the instruction afterHalt)
Still, rgba is rough in places. Interrupts are only checked at instruction boundaries, and the cycles for entering an interrupt are just an arbitrary value added on.
DMA
The GBA has 4 DMA channels (DMA0-DMA3), which can transfer data from memory to memory without going through the CPU. The CPU is stopped during the transfer, so there's no need to wait for it to finish. The Famicom also had DMA for sprites (OAMDMA), but all it did was send 256 bytes to OAM from a specified source page. GBA DMA is much more general: you can freely configure the source, destination, count, and transfer timing.
| Register | Address (for DMA0) | Contents |
|---|---|---|
DMAxSAD | 0x040000B0 | Source address |
DMAxDAD | 0x040000B4 | Destination address |
DMAxCNT_L | 0x040000B8 | Transfer count. Writing 0 means maximum (0x4000 for DMA0-DMA2, 0x10000 for DMA3) |
DMAxCNT_H | 0x040000BA | bit5-6: destination increment/decrement, bit7-8: source increment/decrement, bit9: repeat, bit10: 16bit/32bit, bit12-13: start timing, bit14: interrupt, bit15: enable |
DMA1 onward are laid out at 12-byte offsets. There are four address adjustment modes: "increment," "decrement," "fixed," and "increment (reset on each repeat)," and with a fixed source you can fill memory with the same value.
There are four start timings.
| Value | Timing | Main uses |
|---|---|---|
| 0 | Immediate | Copying or filling memory |
| 1 | VBlank | Rewriting OAM or palettes during VBlank |
| 2 | HBlank | Rewriting scroll values etc. per line (raster scrolling) |
| 3 | Special | DMA1/DMA2 refill the sound FIFOs, DMA3 does video capture |
The channels also have different roles: DMA0 has the highest priority and suits HBlank raster effects. DMA1 and DMA2 are used to refill the DirectSound FIFOs mentioned earlier, and DMA3 is used for general-purpose transfers. DMA0 can't read from cartridge ROM, and only DMA3 can write to the cartridge.
The sound refill is a bit special: if you set the destination to a FIFO address and the timing to special, it transfers just 4 words (16 bytes) each time the FIFO runs low. In this case, the count in DMAxCNT_L and the 16bit/32bit setting are ignored, and the destination address doesn't increment.
Something less flashy: EEPROM save data is also read and written via DMA. The EEPROM is serially connected and exchanges 1 bit per 16-bit transfer, so you lay out the command and address bit sequence in memory and send it all at once with DMA3.
Here are the key points when writing it for an emulator.
- Registers and internal counters are separate: When a transfer starts, the values of
DMAxSAD,DMAxDAD, andDMAxCNT_Lare copied into internal counters, and the transfer advances those. The register values stay as they are. When a repeat resumes the transfer at the next HBlank, only the count (and the destination, if it's set to "reset") is reloaded from the registers, and the source continues from where it left off - Load only at the moment it's enabled: Copying into the internal counters happens only when bit15 goes from 0 to 1. Rewriting
DMAxCNT_Hof an already-enabled channel doesn't start an immediate transfer - Watch timing on the rising edge: Transfer once at the moment VBlank or HBlank starts. HBlank DMA only happens on visible lines (0-159), not during HBlanks within VBlank. Video capture runs during HBlank on lines 2-161 and is automatically disabled when line 162 is reached
- Time advances during transfers: rgba runs DMA all at once at instruction boundaries, but for each unit transferred it advances the clock by the cycle count, advancing the timers and LCD along with it. There are tests that keep reading a timer counter with a fixed source, so without this the value doesn't change
- Higher priority interrupts it: If an HBlank comes in while
DMA3is in the middle of a long transfer,DMA0's HBlank DMA interrupts it and runs first. rgba checks whether an HBlank has arrived after each unit transferred, only when a higher-priority HBlank DMA is enabled - Determine the EEPROM size from the transfer count: There are two EEPROM sizes, 512 bytes and 8KB, with different address bit counts (6 bits and 14 bits). You can't tell them apart by looking at the ROM, so rgba determines the address bit count from the DMA transfer count when the game sends a command (9 or 17 for reads)
Timing
Once the CPU instructions are more or less working, the next thing you start to care about is timing. This may have been the hardest part.
Timing broadly involves these three things.
- Rendering: how many cycles one line and one frame take
- Instructions: how many bus accesses one instruction makes (S/N/I cycles)
- Memory: how many cycles one of those accesses takes depending on where it goes (wait states)
Rendering Timing
According to GBATEK, drawing one dot takes 4 cycles.
| Item | Dots | Cycles |
|---|---|---|
| Drawing | 240 | 960 |
| HBlank | 68 | 272 |
| Total (1 line) | 308 | 1232 |
After 160 lines are drawn there are 68 lines of VBlank, so one frame is 1232 × 228 = 280896 cycles, about 59.73Hz. The confusing part is that according to GBATEK, drawing itself takes 960 cycles (240 × 4), but the period during which the H-Blank flag in DISPSTAT is 0 is 1006 cycles. In other words, the H-Blank flag isn't set right after drawing ends but a little later. A line is still 1232 cycles, but if you mix these up it's easy to mistakenly think a line is 1006 cycles.
Instruction Timing: S, N, and I Cycles
If you look at the ARM7TDMI datasheet, instruction execution times are written not as "so many clocks" but as combinations of cycle types, like 2S + 1N.
| Type | Name | Meaning |
|---|---|---|
| S | Sequential | Access to the address following the previous access (+2 or +4) |
| N | Non-sequential | Access to an address unrelated to the previous access |
| I | Internal | A cycle of internal CPU processing only, not using the bus |
According to ARM's documentation, on each access the ARM7TDMI tells the bus whether the next cycle is N, S, or I through the nMREQ and SEQ signals. S is an advance notice saying "I'm going to access the address after the last one," and the memory controller can use it to take a faster access path like DRAM page mode. For memory that can read consecutive addresses faster, S ends up faster.
This mechanism goes back to the very first ARM. DRAM at the time could read consecutive accesses to nearby addresses about twice as fast using page mode. So ARM introduced S cycles to take advantage of page mode for consecutive accesses like instruction fetches and LDM/STM.
On the GBA, the cartridge bus takes exactly this approach. The cartridge bus shares the same lines for address and data; the cartridge latches the lower 16 bits of the address on an N access and increments it itself on each S access. So an S access doesn't need to resend the address, and the wait states described later are set lower than for N.
So, summarizing the per-instruction cycle counts from the ARM7TDMI datasheet (Technical Reference Manual) gives the following. Details for each instruction are in the "Instruction Cycle Timings" chapter, and the list is in "Instruction speed summary."
https://developer.arm.com/documentation/ddi0210/c/Instruction-Cycle-Timings
| Instruction | Cycles |
|---|---|
Data processing (ADD, MOV, etc.) | 1S |
| + shift amount specified in a register | 1S + 1I |
+ result written to PC | 2S + 1N |
B, BL, BX | 2S + 1N |
MUL / MLA | 1S + mI / 1S + (m+1)I |
MULL / MLAL | 1S + (m+1)I / 1S + (m+2)I |
LDR | 1S + 1N + 1I |
LDR (load into PC) | 2S + 2N + 1I |
STR | 2N |
LDM (n registers) | nS + 1N + 1I |
LDM (including PC) | (n+1)S + 2N + 1I |
STM (n registers) | (n-1)S + 2N |
SWP | 1S + 2N + 1I |
SWI | 2S + 1N |
MRS, MSR | 1S |
By the way, the "Instruction Cycle Timings" section of the book ARM System Developer's Guide by Andrew Sloss, Dominic Symes (both of ARM), and Chris Wright also has a summary of ARM7TDMI cycle tables, and I referred to it a lot. It gives total cycle counts without splitting S, N, and I (3 for LDR, 2+N for LDM), and they match the table above when you add things up. It also has tables for the ARM9TDMI (5 stages) and ARM11 (8 stages) side by side, so it's fun to compare how cycle counts change as the pipeline gets deeper.
It took me a while to understand how to read this table. The key point is that most of the S cycles are fetches of the next instruction.
Because it's pipelined, the next instruction is always being fetched behind the scenes during execution. For a normal instruction the fetch is from a consecutive address, so it's S. ADD being 1S means "execute in 1 clock, and fetch the next instruction with S during that time."
A branch being 2S + 1N is the cost of refilling the pipeline.
- Compute the branch target address. Fetching continues during this time, but that is discarded (S)
- Fetch the instruction at the branch target. The address jumps, so it's N
- Fetch the instruction after the branch target (S)
Only then are all three stages, fetch, decode, and execute, filled. Two instructions' worth is wasted every time you branch, and seeing this makes it clear why conditional execution, mentioned earlier, exists to avoid branching.
LDR's 1S + 1N + 1I breaks down as: fetch the next instruction while computing the address (S), read the data (N, since it's an address unrelated to the code), and write the read value to the register (I). The +1I when the shift amount is specified in a register is because there aren't enough register read ports, so it takes one extra cycle, and PC appearing as +12 is because PC advances during that one cycle. The pipeline shows its face here too.
The m in multiplication depends on the value of the multiplier (Rs). The ARM7TDMI's multiplier is 32 bits × 8 bits; it computes 8 bits at a time and stops once the upper bits are all 0 (or all 1) (early termination).
| m | Condition |
|---|---|
| 1 | Bits 8-31 of Rs are all 0 or all 1 |
| 2 | Bits 16-31 of Rs are all 0 or all 1 |
| 3 | Bits 24-31 of Rs are all 0 or all 1 |
| 4 | Otherwise |
However, the unsigned UMULL/UMLAL only terminate early in the "all 0" case. In other words, the smaller the number you multiply by, the faster it is. Since the cycle count changes with the value, timing tests won't pass unless you implement this properly too.
Memory Timing: Wait States
So far we know the number of S, N, and I accesses. Next, how many cycles each of those accesses takes is determined by the memory being accessed. I is always 1 cycle, and S and N take "1 + wait" cycles.
Cartridge ROM wait states can be set with the WAITCNT register, and the first access (N) and consecutive accesses (S) can be set separately. Commercial cartridges mostly use WAITCNT = 4317h, where ROM has 3 wait states for N and 1 for S, i.e. N is 4 cycles and S is 2 cycles. I suppose the GBA is using the ARM7TDMI's general-purpose S/N mechanism directly for cartridge access speed.
Bus width also comes into play. The cartridge bus is 16 bits, so a 32-bit access is split into two 16-bit accesses (the second is always S). With WAITCNT at 4317h, the cycles per access are as follows.
| Target | N (16bit) | S (16bit) | N (32bit) | S (32bit) |
|---|---|---|---|---|
| IWRAM | 1 | 1 | 1 | 1 |
| EWRAM | 3 | 3 | 6 | 6 |
| ROM | 4 | 2 | 6 | 4 |
Combining this with the instruction table finally gives the cycle count of one instruction. For example:
- Thumb
addin ROM: 1S = 2 cycles - ARM
addin ROM: 1S (32bit) = 4 cycles - ARM
addin IWRAM: 1S = 1 cycle - Thumb branch in ROM: 2S + 1N = 2 + 2 + 4 = 8 cycles
The same add differs by 4x depending on where it lives and which state it's in. Looking at this table makes it very clear why GBA games are written in Thumb, with only the speed-critical parts in ARM placed in IWRAM.
So What Was Actually Hard?
If that were all, you'd just look things up in the tables and add them, but in practice the following are hard. I'll also note how far rgba gets with each. Honestly, all of them are just done in a way that seems about right, and few are properly reproduced.
- S/N depends on surrounding instructions: It's S if the address follows the previous access and N otherwise, so it can't be determined from the instruction alone. When
LDRorSTRaccesses data, the following instruction fetch becomes N even though it continues the code (because the previous access was data). rgba doesn't track the previous access target and decide each time; it just applies the cycle table formula per instruction. Representative patterns, like making the fetch after a load/store N, are put in by hand - Relationship with the pipeline: Emulators are often written around "execute," but what consumes cycles is fetching. If you don't keep track of what was fetched when, the S and N counts drift. rgba computes fetch cycles based on the address in
PC - ROM 128KB boundaries: The cartridge latches the address once and then increments it internally, but that counter can't cross a 128KB block. So an access to the start of a block is forced to be N even if it's consecutive. rgba checks this for both CPU accesses and DMA
- Prefetch buffer: Setting bit14 of
WAITCNTmakes the cartridge read ahead while the CPU is accessing something other than ROM or during I cycles. If the prefetch hits, a ROM S access takes 1 cycle. But tracking the buffer state accurately is quite hard, so rgba simplifies it very crudely to "if prefetch is enabled, ROM S is 1 cycle" - Interaction with DMA and interrupts: The CPU stops while DMA is running, and when interrupts come in also depends on instruction cycle counts. rgba runs DMA all at once at instruction boundaries and only advances the clock during that time. I did add the 2 internal cycles at start (4 cycles if both the source and destination are on the cartridge) and the first access being N. Interrupts are also only checked at instruction boundaries
In the mGBA test suite's timing tests, only 381 of 1660 items passed before the fixes, and 691 after. Still, that's less than half, so I'm not done with cycle accuracy. There's plenty left to do, like deciding S/N by tracking the previous access, and properly keeping the prefetch buffer state.
If you just want games to run, they'll run even if timing is a bit off, so how far you push is up to the implementer's motivation. But games that do things like raster scrolling, rewriting things with precise timing within a single line, can have their graphics glitch because of these discrepancies. rgba once had a bug where it estimated ROM S accesses at twice the cost when prefetch was enabled. That made code in ROM run twice as slow, and raster effects were off.
You Can Write GBA Games in Rust
So far I've written nothing but troublesome ARM7TDMI stories, but flip that around and the GBA is an ordinary 32-bit ARM machine, so you can write games in Rust. On the Famicom or Game Boy you'd be grinding away in assembly or C, so I think this is a kind of fun unique to the GBA.
I previously wrote a post about implementing Conway's Game of Life in Rust (in Japanese).
https://bokuweb.hatenablog.com/entry/2020/04/14/101202
I succeeded to run Conway's Game of Life written in Rust on GameBoyAdvance. #rustlang https://t.co/A7rOJg3SwV https://t.co/KEiokbDCI7
— bokuweb (@bokuweb17) April 5, 2020
Back then Rust didn't support the ARM7TDMI, so I had to write my own target JSON, specify thumbv4-none-eabi to LLVM, build with cargo-xbuild, build binutils myself... it was quite a lot of work.
Now Rust has a thumbv4t-none-eabi target (it's Tier 3, so you still need nightly and build-std). You can also use rust-lld as the linker, so you can build without setting up an arm-none-eabi toolchain. It's gotten a lot easier.
As an introduction to GBA game development, I also recommend "Writing a Game Boy Advance Game," which has been translated into Japanese on POSTD.
https://postd.cc/writing-a-game-boy-advance-game/
It uses C and devkitARM, starting from putting a dot on the screen and ending with a simple game. It covers the memory map, the difference between bitmap mode 3 and tile mode 0, sprites and OAM, key input, waiting for VBlank before drawing, and so on, all concisely. Even from the emulator writer's side it's helpful, since it shows how games use the hardware. It was also the very first article I read when I started implementing.
There are also GBA crates like gba and the more game-engine-oriented agb, so if you're building something serious, using those seems like a good idea. Here, to see how things work, I'll write it without any crates.
Hello World
Hello World in GBA programming is apparently putting a dot on the screen. So let's put a single red dot in the center of the screen.
These are the five files we need.
hello-gba
├── .cargo/config.toml
├── Cargo.toml
├── linker.ld
├── rust-toolchain.toml
└── src/main.rs
src/main.rs
#![no_std]
#![no_main]
// Startup routine (crt0)
core::arch::global_asm!(
".section .text._start, \"ax\"",
".arm",
".global _start",
"_start:",
" b 1f", // Jump over the ROM header
" .space 0xC0 - 4", // ROM header (area for the logo and title)
"1:",
" ldr sp, =0x03007F00",
" ldr r0, =main",
" bx r0", // main is Thumb, so its address is odd → switches to Thumb
);
const DISPCNT: *mut u16 = 0x0400_0000 as *mut u16;
const VRAM: *mut u16 = 0x0600_0000 as *mut u16;
#[unsafe(no_mangle)]
extern "C" fn main() -> ! {
unsafe {
// Enable Mode 3 + BG2
DISPCNT.write_volatile(0x0403);
// Put a red dot at the center of the screen (x=120, y=80)
VRAM.add(80 * 240 + 120).write_volatile(0x001F);
}
loop {}
}
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
Let's go through it in order.
#![no_std] says to link core instead of std. std uses OS features, so it can't be used on the GBA, which has no OS. There's no allocator either, so as-is you can't use Vec or String.
#![no_main] says not to use the entry point Rust provides. The 2020 post used #![feature(start)] and #[start], but that feature was later removed, so now you write it this way. Instead, you write your own startup routine and call main from it.
I used to put the startup routine in a separate crt0.S file and assemble it with arm-none-eabi-as, but now you can write it directly in the Rust source with global_asm!. All it does is the following.
- Execution starts at the beginning of the cartridge (
0x08000000), so firstbjumps past the ROM header. The first0xC0bytes of a GBA ROM are the header, which holds the Nintendo logo and the title - Set
SP.0x03007F00is the same value the BIOS sets as the user modeSP - Load the address of
mainintor0and jump withbx
The final bx r0 is the "jumping to an odd address switches to Thumb" thing mentioned earlier. Since the target is thumbv4t-none-eabi, main is compiled as Thumb. And the linker sets the lowest bit of main's address to 1 for us. So the moment you bx, it switches to Thumb state. I thought this spec was scary while writing the emulator, but from the user's side it's actually convenient.
The body of main just writes to a register and VRAM.
DISPCNT.write_volatile(0x0403);
0x04000000 is DISPCNT, the LCD control register. The lower 3 bits are the video mode, and bit10 enables BG2. So 0x0403 means display BG2 in mode 3.
The GBA basically draws by tiling 8x8 tiles, like the Famicom and the Game Boy, but modes 3-5 are bitmap modes, where you can draw just by writing pixels directly into VRAM. You don't need to prepare tiles or palettes, so it's perfect for Hello World.
write_volatile is there to prevent compiler optimizations from omitting or reordering the writes. If the compiler thinks it's ordinary memory, it might remove the write with "it's written but nobody reads it, so it's unnecessary."
VRAM.add(80 * 240 + 120).write_volatile(0x001F);
0x06000000 is VRAM, and in mode 3 the 240×160 pixels are laid out at 2 bytes per pixel. So pixel number 80 * 240 + 120 is the center of the screen.
Colors are 15-bit: bits 0-4 are red, bits 5-9 green, and bits 10-14 blue. 0x001F has red at max and green and blue at 0, so it's a red dot.
#[panic_handler] is what happens on panic, and with no_std you have to define it yourself. Here it's an infinite loop.
linker.ld
This tells the linker which sections to place at which addresses. On the GBA, the program goes in cartridge ROM (0x08000000-), with _start at the beginning.
ENTRY(_start)
MEMORY {
ewram (w!x) : ORIGIN = 0x02000000, LENGTH = 256K
iwram (w!x) : ORIGIN = 0x03000000, LENGTH = 32K
rom (rx) : ORIGIN = 0x08000000, LENGTH = 32M
}
SECTIONS {
.text : {
KEEP(*(.text._start));
*(.text .text.*);
. = ALIGN(4);
} >rom
.rodata : {
*(.rodata .rodata.*);
. = ALIGN(4);
} >rom
/DISCARD/ : { *(.ARM.exidx*) }
}
If you use global variables, you need to put .data and .bss in WRAM and initialize them in the startup routine. They're not used this time, so I left that out.
.cargo/config.toml / rust-toolchain.toml / Cargo.toml
# .cargo/config.toml
[build]
target = "thumbv4t-none-eabi"
[unstable]
build-std = ["core"]
[target.thumbv4t-none-eabi]
linker = "rust-lld"
rustflags = ["-Clink-arg=-Tlinker.ld"]
# rust-toolchain.toml
[toolchain]
channel = "nightly"
components = ["rust-src"]
# Cargo.toml
[package]
name = "hello-gba"
version = "0.1.0"
edition = "2024"
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"
There's no prebuilt core distributed for thumbv4t-none-eabi, so build-std builds core from source. That's why rust-src is needed.
Build and Run
cargo build --release
rust-objcopy -O binary target/thumbv4t-none-eabi/release/hello-gba hello.gba
rust-objcopy comes from cargo install cargo-binutils and rustup component add llvm-tools. It strips the headers and so on from the ELF to make a ROM image. The resulting hello.gba is only 240 bytes.
While we're at it, let's disassemble it.
08000000 <_start>:
8000000: ea00002e b 0x80000c0
...
80000c0: e59fd004 ldr sp, [pc, #0x4] @ 0x80000cc
80000c4: e59f0004 ldr r0, [pc, #0x4] @ 0x80000d0
80000c8: e12fff10 bx r0
80000cc: 00 7f 00 03 .word 0x03007f00
80000d0: d5 00 00 08 .word 0x080000d5
080000d4 <main>:
80000d4: b580 push {r7, lr}
80000d6: af00 add r7, sp, #0x0
80000d8: 2001 movs r0, #0x1
80000da: 0680 lsls r0, r0, #0x1a
80000dc: 4902 ldr r1, [pc, #0x8] @ 0x80000e8
80000de: 8001 strh r1, [r0]
80000e0: 4802 ldr r0, [pc, #0x8] @ 0x80000ec
80000e2: 211f movs r1, #0x1f
80000e4: 8001 strh r1, [r0]
80000e6: e7fe b 0x80000e6
80000e8: 03 04 00 00 .word 0x00000403
80000ec: f0 96 00 06 .word 0x060096f0
A lot of what I've written about in this post shows up here, which is fun.
_startis ARM instructions, so every one starts withe(AL)- The
ldr sp, [pc, #0x4]at0x80000c0reads0x80000cc. Not0x80000c0+ 4, but sincePCis +8,0x80000c8+ 4 =0x80000cc main's address is0x080000d4, but the literal pool holds the odd value0x080000d5.bx-ing to it switches to Thumb, and frommainon it's 2-byte Thumb instructions- Making
0x04000000takes two instructions,movs r0, #1andlsls r0, r0, #26. Thumb'smovcan only hold an 8-bit immediate, so it apparently builds the value with a shift
Running this in rgba looks like this.
A single red dot in the middle. Plain, but it works.
By the way, the ROM header is zero-filled, so it won't boot on real hardware. To run it on real hardware, you need to write the logo and checksum with something like gbafix.
The web version of rgba's debugger can load a local .gba file, so you can throw the ROM you built right in and check it while stepping through. Being able to trace a game I wrote with the debugger of an emulator I wrote is pretty fun.
Test ROMs
Once you start writing the CPU, I think it's good to first aim to pass armwrestler. armwrestler is a test ROM that relentlessly tests ARM7TDMI instructions, with categories for ALU (arithmetic instructions), LDR/STR, and LDM/STM for both ARM and Thumb. When you pick one from the menu, it shows the result for each instruction on screen. Below is armwrestler-gba-fixed running in rgba; on the left is the menu, and on the right the results of the ARM ALU test.


Results are shown per instruction, so you can immediately see which instruction is broken, and since the display is just text, you can try it even if your rendering isn't that far along. Getting this to pass before running games helps you avoid the state of "the screen is broken, but I can't tell whether the cause is in the CPU or the rendering."
However, the original armwrestler has some LDM/STM tests that don't work properly. There's armwrestler-gba-fixed, which fixes them, and its repository also includes a prebuilt ROM (armwrestler-gba-fixed.gba), so if you're starting now, this is the one to use.
https://github.com/destoer/armwrestler-gba-fixed
After armwrestler, it's good to work through the following, which test things in more detail. rgba also aims to pass these three.
What's Next
- Tighten up timing more to increase the number of passing mGBA test suite tests
- Fix homebrew that doesn't run
- Make the debugger a bit more convenient
Compared to the Famicom and the Game Boy, the GBA has plenty of documentation and test ROMs, and GBATEK and Tonc in particular helped me enormously. On the other hand, the ARM7TDMI is a CPU deep enough to fill a whole book on its own, and I feel like I finally understood a little of it by writing an emulator.
References
- https://problemkaputt.de/gbatek.htm
- https://www.coranac.com/tonc/text/
- https://postd.cc/writing-a-game-boy-advance-game/
- https://github.com/mgba-emu/mgba
- https://github.com/ExPixel/Pyrite
- https://github.com/michelhe/rustboyadvance-ng
- https://github.com/jsmolka/gba-tests
- https://github.com/gbdev/awesome-gbadev
- https://github.com/endrift/gbajs
- https://github.com/Cult-of-GBA/BIOS
- https://github.com/Nebuleon/ReGBA/tree/master/bios
- https://github.com/camthesaxman/gba_bios
- https://github.com/destoer/armwrestler-gba-fixed
- https://github.com/DenSinH/FuzzARM
- https://github.com/devkitPro/gba-examples

