veko-lang.org
Download Free EPUB 3.0

Part IV · Compiler Architecture, Backend Internals, Safety Proofs & ADRs

Chapter 18

Safety Classification & ORO Memory Model Proof

16-byte Value and SlabHdr layouts, mechanical DAG cycle-freedom proof, 12-bucket slab recycling, and formal trust boundaries

This specification details Veko's One Reference Only (ORO) + Copy-on-Write (CoW) memory architecture across all three execution backends (oro_vm.vk, codegen.vk / vvm, and native_emit.vk / arm64_emit.vk), mechanical proof of cycle freedom, deterministic .secret zeroization and sink firewalls (including .ui clipboard/window and .ffi), vvm sandbox confinement, opt-in .ffi isolation with zero-W^X static trampolines, and atomic slab recycling across Windows (x86_64), Linux (x86_64/arm64), and macOS (arm64).


1. 16-Byte Value & SlabArena Architecture

Every Veko runtime value—whether inside oro_vm.vk frames, codegen.vk Wasm linear memory, or native_emit.vk / arm64_emit.vk registers and OS-allocated slabs (VirtualAlloc on win-x64, mmap on linux-x64, linux-arm64, and macos-arm64)—occupies an aligned 16-byte cell (4 cells per 64-byte CPU cache line):

MEMORY LAYOUT & SAFETY

16-Byte Value Cell, 14-Byte Inline SSO & 12-Bucket Slab Arena

Exact binary representation shared across 64-bit VKO VM, Wasm 3.0 linear memory, x86_64, and AArch64.

REGISTER / STACK VALUE CELL (16 BYTES) 2 x i64 registers in native ABI THREAD-LOCAL ORO SLAB ARENA Zero lock contention + volatile secret scrub len <= 14B tag == closure heap ptr rc == 0 flag_secret zeroed slab Value ABI16-Byte Value Wordtag:u8 | flags:u8 | len/aux + payload Zero-Heap SSO14-Byte Inline SSOstr_inline & bytes <= 14B ClosuresAcyclic Closure Cellfn_idx + frozen env slab Heap Header16-Byte SlabHdrrc:i32 | cap_class:u16 | flags:u16 Allocator12-Bucket Free-ListsO(1) pop / push recycling Cryptographic HygieneVolatile .secret Scrubflag_secret + zeroize!
Component & ModuleArchitectural Role
16-Byte Value Word
runtime.vk + native_rt.vk
Uniform 128-bit representation holding unboxed scalars, inline SSO bytes, or a slab pointer.
14-Byte Inline SSO
runtime.vk + native_rt.vk
Stores short identifiers, map keys, HTTP tokens, and nonces directly inside bytes 2..15.
Acyclic Closure Cell
vko_emit.vk + native_emit.vk
Pairs a compiled function table index with an immutable snapshot of captured outer values.
16-Byte SlabHdr
native_rt.vk + arm64_rt_core.vk
Prefixes every heap-allocated bytes, str_heap, block, map, and struct payload.
12-Bucket Free-Lists
native_rt.vk + runtime.vk
Recycles freed slabs immediately into per-thread size-class singly linked lists.
Volatile .secret Scrub
types.vk + native_rt.vk
Zeroes secret key material deterministically before returning memory to any free-list.

Byte-Accurate Value Cell Layout

OffsetSizeFieldRole
01 BtagDiscriminant (uninit, bool, i64, f64, dur, size, word, enum, str_sso, str_heap, bytes, block, map, closure, native_fn, err)
11 BflagsWasm: flag_owned (0x01), flag_secret (0x02), flag_const (0x04), flag_mut_ref (0x08), flag_struct (0x10), flag_map_hashed (0x20 on map_val with >16 pairs; on str_sso, upper nibble stores length 0..14). Native: FLAG-OWNED=1, FLAG-MUT-REF=2, FLAG-SECRET=4, FLAG-CONST=8, FLAG-STRUCT=16, FLAG-MAP-HASHED=32 (.rdata constant slabs carry rc = -1).
2..32 BauxWord binding kind, native arity, canonical struct schema symbol ID, or str_sso bytes 0..1
4..74 Bmeta32-bit SlabId (Wasm), interned symbol ID, closure fn_idx, or str_sso bytes 2..5
8..158 BdataUnboxed i64/f64, 64-bit native slab pointer, str_sso bytes 6..13, or closure env_slab

