8000 GitHub - AFK-surf/beamc: Formally verified closed-world AOT BEAM compiler (OTP 29, Rust + Aeneas/Lean 4, Linux x86-64 & Linux/macOS AArch64) · GitHub
[go: up one dir, main page]

Skip to content
AFK-surfPublic

About

Formally verified closed-world AOT BEAM compiler (OTP 29, Rust + Aeneas/Lean 4, Linux x86-64 & Linux/macOS AArch64)

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

beamc

beamc is a closed-world, ahead-of-time (AOT) native compiler for Erlang/OTP 29 .beam bytecode written in Rust, paired with a soft real-time BEAM runtime (beamrt) and Lean 4.36 formal verification of the compiler kernel (beamc-core) extracted via Charon and Aeneas.

It compiles standard OTP 29 .beam files produced by Erlang (erlc), Elixir (mix), Gleam (gleam build), LFE, and OTP standard libraries (erts, kernel, stdlib, ...) directly into standalone ELF64 / Mach-O native executables with no runtime bytecode interpreter and no runtime JIT.

Highlights

  • Pure closed-world AOT: No BEAM interpreter or JIT ships at runtime (formal BEAM/CoreSSA operational semantics exist strictly inside Lean 4 as specification). Dynamic BEAM code loading (code:load_binary/3, hot code upgrade) is explicitly out of scope and returns {error, dynamic_code_loading_disabled}.
  • Native multi-target codegen:
    • Linux x86-64 (ELF64, System V AMD64)
    • Linux AArch64 (ELF64, AAPCS64)
    • macOS AArch64 (Mach-O, Darwin AAPCS64)
  • Full OTP 29 erl_nif C ABI (NIF 2.18): Supports both dynamic dlopen .so NIFs (including rustler_precompiled, C/C++, etc.) and static .a NIFs (enif_alloc_resource, destructors, enif_send, enif_schedule_nif, dirty CPU/IO schedulers, 180 exported enif_* symbols).
  • Soft real-time BEAM runtime (beamrt):
    • Per-process isolated heaps with per-process generational copying GC driven by precise StackMap[pc] tables (zero global stop-the-world pauses).
    • Dual-stack execution: lightweight growable per-process native stacks (2 KiB initial, supporting 100k+ processes) with fast OS stack switching for BIF/NIF calls.
    • Deterministic reduction-based preemption pinned in hardware registers (r14 on x86-64, x27 on AArch64) with low tail latency (p99 <= 20 us).
    • EEP-76 priority messages & recv_marker, ETS, ports, and OTP distribution / ETF interop.
  • Zero-TCB optimizing compiler:
    • beamc-oracle runs whole-program type/range inference (treating OTP 29 Type chunks as untrusted hints), inlining, SROA, FBIP reuse planning, escape analysis, and iterated register coalescing (IRC) to emit untrusted Witnesses.
    • beamc-core (#![no_std], extern crate alloc, #![forbid(unsafe_code)], zero external dependencies) verifies every witness in linear time before applying it and rejects or falls back cleanly on forged or malformed witnesses.
  • Formally verified compiler kernel (proofs/): beamc-core obeys an Aeneas-extractable Rust subset enforced on every commit (scripts/check-aeneas-subset.sh) and is extracted directly into Lean 4.36 with CI-enforced axiom auditing (proofs/scripts/audit.sh: zero sorry, zero bv_decide, standard Lean axioms only).

Architecture

  .beam files (OTP 29)
         │
         ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  beamc-core  (#![no_std], #![forbid(unsafe_code)], 0 deps, Aeneas)  │
  │                                                                     │
  │  V1 beam      ──► decode, inflate, structural validation            │
  │  V2 ssa       ──► CoreSSA lifting + well-formedness & RedsCheck CFG │
  │  V3 opt       ──► witness checking (facts, nothrow, escape) + opts  │
  │  V4 lower_rt  ──► runtime/GC lowering, safepoints, bit-syntax webs  │
  │  V5/V6 mach   ──► instruction selection + regcheck witness verifier │
  │  V7 encode    ──► native x86-64 & AArch64 machine-code emitters     │
  └──────────────────────────▲──────────────────────────────────────────┘
                             │ untrusted Witness (zero-TCB)
                   ┌─────────┴──────────┐
                   │    beamc-oracle    │  type/range inference, SROA,
                   │   (full std, par)  │  inlining, FBIP, IRC regalloc
                   └────────────────────┘
                             │
                             ▼
            beamc-driver (ELF64 / Mach-O + CAS cache)
                             │ link with libbeamrt.a
                             ▼
                Standalone native executable

Workspace Layout

Path Description
crates/beamc-core #![no_std], #![forbid(unsafe_code)], zero-dependency compiler kernel (V1–V7) and witness verifiers, extracted to Lean 4 via Charon + Aeneas.
crates/beamc-oracle Untrusted whole-program analysis, optimization planner, and IRC register allocator producing Witness certificates.
crates/beamc-driver beamc CLI driver, ELF64 / Mach-O object writers, content-addressed build cache (--cache-dir), and native linker driver.
crates/beamrt Soft real-time BEAM runtime (libbeamrt.a): process scheduler, isolated generational GC, BIFs, ETS, ports, ETF/distribution, and OTP 29 erl_nif ABI.
crates/beamc-bench Cross-language benchmark harness comparing beamc, Go, and OTP 29 BeamAsm.
proofs/ Lean 4.36 formalization and Aeneas-extracted models of beamc-core (BeamcCore/** + BeamcProofs/**).
docs/ Benchmark reports and corpus compatibility audits (CLBG_BENCHMARKS.md, CORPUS_AUDIT.md, POPULAR_APPS_AUDIT.md).
DESIGN.md Architecture notes and frozen binary ABI (Eterm tagging, pinned registers, ProcessCtx layout).

Quick Start

Prerequisites

  • Rust toolchain (see Cargo.toml; beamrt uses stabilized C-variadic functions for enif_make_tuple/enif_snprintf and requires a recent Rust 1.100+ / nightly toolchain)
  • A C linker (cc / clang / lld) for --emit exe
  • Erlang/OTP 29 (erlc) to produce .beam files (optional for compiling pre-existing .beam inputs)

Build

cargo build --release -p beamc-driver -p beamrt

This produces target/release/beamc and target/release/libbeamrt.a.

Compile .beam Modules

Emit a single closed-world native object file:

./target/release/beamc \
  --target linux-x86_64 \
  -o app.o \
  mod1.beam mod2.beam

Compile and link a standalone native executable running mod:main/1 (passing CLI arguments as Erlang strings):

./target/release/beamc \
  --emit exe \
  --entry mod:main/1 \
  --runtime target/release/libbeamrt.a \
  --cache-dir .beamc-cache \
  -o app \
  mod.beam /path/to/otp/stdlib/ebin/lists.beam

Useful CLI flags:

  • --target linux-x86_64|linux-aarch64|macos-aarch64 — cross-target object emission
  • --emit obj|exe — emit a relocatable object (default) or link a standalone executable
  • --entry mod:fun[/1] — entry MFA for standalone executables (BEAMRT_LIB env var can supply libbeamrt.a)
  • --cache-dir DIR — enable content-addressed caching for per-function V3/IRC/backend stages and whole-program objects
  • --timings — print per-stage wall-time breakdown on stderr (or set BEAMC_TIMINGS=1; BEAMC_THREADS=N caps worker threads)
  • --no-opt — skip beamc-oracle witnesses (A/B baseline and debugging)
  • --link-extra FILE — pass extra static archives / object files (e.g. static NIF .a libraries) to the linker

Boot an OTP release

Compile the release's BEAM modules with --emit exe --entry init:boot/1. Run the executable with the release root, ERTS bin directory and boot script as OTP arguments. The .boot script controls when the linked modules' on-load functions run.

BEAMRT_RELEASE_ROOT="$release_root" ./my_release \
  -- -root "$release_root" -bindir "$erts_bin_dir" \
  -boot "$release_root/releases/1.0/start" -mode embedded -noshell

Keep the original release objects available on the OTP code path. During the boot sequence, the loader verifies each on-load object's digest against the linked input before activating its native callback.

Tests & Subset Check

bash scripts/check-aeneas-subset.sh
cargo test -p beamc-core
cargo test --workspace
cargo clippy --workspace --all-targets -- -D warnings

Formal Verification (proofs/)

Phase 2 verifies crates/beamc-core only in Lean 4.36 by extracting Rust slices directly with Charon + Aeneas into proofs/BeamcCore/** (never edited by hand) and proving properties in proofs/BeamcProofs/**.

What is verified on main:

  • Frozen Binary ABI (Abi.lean): 64-bit Eterm tagging/untagging round-trips (small integers, atoms, headers, lists, boxed pointers), ProcessCtx field layout, and x86-64 / AArch64 register roles.
  • V1 Frontend (Frontend.lean): Extracted .beam Reader never panics, keeps cursors in bounds, decodes big-endian values exactly; opcode table totality; validate operand checks never panic and are sound.
  • Native Encoders (EncodeAArch64/*, EncodeX86/*, EncodePatch.lean): Bit-level encode/decode soundness for x86-64 (REX/ModRM/SIB/disp/imm, mov_ri, patch_u32) and AArch64 (decode_bitmask witness checker, 4-path mov_imm, load/store offset dispatch, lea/alu_ri large immediates).
  • Zero-TCB Witness Verifiers (Opt/*, Ssa/*):
    • opt::wf::compute_nothrow: greatest-fixpoint equivalence and exception-freedom soundness (NothrowSound).
    • opt::facts: lattice soundness, interval arithmetic overflow discharge (arith_proven_small), and check_function local soundness (FactsSound, FactsCheckSound).
    • opt::regcheck: register-class safety, non-interference, cross-call spilling, liveness_is_postfix, and missing_location (RegCheckSound, RegCheckInterf, RegCheckLiveness).
    • ssa::verify::verify_code: structural well-formedness (VerifyWF), uncharged-edge cycle absence (VerifyReds), and intraprocedural ReductionCertificate yielding machine-level bounded preemption (VerifyCert).
  • Three-Stage Forward Simulation (Sim/*):
    • Sim/BeamToSsa: full reference translation covering all 37 Beam.Instr constructors (x/y registers, frames, allocate/deallocate, call/call_only/call_last/ret, try/try_end/try_case, select_val, test_arity, fixnum+bignum arithmetic, and exact reduction yields) with trace and outcome preservation.
    • Sim/SsaToMach: CoreSSA-to-machine forward simulation (including arbitrary overlapping/cyclic parallel_move), composed via ForwardSim.comp into SimBeamToMach, bridged to ssa::verify (lower_bounded_preemption), RegCheck, and copying-GC safepoint preservation (safepoint_inv, gc_preserves_sim).
    • Sim/MachToIsa: dual-backend forward simulations (a64_emit_ops_sim, x86_emit_ops_sim) proved directly against Aeneas-extracted encode::{aarch64,x86_64}::emit_ops, plus ISA-level reduction accounting (a64_reds_contract, x86_reds_contract) bounding quiet ISA instructions to 2 * (reds₀ * (R + 1) + R).

Run the proof suite locally (see proofs/README.md for details):

bash proofs/scripts/setup-aeneas.sh    # install Charon/Aeneas + Mathlib cache (idempotent)
bash proofs/scripts/extract.sh --check # verify extracted Lean models match crates/beamc-core
cd proofs && lake build BeamcProofs    # build all proofs
bash proofs/scripts/audit.sh --verbose # enforce 0 sorry / 0 bv_decide / standard axioms only

Corpus Compatibility & Benchmarks

  • OTP 29 & Hex ecosystem corpus:
    • 100% of OTP 29.1.2 (1,323 / 1,323 .beam modules) compiles cleanly across Linux x86-64, Linux AArch64, and macOS AArch64.
    • 100% of the 30-package Erlang/Elixir Hex audit (1,023 / 1,023 modules across cowlib, cowboy, ranch, jsx, ra, plug, etc.) compiles cleanly across all three targets; see docs/CORPUS_AUDIT.md and docs/POPULAR_APPS_AUDIT.md.
  • Compile speed: Linear O(N) scaling with parallel stages and content-addressed caching (--cache-dir), achieving cold and warm multi-module compile times competitive with or faster than go build on comparable module counts while producing byte-identical .o outputs across sequential/parallel and cold/warm builds.
  • Runtime performance:
    • Matches or beats Go on core compute, binary scanning, tuple/record pipeline, and ping-pong message-passing kernels (crates/beamc-bench).
    • All 10 official Computer Language Benchmarks Game Erlang programs compile into standalone executables, match OTP 29 erl stdout byte-for-byte, and outperform OTP 29 BeamAsm across all 10 tasks; see docs/CLBG_BENCHMARKS.md.

Reproduce benchmarks locally:

# Core kernels (beamc vs Go vs OTP BeamAsm)
cargo run --release -p beamc-bench -- --beamc-compile

# CLBG correctness and benchmarks
cargo test -p beamc-driver --test clbg_tests
BEAMC_CLBG_BENCH=1 cargo test --release -p beamc-driver --test clbg_tests -- --nocapture

# Corpus & popular Erlang/Elixir apps regression suites
cargo test -p beamc-driver --test corpus_tests
cargo test -p beamc-driver --test popular_apps_tests

License

Copyright (c) 2026 AFK AI, Inc.

Licensed under the MIT License.

About

Formally verified closed-world AOT BEAM compiler (OTP 29, Rust + Aeneas/Lean 4, Linux x86-64 & Linux/macOS AArch64)

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0