Choose an image and entry point
Open the memory placement demo. It declares visible code at $2000, an arena at $9000, and a region at $e000 behind KERNAL ROM. The resident image starts from its configured entry at $1000.
const c64 = @import("c64");
const hidden_values linksection("hidden") = [_]u8{ 0x21, 0x42, 0x63 };
memory {
region direct_code: c64 at 0x2000 size 0x0100;
region near_arena: c64 at 0x9000 size 0x0100;
region hidden_code: c64 at 0xe000 size 0x0100 bank .ram_under_kernal;
placement direct in direct_code;
placement hidden in hidden_code load .startup_copy;
arena near_heap in near_arena;
image prg {
load_addr = 0x0801;
entry_addr = 0x1000;
basic_stub = true;
address_limit = 0xc600;
}
}
fn directAdd(value: u8) linksection("direct") u8 {
return value + 1;
}
fn hiddenLookup(index: u8) linksection("hidden") u8 {
return hidden_values[index];
}
linksection("hidden") places the lookup function and table together. .startup_copy keeps their bytes in the load image and copies them to the run address before main. A resident call gateway exposes the hidden RAM and restores the previous mapping. The demo also uses near_heap.allocBytes(2), which returns an optional pointer to visible C64 RAM.
Expect PLACEMENT ARENA OK. Open build/placement.prg.zpmap.json and compare the load and run addresses of the hidden placement. A named pool allocates equal-sized blocks, while an arena releases its allocations together with reset(). The separate zero_page policy governs borrowed bytes and fixed reservations. Region ownership and zero-page policy
A default PRG loads at $0801 and supplies a BASIC startup line. A raw image uses basic_stub = false and needs an external caller or emulator to enter the declared address. The address_limit is exclusive. A directly loaded distant segment can pad a contiguous PRG. A startup copy keeps the load image compact while giving the code or data a fixed run address. Image rules
Declare and claim regions
A region names a physical address range, its address space, and C64 bank visibility where relevant. The compiler validates bounds, overlap, expected space and bank, and claims against the assembled resident image. A region has one reservation role. The same map can describe arenas, pools, a software stack, fixed code, and DLL windows or staging.
Current resident placement supports static functions and constant strings or arrays. Bank gateways expose RAM under ROM, make the call, and restore the processor mapping. KERNAL-dependent calls require particular care when KERNAL is hidden. A banked table belongs with the code that can access it. Entry and placement gateways
Read the raw entry contract before handing off control
The PRG header gives the load address. The caller must also know where to start executing. This example loads at $1000 and enters at $1010. Load the PRG at its embedded address and enter SYS 4112 from BASIC. The border turns green and the subroutine returns to BASIC.
const c64 = @import("c64");
memory {
image prg {
load_addr = 0x1000;
entry_addr = 0x1010;
basic_stub = false;
address_limit = 0xc600;
}
}
export fn main() void {
c64.vic.border = 5;
}
A host supplies the C64 mapping and a usable hardware stack. If entry returns with RTS, call it or supply an equivalent return frame. Keep the ROM and workspace available when using firmware. With the bare zero-page profile, the host already owns IRQ and NMI before entry. See the ReadyOS application entry. Executable entry and lifecycle
Repair a read from RAM hidden under ROM
After startup copies a table to RAM at $e000, ordinary resident code still sees KERNAL ROM at that address. A direct table read is therefore rejected. Move the lookup function into the table's placement. The resident caller now calls through a gateway, which exposes the RAM, runs the lookup, and restores the prior mapping while preserving its byte result.
Rejected resident read
const table: [2]u8 linksection("cold") = .{ 5, 7 };
export fn main() void {
const index: u8 = 1;
const border: *volatile u8 = @ptrFromInt(0xd020);
border.* = table[index];
}
Lookup in the same placement
fn hiddenLookup(index: u8) linksection("hidden") u8 {
return hidden_values[index];
}
In the complete placement demo, the caller uses hiddenLookup(1) and gets $42. Keep both the code and its table in the same named region, check that their assembled run ranges fit, and leave firmware-dependent work in resident code. A declaration with start $f800 and size $1000 has exclusive end $10800, outside the 16-bit address space. Reduce its size to at most $0800 or move its start down while staying wholly within the KERNAL bank.
Rejected banked table access · Rejected window crossing the address-space end · Complete banked lookup and placement demo · Inspect the demo's memory map
Own zero-page bytes explicitly
memory {
zero_page {
profile = .kernal;
allocation = .scalars;
reserve at 0x40 size 4;
restore_basic = true;
interrupts = .system;
}
}
The compatibility profile retains the default pointer and frame conventions. The BASIC profile preserves system workspace. The KERNAL profile can borrow BASIC workspace while retaining documented KERNAL services. Bare mode requires a raw image and a caller that already owns interrupts and ROM policy.
range defines candidate bytes and reserve subtracts fixed application claims. Reserve bytes used through literal pointers or assembly. With .scratch or .scalars, allocation still depends on eligibility, space, and proof. The map lists what was actually allocated or spilled. Normal return can restore borrowed bytes. Reset and forced warmstart do not run that cleanup. DLL loader programs currently use the compatibility policy. Zero-page profiles, IRQ/NMI, and restoration
Read a map before counting bytes
Candidate ranges describe what the compiler may consider. Actual claims show where it allocated pointer pairs, scratch, and eligible parameters. Reserved bytes belong to the application. A spill stays in ordinary RAM. Under the KERNAL profile, restoration on normal return covers the system bytes the compiler borrowed. When assembly writes reserved bytes, your code owns their lifetime and any restoration.
The stack can use explicitly admitted pointer pairs. In the lifecycle fixture, the stack pointer is at $30/$31 and the frame pointer at $32/$33. The test seeds zero page before entry and checks cleanup after the real return. Running only main would skip that entry and exit contract. Stack-pointer configuration fixture · Entry and exit verification
To see the difference in a real program, compare the fixture that reserves two application bytes and the compiler's reported allocations. Explicit reservations let assembly and generated code coexist, while optional scalar allocation depends on what the compiler can prove. Rejected claim on KERNAL workspace
Check a reservation against the actual allocation
This example borrows BASIC workspace at $30 and lists $30–$31 as reserved so the compiler cannot allocate there. It saves the previous byte, writes and reads a value, then restores the previous byte before returning from the helper. Expect INPUT AND STORE 81D4.
const c64 = @import("c64");
memory {
zero_page {
profile = .kernal;
allocation = .scalars;
reserve at 0x30 size 2;
}
}
fn useReserved(value: u8) u16 {
const cell: *volatile u8 = @ptrFromInt(0x30);
const previous: u8 = cell.*;
cell.* = value ^ 0x55;
const written: u8 = cell.*;
cell.* = previous;
return (@as(u16, value) << 8) | @as(u16, written);
}
export fn main() void {
c64.console.clear();
const pair = useReserved(0x81);
c64.console.print("INPUT AND STORE {x16}\n", .{pair});
}
In the map, find reserved_ranges and claims. The preview build places the private parameter useReserved_value at $02, outside the reservation. Read your own map after changes to the program. The normal-return restoration covers the compiler's claims on borrowed workspace. Your code is responsible for any bytes it borrows and reserves itself.
Choose storage by lifetime
| Declaration | Allocation result | Release |
|---|---|---|
| Near arena in C64 RAM | Optional many-item byte pointer | Reset the entire arena |
| Fixed-block pool in C64 RAM | Optional many-item byte pointer to one block | Free a block or reset the pool |
| Far arena in REU RAM | Optional opaque far handle | Reset the entire arena |
Handle allocation failure before use. Byte counts can use supported expressions. A zero-byte request fails. Arena reset reclaims the space and makes previous allocations stale. The compiler does not track all aliases held by application code.
Use a near arena for work done together
A near arena advances a cursor through its region. Use it for temporary work that can be discarded together. In this example, an allocation writes two bytes and reset lets the next allocation start again at $9000.
const c64 = @import("c64");
memory {
region main_ram: c64 at 0x9000 size 0x0100;
arena near_heap in main_ram;
}
export fn main() void {
c64.console.clear();
c64.console.print("NEAR HEAP ARENA\n", .{});
const first = near_heap.allocBytes(8);
if (first) |first_buf| {
first_buf[0] = 0x48;
first_buf[1] = 0x50;
if (first_buf[0] == 0x48 and first_buf[1] == 0x50) {
c64.console.print("ALLOC OK\n", .{});
}
}
near_heap.reset();
const again = near_heap.allocBytes(1);
if (again) |again_buf| {
if (@intFromPtr(again_buf) == 0x9000) {
c64.console.print("RESET OK\n", .{});
c64.vic.border = 5;
}
}
}
Store a structured record in a byte allocation
allocBytes returns bytes. This example uses @sizeOf to request enough space for an Actor and @offsetOf to encode and decode its fields. Normal typed code works with the reconstructed record. Use explicit low and high bytes when encoding a word. A near allocation does not supply a general typed allocator or an integer-to-struct-pointer cast.
const c64 = @import("c64");
const Actor = struct {
x: u8,
hp: u8,
facing: u8,
};
memory {
region work_ram: c64 at 0x9000 size 0x0100;
arena frame in work_ram;
}
fn storeActor(bytes: [*]u8, actor: Actor) void {
bytes[@offsetOf(Actor, "x")] = actor.x;
bytes[@offsetOf(Actor, "hp")] = actor.hp;
bytes[@offsetOf(Actor, "facing")] = actor.facing;
}
fn loadActor(bytes: [*]u8) Actor {
return Actor{
.x = bytes[@offsetOf(Actor, "x")],
.hp = bytes[@offsetOf(Actor, "hp")],
.facing = bytes[@offsetOf(Actor, "facing")],
};
}
export fn main() void {
c64.console.clear();
if (frame.allocBytes(@sizeOf(Actor))) |bytes| {
storeActor(bytes, Actor{ .x = 12, .hp = 5, .facing = 1 });
const actor = loadActor(bytes);
c64.console.print("X {x} HP {x} FACE {x}\n", .{ actor.x, actor.hp, actor.facing });
}
frame.reset();
}
Expect X 0C HP 05 FACE 01. For typed records that live in an REU, see the nested record example.
Reuse fixed-size blocks
A pool divides visible RAM into equal blocks. This one has four 16-byte blocks. An allocation consumes a whole block even when it requests fewer bytes. The demo frees the first block and checks that the next allocation gets it back. Pass only a live pointer from that pool to free. Keep using the pointer only while its block is owned by that allocation.
const c64 = @import("c64");
memory {
region sprites_ram: c64 at 0x9200 size 0x0040;
pool sprites in sprites_ram block 16;
}
export fn main() void {
c64.console.clear();
c64.console.print("FIXED HEAP BLOCKS\n", .{});
const first = sprites.allocBytes(8);
const second = sprites.allocBytes(8);
if (first) |first_buf| {
first_buf[0] = 0x46;
first_buf[1] = 0x48;
sprites.free(first_buf);
}
if (second) |second_buf| {
second_buf[0] = 0x42;
}
const reused = sprites.allocBytes(4);
if (reused) |reused_buf| {
if (@intFromPtr(reused_buf) == 0x9200) {
reused_buf[2] = 0x52;
c64.console.print("FREE REUSE OK\n", .{});
}
}
sprites.reset();
const reset_block = sprites.allocBytes(1);
if (reset_block) |reset_buf| {
if (@intFromPtr(reset_buf) == 0x9200) {
c64.console.print("RESET OK\n", .{});
c64.vic.border = 5;
}
}
}
Size a pool for reusable objects
Suppose you need at most four live messages and each encoded message fits in 16 bytes. Reserve 64 bytes and choose a block size of 16. A six-byte message uses one block, with ten bytes of spare capacity in that block. A seventeen-byte message fails even if the pool is otherwise empty. Choose an arena if the messages can all expire together. Choose a pool if you need to return one block while the other messages stay live.
Give a fixed pool a region whose size divides exactly into blocks. Keep it in visible RAM and outside the assembled PRG, stack, and other claims. Allocate record bytes as in the near arena example, using @sizeOf and an explicit byte layout. Keep the block pointer alive until you have finished every read or write, then return it to its own pool.
Allocate, exhaust, free, and reuse blocks · Rejected uneven block layout · Rejected per-allocation free on an arena
Plan for exhaustion and reuse
Each allocator returns an optional. A failed request gives you a chance to retry after a reset, fall back to another buffer, or report that the requested work does not fit. Resetting an arena is a lifetime decision: finish using every pointer and view from that arena first. Freeing a pool block gives only that block back. A request larger than one pool block cannot span multiple blocks.
Near arena allocation and reset fixture · Pool exhaustion and reuse fixture · Far allocation, transfer, and reset fixture
Use a far arena for bulk data
A far arena allocates in the REU address space. Its handle carries a far address and length. Read and write through copyFromC64, copyToC64, or a typed view. A far handle cannot be cast to a near pointer. The example copies bytes through two screen RAM locations.
const c64 = @import("c64");
const ZeroPage = @import("ZeroPage");
memory {
region assets_ram: reu at 0x010000 size 0x0100;
arena assets in assets_ram;
}
fn poke(addr: u16, value: u8) void {
const ptr: *volatile u8 = @ptrFromInt(addr);
ptr.* = value;
}
fn peek(addr: u16) u8 {
const ptr: *volatile u8 = @ptrFromInt(addr);
return ptr.*;
}
export fn main() void {
c64.console.clear();
c64.console.print("FAR REU ARENA\n", .{});
poke(0x0500, 'O');
poke(0x0501, 'K');
poke(0x0528, '.');
poke(0x0529, '.');
const maybe_far = assets.allocBytes(2);
if (maybe_far) |far| {
ZeroPage.reu.copyFromC64(far, 0x0500, 2);
ZeroPage.reu.copyToC64(far, 0x0528, 2);
if (peek(0x0528) == 'O' and peek(0x0529) == 'K') {
c64.console.print("FAR COPY OK\n", .{});
c64.vic.border = 5;
} else {
c64.console.print("FAR COPY BAD\n", .{});
c64.vic.border = 2;
}
} else {
c64.console.print("FAR ALLOC BAD\n", .{});
c64.vic.border = 2;
}
}