8000 GitHub - expo/ibex3 · GitHub
[go: up one dir, main page]

Skip to content
expoPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ibex3

A ~1.4 MiB JavaScript & TypeScript virtual machine in Rust built to share values directly across Rust, Contract, and JS/TS — tiny, zero-JIT, and very fast for its size.

ibex3 is an embeddable, ahead-of-time (AOT) bytecode and native-AOT JS/TS runtime built primarily for Exact3 (expo/exact3) and usable by any Rust host that wants direct Rust ↔ JS data sharing, minimal binary/memory footprint, deterministic resource containment, and fast startup without embedding a multi-megabyte C++ engine or paying JSON serialization taxes across the host boundary. (Pre-1.0: bytecode, snapshots, and crate APIs break freely.)


Top 3 Reasons to Care

1. Shares values directly across Rust, Contract, and TypeScript/JavaScript

  • Zero-JSON host seam (ibex-seam): Pass pre-shaped records, immutable strings, and owned/detached byte buffers (DetachedOnReturn) directly across the Rust ↔ Contract ↔ JS boundary without serializing through JSON (< 1 ms for 4,096 rows).
  • First-class TypeScript & JSX (ibex3c): Single-parse Oxc AST-direct compiler lowers .ts, .tsx, .js, and .mjs straight to compact verified .ibc bytecode with exact original file:line:col stack traces, classic + automatic JSX, strict CJS interop, JSON/text/bytes assets, pluggable module resolution, and static admission (AdmitPolicy).

2. Tiny — and you only pay for what you use

  • ~1.37 MiB stripped runtime binary, ~3 MiB cold-boot peak RSS: The runtime (ibex-vm) is strictly separated from the compiler (ibex-compile / Oxc), has zero JIT (so it works identically on iOS and locked-down mobile devices), and ships no built-in HTTP/TLS stack, event loop, or ambient std::fs.
  • Modular opt-in crates (0 bytes when omitted): Pure-Rust Web primitives (ibex-web-core), icu4x Intl (ibex-intl), profiling/heap snapshots (ibex-inspect), the zero-copy seam (ibex-seam), and native AOT (ibex-aot) link 0 bytes unless explicitly enabled — verified fail-closed at load time via .ibc requires manifests.

3. Very fast for its size

  • High-speed interpreter + ~33 µs isolated resets: 64-bit NaN-boxed registers, 32-bit compressed heap slots in a 4 GiB cage, generational copying GC, hidden-class shapes with 4-entry polymorphic inline caches, and a register-pinned C computed-goto dispatch kernel deliver 2×–10× higher throughput than comparably sized embeddable interpreters (and ~2× faster geomean across 21 workloads than 5× larger bytecode VMs on both Linux x86-64 and Android arm64), plus pooled zero-mmap RealmTemplate resets in ~33 µs.
  • Optional selective C11 native AOT (ibex3c --aot): Compiles whole modules or profile-selected hot functions (within a hard --aot-text-budget-kb cap) to native machine code, reaching JIT-class speed on application-shaped JS kernels at ~1/60 the binary size of full JIT runtimes.

Try It in 30 Seconds

# 1. Build the compiler (ibex3c) and minimal runtime (ibex3)
cargo build --release -p ibex-compiler-cli -p ibex-cli

# 2. Write a TypeScript file, compile to verified .ibc bytecode, and run it capped
cat <<'EOF' > /tmp/hello.ts
const greet = (name: string): string => `hello, ${name}!`;
console.log(greet("ibex3"));
EOF

./target/release/ibex3c /tmp/hello.ts -o /tmp/hello.ibc
./target/release/ibex3 --max-heap-mb 32 --fuel 100000 --print-fuel /tmp/hello.ibc
# stdout: hello, ibex3!
# stderr: fuel_spent=1

