Skip to Content
The Alchemy Project

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.hParent translation unit #includeing the system_*.c parts in ROM order
entry.s, system_start_up.c, irq.s, irq_table.sROM entry vector, syInit, IWRAM setup, ARM IRQ dispatcher (saves r4 itself)
system_frame.csySynch() (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.c20-entry EventBuf (EVENT_PASS_TICK = 0xC80, EVENT_PASS_VBLANK = 0x480), sySetEvent, syCloseEvent, and suspend and resume
system_heap.c, heap_release.sIWRAM 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.incFixed 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.c256-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.s16.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.incByte LZ, tagged LZ, move-to-front LZ, halfword LZ, sprite picture, and 1bpp glyph decoders
system_bup.c, bupdata.cAtomic copy-on-write flash saving (3 files × 2 × 4 KB parts across 16 sectors; vendor drivers in games/common/sdk/flash/)
system_serial.cPer-VBlank link-cable packet exchange and 20-byte chunked block transfers
system_debug_text.c, number_text.cBG0 cursor-based debug printer (syPrint, syPrintHex, syPrintDecimal)
rom_start.c, rom_header.s, resource_directory.s192-byte GBA header (AGSJ–AGSI), 1,000-row resource directory (25 trailing spare rows), ResourceBuildStamp
stubs.s, stub.inc, sprite_stubs.s, sprite_metadata.cStubsSystem jump table (called by overlays) and stub macros
overlay/overlay.ld, overlay/imports.inc, overlay/overlays.listLinker rules for all 96 compressed overlays and build-generated import stub list
channel_update_entry.s, resident_mixer.s, bios.sCamelot'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 factHow the system library responds
Fast IWRAM is only 32 KBKeeps 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 decodersNever 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 linkLoops 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 handlerCamelot'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 scanlineDrives the tilted World Map ground per scanline via HBlank DMA
Direct Sound is two sample FIFOs; mixing is softwareRuns 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 overwrite r0–r3 (caller-saved scratch) but must preserve r4–r11 on the stack before returning (callee-saved). Camelot compiles with -fcall-used-r4, moving r4 into the scratch pool across all game code. That covers every Thumb C file (Alchemy GCC xgcc, 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 (syDMAXCopy takes its 4 arguments in r0–r3 and clobbers no callee-saved registers). Only the reconstructed flash and m4a sound routines in games/common/sdk/ compile with old_agbcc.
  • Empirical measurements from matching: Outside syAtan's 16-bit return, angles pass in 32-bit registers (narrowing to 16-bit ANGLE breaks matching in 349 TBS functions and 663 TLA functions). Outside system/, 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

CallBehaviourSGL counterpart
sySynchRuns n game ticks (tick-pass events, OAM build, VBlank wait) and returnsslExecuteEvent + slSynch combined
syInitEventClears the 20-entry event tableslInitEvent (64 entries in SGL)
sySetEventRegisters an event at a priority and sorts EventBuf; updates priority if presentslSetEvent (no priority; returns EVENT *)
syCloseEventRemoves an event callback from EventBufslCloseEvent (takes EVENT *)
sySuspendEvent / syResumeEventSuspends or resumes one event (or all if NULL)None
syExecuteEventRuns all active events in a pass (EVENT_PASS_TICK or EVENT_PASS_VBLANK)slExecuteEvent (single pass in SGL)
sySetEventFlagsSets per-event flags (e.g., keep running while overlay events are suspended)None
syIntFunctionInstalls or enables an interrupt handler (NULL disables)slIntFunction (VBlank-only in SGL)
syInputResetKeyRepeatResets held-button repeat timersNone

Math & Matrix

CallBehaviourSGL counterpart
syRandomNext 16-bit PRNG output (0..65535; callers mask bits rather than scaling)slRandom
syAtanVector angle from Y axis (16-bit ANGLE)slAtan
sySquart, sySquartIWRAM, sySquartFXInteger (ROM or IWRAM) and fixed-point sqrt (sySquartFX computes 8 fractional bits)slSquart / slSquartFX
sySin, syCos, syVectorAddPolarOffsetQuarter-turn trig and polar ground offsetslSin / slCos
syMulFX, syDivFX, syIntegerDivide, syIntegerDivideUnsigned16.16 multiply and divide (b / a divisor first) and integer divisionslMulFX / slDivFX
syInitMatrix, syUnitMatrix, syUnitMatrixCurrent, syUnitMatrixCurrentInlineInitialise stack and identity matricesslInitMatrix / slUnitMatrix
syPushMatrix, syPopMatrix1-level matrix save and restore (second push ignored)slPushMatrix / slPopMatrix (20 deep)
syGetMatrix, syLoadMatrix, syMultiMatrixCopy out, load, or multiply into current matrixslGetMatrix / slLoadMatrix / slMultiMatrix
syRotX, syRotY, syRotZ, syMatrixRotateRotate current matrix about axesslRotX / slRotY / slRotZ
syMatrixTranslateVector, syMatrixScaleVector, syMatrixRotateTranslate, syMatrixRotateTranslateScaleVector translate and scale, plus combined transformsslTranslate / slScale (scalars in SGL)
syLookAt, syLookAtLoadMultiply or load level-horizon camera matrixslLookAt (adds roll in SGL)
syCalcPoint, syConvert3Dto2DTransform 3D point and project to screen (returns draw scale, writes depth)slCalcPoint / slConvert3Dto2D
syPerspective, sySetScreenDistSet vertical FOV or focal length and near and far clipslPerspective (horizontal FOV) / slSetScreenDist
CallBehaviourSGL counterpart
syHeapInit, syHeapSlotAllocate, syHeapSlotAllocateEWRAM, syHeapSlotRelease, syHeapAllocate, syHeapAllocateEWRAM, syHeapRelease, syHeapGetRemainingIWRAM, syHeapGetRemainingEWRAMLIFO bump allocators and 62 heap slotsNone
syWordsClear, syWordsFill, syWordsCopyWord-aligned RAM operationsNone
syDMAXCopy, syDMAWait, DMA_FILL16, DMA_FILL32, DMA0_STOPDMA transfers, fills, and HBlank DMA0 stopslDMAXCopy / slDMAWait
syIOWriteQueueStore8, syIOWriteQueueStore16, syIOWriteQueueStore32, syIOWriteQueueSetBits8, syIOWriteQueueSetBits16, syIOWriteQueueSetBits32, syIOWriteQueueClearBits8, syIOWriteQueueClearBits16, syIOWriteQueueClearBits32Queued VBlank hardware register writesslTransferEntry (role equivalent)
IO_WRITE8, IO_WRITE16, IO_WRITE32, syIORead16Immediate hardware register read and writeNone
syDecompressByteLZ, syDecompressTaggedLZ, syDecompressMoveToFrontLZ, syDecompressHalfwords, syDecompressSpritePicture, syDecompressBitRunsAsset and 1bpp font decodersNone
syVRAMCacheReset, syVRAMCacheFreeEntry, syVRAMCacheReleaseVRAM, syVRAMCacheLoad, syVRAMCacheFindFreeEntry, syVRAMCacheAllocateEntry, syVRAMCacheReloadSprite VRAM block cacheNone
syOAMMatrixAllocateFromTransform, syOAMAddSpriteAtDepthAllocate OAM affine matrix (32) or submit sprite to depth bucket (256)slDispSprite (role equivalent)
syPaletteLoadBasicSpriteColors, syWindowLoadGraphicsLoad shared sprite palettes and UI font and bordersNone
syScreenFadeToBlack, syScreenFadeFromBlack, syScreenFadeToWhite, syScreenFadeFromWhite, syScreenFadeStart, syScreenFadeWaitHardware brightness fades (leaving BG0 debug text untouched on short fades)slColOffsetA (role equivalent)
syPrint, syPrintHex, syPrintDecimalBG0 debug text output (gated by DebugTextEnabled)slPrint / slPrintHex
syPrintBlanks, syPrintClearErase spans or clear BG0 debug text (always writes regardless of DebugTextEnabled)None
sySerialInit, sySerialPollAndTransfer, sySerialWaitForStatusMask, sySerialRemoveIRQHandlers, sySerialStartSend, sySerialStartReceive, sySerialWaitForSend, sySerialWaitForReceive, sySerialWaitForTransfers, sySerialGetActiveTransfers, sySerialStepBlockTransferPer-VBlank link-cable exchange and 20-byte chunked transfersNone
syBupInitState, syBupWritePart, syBupReadPart, syBupDeletePart, syBupLoadFileSummaries, syBupReleaseStateCopy-on-write flash save APISGL backup library (BUP_)
syCopyBuildStamp, syResourceGetTableEntry, syOverlayLoad, sySoundLoadReverbCode, syGetLanguageBuild stamp, resource lookup, overlay unpack + long-branch fixup, reverb code, header languageslGetLanguage
syDummyNoOperationHook, syDummyReturnZero, syDummyReservedNoOperationA–syDummyReservedNoOperationEStub-table placeholdersslNoOperation

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

Isaac walks into the door of a house in Vale: two table lookups find and unpack the house's scene overlay from the resource directory
Isaac walks into the door of a house in Vale: two table lookups find and unpack the house's scene overlay…

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

src/system/

FileDescription
bupdata.cThe save signature and sector header template, and link test data nothing reads.
math_table.cTrigonometry tables: a quarter-wave sine, tangents and the quadrants' sines.
number_text.cThe digit characters and place values numbers are written with.
rom_start.cThe 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.cFinding a sprite animation's metadata row.
system.cThe system library's object: what every other part of the game stands on.
system_bup.cSaving: flash sectors, parts and the save state.
system_debug_text.cNumber text, the debug text screen and the window graphics.
system_decompress.cResource decoding and pixel buffer shading, through RAM copies of ARM code.
system_event.cEvents: per-tick and VBlank functions in priority order.
system_frame.cInterrupt handlers, the tick wait, key repeat and the VBlank handler.
system_heap.cThe heap: its two bump allocators and heap slots.
system_internal.hWhat 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.cThe register write queue that VBlank carries out after each finished tick.
system_math.cRandom numbers, angles and square roots.
system_matrix.cThe 3D transform, its stack, the look-at matrix and the projection.
system_oam.cThe tick's sprite lists: affine matrices, depth slots and the OAM build.
system_screen_fade.cScreen 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.cThe link cable: payload exchange, block transfers and the link test.
system_start_up.c
system_vram_cache.cThe sprite VRAM cache: blocks, entries and loading pictures.

include/system/

FileDescription
asm.hThe matching devices: the asm statements the C holds for the compiler, not for the program, each a fake match.
definitions.hThe 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.hThe system library's variables, as SGL keeps its system variables and work areas: each group's variables in IWRAM, EWRAM and ROM.
mul_fx.hsyMulFXArm, 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.hThe start of the cartridge, where the console begins the game: a soft reset jumps back to it.