# Memory safety and audit

Guillotine is mission-critical financial execution infrastructure: every allocation, reallocation, container growth, OS virtual-memory mapping (`mmap`/`VirtualAlloc`), thread spawn, FFI heap transfer, and teardown across the entire production codebase is audited in [`MEMORY.md`](https://github.com/evmts/guillotine/blob/main/MEMORY.md) and **continuously enforced by CI** so no allocation or free can ever be introduced without proof and review.

## Audit coverage at a glance

| Metric | Audited & Enforced |
| --- | ---: |
| Production Zig files with memory operations | **122** (`245` total production files scanned) |
| Audited Zig `(file, scope)` entries | **693** |
| Tracked allocation, growth, OS mapping & free operations | **1,868** |
| Rust `extern "C" fn` FFI boundary exports | **30** (`foundry-compilers`, `bn254`/`bls12_381`, `keccak256`, `p256`) |
| Tier 1 Formal Verification (`[FV]`: Lean 4 / SMT / LLVM IR) | **539 / 693** scopes (77%) |
| Tier 2 Leak-Checked & OOM-Swept Fuzzing (`[FUZZ]`) | **684 / 693** scopes (98%) |
| Tier 3 Deterministic Unit / OOM / Integration / EEST Tests (`[TEST]`) | **693 / 693** scopes (100%) |
| Tier 4 Structured English Safety Argument (`[ARG]`, mandatory) | **693 / 693** scopes + **30 / 30** FFI exports (100%) |
| Memory safety defects found & remediated during audit | **29** (all fixed & regression-proved) |

Browse the complete, machine-checked 693-scope and 30-FFI-export registry directly in [`MEMORY.md`](https://github.com/evmts/guillotine/blob/main/MEMORY.md).

***

## 4-tier proof hierarchy

Every audited allocation and free carries proofs ranked from highest mathematical assurance down to a mandatory explicit safety argument:

1. **`[FV]` Formal Verification (Preferred)**:
   * **Lean `4.35.0`** (`verify/lean/GuillotineVerify/`): [`MemoryAudit.lean`](https://github.com/evmts/guillotine/blob/main/verify/lean/GuillotineVerify/MemoryAudit.lean) (13 machine-checked theorems with zero `sorry` and zero axioms covering `SlabPool`, `GrowingArenaAllocator`, `FrameStackPool`, `DispatchCache`, C-ABI `HandleBox`, `KeccakCache`, `logSlabLayout`, `StackPool`, Base `b20` disjoint buffers, `CallTracer`, `MVMemory`, and `BoundedAllocatingWriter`), alongside `MemorySafety.lean`, `Memory.lean`, `JitRuntime.lean`, `JitVStack.lean`, `BlockSTM.lean`, `PrecompilesL2FFI.lean`, `StatefulHost.lean`, `JumpTable.lean`, `BasicBlock.lean`, and Zean direct Zig AIR proofs in `GuillotineZean/MemoryHelpers.lean`.
   * **SMT-LIB2 via Bitwuzla / Z3** (`verify/smt/run_smt_suite.py`): **151 source-pinned `QF_BV` theorems** (`verify/smt/model_pins.json`), including **10 audit theorems**: `slab_pool_checked_bump_and_zero_len_safety`, `log_slab_layout_checked_disjoint_partition`, `keccak_cache_mask_and_entry_bounds`, `flat_memory_u64_wrap_free_bounds`, `b20_padded32_and_dynamic_layout_bounds`, `base_native_context_buffer_selection_bounds`, `mv_memory_reset_checked_stride_and_index`, `provider_bounded_writer_ceiling_safety`, `jit_mcopy_slow_bounds_and_gas_safety`, and `call_tracer_skipped_depth_oom_safety`.
   * **LLVM 20 IR equivalence & UB-freedom** (`zig build verify-ir`).
2. **`[FUZZ]` Leak-Checked & OOM-Swept Fuzzing (2nd Preferred)**:
   * 21 Zig `std.testing.fuzz` suites (`test/fuzz/`) running under `std.testing.allocator` strict leak detection, including [`test/fuzz/memory_oom_audit_fuzz.zig`](https://github.com/evmts/guillotine/blob/main/test/fuzz/memory_oom_audit_fuzz.zig) which runs exhaustive `std.testing.FailingAllocator` sweeps across every critical allocator, trie mutation, storage/journal, RPC provider, Base native precompile, tracer, JIT analysis, and Block-STM path.
3. **`[TEST]` Deterministic Unit, OOM, Integration & EEST Tests (3rd Preferred)**:
   * `zig build test`, `zig build test-evmc`, `zig build state-tests -Doptimize=ReleaseSafe`, `cargo test --locked`, and C/TypeScript SDK tests.
4. **`[ARG]` Mandatory Structured English Safety Argument**:
   * Every single production allocation and free states its owning struct/caller, allocator matching, `defer`/`errdefer` unwinding, checked size arithmetic, and UAF/double-free/aliasing invariants.

***

## Memory & allocator architecture

Guillotine isolates lifetimes into explicit, non-overlapping ownership domains:

| Domain / Allocator | Location | Lifetime & Safety Invariants |
| --- | --- | --- |
| **`GrowingArenaAllocator`** | `src/evm_arena_allocator.zig` | Per-transaction call arena owned by `Evm`; enforces hard `max_capacity` ceiling and trims oversized buffers back to `initial_capacity` on reset. |
| **`SlabPool`** | `src/internal/slab_pool.zig` | Refcounted geometric bump-slab allocator for `DispatchCache` schedules; checked `alignForwardChecked` and overflow guards, zero-len fast path without bumping `slab.live`, rejects `resize(non_zero, 0)`, frees retired slabs at `live == 0`. |
| **`FrameMemoryPool` & `Memory`** | `src/memory/frame_memory_pool.zig`, `src/memory/memory.zig`, `src/memory/reservation.zig` | Pooled root buffer (heap or `VirtualReservation` via `mmap`/`VirtualAlloc`); child frames borrow disjoint checkpointed sub-slices bounded by quadratic gas + `memory_limit` and 64-bit wrap-free bounds checks. |
| **`FrameStackPool` & `Stack`** | `src/stack/stack.zig`, `src/native_stack.zig` | Pooled fixed 1024-word LIFO stacks per call depth; basic-block pre-validation guarantees `_unsafe` stack accesses never escape `[buf_ptr, buf_ptr + 1024]`. |
| **W^X Native JIT (`ExecPool`, `ExecSlab`, `JitCache`)** | `src/jit/jit_mem.zig`, `src/jit/jit_cache.zig` | Refcounted executable slabs (macOS `MAP_JIT`, Linux dual RW/RX `memfd` with `dc cvau` → `dsb ish` → `ic ivau` and immediate RW `munmap` on `retire()`, Windows `RW → RX`); `ExecMemory` owns an independent slab ref so teardown order is safe. |
| **Block-STM (`MVMemory`, `WorkerPool`)** | `src/block/mv_memory.zig`, `src/block/worker_pool.zig` | 256 per-shard `ArenaAllocator`s + overflow-checked reader bitset stride; resets every shard with `used_list != null` between blocks; speculative OOM aborts deterministically via `SpeculativeDb.note`. |
| **Atomic `StackPool` & `keccak_cache`** | `src/frame/call_result.zig`, `src/instructions/keccak_cache.zig` | `StackPool` uses `std.atomic.Value(usize)` with `.acq_rel` release and stored owning `allocator`; thread-local `keccak_cache` reclaims automatically via POSIX `pthread_key_create` destructor plus explicit `deinitThread()`. |
| **C ABI v1–v4, EVMC v12 & Rust FFI** | `src/evm_c_api.zig`, `src/bytecode/bytecode_c.zig`, `src/evmc_c_api.zig`, `lib/` | Atomic `HandleBox` borrow/drain protocol prevents concurrent destroy UAF; optional `?[*]T` analysis pointers; all 30 Rust `extern "C" fn` exports wrapped in `catch_unwind` with null and length validation. |

***

## Key audit findings fixed

The audit uncovered and fixed **29 concrete memory-safety bugs**, including:

* **Merkle Patricia Trie & RLP (`src/trie/hash_builder_complete.zig`, `lib/voltaire/src/primitives/rlp.zig`)**: Eliminated 5 double-free / UAF paths across `insert_node`, `split_extension`, `delete_node`, `unwind_delete_*`, and `collapse_branch` by making `store_node` unconditionally take ownership and nulling moved ownership slots immediately, and fixed OOM leaks in `Rlp.encode` and `Rlp._decode` list loops caught by `memory_oom_audit_fuzz`.
* **RPC Provider (`src/provider/{provider,connection_pool,config,transport/http_simple,transport/json_rpc}.zig`)**: Fixed a guaranteed UAF in `Provider.call()`, heap-allocated individual `*PooledConnection` entries so `*std.http.Client` pointers remain stable across list growth and `cleanup_idle()`, fixed mutex deadlock on OOM, added streaming `BoundedAllocatingWriter` response caps, and guarded JSON numeric casts.
* **Native JIT (`src/jit/{evm_bridge,x86_64_codegen,jit_mem,analysis,runtime_helpers,fast_paths,jit_cache}.zig`)**: Fixed x86-64 `MCOPY` slow-stub stack aliasing, propagated memory OOM/overflow errors instead of swallowing them as `.fallback`, fixed Linux AArch64 `dc cvau`/`ic ivau` + immediate RW alias `munmap` on `retire()`, and added missing `max_code_size` and capacity guards.
* **Base Native Precompiles (`src/layer2/base/native/`)**: Eliminated 64 KiB upfront arena DoS per call, fixed-buffer overflows on dynamic strings, and aliased `@memcpy`/`@memset` UB by introducing `Context` with `inline_out: [256]u8`, growable `dyn_out`, and strictly disjoint `scratch`.
* **State Root & Storage (`src/storage/{state_root,database,journal,access_list,self_destruct}.zig`)**: Deduplicated sorted keys in `trieRoot` (preventing `key[32]` OOB reads), prevented unbounded `delegation_targets` growth across `simulate()` views, and guarded stale revert checkpoints.
* **Allocators, Caches & FFI (`src/internal/slab_pool.zig`, `src/instructions/keccak_cache.zig`, `src/frame/call_result.zig`, `src/tx_runner.zig`, `src/bytecode/bytecode_c.zig`, `lib/foundry-compilers/`)**: Fixed `SlabPool` zero-len refcount leak & overflow checks, added POSIX thread-exit reclamation for `keccak_cache`, made `StackPool.refcount` atomic with stored allocator, fixed `executeFrameTx` trace leak, switched `CBytecodeAnalysis` to optional `?[*]T`, and wrapped Rust FFI in `catch_unwind` with null-safe error writes.

See Section 3 of [`MEMORY.md`](https://github.com/evmts/guillotine/blob/main/MEMORY.md) for the complete 29-item remediation log.

***

## CI-enforced memory audit linter

No contributor can add, remove, or modify an allocation or free in production code without documenting and arguing its safety in `MEMORY.md`.

```bash
# Run the memory audit linter directly
python3 scripts/check-memory-audit.py --stats

# Or through the Zig build system
zig build check-memory-audit

# Run the linter's own unit & regression tests
python3 scripts/check-memory-audit.py --self-test
python3 -m unittest scripts/test_check_memory_audit.py
```

The `ast-check` CI job (`.github/workflows/ci.yml`) runs all three checks on every push and pull request and fails immediately on:

* Any undocumented `(file, scope)` containing an allocation, container growth, OS mapping, thread spawn, allocator construction, or free/deinit/unmap.
* Any operation-count drift (even one added `alloc` or `append` inside an already-audited function).
* Any stale or duplicate registry row, placeholder safety argument (`< 25` chars or `TODO`/`TBD`/`safe`), or broken proof path.
* Any undocumented Rust `pub [unsafe] extern "C" fn` export.

## Related guides

* [TigerStyle and safety guarantees](/guides/tigerstyle)
* [Testing, fuzzing, and formal verification](/guides/testing-and-verification)
* [Full 693-scope registry (`MEMORY.md` on GitHub)](https://github.com/evmts/guillotine/blob/main/MEMORY.md)