Other Features & Capabilities

  • Capability Security & Resource Containment:
    • Zero ambient authority by default (eval, new Function, HTTP, and std::fs are absent unless explicitly wired).
    • Natively frozen built-in prototypes and functions with override-safe subclassing, internal VM #private intrinsics unreachable from globalThis, and per-package lexical capability injection backed by a generational, GC-reclaimed, synchronously revocable CapTable.
    • Hard max_heap_bytes covering JS objects, external ArrayBuffers, host strings, and property atoms (poisoning the heap on OOM so guest try/catch cannot swallow it), deterministic resumable fuel (--fuel, resume_with_fuel), wall-clock deadline preemption, and host-controlled clock/RNG (HostEnv).
  • ES2024 Language & Module Surface: Classes, #private fields/methods, async/await, generators, static-bundle lazy import(), acyclic top-level await, import.meta, BigInt, Proxy/Reflect, Map/Set/WeakMap/WeakSet/WeakRef (deterministic between-turn clearing), TypedArrays + DataView, RegExp (lookbehind, named groups, /u & \p{...} Unicode properties), Date, JSON (replacer/reviver/space/toJSON), structuredClone, queueMicrotask.
  • Verification & Hardening Layers:
    • Continuously built Lean 4 semantic oracle (formal/IbexFormal/): Independent Lean 4 models (0 sorry, built via cd formal && lake build) covering core ISA, verifier, GC, Shape/PIC, and CapSec, differentially tested against the live VM on every commit.
    • Archived Harmonic Aristotle point-in-time audits (formal/aristotle/): Three x86-64 release-binary code-level audits pinned to commit 4aad5cc (archived historical audits, not CI gates and not built by lake build): ibex-bc verifier (6/6 core safety properties proved; 3 refuted counterexamples fixed & regression-tested in 9887d51), ibex-value encoding (6/7 proved; 1 refuted non-canonical immediate fixed and sealed), and ibex-aot loops (3/3 concrete proofs prior to LLP 0005.006 liveness-spill postcondition changes).
    • Continuous off-gate assurance (./scripts/verify-async.sh): Full workspace IBEX_GC_STRESS=1 (moving GC on every allocation), Clang UBSan on AOT binaries (zero no_sanitize escapes), deterministic malformed .ibc/IBS0 corpus fuzzing, and differential --step-fuel 1 AOT == interpreter exact fuel parity.
  • Relocatable Heap Snapshots & PGO: Offset32 IBS0 snapshots (--save-snapshot / --load-snapshot) and a reproducible Clang + Rust PGO release pipeline (./scripts/build-pgo.sh).
  • Opt-In Extensions (0 bytes when omitted):
    • ibex-web-core: zero-dependency pure-Rust DOMException, TextEncoder/TextDecoder, atob/btoa, WHATWG URL/URLSearchParams, AbortController/AbortSignal (with synchronous Rust abort hooks).
    • ibex-intl: pure-Rust icu4x Intl.NumberFormat & Intl.DateTimeFormat.
    • ibex-inspect: Chrome DevTools .cpuprofile, folded fuel flamegraphs, and .heapsnapshot export.

Performance & Footprint

Linux x86-64 — 21-Workload Comparison (committed bench/results-8engine-aot-450a.json, 5 samples)

Relative execution time across 8 engines (normalized to 1.00× baseline; lower is faster):

Metric ibex3 (interp) ibex3-aot quickjs static-hermes hermes bun bun-aot node
Binary size (in run) 0.90 MiB* 0.86–1.04 MiB/prog† 1.37 MiB 3.54 MiB 6.94 MiB 88.5 MiB 88.5 MiB 116.9 MiB
boot-empty peak RSS 3.0 MiB 2.5 MiB 3.1 MiB 10.5 MiB 9.1 MiB 31.6 MiB 28.5 MiB 43.5 MiB
Boot (3) 0.49× 0.49× 0.88× 1.31× 1.00× 3.64× 2.89× 5.21×
App-shaped J kernels (8) 0.37× 0.20× 2.12× 0.83× 1.00× 0.20× 0.20× 0.18×
Microbenchmarks (10) 0.63× 0.26× 3.17× 0.62× 1.00× 0.06× 0.06× 0.07×
All 21 geomean 0.50× 0.25× 2.27× 0.77× 1.00× 0.17× 0.17× 0.19×

