Memory safety
What TryC guarantees today, what it does not, how --check-arena turns silent corruption into a precise report, and the plan to make the language memory-safe in the strict sense: the semantics guarantee the absence of corruption; static analysis only removes cost; when analysis cannot prove something, the program pays a runtime check or does not compile; never silent corruption.
What is checked today
| Hazard | Status |
|---|---|
| Array index out of range | Checked on every access against the length header (rt_check_array_bounds); elided only when provably in range or inside an unsafe: block. Failure is loud: message plus crash report. |
| Freeing memory too early / use-after-scope | Prevented by the arena's design for values the compiler can see: a str, an array or an object stored in a field, an element, a global or a container is counted there, a returned one moves into the caller's scope, one kept across a loop moves out of it. Missed cases exist (see below) and are silent. |
| Manual double free | Not applicable in normal code: there is no free(). rt_free of an untracked pointer is ignored. |
| Out of memory, runaway recursion | Fatal error with a message (arena full under --noheap, scope checkpoint stack full for recursion deeper than 16,384 scopes), never corruption. |
| Null dereference | Not checked; the SIGSEGV handler reports it with the function history. |
| Uninitialised memory | Every allocation is zeroed (fresh pages are zero, freed blocks are zeroed on free). |
What is not
- Unsealed strings and
s + n.s[i]is checked on a sealedstr(see Strings), but a string that is not sealed (a buffer still being filled, a string from C, an interior pointer) has no length to check against, and a missing terminator makesstrlenread on.s + nis tracked (a promotion of an interior pointer promotes its allocation) but not bounded:s + 1000may point into the next allocation, and then the wrong one is kept alive. ptr Tandunsafe:. Indexing a raw pointer is unchecked. Insideunsafe:a pointer may still be hidden in along: the cast pins the allocation (safe, at the price of a leak) but the type is gone, and reading it back as the wrong type is not detected. Outside, a pointer travels asrefand comes back through a checked downcast.- Cycles leak. A value is freed when its last counted reference goes; two objects that hold each other keep both counts above zero until the program exits (see The arena).
- Missed promotions are silent. A pointer produced by
asminlineand stored raw, handed to C, or freed early withrt_free: the arena frees the base at scope exit and the program reads freed (zeroed, later reused) memory with no error. - Sharing objects between threads. Every thread has its own arena and the compiler keeps arena values inside their thread (no tracked globals in thread code); data shared through
raw_allocmemory andlibstd/syncis unchecked. - Inline assembly can do anything.
In short: normal TryC code that uses str, arrays, classes and the containers is protected against the common mistakes, but the language has escape hatches that are the normal way of writing low-level code, and when the compiler's analysis is wrong the failure mode is the one of C. The verification runtime exists to make that failure loud.
--check-arena: the arena's address sanitizer
Build with --check-arena to link the verification runtime (the same runtime source assembled with -D CHECK_ARENA). The program runs unchanged; only where the bytes come from changes:
- Every allocation (arena and string-builder pool alike) gets pages of its own inside an 8 MB slab; the header/data end exactly at a page boundary, followed by a 32-byte canary redzone. The rest of the first page, in front of the header, is canary too, and a page that no allocation has taken yet must stay zero.
- When a scope frees a batch, the pages of the freed allocations become
PROT_NONE: any later read or write is a SIGSEGV. Freed ranges stay protected in a quarantine (16,384 ranges, up to 64 MB) and are only then recycled. - Each allocation has a record: pointer, size, state, the function that allocated it (from the crash reporter's history), the function that freed it and the scope depth at the free. A page-to-record table maps any address back to its allocation.
| Bug | Detected as |
|---|---|
| Use after free (any access to a freed allocation) | SIGSEGV with a report: "inside a freed allocation", offset, allocated in f, freed in g |
| Write past the end (within 32 bytes) | canary corrupted: abort at the free of that allocation, or at exit for allocations still alive; the report gives the offset of the first corrupted byte |
| Write past the end by more than the redzone | with plain --check-arena the write lands in the next page, which must still be canary (the front of the next allocation) or zero (not taken yet): abort at the free of the allocation that overflowed, when another allocation takes that page, or at exit, with the offset of the write. A write that reaches the data of another live allocation needs --check-arena-guard, where it is an immediate SIGSEGV |
| Read past the end by more than the redzone | SIGSEGV "past the end of an allocation" with --check-arena-guard (guard page after each allocation) |
| Write before the start | the canary in front of the header is corrupted: abort at the free or at exit; without the guard the report also describes the allocation before, whose overflow lands in the same place |
| Double free, free of a pointer that is not an allocation | abort with the report (exit code 134) |
| Promotion of a pointer that was already freed | abort at the promotion, before the value can be used |
A pin nobody needed (rt_promote_to_root, as long in unsafe:) | not an error: at exit stderr lists the allocations still immortal, grouped by the place that pinned them |
arena_exit without a matching arena_enter | abort |
Example
An asminline block that stores a pointer into a global with a raw mov. The counted store the compiler emits for kept = s never runs, so the string is freed with build's scope and the global keeps pointing at the block:
#include <libstd/stdio>
kept = ""
def keep(s: str) -> None:
asminline (
mov rax, [s]
mov [kept], rax ; raw store: the counted store of 'kept = s' is skipped
) endasm
def build() -> None:
s = "abc" + "def"
keep(s) // 's' dies with build's scope
def main() -> int:
build()
b = "x" + "y" // reuses the block that 's' occupied
print(kept, "\n") // prints "xy" with the normal runtime, silently
return 0
main()
python3 main.py uaf.tryc -o uaf --check-arena
./uaf 2>&1 | python3 check_arena_syms.py ./uaf
==================== CRASH ====================
Segnale n.: 000000000000000B
Indirizzo del fault: 00007828C8E00DE8
check-arena: dentro un'allocazione GIA' LIBERATA (use-after-free)
allocazione: 00007828C8E00DF0
byte: 00000000000001F8
offset: FFFFFFFFFFFFFFF8
allocata in: 00000000004013A0 build
liberata in: 00000000004013A0 build
scope alla free: 0000000000000002
Stack delle funzioni chiamate:
0000000000401240 fprint
0000000000401280 print
00000000004013D0 main
0000000000401490 _start
RIP: 000000000040100D strlen+0xd
The report says everything needed: the access is 8 bytes before a string allocated in build (strlen reading its length header, see Strings), freed when build's scope closed, and made inside strlen called by print from main.
Using it
# the test suites
TRYC_TEST_EXTRA_ARGS="--check-arena" python3 test_llvm.py
TRYC_TEST_EXTRA_ARGS="--check-arena" python3 test_automa.py
# the self-hosted compiler, built with the verification runtime, precompiling its own source
python3 main.py compiler.tryc -o compiler_check --hugepages --llvm-static --check-arena
./compiler_check compiler.tryc --dbi
Run it after any change to promotions, scopes or the runtime, and before committing an optimisation of the arena. It found, on its first run, a bug in the runtime itself: rt_alloc_log_grow clobbered two registers rt_alloc relied on, so the first time the log grew past 4,096 live entries the allocation returned the address of the old log instead of a block.
Cost and limits
- About 3× the time of the normal runtime on the compiler (30 → 90 ms per file), most of it in the kernel: one
mprotectper batch of freed pages and the zeroing of fresh pages. Memory: every allocation occupies at least one 4 KB page (~200 MB for the compiler run). - Freed ranges are protected in batches (one syscall per contiguous run) and recycled after the quarantine, so a use-after-free of memory freed long ago (more than 16,384 ranges or 64 MB earlier) is caught only when it goes through a promotion or a free, not on a plain read.
- Read overflows between allocations need
--check-arena-guard, whose guard pages double the kernel VMAs per live allocation; raisevm.max_map_countfor large programs. - Not available with
--noheap(it needsmmap/mprotect), and only for programs compiled by c1 (the self-hosted compiler links its own copy of the runtime).
Roadmap to a memory-safe language
The audit of the language identified six points, ordered by effect and by how mechanical the migration is. The self-hosted compiler (26,500 lines of TryC) contains about 70 reinterpret casts (as long/as str/as ptr/as ClassName) and about 30 sites of pointer arithmetic on strings: small numbers, concentrated in a few files. The first four points are in place; the others change the language further.
| Step | Status | What it means |
|---|---|---|
| 0. Loud failures first | done | --check-arena above. Everything below is verified on the real compiler under it rather than trusted. Its first runs found two bugs in the runtime (rt_alloc_log_grow, print_hex), one in the code generator (an asminline body with a call got no scope of its own), one in the language (return a, b promoted neither value) and two in libstd (sdict_new with a non-power-of-two capacity, a thread using its stack after the parent freed it). |
| 1. Conservative promotion as the invariant | done | Promotion at every store into a longer-lived location is the semantic rule; skip_promotion, scope elision and not-fresh tracking are optimisations that must be proved, and when the proof is missing the store pays the promotion. Concretely: a promotion of an interior pointer promotes the allocation that contains it (rt_alloc_base_of), as long pins, both values of a double return are promoted, and a return moves its value into the caller's scope instead of pinning it (rt_promote_swap). Measured on the self-hosted compiler: resident memory 120 to 92 MB, time +6% on a file and +13% on a self-precompile, the cost of freeing what used to leak. Still silent: a pointer stored raw from asminline, handed to C, or freed early with rt_free. |
2. long must never carry a pointer | done | The opaque pointer type ref: any pointer becomes one (implicitly where a ref is expected), comes back with a cast, and ref as Class is checked against the class id that new writes in the allocation header ("cast to Token: the object is a Point"). Pointer-to-integer, integer-to-pointer and as ptr T casts are compile errors outside unsafe:. List holds ref, the dict prelude str[]/ref[]; the self-hosted compiler was migrated (about 250 casts removed, one unsafe: block left) with identical output and speed. What it did not change: a ref was still pinned by the cast that created it, so container memory stayed immortal until step 3. |
| 3. Contents freed with their container | done | A field, an element, a global and a container hold a counted reference; the count lives in the allocation header, beside the immortal bit. When the last reference goes and no scope still owns the value, it is freed at once, and what it points to is released with it, walked by the class id in the header with the per-class maps of pointer fields that the compiler emits. A local that read the value from a container borrows it: if the container drops it first, the value moves into the local's scope instead of being freed. A ref is counted like any pointer; pins are left only where a pointer leaves the language (as long, dict_poke64), and rt_promote_to_root/rt_promote_swap written by hand are a compile error outside unsafe:. On the self-hosted compiler, with its 113 explicit pins removed, resident memory went from 81 to 51 MB; a loop parsing the same JSON document 300 times, from 447 to 8 MB. Cycles still leak. |
4. str with a length | length and s[i] done, slice next | The length lives in the 16-byte allocation header before the pointer, never at it (an earlier attempt put it in front of the bytes like arrays do, and every C library that received the string read the header as text): a str value is still a char* for C, the 8-byte value convention holds, and strlen on a sealed string costs one compare (20,000 strlen + == on a 155 KB string: 229 ms to 1.2 ms; short strings and the self-hosted compiler unchanged). Strings from C are copied in with str_from_c. s[i] on a sealed string is checked against that length like a[i]: reads up to the terminator, writes below it; an unsealed string and unsafe: stay unchecked. The compiler leaves the check out where it proves the index in bounds, with linear inequalities collected from the function: branch and loop conditions, assignments, accesses already checked, the terminator a sealed string always has at len, and loop invariants. Every proof also excludes 32-bit wraparound, which is why a string is at most 231 − 2 bytes long. On the self-hosted compiler, which indexes strings in every scanning loop, the checks left cost 3.2% of the instructions (372 to 384 million; 6.3% with the two fixed rules used before). It also needs the full inlining of -O2: with the lower threshold the compiler used before, the small helpers of libstd/string grew past it and stayed calls. Still to do: a bounded slice type so that s + n stops being an unchecked interior pointer. |
| 5. Nullability and threads | threads done; nullability planned | T? in the type, non-null by default, field access only after a test. Per-thread arena state is done: a runtime variant with threads, linked only by programs that start one, and a compiler rule that keeps arena values inside their thread; sharing objects between threads is still to do. The same per-thread state is the answer for per-CPU state in a kernel. |
| 6. Kernel mode | planned | A noalloc attribute checked by the compiler for code that must not touch the arena (interrupt handlers, early boot before the heap exists) and a hook for out-of-memory instead of the fatal error. |
Alongside the language steps, the cost of step 1 is to be recovered by analysis, never by weakening the rule: most of the remaining promotions that find nothing are loop assignments of a call result that is a pointer into the caller's own data (a reader returning a line of its buffer), which an interprocedural "returns an interior of its parameter" analysis can prove and elide.
One strategic decision goes with it: change the reference compiler first so that the self-hosted one can be migrated mechanically. The honest estimate is six to twelve months of steady work before "memory-safe" is a true statement; the language is usable throughout, and every step is measured with the verification runtime.