2. Why flag_owned Eliminates Borrow Reference-Counting

Traditional reference-counted languages increment and decrement heap counters on every function call. Veko stores ownership directly on the 16-byte Value cell:

  1. Read-Only Borrow: Passing buf to a plain parameter copies the 16-byte Value into the callee frame with flag_owned = 0. When the callee exits, scope cleanup inspects (v.flags & flag_owned) != 0, skips borrowed values, and performs zero heap memory touches.
  2. Ownership Move: Assigning y = x or returning a value transfers flag_owned = 1 to the destination and immediately releases any previous slab owned by y.
  3. Explicit mut Loan: Marking both signature and call site with mut (including disjoint field borrows mut state.tx_buf) sets flag_mut_ref targeting the caller's slot so in-place mutations (bytes/push, ascii/upper!) operate directly on the caller's buffer and update the slot if a CoW split reallocates.

3. Mechanical Proof That Reference Cycles Cannot Exist

Appending a container to itself (push mut a a) cannot form a reference cycle under Copy-on-Write ensure_unique:

  1. Evaluating the second argument a creates a temporary snapshot, bumping hdr(a).rc from 1 to 2.
  2. push invokes ensure_unique(mut a) before mutating.
  3. Because hdr(a).rc == 2 (shared), ensure_unique allocates a fresh slab a' (rc = 1), copies existing elements into a', decrements old a's rc back to 1, and appends old a inside new a'.
  4. Invariant: Only a slab with rc == 1 can ever be mutated; an older slab can never be mutated to point to a newer or ancestor slab. Every heap pointer points strictly backward in allocation time, guaranteeing a Directed Acyclic Graph (DAG) and 100% deterministic scope-exit deallocation.