On Android arm64 (Pixel 5, Kryo 475 Prime — committed bench/results-android-pixel5.json, 5 samples), ibex3 ran 2.15× faster overall (0.47×), 2.99× faster on the 8 J kernels (0.33×), and 1.63× faster on cold boot (0.61×) with 3.6 MiB peak RSS vs. 5.5 MiB for the lean arm64 bytecode baseline.

Notes on the numbers:

  • * The committed 8-engine JSON ran on an earlier 0.90 MiB (939,680 B) build; current HEAD stripped target/release/ibex3 is 1.37 MiB (1,432,512 B) after adding full ES2024 builtins (DataView, JSON replacer/reviver/space, Object.groupBy), CapTable, and RealmTemplate.
  • † ibex3-aot emits standalone per-program native executables linking libibex_aot_rt.a (0.86–1.04 MiB per workload in the committed run), not a shared runtime binary.
  • The 8 J workloads in bench/workloads.mjs are compact application-shaped JS kernels (10–40 lines each, 1–2 warmup iterations), not full npm libraries. Both ibex3 and ibex3-aot trail full JIT runtimes (Bun/Node) on numeric microbenchmarks, on the all-21 geomean, and on long-running JIT-warmed compute; ibex3-aot matches Bun on the 8 J kernels while trailing Node there.
  • Reproduce locally with node bench/run.mjs --engines ibex3,ibex3-aot,node (optionally set HERMES_BIN/HERMESC_BIN or QJS_BIN to include other engines).

Honest Project Status

  • Maturity: ibex3 is days old (initial commits 2026-12-02), built primarily for Exact3 (expo/exact3, integration underway on a feature branch), with no external production deployments and no independent third-party security audit yet.
  • Security caveat: Because ibex3 combines unsafe Rust with a C dispatch loop and has only deterministic corpus fuzzing (no coverage-guided fuzzing or external audit yet), do not rely on the VM as your sole boundary against hostile code — run untrusted workloads inside an OS or process sandbox as well.
  • Conformance evidence (not official Test262): Official Test262 (~45,000+ tests) has not been run. Current evidence is 107/107 hand-written ES2024 differential cases (tests/test262-core.mjs), 39/39 feature suites (tests/conformance.mjs), and 5/5 hand-written library-pattern smoke tests (tests/real-libs.mjs), all passing in interpreter, AOT+GC-stress, and AOT+UBSan modes.
  • Not built / deferred: Obscure ECMAScript corners (exotic Proxy invariants, Annex B sloppy quirks, with, SharedArrayBuffer/Atomics, legacy RegExp.$1–$9), async function* / for await..of, cyclic static ES module imports (cyclic CJS require() works; cyclic static ESM fails at compile time), and ReadableStream.
  • Deliberate non-goals (rules/NOT-DOING.md): No JIT; no built-in event loop, fetch, node:* runtime, or ambient filesystem access (hosts inject grant-gated capabilities); no pre-1.0 backwards compatibility for .ibc, IBS0, or Rust APIs.

Embedding ibex3 in Your Own Rust Project

Prerequisites

  • Rust 1.97+ (edition 2024)
  • Clang (compiles crates/ibex-vm/src/dispatch.c and optional --aot outputs)

Split build-time compilation from your runtime binary

To keep your production binary tiny and free of ibex-compile / Oxc, compile .ts/.js to .ibc at build time (via ibex3c or a build script pinned to the exact same ibex3 git revision) and link only ibex-vm + ibex-value into your runtime binary:

