System Library
This page is a guide to the games/tbs/src/system/ folder of the Alchemy
project. The system library in it is the low-level runtime kernel that boots
Golden Sun: The Broken Seal and drives every frame on Game Boy Advance hardware.
Everything else in the game sits on top of this folder. It owns startup, the
sySynch() tick loop, the 20-slot event table, IWRAM and EWRAM heaps, and
fixed-point and matrix math. It also handles sprite depth sorting,
decompressors, link-cable transfers, atomic flash saving, and the 8 MB Game Pak
layout.
The system library is never seen directly on screen, yet it underlies every
fade, tilted World Map scanline, and corruption-safe save slot. The sections
below give the file map, the GBA hardware and r4 ABI rules, the full SGL-style
call reference, and the ROM and flash layout. The high-level runtime model is
described in The system library.
File map
| File(s) | Role |
|---|---|
system.c, system_internal.h | Parent translation unit #includeing the system_*.c parts in ROM order |
entry.s, system_start_up.c, irq.s, irq_table.s | ROM entry vector, syInit, IWRAM setup, ARM IRQ dispatcher (saves r4 itself) |
system_frame.c | sySynch() (relocates stack to a fixed IWRAM address during events, copies any overlapping caller stack slice aside and restores it on return, and checks EventsRunning), syVBlankHandler, key repeat, and sleep (L + R for 3 s or 3 min idle) |
system_event.c | 20-entry EventBuf (EVENT_PASS_TICK = 0xC80, EVENT_PASS_VBLANK = 0x480), sySetEvent, syCloseEvent, and suspend and resume |
system_heap.c, heap_release.s | IWRAM and EWRAM LIFO bump allocators (syHeapRelease frees the block and everything allocated after it) and 62 numbered slots in HeapSlots[64] (syHeapSlotAllocate prefers IWRAM and is idempotent on occupied slots; syHeapSlotAllocateEWRAM prefers EWRAM) |
ewram.s, iwram.s, iwram_entry.s, iwram_high.s, iwram_routines.s, ram.inc | Fixed RAM layout (MainRoutineStateWork, ActorSnapshotWork) and hot ARM math, fill, and decompressor routines |
system_oam.c, system_vram_cache.c, system_io_write_queue.c, system_screen_fade.c | 256-bucket OAM depth sorter, sprite VRAM cache, VBlank register write queue, hardware brightness fades |
system_math.c, system_matrix.c, math_table.c, trig.s, inner_product.s | 16.16 fixed-point math, quarter-turn sine table, 3×4 matrix transforms, 3D-to-2D projection |
system_decompress.c, decompress_byte_lz.s, decompress_tagged_lz.s, move_to_front.inc | Byte LZ, tagged LZ, move-to-front LZ, halfword LZ, sprite picture, and 1bpp glyph decoders |
system_bup.c, bupdata.c | Atomic copy-on-write flash saving (3 files × 2 × 4 KB parts across 16 sectors; vendor drivers in games/common/sdk/flash/) |
system_serial.c | Per-VBlank link-cable packet exchange and 20-byte chunked block transfers |
system_debug_text.c, number_text.c | BG0 cursor-based debug printer (syPrint, syPrintHex, syPrintDecimal) |
rom_start.c, rom_header.s, resource_directory.s | 192-byte GBA header (AGSJ–AGSI), 1,000-row resource directory (25 trailing spare rows), ResourceBuildStamp |
stubs.s, stub.inc, sprite_stubs.s, sprite_metadata.c | StubsSystem jump table (called by overlays) and stub macros |
overlay/overlay.ld, overlay/imports.inc, overlay/overlays.list | Linker rules for all 96 compressed overlays and build-generated import stub list |
channel_update_entry.s, resident_mixer.s, bios.s | Camelot's 352-samples-per-frame IWRAM audio mixer (kept here to share the r4-scratch ABI) and 4 BIOS wrappers |
Raw GBA hardware and the r4 ABI
Reading the ROM beside GBATEK shows one
hardware constraint driving almost every low-level decision. The 16-bit Game Pak
bus takes 8 cycles to fetch a 32-bit ARM instruction, while the 32 KB
on-chip IWRAM delivers one in 1 cycle. Because of that gap, ARM code
never runs directly from ROM. Hot ARM routines live permanently in IWRAM
(iwram_routines.s) or copy into IWRAM or the stack on demand, while ROM code
runs in 16-bit Thumb mode.
| GBATEK hardware fact | How the system library responds |
|---|---|
| Fast IWRAM is only 32 KB | Keeps bookkeeping tiny (1-level matrix stack, 20-slot EventBuf) and stages temporary ARM helpers in heap slots |
Only ARM mode has 64-bit multiply (smull) | Keeps 16.16 syMulFX as an ARM routine in IWRAM called from Thumb |
| BIOS provides div, sqrt, atan, and LZ decoders | Never uses them: Camelot supplies faster custom routines (even compiler division routes to system/), calling only 4 BIOS SWIs: Halt (02h), Stop (03h), CpuSet (0Bh), and SoundBias (19h) |
Halt wakes on any IRQ; Stop wakes only on keypad, cartridge, or link | Loops on Halt until its own VBlank flag sets, and arms the keypad IRQ before Stop sleep |
BIOS IRQ prologue saves r0–r3, r12, lr before calling the user handler | Camelot's IWRAM IRQ handler (irq.s) explicitly saves r4 itself to honour -fcall-used-r4 |
| A DMA channel is 3 contiguous words (source, dest, control) | Writes all three atomically with one store instruction and feeds per-scanline registers via HBlank DMA |
| Affine BG reference origin can change every scanline | Drives the tilted World Map ground per scanline via HBlank DMA |
| Direct Sound is two sample FIFOs; mixing is software | Runs Camelot's custom 352-samples-per-frame IWRAM mixer every VBlank |
- Registers and
-fcall-used-r4: The GBA's CPU keeps working values in sixteen registers (r0–r15). Under the standard ARM and Thumb calling convention, a function may freely overwriter0–r3(caller-saved scratch) but must preserver4–r11on the stack before returning (callee-saved). Camelot compiles with-fcall-used-r4, movingr4into the scratch pool across all game code. That covers every Thumb C file (Alchemy GCCxgcc, a July 2000 GCC 2.96 snapshot), ARM C file (GCC 2.95.2), hand-written assembly routine, and inline asm statement. Doing so trades one saved register for smaller, faster Thumb prologues (syDMAXCopytakes its 4 arguments inr0–r3and clobbers no callee-saved registers). Only the reconstructed flash andm4asound routines ingames/common/sdk/compile withold_agbcc. - Empirical measurements from matching: Outside
syAtan's 16-bit return, angles pass in 32-bit registers (narrowing to 16-bitANGLEbreaks matching in 349 TBS functions and 663 TLA functions). Outsidesystem/, game code writes hardware MMIO registers directly far more often than through the VBlank queue (521 direct stores vs. 75 queued).
SGL lineage and call reference
Comparing the ROM against
SGL's manual (Sega's
Saturn library) shows 37 sy* functions mirroring SGL's sl* counterparts
wherever math flows. They share FIXED, 65,536-unit ANGLE, 12-word MATRIX,
identical syRotX, syRotY, and syRotZ matrix entries and signs,
divisor-first syDivFX(divisor, dividend), syAtan, syPerspective, and
syDMAXCopy. Bookkeeping is trimmed to fit 32 KB IWRAM: a 1-level matrix stack
instead of 20, a 20-slot EventBuf instead of 64 × 128-byte work blocks,
level-only syLookAt, and cursor-based syPrint. The tables below follow
StubsSystem in stubs.s, plus common inlines.
Events and the tick
| Call | Behaviour | SGL counterpart |
|---|---|---|
sySynch | Runs n game ticks (tick-pass events, OAM build, VBlank wait) and returns | slExecuteEvent + slSynch combined |
syInitEvent | Clears the 20-entry event table | slInitEvent (64 entries in SGL) |
sySetEvent | Registers an event at a priority and sorts EventBuf; updates priority if present | slSetEvent (no priority; returns EVENT *) |
syCloseEvent | Removes an event callback from EventBuf | slCloseEvent (takes EVENT *) |
sySuspendEvent / syResumeEvent | Suspends or resumes one event (or all if NULL) | None |
syExecuteEvent | Runs all active events in a pass (EVENT_PASS_TICK or EVENT_PASS_VBLANK) | slExecuteEvent (single pass in SGL) |
sySetEventFlags | Sets per-event flags (e.g., keep running while overlay events are suspended) | None |
syIntFunction | Installs or enables an interrupt handler (NULL disables) | slIntFunction (VBlank-only in SGL) |
syInputResetKeyRepeat | Resets held-button repeat timers | None |
Math & Matrix
| Call | Behaviour | SGL counterpart |
|---|---|---|
syRandom | Next 16-bit PRNG output (0..65535; callers mask bits rather than scaling) | slRandom |
syAtan | Vector angle from Y axis (16-bit ANGLE) | slAtan |
sySquart, sySquartIWRAM, sySquartFX | Integer (ROM or IWRAM) and fixed-point sqrt (sySquartFX computes 8 fractional bits) | slSquart / slSquartFX |
sySin, syCos, syVectorAddPolarOffset | Quarter-turn trig and polar ground offset | slSin / slCos |
syMulFX, syDivFX, syIntegerDivide, syIntegerDivideUnsigned | 16.16 multiply and divide (b / a divisor first) and integer division | slMulFX / slDivFX |
syInitMatrix, syUnitMatrix, syUnitMatrixCurrent, syUnitMatrixCurrentInline | Initialise stack and identity matrices | slInitMatrix / slUnitMatrix |
syPushMatrix, syPopMatrix | 1-level matrix save and restore (second push ignored) | slPushMatrix / slPopMatrix (20 deep) |
syGetMatrix, syLoadMatrix, syMultiMatrix | Copy out, load, or multiply into current matrix | slGetMatrix / slLoadMatrix / slMultiMatrix |
syRotX, syRotY, syRotZ, syMatrixRotate | Rotate current matrix about axes | slRotX / slRotY / slRotZ |
syMatrixTranslateVector, syMatrixScaleVector, syMatrixRotateTranslate, syMatrixRotateTranslateScale | Vector translate and scale, plus combined transforms | slTranslate / slScale (scalars in SGL) |
syLookAt, syLookAtLoad | Multiply or load level-horizon camera matrix | slLookAt (adds roll in SGL) |
syCalcPoint, syConvert3Dto2D | Transform 3D point and project to screen (returns draw scale, writes depth) | slCalcPoint / slConvert3Dto2D |
syPerspective, sySetScreenDist | Set vertical FOV or focal length and near and far clip | slPerspective (horizontal FOV) / slSetScreenDist |
Memory, DMA, I/O, Graphics, Link, Save & Resources
The 8 MB Game Pak, modules, and flash hardware
Modules and stub calls
The 8 MB ROM (0x08000000–0x08800000) splits into 14 fixed-address resident
modules in ld_script.ld. Each opens with an
append-only stubs.s jump table of 8-byte *Stub thunks (e.g., btRunStub →
btRun). Camelot's adherence to that append-only rule is visible in the
European editions, where a single new stub was added at the end. Cross-module
calls hit the target module's stub table, and overlay calls take two hops
(overlay import stub → module stub → target). Module 0 (system/) is the
exception: other resident modules call its functions directly without going
through StubsSystem, so only overlays use StubsSystem.
Resource directory