4. Deterministic .secret Zeroization & End-to-End Sink Firewalls

  1. No Inline SSO for Secrets: os/getenv/secret, ui/clipboard-get/secret, bytes/with-secret, and interpolated backtick templates containing secret expressions always allocate heap slabs carrying flag_secret so full capacity is zero-wiped (0x00) inside release ([16 .. 16 + cap) for raw slabs, cap * 16 for value slabs) before the slab returns to any free-list or OS page pool.
  2. Automatic Redaction: print, println, mold, and log/* redact .secret values to <secret>.
  3. Static & Runtime Sink Firewalls: Both veko check (types.vk) and recursive runtime inspection block .secret values, struct fields, and containers from crossing:
    • Disk & stdio (os/write-file, os/pwrite, os/stderr, os/exec),
    • Wire serialization & networking (json/encode, net/*, http/*),
    • Concurrency channels & tasks (spawn, chan/send),
    • Desktop UI & OS clipboard (ui/present, ui/clipboard-set), and
    • Foreign C-ABI boundaries (ffi/open, ffi/sym, ffi/call).

5. Cross-Module Isolation, Shared-Nothing Concurrency & Sandbox Confinement

  • Controlled Module Exports: pub and export [...] permit functions, macros, struct / sealed struct schemas, and interface contracts—rejecting pub mut state so mutable slabs never alias across module boundaries.
  • Stage 1 --strict-types Static Soundness (types.vk): Enforces fallible T|err expression tracking across I/O, network, map, and parsing APIs (requiring /or recovery or if err? x branch narrowing before typed T use), exhaustive match arm verification over booleans and closed enums, homogeneous block[T] literals, strict mut local reassignment, and identical err semantics for missing os/getenv keys across VM, Wasm, and Native.
  • Shared-Nothing spawn Workers: Each spawn [ ... ] worker runs with private ThreadState (R12 on x86_64, X19 on AArch64) or an isolated vvm HostSandbox store, updating shared refcounts atomically (lock xadd / ldaddal) while prohibiting shared mut borrows and closures across threads.
  • vvm WebAssembly 3.0 Confinement: Enforces bounded linear memory (--mem-pages), deterministic instruction fuel (--fuel), confined WASI filesystem roots (--allow-fs=<dir>), SSRF loopback/RFC1918 guards (--no-private-net), and unconditional denial of .ffi.

6. Atomic 12-Bucket Slab Recycling & Unwind Safety

  1. 16-Byte Native Slab Header: [+0 rc:i32, +4 cap:i32, +8 len:i32, +12 flags:i32] packs SLAB-FLAG-VAL = 1, FLAG-SECRET = 4, FLAG-STRUCT = 16, 16-bit type_sym << 8, and bucket_tag << 24 (1..12 for 32 B..65536 B; 0 for >64 KiB direct OS pages).
  2. Unwind-Safe /or & defer Isolation: During /or error unwinding, outer error cells and RT-TRY-TOP indices remain isolated across nested LIFO defer executions, and division/modulo by zero (OP-DIV, OP-MOD) raise catchable /or errors rather than OS hardware traps.
  3. Formal Safety Pillars:
Safety PillarEnforced MechanismGuarantee
Spatial SafetyBounds-checked bytes, str, block, wire intrinsics, and O(1) struct slot access across VM, Wasm, and Native.Eliminates out-of-bounds reads/writes and raw pointer arithmetic in safe .vk code.
Temporal SafetySingle-owner flag_owned moves, CoW rc == 1 mutation invariant, and disjoint lexical mut loans.Eliminates use-after-free, double-free, and cyclic leaks deterministically at scope exit.
Concurrency SafetyCompile-time spawn capture checks + runtime conc_safe transfer validation + atomic rc.Eliminates unsynchronized shared-memory data races.
Confidentiality & Supply Chainflag_secret heap zeroization + I/O sink firewalls + Ed25519/ML-DSA-65 'VKP1' & veko.lock Merkle verification.Prevents secret exfiltration and tampered package injection.

Explicit Trust Boundary & Opt-In .ffi Isolation

Safe .vk guarantees hold modulo Veko's self-hosted compiler/runtime TCB and underlying OS kernel syscalls. Foreign C/Rust library interop (lib/ffi.vk) is denied by default, forbidden on --wasm, implemented strictly via static AOT C-ABI trampolines (zero RWX JIT pages), and gated behind explicit allow-caps = [.ffi] or --allow-ffi.


7. Defense-in-Depth: RASP Policy Guards, IAST Secret Tracking & Global Race Prevention

Veko's AppSec toolchain reinforces the compile-time ORO ownership model and .secret firewall across static auditing, instrumented VM execution, and production native binaries:

  1. Runtime Sink Confinement (VmPolicy + src/rasp_pass.vk + lib/sec/rasp.vk):
    • In Track A (oro_vm.vk), VmPolicy constrains filesystem roots, network/private-net access, and .exec/.ffi capabilities.
    • When compiled or run with --rasp=monitor or --rasp=enforce, rasp_pass.vk wraps outbound URL/socket calls (guard-url), filesystem operations (guard-path), database queries (guard-sql), and process execution (guard-exec) across all 8 native targets, blocking SSRF (including link-local IMDS 169.254.169.254 and RFC1918 addresses unless allowlisted), .. path traversal, unparameterized SQL tampering, and unauthorized command execution—emitting CEF or JSONL SIEM records on every trigger.
  2. Runtime .secret Flow Verification (VKIAST008):
    • While types.vk and flag_secret enforce static and runtime .secret sink firewalls on os/write-file, json/encode, net/*, chan/send, ui/present, and ffi/*, oro_vm.vk with iast_en = true (sec/iast/check-sink) additionally monitors has_secret_arg at print, println, web/text, web/html, web/json-resp, json/encode, net/write, and sec/iast/sink-log, emitting VKIAST008 SARIF findings with the exact source location and call stack whenever a secret value reaches an output sink during testing.
  3. Static Thread-Safety Gate (VKSEC011 on RT-GLOBALS):
    • Module-level bindings reside in RT-GLOBALS, which is shared unsynchronized across native OS threads (and shallow-cloned per VM worker) with unretained OP-LOAD-GLOBAL borrows. A top-level mut map, block, or buffer can cause use-after-free or data races under concurrent spawn workers. sec/sast rule VKSEC011 (CWE-362, NIST SC-39 / SI-16) statically detects and rejects top-level mut heap globals before compilation, steering programs toward explicit mut state passing or chan/* actor serialization.