| <!-- Copyright 2026 The Fuchsia Authors | |
| Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| This file may not be copied, modified, or distributed except according to | |
| those terms. --> | |
| # MIR verifier alpha | |
| > [!WARNING] | |
| > **This is alpha software!** Anneal (`0.2.0-alpha`, Stage 0) is an | |
| > experimental verifier under active development and has **not** yet completed | |
| > an independent audit of its Trusted Computing Base (TCB). Today it verifies | |
| > only a small, pointer-free scalar subset of Rust without returning calls | |
| > (`x86_64-unknown-linux-gnu` Profile v1) across selected functions or | |
| > monomorphizations (`UnitTheorem`) or single library or binary crates with no | |
| > required normal or build dependencies (`CrateTheorem`). Passing results depend | |
| > on an intact build host (`rustc`—and any `build.rs` or proc-macro run to | |
| > produce inputs—executes outside the Lean sandbox) as well as human review of | |
| > stated specifications (the declared primary specification module, every | |
| > `specification`-role module, and their transitive meaning dependencies), | |
| > compilation and scope configuration (`request.json` or `verify rustc` | |
| > flags), and TCB audit logs (complete review-surface reporting remains under | |
| > active development). Do not rely on alpha runs as a production security or | |
| > soundness guarantee, and expect frequent breaking changes. Track maturity | |
| > across | |
| > [Stage 0 (`#32`)](https://github.com/google/anneal/issues/32) -> | |
| > [Stage 1 (`#27`)](https://github.com/google/anneal/issues/27) -> | |
| > [Stage 2 (`#33`)](https://github.com/google/anneal/issues/33). | |
| The developer alpha checks selected Rust functions or scalar crates on x86-64 | |
| Linux with glibc, such as Ubuntu 24.04. It compiles a library or single binary | |
| target with no required normal or build dependencies (dev-dependencies and | |
| inactive optional dependencies are ignored) using the pinned compiler and | |
| checks the authored Lean proof against the captured MIR, the stated | |
| specification, and Anneal's safety obligations. A successful receipt | |
| (`"schema_version": 3`) identifies the verified scope, compilation | |
| configuration, input digests, containment backend, and assumptions. | |
| On Linux, `ExecSeal` isolates target Lean preflight, elaboration, and audit by | |
| default inside Tier 1 `linux_bwrap` or Tier 2 `linux_landlock_seccomp` | |
| (recorded in `elaboration_sandbox`, failing closed when unavailable unless | |
| `--allow-unsandboxed-elaboration` is passed; see | |
| [elaborator containment](trust/elaborator-containment-design.md)). Rust | |
| compilation (`rustc`) still runs as the caller, so supply a separate isolated | |
| execution environment when processing untrusted Rust crates or build scripts, on | |
| non-Linux hosts, or with `--allow-unsandboxed-elaboration`. | |
| ## Try a proof | |
| From the repository root, build and install the pinned tools with Nix. | |
| Keep the same installation cache for setup and verification. | |
| ```sh | |
| mkdir -p target | |
| nix build .#omnibus-archive --max-jobs 1 --cores 2 --out-link target/omnibus-link | |
| export XDG_CACHE_HOME="$(mktemp -d)" | |
| cargo run --locked -p cargo-anneal -- setup --local-archive target/omnibus-link | |
| cargo run --locked -p cargo-anneal -- verify \ | |
| --request trusted/cargo-anneal/assets/scalar/request.json | |
| ``` | |
| The example proves that `zero()` returns zero (`cargo anneal init | |
| --standalone --proof-dir <new-directory>` scaffolds the same four starter | |
| files outside the repository) and prints a human verification card | |
| (`[SCOPED]` for a selected function, `[OK]` only for untainted whole-crate | |
| verification). Inside a Cargo package, `cargo anneal init` scaffolds a | |
| Profile v1 `Specs` starter, and `cargo anneal init --profile v2` scaffolds a | |
| `SpecsV2` starter for crates whose capture emits MIR Profile v2; `--profile` | |
| cannot be combined with `--standalone`. Pass `--receipt-out <path>` to write | |
| the canonical Receipt Schema v3 JSON atomically to disk alongside human | |
| output, or `--format json` to emit JSON directly on stdout | |
| (`--color auto|always|never`, `-q`/`--quiet`, and `-v`/`--verbose` control | |
| terminal styling and detail truncation). To experiment, make a copy of the | |
| fixture directory and change its Rust function to return one. The same proof | |
| then fails (`[FAIL]`, exit code `1`). `--artifacts <new-directory>` retains | |
| the captured Lean program, bound claim, and diagnostic evidence for proof | |
| development; `verify` rejects a path that already exists, or whose parent is | |
| not an existing directory, before it starts any verification work. | |
| To rerun into the same path, add `--overwrite-artifacts`. Every artifact | |
| directory that `verify` writes carries a `.cargo-anneal-artifacts` marker | |
| file. The flag replaces an existing destination only if it is a real directory | |
| (not a symlink) that contains neither the working directory nor any | |
| verification input (request, sources, proofs, shard plan, the selected tools, | |
| or the running `cargo-anneal`), holds only entries that `verify` produces | |
| (each with the expected file or directory type), and, unless empty, carries | |
| that marker; anything else is refused before verification starts. Before | |
| running, `verify` removes an earlier `result.json`, `lean-lib/`, and | |
| `spec-surface.golden.json` from the destination, so a failing rerun never leaves | |
| earlier success evidence behind. The new artifacts are written to a sibling | |
| directory first, and the old directory is removed only after they are complete. | |
| With `--manifest-path`, a destination inside the package or `--proof-dir` is | |
| left out of source | |
| discovery, so a rerun does not pick up its own artifacts, but one holding the | |
| root file of any package target is refused, as is any existing destination | |
| when the package targets cannot be listed. | |
| In `request.json`, each `source_root` resolves relative to the directory | |
| containing the request file or to an existing out-of-tree directory, and | |
| declared inputs must be clean relative regular-file paths inside their | |
| canonicalized `source_root`. Set `scope` to | |
| `{"kind": "selected_unit", "roots": ["module::function"]}` (with optional | |
| `"instantiations": [{"path": "module::generic", "args": ["usize"]}]` for | |
| explicit concrete monomorphizations, or `"roots": []` with a non-empty | |
| `"instantiations"` list when targeting only generic items; `UnitTheorem`, | |
| returning `selected_unit_verified`) or `{"kind": "crate"}` (`CrateTheorem`, | |
| returning `crate_verified`; crate scope also accepts an optional | |
| `"excluded_traits"` list or repeatable `--exclude-trait` from the closed | |
| allowlist `core::fmt::Debug`, `core::fmt::Display`, and `core::error::Error`, | |
| which excludes local impls of those traits only after proving them unreachable | |
| from all verified bodies (items containing `unsafe` code or inline assembly | |
| stay required) and discloses them in Receipt v3 `excluded_items` and | |
| `assumptions`, while Lean's `CrateTheorem` checks every captured body), and | |
| list the `specification` and `proof` Lean modules under `proof.sources`. | |
| Optionally set `proof.spec_closure` to a clean relative | |
| `spec-surface.golden.json` (or `<name>.spec-surface.golden.json`) path inside | |
| `proof.source_root` to verify a structured `Trusted.Framework.MirEnvelopeSpec` | |
| against `Trusted.Framework.{Crate,Unit}MirEnvelopeTheorem`: `verify` checks | |
| strict duplicate-free JSON on the root golden and every companion | |
| `.spec-surface.golden.json` listed in `imported_spec_modules`, matches their | |
| reconstructed source lines and SHA-256 digests byte-for-byte against the | |
| compiled `specification` modules, cross-checks `user_declarations` and | |
| `envelope_summary` against `TrustedBoundary`'s audited metadata, rejects | |
| non-empty `refutations` and fatal envelope warnings (`unsatisfiable_safety`, | |
| `vacuity_check_truncated`), and binds `spec_closure_sha256` into the receipt. | |
| For a Cargo crate with a single library or binary target and no required normal | |
| or build dependencies (dev-dependencies and inactive optional dependencies are | |
| ignored), `--manifest-path <Cargo.toml> --proof-dir <dir>` (with optional | |
| `--no-default-features`, `--features <list>`, `--all-features`, | |
| `--panic unwind|abort`, `--overflow-checks`, `--exclude-trait <trait>`, | |
| `--select <path>`, and `--instantiate <JSON>`) constructs the legacy request | |
| automatically. | |
| The `--manifest-path` shortcut fails closed on Cargo configuration that could | |
| change how the crate is compiled. Inside the package and its workspace (from | |
| the package directory up to the workspace root), a `.cargo/config` or | |
| `.cargo/config.toml` may contain only the `[alias]`, `[term]`, `[doc]`, | |
| `[cargo-new]`, and `[future-incompat-report]` tables. The shortcut also | |
| inspects ancestor directories strictly above the workspace root and the active | |
| `$CARGO_HOME/config{,.toml}` (failing closed on compilation, toolchain, and | |
| download overrides while admitting `[net]`, `[registries]`, `[registry]`, and | |
| `[source]` so offline and vendored host setups keep working), and pins child | |
| `cargo metadata` processes to that exact inspected `$CARGO_HOME`. Any other | |
| table (for example `[build]`, `[target]`, `[profile]`, `[env]`, `[patch]`, | |
| `[http]`, or `[install]`), unparseable TOML, or a symlinked or non-regular | |
| config file, `.cargo` directory, or `$CARGO_HOME` directory is refused as | |
| `unsupported`. A `rust-toolchain` or `rust-toolchain.toml` file in the resolved | |
| ancestry of `$TMPDIR` (the temporary working directory used to run | |
| `cargo metadata`) is likewise refused; clear `$TMPDIR`, point it at a clean | |
| directory, or write an explicit `request.json` instead. | |
| Each `instantiations` entry, like each `--instantiate` value, names a generic | |
| function of the crate being verified by its `rustc` path (`path`) and lists | |
| its generic arguments in Rust syntax (`args`): primitive types, `str`, tuples, | |
| arrays, slices, references, raw pointers, paths to structs, enums, unions, and | |
| type aliases, `bool`, `char`, and integer constants, and lifetimes. `'static` | |
| is the only lifetime a request can name, and `'_` means `'static`. A bare | |
| primitive name (`u8`, `bool`, `str`, and so on) always means the primitive | |
| type, even when the root of the crate being verified declares a type of that | |
| name; `crate::u8` names the latter. Any other type path resolves as follows: | |
| - `crate::a::B` starts at the root of the crate being verified, and | |
| `::krate::a::B` at the root of the crate named `krate`. | |
| - A request has no enclosing module, so the first segment of any other path | |
| is read two ways: as a crate name (an external crate, or the crate being | |
| verified by its own name), continuing from that crate's root, and as a name | |
| at the root of the crate being verified. The path resolves only if the | |
| readings that resolve all name one definition; otherwise the request is | |
| refused as ambiguous. In `zerocopy`, `byteorder::BigEndian` names the | |
| `BigEndian` type of the `byteorder` module. In a crate whose root declares | |
| `mod core` with its own `num::Wrapping`, `core::num::Wrapping<u8>` is | |
| refused. | |
| - Each segment before the last must name a module, and the last a struct, | |
| enum, union, or type alias. A segment that names anything else in the type | |
| namespace, such as a trait, a re-exported primitive type, or a struct or | |
| enum before the last segment, refuses the request. | |
| - A reading that reaches a segment naming nothing in the type namespace may | |
| instead spell how `rustc` prints a local definition, such as `f::Local` for | |
| a type declared inside function `f`, or `_::Local` for one declared inside | |
| `const _: () = { ... };`. No path that also reads as an external crate's | |
| path resolves this way. | |
| - A `_` segment never names an underscore import such as `use m as _;` or | |
| `extern crate k as _;`, which no Rust path can name. | |
| - A name that glob imports make ambiguous in a module, whether of the crate | |
| being verified or of another crate, makes every path through it ambiguous. | |
| A type alias in a request means what it would mean where Rust code uses it: | |
| its expansion must be well-formed and must normalize, including any lifetime | |
| and higher-ranked obligations that normalizing incurs. A lazy type alias | |
| (`#![feature(lazy_type_alias)]`) must also satisfy its own bounds; as in Rust, | |
| the bounds of an ordinary type alias are not enforced. | |
| ## Stage 0 / MIR Profile v1: supported vs. refused | |
| The alpha runs on the x86-64 Linux scalar MIR profile (Profile v1) with | |
| `-Zmir-preserve-ub` (`#4114`) and `-Zmir-opt-level=0` enforced during capture. | |
| Any construct outside this profile returns an explicit fail-closed refusal | |
| rather than approximating semantics, unless it belongs to the experimental | |
| [Profile v2](#experimental-mir-profile-v2-borrowed-slices-and-raw-pointers). | |
| | Category | Supported today (Profile v1) | Refused today (fail-closed) | | |
| | :--- | :--- | :--- | | |
| | **Types** | `bool`, `char`, 8- through 128-bit and pointer-sized integers (`i8`..`i128`, `isize`, `u8`..`u128`, `usize` on 64-bit targets), `()`, `!`, `core::cmp::Ordering`, `(T, bool)` overflowing-arithmetic pairs (via `core::intrinsics::*_with_overflow`), and non-generic inhabited crate-local fieldless enums (including pure scalar explicit discriminants). | References and raw pointers (`&T`, `&mut T`, `*const T`, `*mut T`), slices, arrays, structs, unions, enums with payloads, uninhabited zero-variant enums, enums whose size or alignment differs from their tag's (such as `#[repr(u8, align(4))]` or `#[repr(align(8))]`), floats, general tuples, and generic types. | | |
| | **Statements & rvalues** | `Assign` (`Use` on retag-noop scalar types, unary `Not`/`Neg`, binary bitwise/shift/wrapping-arithmetic/unchecked-arithmetic/`*WithOverflow`/comparison/`Cmp`/unchecked `Div`/`Rem`, `CastKind::IntToInt`, `Discriminant`), `StorageLive`, `StorageDead`, bare unprojected `PlaceMention`, and `Nop`. | Place projections (fields, indexing, dereferencing, projected `PlaceMention`), `Aggregate` rvalues, `PtrMetadata`, pointer/float/`Transmute` casts, and inline assembly. | | |
| | **Terminators & operands** | `Goto`, `SwitchInt`, `Return`, `Unreachable`, returning direct `Call` terminators to non-generic intra-crate functions (non-`Use` `CallSource`, non-cleanup unwind, and supported scalar/unit signature), diverging calls (`TerminatorKind::Call` with `target: None` and non-`Use` `CallSource`, lowered to fail-closed `unsupported` when reachable), primitive `Assert` terminators (`DivByZero`, `RemByZero`, `Overflow(Div | Rem)`, `BoundsCheck`, `MisalignedPtrDeref`, and `NullPtrDeref`) with Profile v1 conditions (modeled via `evalAssertFailure`: `MisalignedPtrDeref` and `NullPtrDeref` fault `.undefined`; the other safe assertions abort under `--panic abort` without a crate-local `#[panic_handler]` on non-cleanup unwinds and otherwise fault `.unsupported`), and closed `core::num` `sysrootCall` arithmetic (`unchecked_{add,sub,mul}` under `-Cdebug-assertions=no -Coverflow-checks=no` with UB checks off, and `wrapping_{add,sub,mul}`; `usize::unchecked_sub` instead takes the Profile v2 `core` call path below); `Copy`/`Move` on unprojected locals; scalar constants (including `Const::Unevaluated`, `Const::Ty(Value)`, and read-only provenance-free `.rodata` `ConstValue::Indirect` / `GlobalAlloc::Memory` scalars evaluated via CTFE alongside `required_consts`) and `ZeroSized` unit/single-variant-enum constants. | Indirect, closure, trait-object, generic, or unsupported external calls (including `overflowing_*` methods under `-Copt-level=0`), intra-crate calls to `#[track_caller]` functions or to `unsafe fn`s (refused at entry because callee safety contracts are not yet checked at call sites), calls with cleanup unwind edges, and `CallSource::Use`, diverging calls whose callee or arguments reference `core::panic::Location`, `core::intrinsics::caller_location`, or non-exempt `#[track_caller]` items, optional arithmetic overflow `Assert` terminators (`Overflow(Add | Sub | Mul | Shl | Shr)` and `OverflowNeg`, which select Profile v2), `Drop`, unwind/abort terminators, built-in source-location/module-path macros (`file!()`, `line!()`, `column!()`, `module_path!()`, refused crate-wide), and constants or CTFE evaluations (intercepted crate-wide across analysis, capture, monomorphization, codegen, and local constant/promoted MIR on normal crates; under `--stdlib-crate core`, global CTFE interception plus strict per-selected-body constant auditing) whose evaluation fails, invokes `core::panic::Location::caller()`, non-exempt `#[track_caller]` functions (all non-`core` functions, including crate-local functions outside `--stdlib-crate core`, plus `Location` items and forbidden intrinsics; other trusted `core` helpers remain subject to transitive CTFE MIR auditing), indirect/closure/tail CTFE calls, or ambient intrinsics (`TypeId`/`type_name`, `size_of_type_id`, `field_offset`, `vtable_*`, `const_allocate`, `const_deallocate`, `const_make_global`, `ptr_guaranteed_cmp`, or reified `const_eval_select`), or refers to `static`, thread-local, mutable, or provenance-bearing memory. | | |
| | **Crate scope & items** | Single `lib` or `bin` crates (a `lib` crate may restate its type as `#![crate_type = "lib"]` or `"rlib"`) with no required normal or build dependencies, no `cfg(miri)`, and no active unstable `#![feature(...)]` attributes unless named by `--allow-unstable-feature` (which taints; inactive `#![cfg_attr(..., feature(...))]` lines other than `rustc_private` are permitted, and already-stabilized language features are admitted untainted and recorded in `configuration.stabilized_features_present`; dev-dependencies and inactive optional dependencies are ignored; `Scope::Crate` or `Scope::SelectedUnit`, Cargo `[features]` via `--features`/`--all-features`/`--no-default-features`, configurable `--panic unwind|abort`, and crate-local `#[panic_handler]` in `bin` selected-unit scope), plus opt-in `--allow-stdlib-crate` with `--stdlib-crate core` / `"stdlib_crate": "core"` (taints the receipt because sysroot sources are not yet hash-authenticated; requires `Scope::SelectedUnit`, a `lib` crate, `crate_name == "core"`, a compilation that loads no other crate, no `cfg(miri)`, only `core`'s version-pinned `#![feature(...)]` allowlist, and any crate-local `Ordering` language item to have the modeled shape; admits `core`'s own `#[lang]` items and skips object emission); non-generic free and associated functions (and, in `Scope::Crate`, safe `trait` declarations, safe `impl` blocks, bodyless safe Rust-ABI trait methods (including `#[inline]` hints, which rustc ignores there), non-generic pure-value `const`/`assoc const` items, pure scalar `AnonConst` items, and `struct` owners admitted by Profile v2), plus explicitly requested concrete monomorphizations (`instantiations` / `--instantiate`) in `Scope::SelectedUnit`. | Required normal or build external crate dependencies, multi-target crates, `cfg(miri)` on any crate, any active unstable `#![feature(...)]` attribute on normal crates that `--allow-unstable-feature` does not name (unstable lang and lib features, including library features `rustc` has since stabilized; compiler-internal features, `ergonomic_clones`, and `rustc_private` are refused even when named; `--stdlib-crate core` refuses any feature outside its version-pinned `core` allowlist), uninstantiated polymorphic generics, closures, crate-local `#[lang]` items without `--stdlib-crate` (except `#[panic_handler]` in `bin` selected-unit scope), `union`/`static`/`InlineConst` owners and unadmitted `struct` owners, bodyless free functions, and `unsafe`/unmodeled `trait`/`impl`/`const`/`AnonConst` items in whole-crate scope, exported (`#[macro_export]`, `pub macro`, or publicly re-exported) macros, other `#![crate_type]` attributes, crate-root `#![cfg_attr]` or `#![feature]` attributes whose arguments capture cannot parse (such as non-literal values), `unsafe(..)`-wrapped `feature`/`crate_type` items under `#![cfg_attr]`, global assembly, and proc-macro crates. | | |
| For a realistic scalar example, `ci/verify_starnix_e2e.py` checks Starnix's | |
| `ebpf_core` endianness conversion using symbolic MIR helpers in `Anneal.MirWp`. | |
| ## Experimental MIR Profile v2: borrowed slices and raw pointers | |
| Capture selects Profile v2 (`mirProfileVersion = 2`) for the whole captured | |
| program when any captured body uses one of its additions; a program without | |
| them stays on Profile v1. When capture refuses a Profile v1 call in a Profile | |
| v2 program, its diagnostic names the refused call and the first body and | |
| construct requiring Profile v2. Every body of a Profile v2 program, including | |
| scalar-only ones, is checked against `UnitTheoremV2` or `CrateTheoremV2`. Its | |
| receipt lists an "experimental Profile v2 MIR semantics" assumption and marks | |
| `correspondence_provenance` inapplicable: Pass 2 kernel-replays unlocked | |
| domain-relativized Profile v2 correspondence over curated canary and | |
| conservative-edge domains, but no universal locked claim yet certifies | |
| `initStateV2`/`evalStepV2` across arbitrary captures against | |
| `vendor/lean-miri/`. | |
| | Category | Added by Profile v2 | Refused (fail-closed) | | |
| | :--- | :--- | :--- | | |
| | **Types** | General tuples and `Range<usize>`, `RangeTo<usize>`, and `RangeFrom<usize>` locals; supported `Option<T>` (`bool`, `()`, `&T`/`&mut T`/`&[T]`, integers, raw pointers, and owned `Vec<T>`/`Box<P>` handles); payload enums (non-generic crate-local enums with fields, `Result<T, E>`, `ControlFlow<B, C>`, and every other owned-data `Option<T>`, laid out as `rustc` lays them out, including the `?` residuals `Result<Infallible, E>` and `Option<Infallible>`, whose one inhabited variant `rustc` lays out as `Variants::Single`), including, as locals, arguments, and return values only, payload enums whose fields are shared references or heap-free owned data, such as Starnix eBPF's `Result<&Type, VerifierErrorKind>`, whose references the entry, return, and escape checks see through the active variant; fixed arrays `[T; N]` whose element type is a Profile v1 scalar, `()`, an admitted enum, or a nested fixed array thereof, or is owned data such as `[Vec<u8>; 2]` or Starnix's `[Type; 10]`, whose every element is validated; non-generic crate-local structs (including self-recursive structs whose self-references pass through `Box` or `Vec`) without a `Drop` impl, unsafe or interior-mutable fields, `packed`/`simd` representations, or reference/raw-pointer fields (fields may be plain data or owned heap data; layout taken from `rustc`); single-level `&T` and `&mut T` whose pointee is a sized owned-data non-tuple/non-range type (including admitted fixed arrays, structs, payload enums, `Vec`/`Box` handles, and `Option` of a handle) or a slice `[T]` of sized owned-data elements; single-level `*const T` and `*mut T` whose pointee is a sized ref-free plain-data non-tuple/non-range type or slice `[T]` thereof; shared `&str`; bounded intra-body two-level shared `&&T` locals whose inner `&T` is itself an admitted local (`<&T as PartialEq>` temporaries and match-guard bindings, such as `&&Box<T>` or `&&S` for a struct `S`), from which only a shared inner reference is ever copied; lifetime-only generic signatures. | Signature-level `&&T` parameters or returns (`BodyStaticAdmittedV2` rejects them), all other nested references or pointers (`&&&T`, `&mut &T`, `&&mut T`, `&&[T]`, `Option<&&T>`, `*const &T`, `&[&T]`, `[&T; N]`, `&Option<&T>`), raw pointers to heap-owning types, mutually recursive structs, fixed arrays of tuples, overflow pairs, references, or raw pointers, tuples/overflow pairs/ranges behind `&`/`*const`/`[]`/`Option` (whose unspecified `#[repr(Rust)]` layout capture does not check, so they stay non-addressable; the tuples capture lowers to structs, under **Local-only types** below, are the exception), payload enums that reach themselves other than through a direct `Box<Self>` or `Vec<Self>` field, payload enums with mutable or nested references or raw pointers, with references alongside heap handles, or with references in a heap element, array element, struct field, `Option` payload, or pointee, payload enums with other uninhabited variants, a `Drop` impl, or a `packed` representation, `&mut str`, `*const str`, `*mut str`, bare unsized `str`, generic, lifetime-parameterized, or `Drop` structs, and the remaining Profile v1 refusals. | | |
| | **Bodies** | Bodies whose locals include references or raw pointers, but not both (exempting compiler-synthesized `*const` temporaries written solely by `RawPtrKind::FakeForPtrMetadata` and read solely by `PtrMetadata`). | Bodies whose locals mix references and non-`FakeForPtrMetadata` raw pointers, because Profile v2 does not model Rust's pointer aliasing rules (Stacked or Tree Borrows). For example, `<&mut [u8] as SplitByteSlice>::split_at_unchecked`, which uses `as_mut_ptr` and `from_raw_parts_mut`, is refused. | | |
| | **Statements & rvalues** | `Ref` of locals and of places based on dereferenced references, `RawPtr` (address-of) of locals and of places based on dereferenced raw pointers, `RawPtr(FakeForPtrMetadata)` of dereferenced references or raw pointers into metadata-only `PtrMetadata` temporaries, assignment through projected and dereferenced places (field, `ConstantIndex`, and `usize` index projections, including elements of dereferenced slices), raw-to-raw `PtrToPtr` casts that do not add mutability, `IntToPtr` casts, array-to-slice `Unsize` casts (`&[T; N]`, `&mut [T; N]`, `*const [T; N]`, `*mut [T; N]` without adding mutability), `PtrMetadata`, `Offset`, tuple (including empty unit `()`), crate-local fieldless enum and payload enum variant, `Range`/`RangeTo`/`RangeFrom`/`Option`/`core::cmp::Ordering` aggregates, `Option` and payload-enum `Discriminant`/`Downcast`, array and struct aggregates and `Repeat`, `ConstantIndex` projections and `usize` index projections on arrays and dereferenced slices, copy reads of tuple, struct, overflow-pair, array, range, option, and payload-enum fields (including field, `ConstantIndex`, and supported `Option`/payload-enum downcast projections after a dereference or on in-memory locals, plus shared borrows of payload-enum fields and borrows of supported `Option` payloads), non-overlapping copies of memory-represented values (structs, non-empty arrays, `Option`, `Vec`, and padded or three-or-more-field tuples) out of `usize`-indexed, slice-element, and supported downcast places (including as multi-field aggregate operands when no earlier field write overlaps a later operand, its dereferenced pointer local, or any runtime `usize` index local), projected `PlaceMention` (`let _ = (*p).f;`, `match (*p).f { .. }`), which evaluates the place as a non-moving read and discards it, so it faults wherever the read would, moves of tuple and overflow-pair fields out of locals (which deinitialize only the moved field) and moves of `(x as Some).0` out of immediate `Option` locals or `(x as V).0` out of single-field variants of non-heap-owning immediate payload-enum locals (which deinitialize the whole local), projected `Discriminant` reads (including `Option` and payload-enum discriminants through references and nested projections), read-only provenance-free rodata array and reference constants (returning them fails closed), struct and non-heap payload-enum constants (including zero-sized ones), and `Use` with retags. | General reference-to-raw-pointer and raw-pointer-to-reference conversions (refused with the mixed-locals rule), non-`PtrMetadata` uses of `FakeForPtrMetadata` temporaries, `*const T` to `*mut T` casts and mutability-upgrading `Unsize` casts (Profile v2 cannot tell whether the pointee is an immutable binding, which the cast would let the body mutate), other unsupported casts, nested dereferences, in-memory `Option` payload reads or borrows of `Option<bool>`, `Option<()>`, or `Option<Vec<ZST>>`, writes through any downcast (direct-local or post-deref) and mutable borrows through payload-enum downcasts, unsupported projections after a dereference, other projected moves (`move (*p)`, nested fields, in-memory `Option`/payload-enum downcast moves, multi-field or heap-owning payload-enum downcast moves, `ConstantIndex` moves), piecemeal projected initialization of an uninitialized immediate local (fails closed with `.unsupported` at runtime), self-overlapping copies of memory-represented values (faulting `.undefined` at runtime), multi-field aggregates where an earlier field write overlaps a later operand, its dereferenced pointer local, or a runtime `usize` index local, or where a non-constant operand's source span cannot be resolved (failing closed with `.unsupported` at runtime), returning references or pointers to callee rodata allocations, heap-owning struct or payload-enum constants, and unsupported aggregates. | | |
| | **Terminators** | `Assert`; returning calls to non-generic crate-local functions (direct, or trait methods that resolve to crate-local impl items), which run in a new frame with argument and return types checked against the callee, the provided `PartialEq::ne` on crate-local types (a negated call of the impl's `eq`), `<&A as PartialEq>::{eq, ne}` forwarding to a crate-local `A`'s `PartialEq` (`TerminatorKind.callVia (.refPartialEq _)`), and `<Box<T> as Clone>::clone` for non-`TrivialClone` crate-local `T` (`TerminatorKind.callVia (.boxClone T)`); returning `core::num` `sysrootCall`s (`wrapping_{add,sub,mul}` and `unchecked_{add,sub,mul}`); returning calls to the closed-set `CoreCallOp`s (`<[T]>::{len, is_empty, split_at, split_at_mut, Index/IndexMut<Range<usize>>, Index/IndexMut<RangeFrom<usize>>}`, `<[T; N]>::{Index/IndexMut<Range<usize>>, Index/IndexMut<RangeFrom<usize>>}` (for integer, `bool`, `char`, `Ordering`, `()`, `!`, and admitted enum elements, not `Option<T>`, structs, nested arrays, tuples, or ranges), `<[T]>::get_unchecked` (`usize` index for sized ref-free elements; `Range<usize>` / `RangeTo<usize>` / `RangeFrom<usize>` over integer slices), `<*const/*mut T>::add`, `usize::unchecked_sub`, integer `count_ones`, `trailing_zeros`, `leading_zeros`, `checked_{add,mul,sub,shl}`, `saturating_add`, `wrapping_{shl,shr}`, `overflowing_{add,sub,mul}`, `to_le_bytes`, `from_le_bytes`, unsigned `is_multiple_of` / `next_multiple_of` / `div_ceil` / `next_power_of_two`, `cmp::{min,max}`, `mem::replace`, `mem::size_of` for Profile v2 local types with a modeled layout (not general tuples, `Range<usize>`, or `Option` of references or raw pointers), `Option::{is_some,is_none,take,unwrap}`, `?` on `Result` and `Option` (`Try::branch` and `FromResidual::from_residual`, whose error conversion must be the identity `From`), primitive integer/`bool` `Default::default`, `<&int as PartialEq>::{eq,ne}`, `<() as PartialEq>::{eq,ne}`, and `<[T; N] as PartialEq>::eq` for integer, `bool`, `char`, `()`, `Ordering`, and nested-array elements; enums are refused), and structural `PartialEq::ne` on primitives and arrays; and `Drop` of locals whose type has no drop glue, and of heap-owning places: a `Vec<T>`/`Box<T>`/`Box<[T]>` local, a tuple, struct, `Option`, payload enum, or self-recursive struct or payload enum local holding them (including nested handles such as `Vec<Vec<T>>`), `*r` or a field path `(*r).f...` through `r: &mut T` to any admitted pointee with drop glue (such as `Vec<T>`, `Box<P>`, `Option<Box<T>>`, or a struct field), or a field of a partially moved tuple local. Drop glue drops fields in declaration order, then frees the `Vec`/`Box` heap allocation, after which pointers into it dangle; the dropped place is deinitialized, and dropping an uninitialized (moved-out) place faults. Drop flags need no model: drop elaboration has already lowered them to boolean locals and `SwitchInt`; plus—only under `--panic abort` without a crate-local `#[panic_handler]`—diverging `core::panicking::{panic, panic_nounwind}` (evaluating their shared `&str` message operand). Lowering those `core::panicking` calls under `--panic abort` selects Profile v2 for the program; under `--panic unwind` or with a crate-local `#[panic_handler]`, those diverging calls stay `Terminator::Unsupported` (Profile v1-eligible). The captured `UnwindAction` (`Continue`, `Unreachable`, or `Terminate`) is recorded as is. Under opt-in `--panic abort` (when the crate defines no crate-local `#[panic_handler]`), failing non-optional safe `Assert`s, admitted `core::panicking::{panic, panic_nounwind}` calls, and safe panics of the closed-set `core`/`alloc` contracts (out-of-bounds slice and array ranges and `Vec` indices, `slice::{split_at, split_at_mut}` with `mid > len`, `Option::unwrap` on `None`, and `Vec` capacity overflow) terminate as `.aborted` carrying post-mutation `CallerMemory`; this satisfies `BodyVerifiedV2` without a termination claim and leaves panic hooks and handlers (including downstream `#![no_std]` binary `#[panic_handler]`s) unverified (recorded in receipt assumptions), so proving panic-freedom requires an explicit `EffectMaskV2.noAbort` `SafeContractV2` obligation in `SpecsV2.property`. Failing optional overflow checks abort the same way under `--overflow-checks`; under default `-Coverflow-checks=no`, where codegen elides them, they stay `.fault .unsupported`. Crates with a crate-local `#[panic_handler]`, cleanup unwinds, and `--panic unwind` keep failing safe `Assert`s, `core::panicking::{panic, panic_nounwind}` calls, and those contract panics fail-closed as `.fault .unsupported`. | Calls to generic or `#[track_caller]` callees, calls to `unsafe fn`s (which fault, because callee safety contracts are not checked at call sites), calls whose moved arguments or destination are projected or overlap, every other call (including `<[T]>::{as_ptr, as_mut_ptr}` and `core::slice::from_raw_parts{,_mut}`, which convert between references and raw pointers, `core::panicking::panic_fmt` including formatted panics and custom `assert!(cond, "...")` messages), calls in crates that shadow `core`, cleanup unwinds, and `Drop` of any other place or of a type whose drop glue the model does not run: a `Drop` impl other than `Vec`/`Box` (including on an otherwise admitted fieldless enum), `ManuallyDrop`, generic types, and any type on which `rustc`'s `needs_drop` and the model's `tyNeedsDropV2` disagree. | | |
| Notes on Profile v2 coverage and traps: | |
| - **Local-only types:** General tuples, overflow pairs `(T, bool)`, and | |
| `Range<usize>` / `RangeTo<usize>` / `RangeFrom<usize>` are `#[repr(Rust)]` | |
| and subject to `rustc` field reordering, so Profile v2 restricts them to | |
| locals and refuses references, raw pointers, slices, or `Option` wrappers | |
| over them. The exception is a tuple of owned data with a non-primitive | |
| element (one that owns a heap buffer, or a struct, enum, or array), such | |
| as the `(MemoryId, u64)` elements of Starnix's `BoundsMap` or its | |
| `Option<(usize, u8, VerifierLogEvent)>`: capture lowers it to a struct | |
| with `rustc`'s field offsets, in source order, keyed by that layout, so it | |
| can be a heap element, a struct or variant field, or a borrowed place like | |
| any struct. A recursive back edge inside such a tuple | |
| is refused; a tuple of primitives and scalar `Option`s only, such as | |
| `(bool, Option<u64>)`, or one holding a reference, stays a local-only | |
| tuple. | |
| - **Dead locals:** A local other than the return place and the arguments | |
| that no statement, terminator, or debuginfo entry mentions (not even a | |
| storage marker) is never read, written, borrowed, or dropped. When the | |
| model cannot express its type, capture keeps it with type `()` rather than | |
| refusing the body. `rustc` leaves such locals behind when it removes a | |
| match guard's fake borrows of the scrutinee, such as the `&&Type` local of | |
| Starnix eBPF's `Type::written_scalar`. A local mentioned in any way keeps | |
| its type. | |
| - **Comparing references to crate-local types:** `a == b` and `a != b` on | |
| `&A` call `core`'s `impl PartialEq<&B> for &A`, whose methods only forward | |
| to `PartialEq::{eq, ne}(*self, *other)`. For a crate-local `A`, capture | |
| checks that forwarding body and keeps the call as | |
| `TerminatorKind.callVia (.refPartialEq negate)`, naming `A`'s method. Its | |
| step checks the two `&&A` arguments as entering the forwarding function | |
| does, reads `*a` and `*b`, and calls `A`'s `eq` (or an overriding `ne`), | |
| negating the result for the provided `ne`, as for Starnix eBPF's | |
| `Type::is_subtype` and `<Type as PartialOrd>::partial_cmp`. The provided | |
| `ne` is admitted on crate-local structs, enums, payload enums, and | |
| self-recursive types such as `Type` and `MemoryId`. Comparing `&A` against | |
| `&B` for distinct `A` and `B` is refused. | |
| - **Cloning a box of a crate-local type:** `<Box<T> as Clone>::clone` for a | |
| crate-local `T` that is not `TrivialClone` allocates a box, runs `T::clone` | |
| on the boxed value, and writes the result into the box. Capture checks | |
| `alloc`'s and `core`'s MIR for exactly that and keeps the call as | |
| `TerminatorKind.callVia (.boxClone T)`, naming `T`'s `clone`, as for | |
| Starnix eBPF's `Type::with_offset` (`Box<StructDescriptor>::clone`). Its | |
| step follows `alloc`'s order: it borrows `&**self`, allocates the box, | |
| calls `T::clone`, and on return writes the result into the box. Until | |
| then the new box is held in the call's destination, which `T::clone` | |
| cannot reach because `T` is owned data. A `TrivialClone` `T` keeps the | |
| bitwise `BoxClone`, and `Box<[T]>` still requires `TrivialClone` | |
| elements. | |
| - **`core` contract ops (`CoreContracts` & `CoreCallOp`):** Beyond slice and | |
| raw-pointer helpers, Profile v2 adds checked (`checked_{add, mul, sub, shl}`), | |
| overflowing, saturating, and wrapping scalar arithmetic, `is_multiple_of`, | |
| `next_multiple_of`, `div_ceil`, `next_power_of_two`, `count_ones`, | |
| `leading_zeros`, `trailing_zeros`, `from_le_bytes`, `core::cmp::{min, max}`, | |
| `core::mem::replace`, `core::mem::size_of`, | |
| `Option::{is_some, is_none, take, unwrap}`, `?` on `Result` and `Option` | |
| (`Try::branch` into a `ControlFlow` and `FromResidual::from_residual` of | |
| the residual, where the error type must not change, so `From` is the | |
| identity), primitive integer/`bool` | |
| `Default::default`, `<&int as PartialEq>::{eq, ne}`, | |
| `<() as PartialEq>::{eq, ne}`, and slice `is_empty`, `split_at`, | |
| `split_at_mut` (returning disjoint subslices whose union is the input span), | |
| slice and array `Index`/`IndexMut<Range<usize>>`, and | |
| `Index`/`IndexMut<RangeFrom<usize>>`. Out-of-bounds slice and array ranges, | |
| `split_at` past the end, and `Option::unwrap` on `None` are panics: they | |
| terminate as `.aborted` under `--panic abort` without a crate-local | |
| `#[panic_handler]`, and otherwise fail closed as `.fault .unsupported`. | |
| `next_power_of_two` overflow, `next_multiple_of` divisor zero or overflow, | |
| and `div_ceil` divisor zero fail closed via `corePanicTrap`. | |
| - Each query (`Query`) supplies caller memory (`callerMem`) alongside its | |
| arguments. `SpecsV2` pairs per-function safety preconditions (`safety`, | |
| required only of `unsafe` functions) with a whole-program `property`. | |
| `ValidEntryArgsV2` requires live, in-bounds, aligned, initialized reference | |
| arguments in caller allocations whose bytes decode to valid pointee values, | |
| mutable caller allocations for non-zero-sized mutable references (zero-byte | |
| mutable references such as `&mut ()` or promoted `.rodata` `&mut []` may point | |
| into shared allocations regardless of allocation size), and disjoint mutable | |
| references. This applies | |
| to `unsafe` functions too, so a receipt says nothing about callers that pass | |
| an `unsafe` function a reference to uninitialized or invalid memory; receipts | |
| state this assumption. | |
| - Raw pointer arguments are unconstrained, so an `unsafe` function's `safety` | |
| precondition must state their liveness, bounds, alignment, initialization, and | |
| mutability. Mutability here means the allocation's mutability: Profile v2 | |
| does not track pointer aliasing permissions, so callers must also pass raw | |
| pointers whose provenance permits the accesses the function makes (for | |
| example, not a pointer derived from a live `&T` that the function writes | |
| through). Profile v2 encodes memory little-endian and assumes natural ABI | |
| alignment (1, 2, 4, 8, and 16 bytes for `i8` through `i128`, 8 bytes for | |
| `isize` and pointers; structs take `rustc`'s computed layout, including any | |
| `#[repr(align(N))]`). Capture admits only targets whose data layout matches. | |
| Profile v2 also models `alloc::vec::Vec<T>` and `alloc::boxed::Box<P>` with the | |
| `Global` allocator, for elements and pointees that are owned data | |
| (`Trusted.MirSemantics.isOwnedDataTyV2`): scalars, `()`, fixed-size arrays and | |
| plain-data structs, nested `Vec`/`Box` handles, `Option` of a handle, and | |
| structs whose fields are owned data (`Trusted.MirSemantics.AllocContracts`): | |
| `Vec::{new, with_capacity, len, push, reserve, resize, extend_from_slice}`, | |
| `Vec` indexing by `usize` and dereferencing, `Box::new`, | |
| `Box::<[T]>::from(Vec<T>)`, `Box::clone`, and `Box` dereferences. A capacity | |
| overflow or an out-of-bounds index is a panic, handled like a failing `Assert`: | |
| it terminates as `.aborted` under `--panic abort` without a crate-local | |
| `#[panic_handler]`, and otherwise fails closed as `.fault .unsupported`. The | |
| model assumes that allocation never fails: it does not model the out-of-memory | |
| path (`handle_alloc_error`), and receipts record this assumption. References | |
| to `Vec` and `Box` handles are admitted, but | |
| raw pointers to them are refused, because Rust leaves the layout of `Vec` | |
| unspecified. A `Box` counts as a reference for the rule against mixing | |
| references and raw pointers, because the aliasing models retag it like a unique | |
| reference: `Box` dereferences yield `&P`, and a body that derives a raw pointer | |
| from a `Box` is refused. Entry arguments that own a heap buffer must point at | |
| the start of an allocation with exactly the buffer's layout. An owned `Vec` or | |
| `Box` buffer counts as a mutable span in the entry and return disjointness | |
| checks (excluding overlap with any other shared or mutable reference or | |
| owned-buffer argument span). | |
| <!-- FIXME: Interim honest disclosure pending handle/buffer and | |
| cross-argument disjointness enforcement for buffers behind references | |
| in `ValidEntryArgsV2` (`Trusted/MirSemantics/Bytes.lean`). --> | |
| Heap buffers reachable through a reference argument (including nested | |
| `Vec`/`Box` buffers and self-recursive struct chains) are not yet excluded by | |
| `ValidEntryArgsV2` from aliasing their own handle or another argument (for | |
| example, a `&mut Vec<u64>` whose buffer shares its handle's allocation, or a | |
| `&[u8]` into the buffer of a `&mut Vec<u8>` argument); because | |
| `ValidEntryArgsV2` is an entry hypothesis, those aliasing caller states remain | |
| quantified over rather than assumed disjoint, and receipts disclose this | |
| explicitly. Under `--panic abort`, | |
| the caller memory that post-abort conditions see omits heap buffers that the | |
| call allocated. Returning a reference into the buffer of a `&mut Vec<T>` | |
| argument that reallocated during the call faults with `.undefined`, because | |
| returned references must point into the caller's entry allocations; this is | |
| conservative. On return, the caller memory that `post` sees also contains the | |
| heap buffers the call allocated and did not free, such as the buffer of a | |
| returned `Box` or of a `Vec` that grew through a `&mut Vec<T>` argument. | |
| Validity of owned data is recursive (`Trusted.MirSemantics.ownedValidInMem`): a | |
| reference to a struct with a `Box` field, for example, is valid only if the | |
| box's buffer is. `Vec::resize`, `Vec::extend_from_slice`, and `Box::clone` copy | |
| elements bitwise, so they are admitted only for plain-data elements whose | |
| `Clone` is `TrivialClone` (such as `#[derive(Clone, Copy)]`), never for elements | |
| that own a handle. Owned data that contains a handle may be a local, a field, an | |
| element, or a reference pointee, but never a raw-pointer pointee or an array | |
| element. A `Drop` of it runs its drop glue recursively: struct fields in | |
| declaration order, the payload of a `Some` or the fields of a payload enum's | |
| active variant, and each element of a `Vec` or `Box<[T]>` before its buffer is | |
| freed. `Option<Box<T>>` and `Option<Vec<T>>` use | |
| the handle's niche. Slices `&[T]` of every scalar, `()`, array, and owned-data | |
| element type, and `*const [T]` of every scalar or `()` element type, are | |
| admitted local types. `<[T]>::len` is modeled for all of them; the other slice | |
| functions above still require integer elements. Both a heap buffer and a `&[T]` | |
| slice of struct elements decode each element field by field, so struct padding | |
| bytes may remain uninitialized. | |
| Profile v2 admits crate-local, non-generic, self-recursive structs, such as | |
| Starnix's `struct MemoryId { ..., parent: Option<Box<MemoryId>> }`, whose | |
| recursive occurrences are each the direct pointee of a `Box` or `Vec` | |
| (`Box<Self>`, `Option<Box<Self>>`, `Vec<Self>`, or, behind further handles, | |
| `Vec<Box<Self>>`). Capture writes each such struct as one | |
| closed type, `MirTy.recAdt id defn`, whose definition refers back to the | |
| struct as `MirTy.recSelf id`. `BodyStaticAdmittedV2` checks that every | |
| recursive occurrence sits under a handle and names its own struct, and that | |
| each struct has one definition throughout the program | |
| (`Trusted.MirSemantics.programRecTysAdmittedV2`). Validity of a recursive value | |
| follows its chain of heap buffers with fuel bounded by the number of | |
| allocations, and a buffer reached twice, through a cycle or through two owning | |
| handles, is invalid (`Trusted.MirSemantics.recOwnedValidV2`). Dropping a | |
| recursive value runs its drop glue down the chain with fuel bounded the same | |
| way; running out of fuel faults rather than skipping a buffer | |
| (`Trusted.MirSemantics.dropGlueFuelV2`). Refused (fail-closed): mutually | |
| recursive structs; recursion through any other shape, such as `Box<[Self]>`, | |
| `Vec<Option<Self>>`, references, or raw pointers; and constants of a recursive | |
| struct. Recursive payload enums follow the same rules (see below). A struct | |
| aggregate of a recursive struct (as in `MemoryId::prepended` or | |
| `Clone::clone`) takes the field types of its one-step unfolding. | |
| Recursive structs exist only in Profile v2, so the `lean-miri` correspondence | |
| covers no program that contains one. | |
| Profile v2 reads the discriminant of, and borrows and reads the payload of, an | |
| `Option` behind a reference or in an in-memory local | |
| (`match &self.parent { Some(p) => ... }`, MIR `discriminant(*r)` and | |
| `&((*r) as Some).0`). The payload sits at offset 0 for the niches of `&T` and | |
| `Box<T>` (a null pointer) and `Vec<T>` (capacity `u64::MAX = 2^64 - 1`, | |
| matching `rustc`'s `UsizeNoHighBit` niche and cross-checked at capture time), | |
| and after the tag for a direct-tag layout | |
| (`Trusted.MirSemantics.optionSomeOffsetV2`). The `Option` is read first, and | |
| the payload of a `None` is `.undefined` (`projectMemoryPlaceV2`); `rustc` | |
| emits such a downcast only after testing the discriminant. Refused | |
| (fail-closed): writing through such a downcast; the in-memory payload of | |
| `Option<bool>`, `Option<()>`, or `Option<Vec<T>>` with a zero-sized `T` | |
| (where `RawVecInner::capacity(0)` is `usize::MAX` rather than `self.cap`, so | |
| in-place payload projection stays conservatively unsupported); and a downcast | |
| within a slice element (`(*s)[i]`). | |
| Profile v2 models enums with payloads (`MirTy.adtEnum`): non-generic | |
| crate-local enums, `core::result::Result<T, E>`, and each `Option<T>` whose | |
| payload has no `MirTy.option` layout (structs, payload enums, `Ordering`, | |
| `char`, fieldless enums). Each variant's fields form one payload struct at | |
| `rustc`'s field offsets within the enum, and the tag follows `rustc`'s | |
| `Variants::Multiple` encoding: a direct tag holding the discriminant, or a | |
| niche in the untagged variant's payload (`Result<u32, E>` stores `Ok` as an | |
| invalid value of `E`'s tag). Capture reads the tag offset, width, valid range, | |
| and encoding from `rustc` and checks every field's layout. Decoding follows | |
| `read_discriminant`: an uninitialized tag, an unknown direct tag, a tag outside | |
| its valid range, or the niche value of the untagged variant is `.undefined`, | |
| and a tag with provenance is accepted only for a pointer niche `{0}`. Encoding | |
| writes the payload, then the tag, and refuses any value that would not decode | |
| back to its variant, which keeps the untagged variant's payload out of the | |
| niche (`Trusted.MirSemantics.adtFinishEncodeV2`). Variant construction | |
| (`Rvalue::Aggregate`), `match` (`discriminant` and `SwitchInt`), reading and | |
| borrowing a variant's fields (locally, through a reference, or in memory, | |
| where a variant the enum does not hold is `.undefined`), constants, and | |
| `Option::{is_some, is_none}` on such an `Option` are modeled. `Option<T>` of | |
| plain sized data (such as `Option<u64>`) may be a struct field or variant | |
| field. A payload enum that reaches itself through a direct `Box<Self>` or | |
| `Vec<Self>` field (`enum Type { .., NullOr { inner: Box<Type> } }`) is the | |
| recursive binder `MirTy.recAdt` over its `adtEnum` definition, as a | |
| self-recursive struct is, and its variants are those of its one-step | |
| unfolding. Dropping a payload enum drops the fields of its active variant, | |
| through the fuelled glue when it is recursive. Refused (fail-closed): any | |
| other recursion through a payload enum (`Box<[Self]>`, mutual recursion), | |
| mutably borrowing or writing through a variant downcast, `SetDiscriminant`, | |
| and payload enums with references, raw pointers, or uninhabited variants. A | |
| `Vec<T>` handle has `rustc`'s word order (capacity, pointer, length), which | |
| capture checks for every `Vec`, because `Result<Vec<T>, E>` stores its niche in | |
| the capacity. Payload enums exist only | |
| in Profile v2, so the `lean-miri` correspondence covers no program that | |
| contains one. | |
| Constructing a variant of a crate-local fieldless enum (`return E::A`) is also | |
| a Profile v2 aggregate: its value is the variant itself, whose discriminant | |
| becomes the tag when the value is stored | |
| (`Trusted.MirSemantics.evalFieldlessEnumAggregateV2`). | |
| `tests/cargo-anneal/tests/profile_v2_e2e.rs` verifies the unmodified | |
| `zerocopy/src/byte_slice.rs` `<&[u8] as SplitByteSlice>::split_at_unchecked` | |
| under `UnitTheoremV2`, raw-pointer load and store fixtures under | |
| `CrateTheoremV2`, `core` range/slice/`Option`/`mem::replace`/scalar contract | |
| fixtures in `tests/cargo-anneal/tests/fixtures/profile_v2_core_contracts/`, | |
| struct, index, call, and `Drop` fixtures in | |
| `tests/cargo-anneal/tests/fixtures/profile_v2_structs_index_drop/`, a | |
| `Vec<u8>` built and dropped (whose freed buffer is no longer caller-visible) in | |
| `tests/cargo-anneal/tests/fixtures/profile_v2_drop_glue/`, the unmodified | |
| Starnix `MemoryId::id` of a self-recursive struct in | |
| `tests/cargo-anneal/tests/fixtures/profile_v2_memory_id/`, `?` on | |
| `Result<u32, E>` and `Option<u32>` in | |
| `tests/cargo-anneal/tests/fixtures/profile_v2_try/`, and the runtime overflow | |
| check fixtures below. | |
| ### Runtime overflow checks | |
| By default capture compiles with `-Coverflow-checks=no`, so `+`, `-`, `*`, | |
| and unary `-` wrap and `<<` and `>>` mask their shift amount, as in a default | |
| release build. `--overflow-checks` (request field | |
| `compilation.overflow_checks: true`) captures with `-Coverflow-checks=yes` | |
| instead, matching builds that enable overflow checks (such as default debug | |
| builds). Rustc then guards each of those operations with an `Assert` | |
| terminator, so such bodies use Profile v2. Under `--panic unwind` a failed | |
| check faults, so a verified theorem proves that no overflow check fires on any | |
| admitted input. Under `--panic abort` (without a crate-local | |
| `#[panic_handler]`) a failed check aborts like the other safe panics, so a | |
| panic-freedom proof needs a `SafeContractV2` with `EffectMaskV2.noAbort`. | |
| Capture records the setting as `configuration.overflow_checks` in | |
| `capture.json` and in the receipt, and as `Program.overflowChecks` in | |
| `Captured.lean`, which specifications can pin. `--overflow-checks` is refused | |
| together with `--stdlib-crate`. Verify the setting against the deployed | |
| build: a proof without `--overflow-checks` says nothing about a build in which | |
| overflow panics, and vice versa. | |
| ### Bundled proof libraries and specification boundaries | |
| - **Proof modules:** May import any of the bundled 3-axiom `Anneal.*` proof | |
| libraries listed in | |
| [`theory/bundle-manifest.json`](../theory/bundle-manifest.json) (such as | |
| `Anneal.MirWp`, `Anneal.LoopInv`, `Anneal.BitVec`, and `Anneal.ClassicalEm`), | |
| which are compiled and audited on demand when imported. Other experimental | |
| modules under `theory/Anneal/` that are not in `theory/bundle-manifest.json` | |
| are not bundled into `cargo-anneal`. | |
| - **Specification modules:** Stay restricted to `Trusted.*`, `Init.*`/`Std.*`, | |
| and declared `specification` helpers. | |
| On Lean `v4.35.0+` toolchains bundling `leanexport`, `nanoda_bin`, and | |
| `con-ron` (with `--allow-unpinned-lean`), `cargo-anneal` verifies proofs via | |
| the out-of-process Universal NDJSON Comparator rather than in-process | |
| `.olean` replay; pass `--paranoid-quorum` to also cross-check with `con-leche` | |
| and `lean4lean`. | |
| Verify the stated compilation configuration in the receipt when comparing a | |
| result with a deployed binary. See the [threat model](../THREAT_MODEL.md) for | |
| the verification assumptions. | |
| ## Build-system and toolchain options | |
| Build systems such as Bazel or GN that already resolve crate inputs and Lean | |
| module mappings can invoke `verify rustc` directly instead of writing a | |
| `request.json` file: | |
| ```sh | |
| cargo anneal verify rustc /path/to/src/lib.rs \ | |
| --crate-name scalar --edition 2024 \ | |
| --source-file /path/to/src/helper.rs \ | |
| --spec-file Spec=/path/to/spec/Spec.lean \ | |
| --proof-file Proof=/path/to/proof/Proof.lean \ | |
| --spec-decl Spec:Spec.specs --theorem Proof:Proof.verify \ | |
| --select module::function --artifacts /path/to/evidence | |
| ``` | |
| Pass `--spec-closure /path/to/spec-surface.golden.json` (with each imported | |
| `specification` module's `<name>.spec-surface.golden.json` companion at the | |
| relative `golden_path` declared in `imported_spec_modules`, resolved next to the | |
| root golden or as a sibling `<SpecFile>.spec-surface.golden.json`) to select the | |
| structured `Trusted.Framework.{Crate,Unit}MirEnvelopeTheorem` root in | |
| `verify rustc`. `verify rustc` stages the root golden and companions into | |
| `<artifacts>/authored/` alongside `<artifacts>/spec-surface.golden.json` and | |
| writes `proof.spec_closure` into the retained `<artifacts>/request.json` so | |
| replaying `verify --request <artifacts>/request.json` reproduces the same | |
| envelope claim. | |
| `verify rustc` dereferences symlinks when staging regular source files so | |
| symlinked runfiles trees work directly, while still rejecting special files and | |
| concurrent source edits. Additional flags support build-system and custom | |
| toolchain integration: | |
| - `--export-lean-lib` (requires `--artifacts <directory>`): atomically stages | |
| Door-1-verified target `.olean` files inside the private work directory and | |
| retains them under `<artifacts>/lean-lib/` after target audit passes; omits | |
| authored `proof` `.olean`s on `proof_failed` (exit `1`)—including authored | |
| `Proof`-module deterministic heartbeat or recursion-depth limit failures, | |
| which classify as `proof_failed` with structured `"reason"` | |
| (`"heartbeat_limit_exceeded"` or `"recursion_depth_exceeded"`) so non-proof | |
| `.olean`s remain exported for debugging while negative and mutation checks | |
| refuse to credit them as kills—and exports nothing on `tool_failed` | |
| (exit `2`). | |
| - `--lean-memory-mb <MB>`: sets Lean's `-M<MB>` memory limit (`resolve-imports` | |
| enforces a `4096` MiB floor). | |
| - `--max-inspector-output-bytes <BYTES>`: sets the maximum Lean inspector | |
| `result.json` output size in bytes (`67108864` / `64 MiB` by default, up to | |
| `1073741824` / `1 GiB`; also raises child `RLIMIT_FSIZE` when set above | |
| `256 MiB`). | |
| - `--child-timeout-secs <SECS>`: sets the wall-clock limit for each | |
| Lean child process (`600` by default, `1` to `86400`). It only bounds run | |
| time: it is not recorded in the receipt and does not taint it. | |
| Parallel Lean compilation uses a bounded number of workers. By default it uses | |
| the smaller of the host's available parallelism and a built-in cap. Setting | |
| `ANNEAL_COMPILE_WORKERS=<n>` (a positive integer) requests `n` workers, still | |
| bounded by available parallelism (standalone NDJSON kernel verification with | |
| `con-ron` and `con-leche` remains hard-capped at `2` jobs); invalid or | |
| non-positive values are ignored. The worker count is then limited to one worker | |
| per `4096` MiB of memory (never fewer than one worker), using the tighter of | |
| `ANNEAL_LEAN_RUN_MEM_MB=<MB>` and, on Linux, the cgroup v2 `memory.max` of the | |
| current cgroup and its ancestors, so concurrent Lean workers stay within a | |
| container or job memory budget. An invalid or non-positive | |
| `ANNEAL_LEAN_RUN_MEM_MB` is ignored. | |
| When building `cargo-anneal` itself with Cargo's `--no-default-features` flag | |
| (for example, `cargo install --locked --no-default-features cargo-anneal`), the | |
| default `setup` feature and remote archive download support (`exocrate`) are | |
| omitted, so pass explicit `--capture`, `--sysroot`, and `--lean` paths to | |
| `verify`. On `cargo anneal verify --manifest-path`, `--no-default-features` | |
| instead disables default features of the target crate being verified. | |
| Each `--allow-*` relaxation flag follows Receipt Schema v3's Uniform | |
| Flag-Driven Taint Law: passing the flag prints a `TAINTED` warning banner on | |
| stderr, adds its sorted entry to `taint_reasons` even on clean runs, and | |
| switches passing status to `tainted_crate_verified` or | |
| `tainted_selected_unit_verified`: | |
| - `--allow-unpinned-lean` (requires explicit `--lean <path>`): adds | |
| `"unpinned_lean"`, dynamically discovers and hashes the minimal `Init.*` and | |
| `Std.*` sysroot import closure (recorded in `unpinned_lean` and | |
| `audit.unpinnedLean`), and marks `correspondence_provenance.applicable` as | |
| `false`. | |
| - `--allow-unsandboxed-elaboration`: adds `"unsandboxed_elaboration"`, disables | |
| `ExecSeal` (`"elaboration_sandbox": "none"`), and retains `"hostile Lean | |
| elaborator effects"` in `deferred`. | |
| - `--allow-sorry-in-proof`: adds `"sorry_in_proof"`, permits `sorry` strictly | |
| in authored `proof` modules outside Phase 1 (never in `specification`, | |
| `Model`, `Capture`, or `Expected` modules; `"spec-preflight"` also enforces | |
| pure declarative syntax on `specification` modules), and records | |
| `sorry`-using proof declarations in `sorry_declarations`. | |
| - `--allow-unstable-feature <NAME>` (repeat or comma-separate; no wildcards): | |
| adds `"unmodeled_unstable_features"`, admits exactly the named unstable | |
| `#![feature(...)]` gates on a normal crate (never with `--stdlib-crate`), and | |
| records a top-level `unstable_features` object (`allowed`, the enabled | |
| `observed` subset, and the `incomplete_observed` subset that `rustc` marks | |
| incomplete) plus a static assumption that their semantics are unmodeled. | |
| Compiler-internal features (as `rustc` classifies them), `ergonomic_clones`, | |
| and `rustc_private` stay refused. Gate CI on the exact feature set with | |
| `cargo anneal inspect --allowed-unstable-features <NAME,...>` (which admits | |
| that taint and no other) and optionally | |
| `--forbid-incomplete-unstable-features`. | |
| <!-- FIXME: Interim opt-in taint gate pending pinned sysroot `library/core` | |
| source-hash authentication in capture. --> | |
| - `--allow-stdlib-crate`: adds `"unauthenticated_stdlib_crate"` and is required | |
| to permit `compilation.stdlib_crate` in `--request` JSON or `--stdlib-crate` | |
| on `verify rustc` (which unlocks the pinned stdlib feature allowlist, | |
| crate-local `#[lang]` items, reduced whole-crate CTFE seeding, and | |
| metadata-only capture without authenticating that the crate sources match the | |
| pinned Rust sysroot; cannot be combined with `--allow-unstable-feature`). | |
| For inner-loop proof iteration, `--fast-check` runs capture, toolchain | |
| admission, specification preflight, and full Lean elaboration while skipping | |
| stage `[6/6]` kernel replay and target auditing. Because replay is skipped, | |
| `--fast-check` prints `TAINTED` / `UNVERIFIED_DEV_ONLY`, exits with code `3` | |
| (never `0`), forces unverified dev output (never Receipt v3 JSON), and fails | |
| closed if combined with `--receipt-out`, `--artifacts`, | |
| `--overwrite-artifacts`, `--export-lean-lib`, `--paranoid-quorum`, or | |
| `--format json`. Re-run without `--fast-check` to emit a verification receipt. | |
| ## Inspect receipts offline | |
| Run `cargo anneal inspect <receipt.json>` (including under | |
| `--no-default-features`) to validate Receipt Schema v3 cross-checks, compute the | |
| 6-axis assurance profile, compare two receipts with `--diff <BASE> <HEAD>` | |
| (`--no-regressions`), or verify local retained artifact hashes with | |
| `--verify-artifacts <DIR>` (including retained `spec-surface.golden.json` and | |
| companion `.spec-surface.golden.json` artifacts when `spec_closure_sha256` is | |
| present). Bare single-receipt `inspect` fails closed on | |
| failed, tainted, or warn-mode extension receipts (`exit 1`, or `exit 2` with | |
| `--unknown-fields deny`). Under `--diff <BASE> <HEAD>`, invariant violations | |
| and default warn-mode extension fields also fail closed (`exit 1`, or `exit 2` | |
| with `--unknown-fields deny`), while `--no-regressions` gates on Tier A | |
| assurance downgrades. Pass `--passive` to inspect receipts without status, | |
| taint, or warn-mode extension gating (invariant, artifact, and | |
| `--compare-ledger` failures still exit `1`). Pass | |
| `--max-receipt-bytes <BYTES>` (`67108864` / `64 MiB` by default, up to | |
| `1073741824` / `1 GiB`) to inspect or diff larger receipts. Note that `inspect` | |
| checks internal consistency and local digests offline and does not | |
| cryptographically authenticate external receipts. | |
| ## Install a published alpha | |
| Replace `<version>` with the semver version from a published `anneal-v<version>` | |
| prerelease tag on GitHub Releases (for example, `0.2.0-alpha.11`, without the | |
| `anneal-v` prefix; `main` stays at `0.0.0-dev` with an all-zero archive digest | |
| rather than tracking published release metadata, so when running from a source | |
| checkout use `cargo anneal setup --local-archive target/omnibus-link` as shown | |
| in [Try a proof](#try-a-proof) above): | |
| ```sh | |
| cargo install --locked cargo-anneal@<version> | |
| cargo anneal setup | |
| cargo anneal verify --request /path/to/scalar/request.json | |
| ``` | |
| To install the alpha alongside an earlier version of `cargo-anneal`, use | |
| `cargo install --root <directory>` and invoke | |
| `<directory>/bin/cargo-anneal` directly. | |
| ## Cut the release | |
| Before the first publication, create the GitHub environment `release` with | |
| required reviewers and a deployment branch rule allowing only `main`. In the | |
| crates.io settings for `cargo-anneal`, add a trusted publisher for | |
| `google/anneal`, workflow `release.yml`, and environment `release`. These | |
| environment bindings keep credentials scoped to the publication job. See | |
| [crates.io Trusted Publishing](https://crates.io/docs/trusted-publishing). | |
| 1. Run **Release** (`workflow_dispatch`) on `main`. Enter the desired | |
| `0.2.0-alpha.<N>` version (such as `0.2.0-alpha.15`), keep `branch` set to | |
| `main`, and optionally pass a 40-character first-parent `main` `commit` SHA | |
| (leave blank to release current `main` `HEAD`). On `main`, | |
| `trusted/cargo-anneal/Cargo.toml` and `Cargo.lock` remain at `0.0.0-dev` | |
| with an all-zero archive digest; cutting a release opens no pull request and | |
| pushes no commits to `main`. | |
| 2. Wait for `anneal-build-archive`, `anneal-host-archive`, and | |
| `anneal-qualify-package` to finish on Ubuntu 24.04. Running release | |
| scripts and composite actions from the dispatched `main` workflow revision, | |
| the workflow resolves and pins the target commit SHA, builds the | |
| `x86_64-unknown-linux-gnu` omnibus archive from an isolated detached | |
| checkout of that commit, publishes it to a commit-and-digest-addressed | |
| GitHub prerelease (`anneal-toolchain-<commit12>-<sha256_16>`) after | |
| verifying GitHub's asset SHA-256, checks `release` environment | |
| protections, stamps the isolated target checkout in place, installs the | |
| packaged `.crate`, runs remote `cargo anneal setup` twice, and runs | |
| `ci/probe_alpha.py`. | |
| 3. Verify the resolved commit SHA, hosted toolchain digest, and qualification | |
| log, then approve the `release` deployment. Because `main` remains | |
| unpinned (`anneal-v<version>` tags commit `C`), `release` approvers | |
| act as the human review gate for the stamped release metadata before | |
| crates.io upload. `anneal-publish-crate` re-verifies SemVer ordering, live | |
| hosted archive integrity, and exact packaged source parity, publishes | |
| `cargo-anneal` from a freshly stamped clean checkout via OIDC, and verifies | |
| the uploaded `.crate` and crates.io checksum; `anneal-publish-github` tags | |
| `C` as `anneal-v<version>` and publishes path-scoped GitHub Release notes. | |
| Concurrent merges to `main` do not disturb an in-flight release, and failed | |
| qualification or rejected deployment approvals leave the SemVer version | |
| reusable on a subsequent commit. `resolve-and-validate` checks `anneal-v*` Git | |
| tags on `origin/main` first-parent history against un-yanked `crates.io` | |
| versions: it fails closed if the target `anneal-v<version>` tag already exists | |
| without a matching `crates.io` release or if any un-yanked `crates.io` release | |
| strictly above both the pre-standalone cutover high-water mark | |
| (`0.2.0-alpha.14`, published from `google/zerocopy`) and the highest existing | |
| `anneal-v*` tag lacks a first-parent `anneal-v*` tag on `main`. It also pins | |
| the standalone cutover floor commit (`PRE_STANDALONE_FLOOR_COMMIT` in | |
| `ci/alpha_release.py`, `c62e87e388ed278c355cb933b9ed95cefb696e50`) so every | |
| standalone release commit must strictly descend from the cutover commit on | |
| `origin/main` first-parent history even before the first `anneal-v*` tag exists | |
| in `google/anneal`. | |
| Post-crate recovery re-dispatch applies to commit-bound releases | |
| (`anneal-toolchain-<C12>-<D16>`): if a transient failure occurs during archive | |
| hosting, qualification, or GitHub Release creation, rerun the failed jobs within | |
| the 24-hour (`retention-days: 1`) `upload-file-artifact` window; once that | |
| artifact expires (or after `cargo publish` succeeds), dispatch **Release** again | |
| for the same commit and version to rebuild or complete `anneal-v<version>` | |
| against the published crate's commit and toolchain digest. If any un-yanked | |
| `crates.io` release strictly above both the pre-standalone cutover high-water | |
| mark (`0.2.0-alpha.14`) and the highest `anneal-v*` tag lacked its | |
| `anneal-v<version>` tag, push that tag onto its first-parent release commit | |
| manually before dispatching a newer version. |