# Runtime Cargo.toml — links 0 bytes of Oxc / ibex-compile / web-core / intl
[dependencies]
ibex-vm = { git = "https://github.com/expo/ibex3.git", rev = "<pinned-rev>" }
ibex-value = { git = "https://github.com/expo/ibex3.git", rev = "<pinned-rev>" }
# Optional zero-cost-when-omitted crates:
# ibex-seam = { git = "https://github.com/expo/ibex3.git", rev = "<pinned-rev>" }
# ibex-web-core = { git = "https://github.com/expo/ibex3.git", rev = "<pinned-rev>" }
use ibex_value::Value;
use ibex_vm::{Vm, VmConfig};
use std::time::{Duration, Instant};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Load verified .ibc bytecode compiled ahead of time with `ibex3c`.
    let ibc = std::fs::read("app.ibc")?;

    // 2. Build a locked-down template ONCE.
    // IMPORTANT: Install any opt-in globals (`ibex_web_core::install(&mut vm)?`, etc.)
    // while `lockdown: false`, THEN call `vm.lockdown_intrinsics()` before capturing.
    let mut vm = Vm::new(VmConfig {
        max_heap_bytes: 32 * 1024 * 1024,
        lockdown: false,
        ..Default::default()
    })?;
    // ibex_web_core::install(&mut vm)?; // opt-in URL, TextEncoder/Decoder, AbortController, DOMException
    vm.lockdown_intrinsics();
    let template = vm.capture_realm_template()?;

    // 3. Per-request isolated turn (~33 us zero-mmap reset) with explicit host capability.
    vm.reset_from_template(&template)?;
    vm.set_deadline(Some(Instant::now() + Duration::from_millis(500)));

    let (cap_fn, cap_slot) = vm.mint_host_cap(
        "hostLog",
        Box::new(|vm, args| {
            let msg = args.first().copied().map(|v| vm.format_value(v)).unwrap
9DC0
_or_default();
            println!("[host] {msg}");
            Ok(Value::UNDEFINED)
        }),
    )?;
    vm.set_global("hostLog", cap_fn)?; // or pass directly as an argument to an exported function

    let _ = vm.run_module(ibc)?;

    // GC-safe invocation of a JS function using RootScope:
    let mut scope = vm.root_scope();
    let f = scope.vm().get_global("greet");
    let h_f = scope.root(f);
    let arg_ptr = scope.vm().alloc_str("world").map_err(|_| "oom")?;
    let callee = scope.get(h_f);
    let out = scope
        .vm()
        .call_value(callee, Value::UNDEFINED, &[Value::from_string(arg_ptr)])
        .map_err(|exc| scope.vm().format_value(exc))?;
    println!("{}", scope.vm().format_value(out));
    drop(scope);

    // Revoke capability immediately after the turn (even if guest code stashed it):
    vm.revoke_cap(cap_slot);
    Ok(())
}

Crate & Feature Matrix ("Only Pay For What You Use")

Crate / Feature How to enable What it adds Cost when omitted
ibex-vm (default) default dependency ES2024 core VM, GC, RealmTemplate, CapTable, fuel/deadlines Core runtime
ibex-vm feature intl features = ["intl"] Pure-Rust icu4x Intl.NumberFormat / Intl.DateTimeFormat 0 bytes
ibex-seam optional crate Zero-copy strings, pre-shaped records, DetachedBufferScope 0 bytes
ibex-web-core optional crate DOMException, TextEncoder/TextDecoder, atob/btoa, URL, AbortController 0 bytes
ibex-inspect optional crate (or ibex-cli --features inspect) .cpuprofile, folded fuel flamegraphs, .heapsnapshot 0 bytes
ibex-compile / ibex-aot build/dev-only crates Oxc TS/JSX compiler & C11 selective AOT emitter 0 bytes in runtime
ibex-cli features intl, inspect, eval cargo build -p ibex-cli --features ... CLI opt-ins (note: eval links ibex-compile / Oxc into ibex3) 0 bytes

Using ibex3 from AI & Coding Agents

