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

HazardStatus
Array index out of rangeChecked 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-scopePrevented 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 freeNot applicable in normal code: there is no free(). rt_free of an untracked pointer is ignored.
Out of memory, runaway recursionFatal error with a message (arena full under --noheap, scope checkpoint stack full for recursion deeper than 16,384 scopes), never corruption.
Null dereferenceNot checked; the SIGSEGV handler reports it with the function history.
Uninitialised memoryEvery allocation is zeroed (fresh pages are zero, freed blocks are zeroed on free).

What is not

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:

BugDetected 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 redzonewith 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 redzoneSIGSEGV "past the end of an allocation" with --check-arena-guard (guard page after each allocation)
Write before the startthe 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 allocationabort with the report (exit code 134)
Promotion of a pointer that was already freedabort 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_enterabort

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

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.

StepStatusWhat it means
0. Loud failures firstdone--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 invariantdonePromotion 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 pointerdoneThe 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 containerdoneA 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 lengthlength and s[i] done, slice nextThe 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 threadsthreads done; nullability plannedT? 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 modeplannedA 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.