Memory
1. Memory layout
cc65 generated programs with the default setup run with the I/O area and the kernal enabled, which gives a usable memory range of $200 - $C037.
Special locations (default lynx.cfg):
0000 - 00FF Zero page
0100 - 01FF Machine stack (6502 hardware stack)
0200 - C037 Program, data, heap and C stack (MAIN area)
($A058 - $C037 is the collision buffer under lynx-coll.cfg)
C038 - E017 Screen buffer 1
E018 - FFF7 Screen buffer 0 (shares addresses with the I/O overlay)
FC00 - FFF7 Suzy / Mikey / boot-ROM overlay -- CPU view only
FFF8 - FFFF Hardware vectors and MAPCTL
The $E018–$FFF7 and $FC00–$FFF7 lines
overlap on purpose: that is one physical block of DRAM holding screen
buffer 0, but at those same addresses the CPU sees Suzy, Mikey and the boot
ROM. It is not a conflict — the display and the sprite engine reach that RAM
by a different path than the CPU, so the buffer and the registers coexist.
Section 2 explains how.
The same map is shown below. With the default config (lynx.cfg)
the program, heap and C stack share the RAM below the screen buffers; the
__STACKSIZE__ reservation (1 KB by default) sits at the very top
of that area, just under the first screen buffer:
lynx.cfg) — regions not to scale. Only a small
resident stub of STARTUP stays in memory; the crt0 one-shot init
(ONCE) sits at the floor of the free-RAM/heap region and is reclaimed by
the first allocation.When collision detection is enabled (lynx-coll.cfg) a 2 KB
collision buffer is carved out below the screen buffers, so the usable program
area and the top of the C stack move down to $A057:
lynx-coll.cfg) — regions not to scale.
As with the default layout, the crt0 one-shot init (ONCE) sits at the
heap floor and is reclaimed once main() begins allocating.- Text screen
-
There is no conio support: the Lynx has no text mode. Text output goes through the Lynx graphics bitmap-font functions (
gfx_outtext,gfx_outtextxy). - Keyboard
-
There is no keyboard. The Opt 1, Opt 2 and Pause switches are joypad inputs, reported by
joy_read()together with the d-pad and the A/B buttons (masksJOY_OPT1_MASK,JOY_OPT2_MASK,JOY_PAUSE_MASKinlynx/lynx.h). The classic conventions Pause+Opt 1 = restart and Pause+Opt 2 = flip screen are game conventions for the application to honor. - Stack
-
The C runtime stack is located at $C037 (or $A057 if collision detection is enabled) and growing downwards.
- Heap
-
The C heap is located at the end of the program and grows towards the C runtime stack. Its first bytes are the
ONCEsegment — the crt0 one-shot startup code, which runs once beforemain()and is then reclaimed: the first allocation grows the heap straight over it. Only a small resident stub ofSTARTUP(the reset entry, the_exittrap and a relocator) stays permanently in memory. See §4 anddesign/LYNX_STARTUP_RECLAIM_DESIGN.md. - Screen
-
The collision detection screen is at $A058 if it is enabled. The double buffered screens are at $C038 and $E018; see Graphics → Frame buffers for the two 8160-byte pages and how double buffering flips them.
- Maximum program size
-
The MAIN segment (
STARTUP,CODE,RODATA,DATA,BSS, and the reclaimableONCEone-shot startup code that the heap grows over), the C heap and the C stack all share the RAM below the screen buffers — $0200 - $C037, which is $BE38 (48,696) bytes in total. With the default 1 KB stack that leaves $BA38 (47,672) bytes for code, data and heap combined. With collision detection (lynx-coll.cfg) the shared region shrinks to $0200 - $A057, so code, data and heap must fit in $9A58 (39,512) bytes. This is a hard ceiling: the linked program is copied into RAM at boot, and there is no usable RAM above the screen buffers.The
ONCEone-shot startup code counts against this ceiling only at boot. Oncemain()begins allocating, the heap grows straight over it and those bytes —__ONCE_SIZE__, 137 ($89) bytes in the default build and growing with each module constructor (for example 155 bytes when the heap allocator's own constructor is linked in) — are returned to the heap and become available for allocation. So the effective budget for code and data is the figure above plus the reclaimedONCEregion, which is handed back as free heap.A cart can hold far more than this — 128, 256 or 512 KB (see Cart ROM and EEPROM) — but only that ~47 KB RAM image is directly addressable. Anything beyond it (extra levels, graphics, audio banks or code overlays) has to be streamed from the cart at run time with the cart file API (
openn,read,lseek,lynx_load), not linked into the program image.
2. Memory-mapped I/O and the display overlay
The map in §1 has an apparent impossibility in it:
screen buffer 0 occupies $E018–$FFF7, yet that same range is
where the CPU finds Suzy, Mikey and the boot ROM. The two do not actually collide,
because the top of memory is reached by three different bus masters over three
different paths — and only one of them sees the hardware overlay.
The 64 KB is a single physical DRAM array. What answers at
$FC00–$FFFF depends on who is asking:
- The CPU — through the MAPCTL decoder
-
Only the CPU is subject to the overlay, and the
MAPCTLregister at$FFF9decides what it sees. Each of the four low bits disables one overlay window and exposes the RAM underneath:SUZYSPACE($FC00–$FCFF),MIKEYSPACE($FD00–$FDFF),ROMSPACE($FE00–$FFF7) andVECTORSPACE($FFF8–$FFFF) — the masks are defined in<lynx/lynx.h>.crt0.sprogramsMAPCTL = $0C, which disables the ROM and vector windows (the boot ROM only matters at reset, and the CPU then fetches its interrupt vectors from RAM) but leaves the Suzy and Mikey windows enabled. So from the CPU's side the only part of screen buffer 0 hidden behind hardware is the 512-byte strip at$FC00–$FDFF: a plainsta $FD00writes a Mikey register, not a pixel. - Mikey's video DMA — straight to DRAM
-
The circuit that refreshes the LCD reads the frame buffer directly from physical DRAM, starting at
scrbase($FD94), and ignoresMAPCTLentirely. It scans$E018–$FFF7out as pixels no matter what the CPU sees at those addresses. - Suzy's sprite engine — straight to DRAM
-
When Suzy paints a sprite it reads the SCB and sprite data and writes the rendered pixels to the buffer as its own DMA accesses to physical DRAM, again bypassing
MAPCTL. Suzy can write$FC00–$FFF7as RAM even though those addresses are registers to the CPU.
MAPCTL decoder — so it sees Suzy/Mikey registers at
$FC00–$FDFF — while Suzy's blitter and Mikey's video DMA
read and write the underlying screen buffer directly, ignoring MAPCTL.This is why the buffer works, and why it is parked here in the first place.
Programs never draw pixels with the CPU: they hand Suzy a sprite and a destination
and let it blit, and Mikey's DMA reads the result — both go straight to RAM.
The CPU only ever writes the registers at $FC00–$FDFF to
tell Suzy and Mikey what to do. RAM sitting under a permanent I/O overlay is awkward
for the CPU to use — you would have to toggle MAPCTL around every
access — so it is the ideal home for something touched only by DMA. Screen
buffer 0 stops at $FFF7 precisely so it clears the hardware vectors
at $FFF8–$FFFF that the CPU still needs.
3. The C runtime stack and stack-overflow checking
cc65 programs use two independent stacks. The 6502 hardware
stack lives in page 1 ($0100–$01FF, a fixed
256 bytes) and holds subroutine return addresses and interrupt state. The
C software stack — also called the parameter stack —
holds function parameters and local variables; it is addressed through the
zero-page pointer sp and grows downwards from the top of the
MAIN memory area. The amount of RAM reserved for it is the link-time
symbol __STACKSIZE__, which defaults to $0400
(1 KB).
3.1. Setting the stack size
All of the Lynx configs (lynx.cfg, lynx-bll.cfg,
lynx-coll.cfg, lynx-uploader.cfg and the fixed-size
lynx-128k.cfg / lynx-256k.cfg / lynx-512k.cfg
— see Cart §1.1) reserve the stack
the same way. They declare a weak symbol and then shrink the
MAIN region by exactly that amount, for example in
lynx.cfg:
SYMBOLS {
__STACKSIZE__: type = weak, value = $0400; # 1k stack
}
MEMORY {
MAIN: file = %O, define = yes, start = $0200, size = $BE38 - __STACKSIZE__;
}
The startup code (crt0.s) then sets the initial stack pointer to
the top of that reservation:
sp = __MAIN_START__ + __MAIN_SIZE__ + __STACKSIZE__
so the stack occupies the top __STACKSIZE__ bytes of
MAIN and grows down toward your code, data and heap. Because the
symbol is weak, the default can be overridden at link time without
editing the config — for example to grow it to 2 KB for a
recursion-heavy program:
cl65 -Wl --define,__STACKSIZE__=$0800 -o game.lnx main.c
Every byte handed to the stack is a byte taken from code, data and heap, so
the goal is to pick the smallest value that still survives the deepest call
nesting and the largest local arrays your program uses. There is no automatic
overflow protection at this size — if the stack grows past its reservation
it silently collides with the top of BSS/heap — unless you
enable stack-overflow checking, described next.
3.2. Enabling stack-overflow checking
The compiler can instrument every function with a call to a small checking
routine (stkchk/cstkchk in the runtime library). This is
off by default. Turn it on for a whole build with the compiler
option:
cl65 --check-stack -o game.lnx main.c cc65 --check-stack main.c # compiler invoked directly
or enable it only around specific code with the
#pragma check-stack, which
understands push/pop:
#pragma check-stack (push, on) /* deeply-recursive or stack-heavy functions here */ #pragma check-stack (pop)
With checking enabled the compiler emits a jsr stkchk at every
function entry (the hardware-stack check) and, for functions that allocate
locals, a jsr cstkchk after the locals are reserved (the C-stack
check). Each routine works against a safety margin rather than the exact
limit: cstkchk treats the bottom 256 bytes of
the C stack as a reserved zone and aborts once sp descends into it,
and stkchk aborts when fewer than 12 bytes of
the hardware stack remain. So with checking on, the effective usable C
stack is about __STACKSIZE__ − 256 bytes:
If either check trips, the routine resets sp to its initial value
and calls _exit(4), so the program aborts. The Lynx has no console,
so there is no diagnostic message — the program simply stops — which
makes this primarily a development-time aid.
Overhead. The instrumentation is cheap per call but it is paid
on every call, including hot loops and recursion. Each call site costs
3 bytes for the jsr, and the routines themselves run in roughly
18 cycles (hardware-stack check) and 21 cycles (C-stack check) on the
normal no-overflow path — about 40 cycles for a function that gets both.
There is also a one-time cost of well under 100 bytes: the routine is linked
once, plus 4 bytes of state and a start-up constructor that records the
initial stack pointer. Because of the per-call tax, enable checking while
debugging and stack-tuning, then build the release without it.
A practical way to size __STACKSIZE__: build with
--check-stack and a deliberately generous stack, exercise the deepest
call paths, and tighten the value until checking no longer aborts — leaving
the 256-byte safety margin as headroom. See
#pragma check-stack in the
cc65 manual and the __STACKSIZE__ notes in the
ld65 manual for more detail.
4. Dynamic memory allocation (the heap)
Dynamic memory is available through the standard <stdlib.h>
functions malloc, calloc, realloc and
free. There is no operating system beneath them: the heap is simply
a window of RAM in the MAIN area (section 1),
bounded below by your program's static data and above by the C-stack reservation
(section 3). The allocator is the standard cc65
implementation — a first-fit free list backed by a bump pointer for fresh
memory — carrying a deliberately small per-block header for the Lynx's flat
64 KB address space.
4.1. How allocation works
Five runtime variables (declared in <_heap.h>) describe the
heap at any moment: _heaporg, the fixed bottom, anchored on
__ONCE_RUN__ — the run base of the reclaimable ONCE
one-shot startup code, which sits immediately above BSS, so the first
allocation grows the heap over the spent crt0 init and reclaims those bytes (see
design/LYNX_STARTUP_RECLAIM_DESIGN.md);
_heapptr, the bump pointer marking the top of the
memory touched so far; _heapend, the ceiling, set once at start-up to
sp − __STACKSIZE__ ($BC38 with the default
1 KB stack); and _heapfirst/_heaplast, the two ends
of a doubly-linked free list of recycled blocks. Everything between
_heaporg and _heapptr has been handed out at least once;
everything from _heapptr up to _heapend is still
untouched.
Every live allocation carries a two-byte header that holds the block's total
size. The pointer you receive points just above that header, so the raw block is
always (p − 2) and the size word can be read directly
from the two bytes below any valid pointer. When a block is freed and entered
into the free list, those same bytes are reinterpreted as a six-byte list node
(size, next, prev) — which is why the smallest possible block is 6 bytes
and a 1-byte request is rounded up to it. (See design/LYNX_HEAP_HEADER_DESIGN.md
for the full layout rationale.)
p − 2. A freed block reuses those same bytes as a 6-byte free-list node — the smallest block the heap can hold.malloc() rounds the request up by the two-byte header (and up to
the 6-byte minimum), then walks the free list for the first block large enough.
A match is either used whole or sliced from its top; if nothing fits, the bytes
are carved from the untouched region by advancing _heapptr. If that
advance would pass _heapend, the request fails and
malloc() returns a null pointer.
free() has a fast path: a block sitting exactly at the heap top is
released by simply lowering _heapptr back over it (and if the last
free-list block is now at the top, it is absorbed as well). Any other block is
inserted into the address-ordered free list and merged with adjacent free
neighbours, so that runs of contiguous frees collapse back into one large block
instead of fragmenting. The figure below shows the resulting picture: live
blocks and free-list holes below _heapptr, untouched space above it,
and the C stack descending from the top of MAIN.
_heaporg (anchored on __ONCE_RUN__, the reclaimable crt0 one-shot init that sits just above BSS) and the stack reservation (_heapend, $BC38 with the default 1 KB stack). It grows upward through _heapptr — the first allocation reclaims the spent ONCE init — while the C stack grows down from $C037. With no MMU, nothing but --check-stack stops the two from meeting.realloc() grows or shrinks a block in place when it is at the heap
top, and otherwise allocates a fresh block and copies the data over;
calloc() is malloc() followed by a zero-fill. Four cc65
extensions round out the API: _heapblocksize() returns the
user-visible size of an allocation, _heapmemavail() the total free
space, _heapmaxavail() the largest single block that could still be
allocated, and _heapadd() donates an arbitrary buffer (for example a
static array) to the free pool.
4.2. How it deviates from POSIX
This is a freestanding allocator for a machine with no operating system, no memory-management unit and a 16-bit address space, so it departs from a hosted POSIX environment in several ways worth knowing before you port code onto the Lynx:
- No
brk,sbrk,mmapor virtual memory. The heap can never grow past the static_heapendceiling; its maximum size is fixed at link time by whereBSSends and how large__STACKSIZE__is. Total capacity is on the order of tens of kilobytes, andsize_tis 16 bits, so no single object can exceed 64 KB. - No aligned allocation.
posix_memalign(andmemalign/aligned_alloc) are deliberately not provided — the Lynx needs no power-of-two alignment, so the admin header was reduced to two bytes and blocks come back at whatever address the allocator yields. Removing them is exactly what lets theraw = p − 2invariant above hold unconditionally. - Allocation failure returns a null pointer but does not set
errnotoENOMEM. The memory functions report failure only through their return value; there is noerrno-based path. free()accepts only a pointer previously returned bymalloc/calloc/realloc(or a null pointer). Interior or fabricated pointers are not tolerated — the word immediately below the pointer is read directly as the block size, with no validation.- Not reentrant and not thread-safe, and unsafe to call from an interrupt handler. The free list is plain global state with no locking; the Lynx is single-threaded, but do not call the heap from an IRQ that might interrupt another heap operation.
- No memory protection. The heap grows up while the C stack grows down toward
it (section 3); at run time nothing keeps them apart
unless you build with
--check-stack. There is no fault or signal — an overrun silently corrupts memory. malloc(0)returns a null pointer. (The C standard also permits a unique, freeable pointer; this implementation chooses null.)_heapblocksize,_heapmemavail,_heapmaxavailand_heapaddare cc65 extensions, not part of POSIX or ISO C.
5. Startup reclamation and relocation
The whole program image is copied into RAM at $0200 and run in
place, so any byte the startup code occupies is a byte lost to code, data and
heap for the entire run. Most of what crt0.s does — masking
interrupts, programming Mikey and Suzy, setting the C stack pointer, clearing
BSS and running the module constructors — happens exactly once,
before main(), and is dead weight ever after. Only a tiny part must
stay resident: the reset entry at $0200 and the _exit
trap that a returning main() (and the stack-overflow checker) lands
on. The startup code is therefore split so that the one-time part can be
reclaimed by the heap. The full rationale is in
design/LYNX_STARTUP_RECLAIM_DESIGN.md.
5.1. The split: resident stub vs one-shot body
crt0.s keeps only a small permanent stub in the STARTUP
segment — the $0200 reset jmp, the resident
_exit trap, and a short relocator. Everything else moves into the
ONCE segment, which runs once and is then grown over by the heap.
ONCE segment.5.2. Relocation and reclaim
There is a catch. The ONCE body has to run at the top of
the static area — immediately above BSS, at the heap origin
(__ONCE_RUN__) — so the heap can grow over it. But the Lynx
copies the file image to RAM verbatim, with no per-segment load step, and a
bss-type hole cannot sit in the middle of the image without padding
it by the full size of BSS. So ONCE is packed
into the image straight after DATA (no hole), which means that after
the verbatim copy it lands lower than where it must run — at
__ONCE_PHYS__ (which equals __BSS_RUN__ on the plain
carts). The permanent relocator copies it up to __ONCE_RUN__ before
entering it; the first allocation then overwrites those very bytes.
The whole ONCE segment — __ONCE_SIZE__ bytes,
137 ($89) in the default lynxdemo build and larger as module
constructors are linked in (155 bytes in heaptest, for instance)
— is therefore reclaimed the moment main() allocates: every
one of those bytes is added to the heap and becomes available for the program to
use. Nothing above __ONCE_RUN__ stays reserved for startup.
ONCE is packed directly after DATA (no bss hole in the image). The relocator copies it up past the BSS gap to __ONCE_RUN__; the heap then grows over it from that same address. On the padded cart-size configs MAIN's fill already lands ONCE at its run address, so __ONCE_PHYS__ == __ONCE_RUN__ and the copy is a harmless self-copy.5.3. The boot sequence
Putting it together, control flows from the fixed reset entry through the
relocator into the relocated body, and finally into main(); the very
first allocation reclaims the spent init. The _exit trap the program
returns to lives in the permanent stub, so it survives even after the heap has
overwritten the ONCE body it was reached from.
_exit trap are resident; onceinit runs from the relocated ONCE copy and is freed once main() begins allocating.