Why ibex3 is a great JS/TS VM for agents

  • Safe defaults with explicit, revocable tool powers: Agents frequently generate and execute arbitrary JS/TS. ibex3 ships with zero ambient authority (no fs, fetch, process, node:*, or eval by default), natively frozen primordials, and host-minted capabilities (CapTable) that can be revoked synchronously — even if agent-generated code stashed a closure. (Until independently audited, still pair with an OS/process sandbox for hostile inputs.)
  • Uncatchable runaway & memory containment: Agent-generated loops and allocations cannot hang or OOM the host: hard max_heap_bytes (covering JS heap, ArrayBuffers, host strings, and atoms; uncatchable by try/catch), deterministic resumable --fuel budgets, and wall-clock deadlines preempt tight loops, RegExp, and JSON cleanly.
  • ~33 µs isolated resets & ~3 MiB RSS per sandbox: Agents run dozens or hundreds of short code-execution turns per task. Pooled zero-mmap RealmTemplate resets (~33 µs) and tiny ~3 MiB memory overhead let an agent harness give every tool call a completely fresh JS realm without container or full-runtime startup latency.
  • Deterministic replay & snapshots: Host-controlled clock/RNG (HostEnv), exact fuel accounting, deterministic between-turn WeakRef clearing, and relocatable IBS0 snapshots make agent runs reproducible and debuggable offline.
  • Native TypeScript with exact .ts stack traces: Models naturally write TypeScript; ibex3c compiles .ts/.tsx directly in a single Oxc parse and reports original file:line:col stack frames so agents can fix their own code without wiring up tsc or a bundler.

1. Running JS/TS as a bounded tool (CLI recipe)

  • Always two steps: ibex3c <input.ts|tsx|js|mjs> -o <out.ibc>, then ibex3 [flags] <out.ibc> (ibex3 executes .ibc bytecode only, not raw JS/TS source).
  • Put all limit flags before the .ibc path (flags after the path are ignored):
    ./target/release/ibex3c script.ts -o script.ibc
    ./target/release/ibex3 --max-heap-mb 32 --fuel 500000 --print-result script.ibc
  • Output & exit codes:
    • console.log(...) / print(...) write to stdout; --print-result prints the module's final return value to stdout; --print-fuel and errors write to stderr.
    • Exit code 0 = success, 1 = runtime error / OOM / fuel exhausted / verification failure, 2 = CLI usage error.
    • Do not build ibex-cli with --features eval when running untrusted code, and pair with an OS sandbox for hostile inputs.
  • What is intentionally absent by default: fetch, setTimeout/setInterval, fs, process, window/document, node:* modules, and eval/new Function. Pure computation and JSON/string/TypedArray/RegExp/Date/Math transforms work out of the box.

2. Agent checklist when integrating ibex3 into a user's Rust project

  • Pin matching git revisions across ibex-compile and ibex-vm (.ibc format is unstable pre-1.0).
  • Never link ibex-compile into production/mobile runtime targets — keep it in a build script, dev CLI, or separate compiler crate.
  • Never hold raw Value or HeapPtr32 across allocating VM calls — moving GC relocates nursery objects; wrap multi-step calls in vm.root_scope() (scope.root(...) / scope.get(...)).
  • Lockdown ordering matters: Construct Vm with lockdown: false, install ibex_web_core::install(&mut vm)? and any frozen host globals, then call vm.lockdown_intrinsics() before vm.capture_realm_template()?.
  • Grant host I/O only via CapTable (vm.mint_host_cap) or per-package CapabilityResolver — never attach ambient host powers to globalThis.

Developing & Contributing to ibex3

If you are editing ibex3 itself, start with AGENTS.md, rules/RULES.md, rules/NOT-DOING.md, and the root design explainer llp/0000-ibex3.explainer.md. Never use git stash across worktrees; run cargo test --workspace, cargo clippy --workspace --all-targets -- -D warnings, node scripts/caps.mjs, ./ref-check, and node scripts/issue.mjs check before committing (and ./scripts/verify-async.sh for full GC-stress, UBSan, and differential verification).


License

MIT (declared in Cargo.toml).

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0