The resource directory holds 1,000 rows (0..999), including 25 trailing spare
slots so additions never shift existing IDs. In rough order, it covers UI and
fonts, the title screen, battle backgrounds, minigames and battle effects,
monsters, maps and tilesets, and the 96 overlays. An early row points to
ResourceBuildStamp, which saves record to detect mismatched builds.
Flash chip hardware
The 64 KB flash chip cannot overwrite bytes in place. Each 4 KB sector must be
erased whole and programmed byte-by-byte with read-back verification and
timeouts so that a failing chip cannot hang the console. Cartridges shipped with
flash chips from four vendors probed at runtime. Because Atmel chips have
128-byte physical sectors,
games/common/sdk/flash/ erases 32 at a time to
emulate 4 KB sectors.
Source files
| File | Description |
|---|---|
bupdata.c | The save signature and sector header template, and link test data nothing reads. |
math_table.c | Trigonometry tables: a quarter-wave sine, tangents and the quadrants' sines. |
number_text.c | The digit characters and place values numbers are written with. |
rom_start.c | The cartridge's first instruction, where the BIOS starts the game: ahead of the cartridge header (rom_header.s), it goes on to the game's start-up. |
sprite_metadata.c | Finding a sprite animation's metadata row. |
system.c | The system library's object: what every other part of the game stands on. |
system_bup.c | Saving: flash sectors, parts and the save state. |
system_debug_text.c | Number text, the debug text screen and the window graphics. |
system_decompress.c | Resource decoding and pixel buffer shading, through RAM copies of ARM code. |
system_event.c | Events: per-tick and VBlank functions in priority order. |
system_frame.c | Interrupt handlers, the tick wait, key repeat and the VBlank handler. |
system_heap.c | The heap: its two bump allocators and heap slots. |
system_internal.h | What every part of the system library's object shares: its includes and the one call into the compiler's library that two parts make. |
system_io_write_queue.c | The register write queue that VBlank carries out after each finished tick. |
system_math.c | Random numbers, angles and square roots. |
system_matrix.c | The 3D transform, its stack, the look-at matrix and the projection. |
system_oam.c | The tick's sprite lists: affine matrices, depth slots and the OAM build. |
system_screen_fade.c | Screen fades through the blend registers: the screen brightens toward white or darkens toward black, BLDY running from 0, the picture as drawn, to FADE_LEVEL_MAX, all white or all black, one step each VBlank. |
system_serial.c | The link cable: payload exchange, block transfers and the link test. |
system_start_up.c | |
system_vram_cache.c | The sprite VRAM cache: blocks, entries and loading pictures. |
| File | Description |
|---|---|
asm.h | The matching devices: the asm statements the C holds for the compiler, not for the program, each a fake match. |
definitions.h | The system library's types and constants, as SGL's sl_def.h holds its own: the hardware's registers, and each group's structures, enums and fixed values. |
globals.h | The system library's variables, as SGL keeps its system variables and work areas: each group's variables in IWRAM, EWRAM and ROM. |
mul_fx.h | syMulFXArm, the 16.16 fixed-point multiply: SGL's slMulFX written out for the C compiled as ARM, where the Thumb C calls the same multiply in IWRAM. |
rom_header.h | The start of the cartridge, where the console begins the game: a soft reset jumps back to it. |