The arena
How TryC decides when the memory of a string, an object or an array is reserved and when it is released, without a free() and without a garbage collector. Everything here is automatic in normal code; the details matter when you write asminline, store pointers in long fields, or want to understand a crash.
The problem
Every program creates data at runtime whose size is not known in advance: a concatenated string, an object built in a loop, an array sized by the input. Getting the space is easy; the hard part is releasing it neither too late (a leak) nor too early (a use-after-free, whose symptom appears somewhere else, later, as a wrong value or a crash). Languages answer this in three ways:
| Strategy | Who frees | Examples | Cost |
|---|---|---|---|
| Manual | the programmer, with free() | C | forgotten frees leak, early frees corrupt |
| Garbage collection | a runtime that scans memory periodically | Python, Java, Go | unpredictable timing, pauses, a big runtime |
| Regions / arena | the structure of the program: what a block allocated is freed when the block ends | TryC; allocators in Rust, Zig, databases and compilers | a value that must outlive its block needs an explicit mechanism |
TryC takes the third road for a reason that comes from its goal of being usable inside a kernel. A garbage collector allocates every object on the heap and assumes the heap exists: inside a kernel that is not true until the kernel itself has set up its memory management, so a language that depends on a GC cannot be used for those first steps. An arena has no such dependency. In TryC the objects live in a fixed-size pool that is part of the program's static memory (the BSS), sized at compile time with --bss-size; with --noheap the pool is all there is and no memory syscall is ever made, so a kernel can create strings, objects and arrays before it has a heap, initialise the heap when it is ready, and keep using the same objects and the same code afterwards. In a normal Linux program the same pool is simply the first chunk, and the runtime maps more chunks when it fills up.
The second reason is structural: a program is already made of nested blocks with a clear start and end, a function call that returns, a loop iteration that completes. Binding the life of memory to those blocks needs no scan, no pauses and no free(); the price is the mechanism that lets a value leave its block, called promotion.
The rule
Every time a block starts (a function is called, a loop iteration begins) a scope opens. When the block ends, everything allocated inside the scope is released, unless it was promoted out of it first.
Think of each function or iteration as a room: you can create anything you want on the table, and when you leave the room the table is cleared. To take something with you, you put it in your pocket before leaving: that is a promotion.
def make_message() -> str:
msg = "hello " + "world" // allocated in make_message's scope
return msg // must survive the scope that is about to close
def main() -> int:
x = "persistent" // lives as long as main
while cond():
y = "temporary" // released at the end of every iteration
m = make_message() // valid: the return promoted it
return 0
How it works
Three pieces of global state in the runtime:
| Name | What it is |
|---|---|
alloc_log | an array of pointers: every allocation appends its address here |
scope_ckpt_stack | a stack of bookmarks into alloc_log, one per open scope: "when this scope opened, the log was this long" |
scope_ckpt_top | how many scopes are open |
alloc_log: [ A ] [ B ] [ C ] [ D ] [ E ] [ F ]
0 1 2 3 4 5
scope_ckpt_stack:
scope 0 (_start) -> bookmark 0 A, B belong to scope 0
scope 1 (a function) -> bookmark 2 C, D belong to scope 1
scope 2 (a loop pass) -> bookmark 4 E, F belong to scope 2 (the innermost)
arena_enter(inserted by the compiler at every function entry and loop iteration) pushes a bookmark with the current length of the log.arena_exit(function epilogue, end of each iteration) pops the bookmark and frees every log entry from the bookmark to the end: everything born in that scope that never left it. Freeing a block marks it free in the pool's bitmap and zeroes it; the memory itself stays mapped and is reused by later allocations.
Step by step
def foo2() -> None:
x = "Ci" + "ao " // a concatenation allocates
y = "Mon" + "do"
xy = x + y
def main() -> None:
n = 22
foo2()
main()
before main(): alloc_log = [] ckpt_stack = [0] top = 1 (the _start scope)
main() called: alloc_log = [] ckpt_stack = [0, 0] top = 2
n = 22: an int lives in the stack frame, the arena is not involved
foo2() called: alloc_log = [] ckpt_stack = [0, 0, 0] top = 3
x = "Ci" + "ao ": alloc_log = [x] (a plain literal would not allocate: it points into the binary)
y = "Mon" + "do": alloc_log = [x, y]
xy = x + y: alloc_log = [x, y, xy]
foo2 returns: top = 2, bookmark = ckpt_stack[2] = 0
free log[2], log[1], log[0] -> alloc_log = []
back in main: ckpt_stack = [0, 0] top = 2
Promotion
Promoting a pointer means moving one or more bookmarks forward (never back) past its log entry, so that the next arena_exit of those scopes no longer covers it. The allocation itself never moves.
before rt_promote(msg, 1): after:
alloc_log: [A][B][C][msg] alloc_log: [A][B][C][msg]
parent scope -> bookmark 2 parent scope -> bookmark 4 (moved past msg)
current scope -> bookmark 3 current scope -> bookmark 3
| Runtime function | Effect | Used for |
|---|---|---|
rt_promote(ptr, n) | raises the n innermost bookmarks past ptr; the entries between the old bookmark and ptr (the "siblings") are freed immediately, otherwise they would leak forever | the runtime; asminline code no longer needs it (the compiler promotes a block's result, see below) |
rt_promote_move(ptr, n) | moves only the value's own entry out through n scopes; what the value points to stays alive through its counts. A value with no entry of its own (read from a container) becomes a borrow of the local instead | a local declared outside a loop that receives a value inside it |
rt_promote_swap(ptr, n) | moves the entry to the bookmark of the outermost of the n scopes by swapping it with the entry there, then raises by one every bookmark that pointed at that position; the siblings stay in their scope, nothing is freed or leaked | return: the value moves into the caller's current scope, in constant time. In TryC code only inside unsafe: |
rt_promote_to_root(ptr) | makes the allocation immortal (the high bit of the reference word in its header): nothing frees it again | as long and dict_poke64, where a pointer leaves the language. In TryC code only inside unsafe: |
rt_alloc_up(size) | rt_alloc + promotion of one level | a function that allocates a buffer and returns it, written in plain TryC |
Every promotion accepts an interior pointer: when s + n is not in the log, the runtime finds the allocation that contains it (rt_alloc_base_of, through the block bitmap) and promotes that. A pointer that is in no allocation at all (a literal, a raw_alloc block, the stack) is left alone, silently. That is what makes the compiler's automatic promotions safe to insert liberally: promoting something that did not need it is never an error.
What the compiler promotes for you
In ordinary TryC code you do not think about any of this. The compiler applies these rules at every store of an arena-tracked value (a str, an array, an object):
| Situation | Rule |
|---|---|
return value, return a, b | each returned value is moved into the caller's current scope (rt_promote_swap over the scopes the function opened): the caller frees it at the end of that scope, or promotes it further by assigning, storing or returning it in turn |
obj.field = value, arr[i] = value, global = value | the field, the element or the global holds a counted reference; the value it replaces loses one |
list_push(l, v), d.set(k, v), sdict_set, ... | the container holds a counted reference, like a field |
x = container.field, x = sdict_get(d, k) | a borrow: if the container drops the value while x still holds it, the value moves into x's scope instead of being freed |
value as ref (explicit or implicit) | a change of label: the ref is counted like any pointer. Inside unsafe:, value as long (or an integer as ref) makes the allocation immortal, because the compiler cannot follow a number |
local = fresh value inside a loop | moved into the scope of the local, out of the loops in between (rt_promote_move), so a value built in an iteration and kept in a variable declared outside the loop stays valid |
local = fresh value at function level | nothing to do: it dies with the function unless one of the rules above applies later |
| a parameter | belongs to the caller; the callee never frees it |
Scopes and counts work together: a scope owns what was allocated in it, and a field, an element or a global holds a counted reference. A value is freed when neither is left, at the arena_exit that closes its scope or at the store that drops its last reference, and what it points to is released with it. One case is never freed: a cycle (A holds B, B holds A) keeps both counts above zero until the program exits.
Before counting, a value stored in a field, a global or a container was pinned for the rest of the program: a leak is bounded, a premature free is a corruption. The price was memory. The self-hosted compiler held 24 MB of objects nobody could reach any more, and a loop parsing the same JSON document 300 times grew to 447 MB; with counting it stays at 8 MB.
Promotion is not written by hand
With these rules TryC code never promotes explicitly. rt_promote_to_root and rt_promote_swap outside unsafe: are a compile error that says why:
'rt_promote_to_root' solo dentro 'unsafe:' - le promozioni le fa il compilatore: un valore
restituito passa al chiamante, e un campo, un elemento o un globale ne tengono un riferimento
('obj.campo = x', 'list_push(l, x)'). Serve solo per un puntatore che esce dalla vista del linguaggio
The habit of pinning a value before storing it was not only unnecessary: a pinned value is immortal, so it outlived the list that held it. Removing the 113 pins of the self-hosted compiler changed none of its output and cut its memory from 81 to 51 MB.
What escapes the compiler's view
The automatic rules see values whose static type is str, an array or a class. They do not see:
- Pointers turned into numbers. Inside
unsafe:,p as longpins the allocation: it becomes immortal, since the compiler cannot follow the number. A pointer thatasminlinewrites somewhere raw, or that is read back from memory the compiler does not type, is invisible. - Memory handed to C. A C function that only uses an argument during the call needs nothing: the argument lives until the call returns. A library that keeps the pointer after the call needs it pinned (inside
unsafe:,rt_promote_to_root(p), ordict_poke64into the structure the library reads) or the data copied into araw_allocblock. asminline. A block that ends a function and leaves a pointer inraxis promoted like areturn, interior pointers included: the compiler does it after the block.
Build with --check-arena. A missing pin becomes an immediate crash that names the allocation, the function that created it and the one whose arena_exit freed it. A pin nobody needed shows up at exit, on stderr, grouped by the place that pinned it (the function name comes from check_arena_syms.py):
check-arena: allocazioni immortali ancora vive all'uscita: 500, 250 KB. Punti in cui sono state fissate (rt_promote_to_root, 'as long'):
check-arena: 500 allocazioni, 250 KB, fissate in 00000000004013CD pin_many+0x5d
A real bug
def uname_field(offset: int) -> str:
asminline(
; ... base = rt_alloc(UTSNAME_TOTAL_SIZE); sys_uname(base) ...
lea rax, [base + offset] ; the returned value
; ... rt_promote(base, 1) ...
) endasm
def hostname() -> str:
return uname_field(UTSNAME_OFF_NODENAME) // offset 65
rt_promote(base, 1) protected base from uname_field's own arena_exit only. hostname() then returned base + 65, which at the time promoted nothing (the runtime only matched exact addresses), so its arena_exit freed base. os_name() (offset 0) worked by coincidence; every other field came back empty, with no error. Today the return of hostname() finds the base of base + 65 and promotes it, and the bug cannot happen from TryC code; the lesson stands for asminline, where counting levels by hand depends on how many functions will wrap yours in the future.
Memory outside the arena
Every thread has an arena of its own: its scopes, its allocation log, its nursery and its pending list live in a per-thread state that the runtime finds through a thread register, while the block pool is shared under a lock. A thread started by libstd/thread allocates like the rest of the program (new, string concatenation, lists, dicts), and what it allocates is freed when it returns. Arena values never cross threads: a thread function takes and returns integers, and the compiler rejects a thread that reads or writes a global str, object, array or ref, even through the functions it calls. The memory shared with C code and with other threads therefore comes from a separate allocator, raw_alloc/raw_free (tryc_malloc/tryc_free in the runtime): one mmap (VirtualAlloc on Windows) per call, never logged, never freed automatically. A program that never calls thread_spawn is linked with a runtime without threads, where the per-thread state is at a fixed address and costs nothing.
Arrays carry a header
An array variable points at a header, not at the first element: [length 8B][elements...] for fixed arrays (nested per dimension), [depth][elem_size][dims...][elements] for dynamic ones. The header is part of the tracked allocation, which is what lets rt_free/rt_promote find the array with an exact pointer match, and what makes every a[i] bounds-checked. Details in Arrays.
Where the bytes come from
Everything above is about tracking. The physical memory is a pool of 2 MB chunks made of 512-byte blocks with a bitmap (or, under --noheap, a single fixed chunk in the BSS). Chunks are never moved or unmapped, so a pointer stays valid forever. The allocator, the lookup table that maps a pointer to its log entry, huge pages and the other machinery are described in Runtime internals.
Quick reference
| Function | Tracked? | Survives | Typical caller |
|---|---|---|---|
rt_alloc(size) | yes | the current scope only | code that uses the buffer locally |
rt_alloc_up(size) | yes, promoted one level | the scope that called the function | TryC functions that return a fresh buffer |
rt_promote(ptr, n) / rt_promote_move / rt_promote_swap | — | n more scopes | the compiler (loops, returns, asminline results) |
| a field, an element, a global | counted | until its last reference goes | the compiler, at every store |
rt_promote_to_root(ptr) | — | the whole program | the compiler (as long), dict_poke64, unsafe: code for C that keeps a pointer |
rt_free(ptr) | — | frees now | arena_exit; rarely, code that wants to free early |
raw_alloc(size) / raw_free | never | until raw_free | threads, C structures |