diff --git a/.github/workflows/atoma.yml b/.github/workflows/atoma.yml index 2cdf48b..0be16fe 100644 --- a/.github/workflows/atoma.yml +++ b/.github/workflows/atoma.yml @@ -42,6 +42,27 @@ jobs: build/scalar-proof-evidence/registry-source/ if-no-files-found: error + wrapper_source: + name: Wrapper source interpretation + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Provision independent Coq checker + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends coq=8.18.0+dfsg-1build2 + - name: Actual wrapper source and conditional effects + run: bash scripts/atoma-wrapper-source-proof-gate.sh + - uses: actions/upload-artifact@v7.0.2 + if: always() + with: + name: wrapper-source-proof-evidence-${{ github.sha }} + path: build/scalar-proof-evidence/wrapper-source/ + if-no-files-found: error + scalar: name: Scalar source proof gate runs-on: ubuntu-24.04 @@ -69,6 +90,8 @@ jobs: run: bash scripts/atoma-word-proof-gate.sh - name: Generic registry theory (compatible Agda, Lean and full Cubical) run: bash scripts/atoma-registry-proof-gate.sh + - name: Borrowed wrapper theory and cleanup control + run: bash scripts/atoma-wrapper-proof-gate.sh - name: Preserve canonical repository map for review run: | bash scripts/gen-repo-map.sh . @@ -82,7 +105,7 @@ jobs: soundness: name: Atoma soundness gate - needs: [scalar, word_source] + needs: [scalar, word_source, wrapper_source] runs-on: ubuntu-24.04 timeout-minutes: 45 steps: diff --git a/docs/decisions/ATOMA-TOOLCHAIN.adoc b/docs/decisions/ATOMA-TOOLCHAIN.adoc index 0c8a409..b045812 100644 --- a/docs/decisions/ATOMA-TOOLCHAIN.adoc +++ b/docs/decisions/ATOMA-TOOLCHAIN.adoc @@ -1,7 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell = Atoma CI toolchain and bounded provisioning deviation -:revdate: 2026-11-07 +:revdate: 2026-11-25 The preferred estate route is a pinned Guix/container closure. Atoma's inherited provisioning does not currently provide its proof stack. To make this repair @@ -14,7 +14,7 @@ the entire transitive system environment. | Tool | CI input | Integrity / local comparison | Zig | 0.15.2 official x86_64 Linux archive | SHA-256 pinned in installer; same version locally | Z3 | 4.13.3 official x86_64 glibc 2.35 archive | SHA-256 pinned in installer; local Debian 4.13.3-1 also exercised -| Idris2 | v0.8.0 commit `15a3e4e70843f7a34100f6470c04b791330788df`, Chez bootstrap | Exact fetched commit checked; local 0.8.0-b6cbc25d5 is a separate recorded profile +| Idris2 | commit `b6cbc25d5cd2ef2a250556266fd7b68dfc360f8b`, Chez bootstrap | Exact fetched commit and `0.8.0-b6cbc25d5` version checked; same compiler/runtime profile required by both native consumer gates | Agda | Ubuntu package `agda-bin=2.6.3-1build1` | apt authentication and exact package version; local Debian 2.6.4.3-1+b2 is a separate recorded profile | Coq replay | Ubuntu Noble `coq=8.18.0+dfsg-1build2` | coqc and coqchk from the authenticated package; local Rocq 9.2 is a separate recorded profile | ECHIDNA | `2ab7574ae1e574b0e881422fde6252bf79dea178`, locked release build, Rust 1.99.0 | No default optional prover features; local build uses Rust 1.99.1. This consumes the existing Rust verifier; it adds no Rust implementation proof claim diff --git a/docs/decisions/ATOMA-WRAPPER-OWNERSHIP.adoc b/docs/decisions/ATOMA-WRAPPER-OWNERSHIP.adoc new file mode 100644 index 0000000..1ff5500 --- /dev/null +++ b/docs/decisions/ATOMA-WRAPPER-OWNERSHIP.adoc @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += Conditional ownership and actual Zig wrappers +:revdate: 2026-11-25 + +== Admitted source and result + +This experimental slice parses the original complete `registry.zig` and +`header_refc.zig` modules. It admits closed signatures, imports, surrounding +declarations, and an ordered call/loop grammar. Numeric guards become operands +of the operational interpretation. Changed callback arguments, missing cleanup, +reordered state updates, changed span guards and changed loop bounds must refuse. +It is not a general Zig parser or a compiler-refinement theorem. + +UAA's theorem covers `uaa_registry_call`: initial idle state, all normal exits, +busy refusal, invalid-span callback refusal and preservation of endpoint +identities under a callback-frame premise. The actual imported state kernel is +checked independently; the protocol-tag source must export `known` and parse as +the 1..9 range. A renamed-export mutation must be rejected. +The surrounding create/destroy/register/unregister declarations are closed by +the grammar and exercised natively, but do not acquire ownership theorems merely +because their tokens match. Allocator correctness remains assumed. + +Proven's theorem covers the actual `header_refc.detect` loop: under the explicit +foreign-step contract, its checked execution equals the authoritative Boolean +fold. Every iteration consumes one element of the borrowed list; the read count +is bounded by its length. The whole public `core.headerHasCrlf` entry, conversion +from machine pointer to slice, private RefC runtime and compiler remain outside +this refinement. The retained `bits8.zig` bytes identify that assumed carrier; +they are not promoted to a pointer-validity proof by appearing in a capsule. + +== Ownership premises + +* One live registry allocation, serialized owner access, no stale-pointer use. +* Callback and context are valid when invoked; registration retains their + identities. The owner must keep them valid while registration can be called, + or unregister before their storage/code lifetime ends. +* The callback may change its own disjoint context. It must preserve registry + storage, keep borrowed input readable and immutable, and return normally. +* No concurrent writes, asynchronous retention, non-local exit, process abort, + arbitrary raw-alias mutation or compiler correctness is established here. +* Proven receives a readable immutable span for its synchronous call. The + foreign RefC step returns a canonical state implementing the Idris contract + and does not write the borrowed span. Immediate tagged values are not heap + objects and must not be dereferenced as pointers. + +These are quantified or stated premises, not facts inferred from non-nullness. +The UAA native raw-alias fixture deliberately deletes an endpoint during a +callback and demonstrates that `finish` does not restore the original frame. +That counterexample must remain visible; it prevents unconditional safety claims. + +== Evidence and status + +Idris2 owns both engineering contracts. UAA's linear Lease checks use of an +already-acquired logical owner: acquisition, unforgeability and machine aliases +are not proved by its constructors. Constructors are hidden, the resource +payload is linear, and release requires a consuming finalizer. Neither direct +duplication nor destruct-and-reconstruct duplication may type check. Wrapping +an already-copyable value does not establish exclusive machine ownership. +Proven proves checked scanning against its actual ByteKernel fold. Native tests +exercise real Zig wrappers and exported ABI; no FFI/API is implemented in C. + +Compatible Agda is checked with safe, without-K, cubical-compatible and +double-check flags, followed by an audited Lean re-proof and full Cubical paths. +The independent Coq source interpretation adds kernel checking and ECHIDNA +replay. Hand re-proofs remain BRIDGE-PENDING; full Cubical is not an independent +kernel. No PWG promotion, universal native-memory safety or COMPLETE receipt. + +The required source/theory jobs and combined consumer replay must pass on the +exact PR head before this slice is accepted. Qualification evidence is recorded +in https://github.com/hyperpolymath/atoma/pull/33[the implementation PR]; the +presence of these files alone is not a successful check or a promotion. + +== Next obligations + +Connect acquisition/release and callback registration lifetimes to an actual +heap model; prove the public pointer-to-slice entry; extend beyond normal return; +discharge or precisely retain foreign-call assumptions; reconcile statement +identity across kernels. Checked generation handles may support a future +versioned ABI, but this slice changes no ABI and silently repairs no stale handle. diff --git a/scripts/atoma-ci-toolchain.sh b/scripts/atoma-ci-toolchain.sh index 9b2401c..00051cd 100644 --- a/scripts/atoma-ci-toolchain.sh +++ b/scripts/atoma-ci-toolchain.sh @@ -18,10 +18,11 @@ unzip -q z3.zip echo "$task/z3-4.13.3-x64-glibc-2.35/bin" >> "$GITHUB_PATH" git init Idris2 git -C Idris2 remote add origin https://github.com/idris-lang/Idris2.git -git -C Idris2 fetch --depth 1 origin 15a3e4e70843f7a34100f6470c04b791330788df +git -C Idris2 fetch --depth 1 origin b6cbc25d5cd2ef2a250556266fd7b68dfc360f8b git -C Idris2 checkout --detach FETCH_HEAD -[[ $(git -C Idris2 rev-parse HEAD) == 15a3e4e70843f7a34100f6470c04b791330788df ]] +[[ $(git -C Idris2 rev-parse HEAD) == b6cbc25d5cd2ef2a250556266fd7b68dfc360f8b ]] make -C Idris2 bootstrap SCHEME=scheme PREFIX="$task/idris2" -j2 make -C Idris2 install PREFIX="$task/idris2" +[[ $("$task/idris2/bin/idris2" --version) == 'Idris 2, version 0.8.0-b6cbc25d5' ]] echo "$task/idris2/bin" >> "$GITHUB_PATH" dpkg-query -W agda-bin chezscheme libgmp-dev diff --git a/scripts/atoma-consumer-wrapper-gate.sh b/scripts/atoma-consumer-wrapper-gate.sh new file mode 100644 index 0000000..6eb4e6a --- /dev/null +++ b/scripts/atoma-consumer-wrapper-gate.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +mkdir -p "$root/build/atoma-evidence/wrapper-consumers" +out=$(mktemp -d "$root/build/atoma-evidence/wrapper-consumers/run.XXXXXXXX") +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +for profile in header registry; do + if [[ $profile == header ]]; then + repo=proven; pin=ownership-proven.pin + source=ffi/zig/src/header_refc.zig; dependency=ffi/zig/src/refc/bits8.zig + else + repo=unified-api-adapter; pin=ownership-uaa.pin + source=src/interface/ffi/src/registry.zig; dependency=src/interface/ffi/src/registry_state.zig + fi + revision=$(cat "$root/tests/consumer-word/$pin") + [[ $revision =~ ^[0-9a-f]{40}$ ]] + checkout="$work/$repo" + git init -q "$checkout" + git -C "$checkout" remote add origin "https://github.com/hyperpolymath/$repo.git" + git -C "$checkout" fetch -q --depth 1 origin "$revision" + git -C "$checkout" checkout -q --detach FETCH_HEAD + [[ $(git -C "$checkout" rev-parse HEAD) == "$revision" ]] + git -C "$checkout" diff --exit-code "$revision" -- + mkdir "$out/$profile" + echo "$revision" > "$out/$profile/revision.txt" + if [[ $profile == header ]]; then + EVIDENCE_DIR="$out/$profile/native" bash "$checkout/scripts/test-header-bridge.sh" + [[ $(cat "$out/$profile/native/result.txt") == PASS ]] + [[ $(cat "$out/$profile/native/ownership/result.txt") == PASS ]] + [[ $(cat "$out/$profile/native/ownership-controls/result.txt") == PASS ]] + else + EVIDENCE_DIR="$out/$profile/native" bash "$checkout/scripts/check-registry-ownership.sh" + [[ $(cat "$out/$profile/native/result.txt") == PASS ]] + EVIDENCE_DIR="$out/$profile/native-controls" bash "$checkout/scripts/check-registry-ownership-controls.sh" + [[ $(cat "$out/$profile/native-controls/result.txt") == PASS ]] + fi + git -C "$checkout" diff --exit-code "$revision" -- > "$out/$profile/consumer-recheck.txt" + bash "$root/scripts/atoma-source-profile-replay.sh" "$profile-wrapper" "$checkout/$source" "$checkout/$dependency" "$out/$profile/replay" + git -C "$checkout" diff --exit-code "$revision" -- > "$out/$profile/post-replay-recheck.txt" +done +echo 'WRAPPER CONSUMERS PASS: fresh native qualification and conditional original-source replay; ownership premises remain' diff --git a/scripts/atoma-gate.sh b/scripts/atoma-gate.sh index aac94fb..e2de457 100644 --- a/scripts/atoma-gate.sh +++ b/scripts/atoma-gate.sh @@ -15,7 +15,7 @@ case $("$AGDA" --version) in 'Agda version 2.6.3'|'Agda version 2.6.4.3') ;; *) echo 'FAIL unsupported Agda version'; exit 1 ;; esac -[[ $("$IDRIS2" --version) == 'Idris 2, version 0.8.0'* ]] || { echo 'FAIL expected Idris2 0.8.0'; exit 1; } +[[ $("$IDRIS2" --version) == 'Idris 2, version 0.8.0-b6cbc25d5' ]] || { echo 'FAIL expected Idris2 0.8.0-b6cbc25d5'; exit 1; } evidence="$root/build/atoma-evidence" mkdir -p "$evidence" { @@ -76,6 +76,7 @@ bash scripts/atoma-gate-falsifiers.sh | tee "$evidence/falsifiers.txt" bash scripts/atoma-replay-gate.sh | tee "$evidence/replay.txt" bash scripts/atoma-consumer-scalar-gate.sh | tee "$evidence/scalar-consumers.txt" bash scripts/atoma-consumer-source-gate.sh | tee "$evidence/source-consumers.txt" +bash scripts/atoma-consumer-wrapper-gate.sh | tee "$evidence/wrapper-consumers.txt" # Bind the source, contracts, proof sources and gate definitions to this run. # Exclude generated caches/witnesses to avoid self-referential digests. find tools/atoma/src examples/atoma/frame-v1/src examples/atoma/frame-v1/abi \ @@ -86,4 +87,3 @@ sha256sum tools/atoma/build.zig scripts/atoma-*.sh examples/atoma/frame-v1/verif verification/proofs/{agda,idris2}/MANIFEST .github/workflows/atoma.yml >> "$evidence/inputs.sha256" cp examples/atoma/frame-v1/witness/phase0.receipt.json "$evidence/" echo 'ATOMA GATE PASS — INCOMPLETE (Warrant); closed source profiles replayed; compiler and foreign-boundary refinement unproved' - diff --git a/scripts/atoma-source-profile-replay.sh b/scripts/atoma-source-profile-replay.sh index 3ce325e..0e5cca9 100644 --- a/scripts/atoma-source-profile-replay.sh +++ b/scripts/atoma-source-profile-replay.sh @@ -22,6 +22,17 @@ case "$profile" in libraries=(ScalarSource RegistrySource) reports=1 ;; + registry-wrapper|header-wrapper) + import_path=$(realpath "$3") + cp "$import_path" "$out/dependency.zig" + libraries=(ScalarSource RegistrySource WrapperSource) + reports=1 + if [[ $profile == registry-wrapper ]]; then + protocol_path=$(dirname "$source_path")/protocol_tag.zig + cp "$protocol_path" "$out/protocol_tag.zig" + reports=3 + fi + ;; *) fail 'unsupported source profile' ;; esac for library in "${libraries[@]}"; do @@ -31,6 +42,8 @@ capsule() { case "$profile" in decoder) bash "$root/scripts/atoma-word-capsule.sh" "$out/source.zig" "$out/encoder.zig" ;; registry) bash "$root/scripts/atoma-registry-capsule.sh" "$out/source.zig" ;; + registry-wrapper) bash "$root/scripts/atoma-wrapper-capsule.sh" registry "$out/source.zig" "$out/dependency.zig" "$out/protocol_tag.zig" ;; + header-wrapper) bash "$root/scripts/atoma-wrapper-capsule.sh" header "$out/source.zig" "$out/dependency.zig" - ;; esac } capsule > "$out/AtomaProof.v" @@ -53,9 +66,11 @@ capsule > Audit.v cmp -s AtomaProof.v Audit.v || fail 'capsule differs from independent regeneration' timeout -k 5 180 coqc -q Audit.v > assumptions.txt 2>&1 [[ $(grep -c '^Closed under the global context$' assumptions.txt) == "$reports" ]] || fail 'unexpected assumptions' -! grep -q '^Axioms:' assumptions.txt +if grep -q '^Axioms:' assumptions.txt; then fail 'audit reported axioms'; fi cmp -s source.zig "$source_path" || fail 'source changed during replay' if [[ $profile == decoder ]]; then cmp -s encoder.zig "$import_path" || fail 'import changed'; fi +if [[ $profile == *-wrapper ]]; then cmp -s dependency.zig "$import_path" || fail 'wrapper dependency changed'; fi +if [[ $profile == registry-wrapper ]]; then cmp -s protocol_tag.zig "$protocol_path" || fail 'protocol dependency changed'; fi for library in "${libraries[@]}"; do cmp -s "$library.v" "$root/verification/atoma/consumer/coq/$library.v" || fail 'checker changed' done @@ -65,6 +80,6 @@ jq -cnS --arg profile "$profile" \ '{schema:"atoma.source.profile/1",status:"INCOMPLETE",profile:$profile, checked:"original source interpretation; independent kernel replay",assumptions:[], open:["Zig parser/compiler refinement","Idris primitive/compiler correspondence", - "cross-kernel witness transport","pointer validity and exclusive ownership","whole-wrapper effects"]}' > receipt.json + "cross-kernel witness transport","pointer validity and exclusive ownership", + "foreign callback and RefC contracts","whole-wrapper effects outside admitted profile"]}' > receipt.json echo "SOURCE-CHECKED $profile: interpreted source; compiler and foreign boundary remain explicit" - diff --git a/scripts/atoma-wrapper-capsule.sh b/scripts/atoma-wrapper-capsule.sh new file mode 100644 index 0000000..6df7204 --- /dev/null +++ b/scripts/atoma-wrapper-capsule.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +set -euo pipefail +[[ $# == 4 && -f $2 && -f $3 ]] +profile=$1 +[[ $profile == registry || $profile == header ]] +for source in "$2" "$3"; do [[ $(wc -c < "$source") -le 65536 ]]; done +cat <<'COQ' +From Coq Require Import List Bool ZArith String. +Require Import WrapperSource RegistrySource. +Import ListNotations. +Open Scope string_scope. +Open Scope nat_scope. +COQ +bytes() { + printf 'Definition %s : list nat := ' "$1" + od -An -v -tu1 "$2" | awk 'BEGIN {printf "["} {for(i=1;i<=NF;i++) {if(n++) printf ";"; printf "%s",$i}} END {print "]."}' +} +bytes wrapper_bytes "$2" +bytes dependency_bytes "$3" +if [[ $profile == registry ]]; then +[[ -f $4 && $(wc -c < "$4") -le 65536 ]] +bytes protocol_bytes "$4" +cat <<'COQ' +Lemma source_accepted : WrapperSource.check_registry wrapper_bytes = true. +Proof. vm_compute. reflexivity. Qed. +Lemma dependency_accepted : RegistrySource.check dependency_bytes = true. +Proof. vm_compute. reflexivity. Qed. +Definition protocol_exports_known : bool := + match ScalarSource.lex (List.length protocol_bytes) protocol_bytes with + | Some ("pub" :: "fn" :: "known" :: _) => true + | _ => false + end. +Lemma protocol_accepted : protocol_exports_known = true /\ + ScalarSource.parse protocol_bytes = Some (ScalarSource.inclusive_range 1 9). +Proof. vm_compute. split; reflexivity. Qed. +Theorem source_checked : forall A present (s : RegistrySource.state A) tag valid callback, + RegistrySource.active s = false -> WrapperSource.callback_frames callback -> + exists p, WrapperSource.parse_registry wrapper_bytes = Some p /\ + WrapperSource.final_registry (WrapperSource.registry_run p present s tag valid callback) = s. +Proof. intros. eapply WrapperSource.registry_normal_frame; eauto using source_accepted. Qed. +Print Assumptions source_checked. +Print Assumptions dependency_accepted. +Print Assumptions protocol_accepted. +COQ +else +# The pointer carrier / RefC runtime remain an explicit call contract. Preserve +# their actual bytes in the capsule rather than pretending this is a proof of them. +cat <<'COQ' +Lemma source_accepted : WrapperSource.check_header wrapper_bytes = true. +Proof. vm_compute. reflexivity. Qed. +Theorem source_checked : forall step foreign bs, + Forall (fun b => b < 256) bs -> + (forall s b, b < 256 -> foreign (WrapperSource.encode s) b = Some (WrapperSource.encode (step s b))) -> + exists p, WrapperSource.parse_header wrapper_bytes = Some p /\ + WrapperSource.header_run p foreign bs = Some (WrapperSource.fold step false bs). +Proof. intros. eapply WrapperSource.header_source_fold; eauto using source_accepted. Qed. +Print Assumptions source_checked. +COQ +fi diff --git a/scripts/atoma-wrapper-proof-gate.sh b/scripts/atoma-wrapper-proof-gate.sh new file mode 100644 index 0000000..70c09b4 --- /dev/null +++ b/scripts/atoma-wrapper-proof-gate.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out="$root/build/scalar-proof-evidence/wrapper-theory" +mkdir -p "$out" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then tail -n 50 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT +cp "$root/verification/atoma/consumer/agda/WrapperEffects"*.agda "$work/" +cp "$root/verification/atoma/consumer/lean4/WrapperEffects.lean" "$work/" +cd "$work" +agda --safe --without-K --cubical-compatible --double-check --warning=error WrapperEffects.agda > "$out/agda.txt" 2>&1 +lean WrapperEffects.lean > "$out/lean.txt" 2>&1 +awk ' +BEGIN {names["normalReturnFrame"]=1; names["invalidSpanCleanup"]=1; names["aliasCounterexample"]=1; names["aliasBreaksFrame"]=1; names["scanRefinesFold"]=1} +{ + found=0 + for (n in names) { + expected="\047WrapperEffects." n "\047 does not depend on any axioms" + if ($0 == expected && names[n] == 1) {names[n]=2; found=1; count++} + } + if (!found) exit 1 +} +END {if (count != 5) exit 1}' "$out/lean.txt" +agda --safe --cubical --double-check --warning=error WrapperEffectsCubical.agda > "$out/cubical.txt" 2>&1 +sed -e 's/module WrapperEffects where/module WrapperEffectsMutant where/' \ + -e 's/finish s = registry (rest s) (mcp s) false/finish s = registry (rest s) (mcp s) true/' WrapperEffects.agda > WrapperEffectsMutant.agda +if agda --safe --cubical-compatible --double-check --warning=error WrapperEffectsMutant.agda > "$out/reject-cleanup.txt" 2>&1; then exit 1; fi +grep -q '!=' "$out/reject-cleanup.txt" +sha256sum ./*.agda ./*.lean > "$out/inputs.sha256" +echo 'WRAPPER THEORY PASS: compatible Agda, audited Lean, Cubical and rejecting cleanup control' diff --git a/scripts/atoma-wrapper-source-proof-gate.sh b/scripts/atoma-wrapper-source-proof-gate.sh new file mode 100644 index 0000000..88dca0e --- /dev/null +++ b/scripts/atoma-wrapper-source-proof-gate.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out="$root/build/scalar-proof-evidence/wrapper-source" +mkdir -p "$out" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then tail -n 45 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT +cp "$root/verification/atoma/consumer/coq/"{ScalarSource,RegistrySource,WrapperSource}.v "$work/" +fetch() { + local repo=$1 revision=$2 path=$3 target=$4 + [[ $revision =~ ^[0-9a-f]{40}$ ]] + curl --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 120 -fsSL --retry 1 \ + "https://raw.githubusercontent.com/hyperpolymath/$repo/$revision/$path" -o "$target" +} +proven=$(cat "$root/tests/consumer-word/ownership-proven.pin") +uaa=$(cat "$root/tests/consumer-word/ownership-uaa.pin") +fetch proven "$proven" ffi/zig/src/header_refc.zig "$work/header.zig" +fetch proven "$proven" ffi/zig/src/refc/bits8.zig "$work/bits8.zig" +fetch unified-api-adapter "$uaa" src/interface/ffi/src/registry.zig "$work/registry.zig" +fetch unified-api-adapter "$uaa" src/interface/ffi/src/registry_state.zig "$work/registry_state.zig" +fetch unified-api-adapter "$uaa" src/interface/ffi/src/protocol_tag.zig "$work/protocol_tag.zig" +cd "$work" +for library in ScalarSource RegistrySource WrapperSource; do + coqc -q "$library.v" > "$out/$library.txt" 2>&1 +done +[[ $(grep -c '^Closed under the global context$' "$out/WrapperSource.txt") == 8 ]] +for profile in registry header; do + dependency=registry_state.zig; [[ $profile != header ]] || dependency=bits8.zig + bash "$root/scripts/atoma-wrapper-capsule.sh" "$profile" "$profile.zig" "$dependency" protocol_tag.zig > AtomaProof.v + coqc -q AtomaProof.v > "$out/$profile.txt" 2>&1 + coqchk -silent -Q . '' WrapperSource AtomaProof > "$out/$profile-coqchk.txt" 2>&1 + cp AtomaProof.v "$out/$profile-capsule.v" +done +reject() { + local name=$1 profile=$2 dependency=$3 + bash "$root/scripts/atoma-wrapper-capsule.sh" "$profile" mutant.zig "$dependency" protocol_tag.zig > Bad.v + if coqc -q Bad.v > "$out/reject-$name.txt" 2>&1; then echo "FAIL $name accepted" >&2; exit 1; fi + grep -q 'Unable to unify' "$out/reject-$name.txt" +} +for mutation in cleanup context order span; do + case "$mutation" in + cleanup) sed '/defer registry\.\* = state.finish/d' registry.zig ;; + context) sed 's/endpoint.callback(endpoint.context, bytes, len)/endpoint.callback(null, bytes, len)/' registry.zig ;; + order) sed 's/registry\.\* = reply.next;/registry.* = state.finish(Endpoint, reply.next);/' registry.zig ;; + span) sed '/if (bytes == null and len != 0) return 4;/d' registry.zig ;; + esac > mutant.zig + if cmp -s registry.zig mutant.zig; then echo 'FAIL unchanged registry mutant' >&2; exit 1; fi + reject "$mutation" registry registry_state.zig +done +for mutation in initial bound final import; do + case "$mutation" in + initial) sed 's/var state: u8 = 0/var state: u8 = 1/' header.zig ;; + bound) sed 's/next > 1/next > 2/' header.zig ;; + final) sed 's/return state == 1/return state == 0/' header.zig ;; + import) sed 's@refc/bits8.zig@refc/ bits8.zig@' header.zig ;; + esac > mutant.zig + if cmp -s header.zig mutant.zig; then echo 'FAIL unchanged header mutant' >&2; exit 1; fi + reject "$mutation" header bits8.zig +done +sed 's/pub fn known(/pub fn renamed(/' protocol_tag.zig > protocol-renamed.zig +if cmp -s protocol_tag.zig protocol-renamed.zig; then echo 'FAIL unchanged protocol-name mutant' >&2; exit 1; fi +bash "$root/scripts/atoma-wrapper-capsule.sh" registry registry.zig registry_state.zig protocol-renamed.zig > Bad.v +if coqc -q Bad.v > "$out/reject-protocol-name.txt" 2>&1; then echo 'FAIL renamed protocol export accepted' >&2; exit 1; fi +grep -q 'Unable to unify' "$out/reject-protocol-name.txt" +sha256sum ./*.v ./*.zig > "$out/inputs.sha256" +cp ./*.zig "$out/" +echo 'WRAPPER SOURCE PASS: conditional frame and borrowed loop; machine pointer and foreign-call premises remain' diff --git a/tests/consumer-word/ownership-proven.pin b/tests/consumer-word/ownership-proven.pin new file mode 100644 index 0000000..32c9536 --- /dev/null +++ b/tests/consumer-word/ownership-proven.pin @@ -0,0 +1 @@ +ca8e1e07ad0777b723f15d2c59fdcd759d505c36 diff --git a/tests/consumer-word/ownership-uaa.pin b/tests/consumer-word/ownership-uaa.pin new file mode 100644 index 0000000..2239479 --- /dev/null +++ b/tests/consumer-word/ownership-uaa.pin @@ -0,0 +1 @@ +f4ff7b06f4b991d64a1577f5d41d8b2ffe78d914 diff --git a/verification/atoma/consumer/agda/WrapperEffects.agda b/verification/atoma/consumer/agda/WrapperEffects.agda new file mode 100644 index 0000000..ef6b128 --- /dev/null +++ b/verification/atoma/consumer/agda/WrapperEffects.agda @@ -0,0 +1,65 @@ +-- SPDX-License-Identifier: MPL-2.0 +{-# OPTIONS --safe --without-K --cubical-compatible #-} +module WrapperEffects where +open import Agda.Builtin.Bool +open import Agda.Builtin.List +open import Agda.Builtin.Equality + +record Registry (A : Set) : Set where + constructor registry + field + rest mcp : A + active : Bool +open Registry public + +finish : {A : Set} → Registry A → Registry A +finish s = registry (rest s) (mcp s) false + +-- A normal callback can modify its disjoint context. Its registry projection +-- must be unchanged; pointer validity and exclusive access are premises. +record FramedReturn {A : Set} (before : Registry A) : Set where + constructor returned + field + after : Registry A + frame : after ≡ before +open FramedReturn public + +normal-return-frame : {A : Set} (r m : A) (out : FramedReturn (registry r m true)) → + finish (after out) ≡ registry r m false +normal-return-frame r m (returned .(registry r m true) refl) = refl + +invalid-span-cleanup : {A : Set} (r m : A) → + finish (registry r m true) ≡ registry r m false +invalid-span-cleanup r m = refl + +-- Explicit counterexample when a raw alias changes the other endpoint. +alias-counterexample : finish (registry false true true) ≡ registry false true false +alias-counterexample = refl + +data Empty : Set where +alias-breaks-frame : finish (registry false true true) ≡ registry true true false → Empty +alias-breaks-frame () + +fold : {B : Set} → (Bool → B → Bool) → Bool → List B → Bool +fold step s [] = s +fold step s (b ∷ bs) = fold step (step s b) bs + +data Checked : Set where + invalid : Checked + valid : Bool → Checked + +scan : {B : Set} → (Bool → B → Checked) → Bool → List B → Checked +scan step s [] = valid s +scan step s (b ∷ bs) with step s b +... | invalid = invalid +... | valid next = scan step next bs + +scan-refines-fold : {B : Set} (step : Bool → B → Bool) + (foreign : Bool → B → Checked) + (contract : ∀ s b → foreign s b ≡ valid (step s b)) → + ∀ s bs → scan foreign s bs ≡ valid (fold step s bs) +scan-refines-fold step foreign contract s [] = refl +scan-refines-fold step foreign contract s (b ∷ bs) + rewrite contract s b = scan-refines-fold step foreign contract (step s b) bs + +-- This is an effect/loop theorem, not a claim that a machine pointer is valid. diff --git a/verification/atoma/consumer/agda/WrapperEffectsCubical.agda b/verification/atoma/consumer/agda/WrapperEffectsCubical.agda new file mode 100644 index 0000000..7a24163 --- /dev/null +++ b/verification/atoma/consumer/agda/WrapperEffectsCubical.agda @@ -0,0 +1,18 @@ +-- SPDX-License-Identifier: MPL-2.0 +{-# OPTIONS --safe --cubical #-} +module WrapperEffectsCubical where +import WrapperEffects as W +open import Agda.Builtin.Bool +open import Agda.Builtin.Equality +open import Agda.Builtin.Cubical.Path using (PathP) + +toPath : {A : Set} {x y : A} → x ≡ y → PathP (λ _ → A) x y +toPath {x = x} refl _ = x + +cleanup-path : {A : Set} (r m : A) → + PathP (λ _ → W.Registry A) (W.finish (W.registry r m true)) (W.registry r m false) +cleanup-path r m = toPath (W.invalid-span-cleanup r m) + +normal-return-path : {A : Set} (r m : A) (out : W.FramedReturn (W.registry r m true)) → + PathP (λ _ → W.Registry A) (W.finish (W.after out)) (W.registry r m false) +normal-return-path r m out = toPath (W.normal-return-frame r m out) diff --git a/verification/atoma/consumer/coq/WrapperSource.v b/verification/atoma/consumer/coq/WrapperSource.v new file mode 100644 index 0000000..77967ae --- /dev/null +++ b/verification/atoma/consumer/coq/WrapperSource.v @@ -0,0 +1,278 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* Original-byte closed wrapper grammar. No claimed full Zig parser/compiler refinement. *) +From Coq Require Import List String Ascii Bool Arith ZArith Lia. +Require Import ScalarSource RegistrySource. +Import ListNotations. +Open Scope string_scope. +Open Scope nat_scope. +Open Scope list_scope. + +Fixpoint literal (fuel : nat) (xs : list nat) : option (string * list nat) := + match fuel, xs with + | S f, 34::rest => Some (EmptyString,rest) + | S f, c::rest => + if (32 <=? c) && (c Some (String (ascii_of_nat c) s,tail) | None => None end + else None + | _,_ => None end. +Fixpoint lex (fuel : nat) (xs : list nat) : option (list string) := + match xs with + | [] => Some [] + | c::rest => match fuel with + | O => None + | S f => if ScalarSource.white c then lex f rest else + match xs with + | 47::47::tail => lex f (ScalarSource.after_comment tail) + | _ => + let token := if Nat.eqb c 34 then + match literal (List.length rest) rest with + | Some (s,tail) => Some (String.append "quoted:" s,tail) | None => None end + else if ScalarSource.wordchar c then Some (ScalarSource.take_word xs) + else match xs with + | 61::61::tail => Some ("==",tail) + | 33::61::tail => Some ("!=",tail) + | 61::62::tail => Some ("=>",tail) + | _ => if existsb (Nat.eqb c) [40;41;58;123;125;59;64;44;61;63;46;42;33;91;93;124;62] + then Some (String (ascii_of_nat c) EmptyString,rest) else None end in + match token with + | Some (t,tail) => match lex f tail with Some ts => Some (t::ts) | None => None end + | None => None end + end + end end. +Definition tokenize (bytes : list nat) := + if forallb (fun c => Nat.ltb c 128) bytes then lex (List.length bytes) bytes else None. + +Record registry_program := CallProgram { + null_code : nat; busy_code : nat; tag_code : nat; + unsupported_code : nat; selected_code : nat; span_code : nat }. +Definition registry_canonical := CallProgram 4 6 2 11 11 4. +(* Literal prefixes are data interpreted by strip, avoiding enormous nested + string-pattern decision trees. Each operand is parsed from the actual source. *) +Fixpoint operands (chunks : list (list string)) (xs : list string) : option (list nat) := + match chunks with + | [] => None + | [last] => if RegistrySource.same last xs then Some [] else None + | prefix::rest => match RegistrySource.strip prefix xs with + | Some (text::tail) => match ScalarSource.decimal text, operands rest tail with + | Some n,Some ns => Some (n::ns) | _,_ => None end + | _ => None end + end. +Definition parse_call (ts : list string) : option registry_program := + match operands [["const";"registry";"=";"r";"orelse";"return"]; +[";";"if";"(";"registry";".";"active";")";"return"]; +[";";"if";"(";"!";"known";"(";"tag";")";")";"return"]; +[";";"const";"slot";":";"state";".";"Slot";"=";"switch";"(";"tag";")";"{";"1";"=>";".";"mcp";",";"9";"=>";".";"rest";",";"else";"=>";"return"]; +[",";"}";";";"const";"reply";"=";"state";".";"begin";"(";"Endpoint";",";"registry";".";"*";",";"slot";")";";";"if";"(";"reply";".";"status";"!=";"0";")";"return";"reply";".";"status";";";"const";"endpoint";"=";"reply";".";"selected";"orelse";"return"]; +[";";"registry";".";"*";"=";"reply";".";"next";";";"defer";"registry";".";"*";"=";"state";".";"finish";"(";"Endpoint";",";"registry";".";"*";")";";";"if";"(";"bytes";"==";"null";"and";"len";"!=";"0";")";"return"]; +[";";"const";"status";"=";"endpoint";".";"callback";"(";"endpoint";".";"context";",";"bytes";",";"len";")";";";"return";"state";".";"sanitize";"(";"status";")";";"]] ts with + | Some [a;b;c;d;e;f] => Some (CallProgram a b c d e f) + | _ => None end. +(* Imported names, callback ABI and surrounding declarations are closed. + Create/destroy/register/unregister are scoped as checked source closure, + not additional ownership/refinement theorems. *) +Definition registry_prefix := ["const";"std";"=";"@";"import";"(";"quoted:std";")";";";"const";"known";"=";"@";"import";"(";"quoted:protocol_tag.zig";")";".";"known";";";"const";"state";"=";"@";"import";"(";"quoted:registry_state.zig";")";";";"pub";"const";"Callback";"=";"*";"const";"fn";"(";"?";"*";"anyopaque";",";"?";"[";"*";"]";"const";"u8";",";"usize";")";"callconv";"(";".";"c";")";"c_int";";";"const";"Endpoint";"=";"struct";"{";"callback";":";"Callback";",";"context";":";"?";"*";"anyopaque";"}";";";"pub";"const";"Registry";"=";"state";".";"State";"(";"Endpoint";")";";"]. +Definition registry_signatures := [["pub";"export";"fn";"uaa_registry_create";"(";")";"?";"*";"Registry";"{"]; +["pub";"export";"fn";"uaa_registry_destroy";"(";"r";":";"?";"*";"Registry";")";"c_int";"{"]; +["pub";"export";"fn";"uaa_registry_register";"(";"r";":";"?";"*";"Registry";",";"tag";":";"u8";",";"callback";":";"?";"Callback";",";"context";":";"?";"*";"anyopaque";")";"c_int";"{"]; +["pub";"export";"fn";"uaa_registry_unregister";"(";"r";":";"?";"*";"Registry";",";"tag";":";"u8";")";"c_int";"{"]; +["pub";"export";"fn";"uaa_registry_call";"(";"r";":";"?";"*";"Registry";",";"tag";":";"u8";",";"bytes";":";"?";"[";"*";"]";"const";"u8";",";"len";":";"usize";")";"c_int";"{"]]. +Definition parse_registry (bytes : list nat) : option registry_program := + match tokenize bytes with + | Some ts => match RegistrySource.strip registry_prefix ts with + | Some tail => match RegistrySource.functions registry_signatures tail with + | Some [create;destroy;register;unregister;call] => + if RegistrySource.same create ["const";"r";"=";"std";".";"heap";".";"c_allocator";".";"create";"(";"Registry";")";"catch";"return";"null";";";"r";".";"*";"=";".";"{";"}";";";"return";"r";";"] && + RegistrySource.same destroy ["const";"registry";"=";"r";"orelse";"return";"4";";";"if";"(";"registry";".";"active";")";"return";"6";";";"std";".";"heap";".";"c_allocator";".";"destroy";"(";"registry";")";";";"return";"0";";"] && + RegistrySource.same register ["const";"registry";"=";"r";"orelse";"return";"4";";";"if";"(";"registry";".";"active";")";"return";"6";";";"if";"(";"!";"known";"(";"tag";")";")";"return";"2";";";"const";"slot";":";"state";".";"Slot";"=";"switch";"(";"tag";")";"{";"1";"=>";".";"mcp";",";"9";"=>";".";"rest";",";"else";"=>";"return";"11";",";"}";";";"const";"cb";"=";"callback";"orelse";"return";"4";";";"const";"reply";"=";"state";".";"register";"(";"Endpoint";",";"registry";".";"*";",";"slot";",";".";"{";".";"callback";"=";"cb";",";".";"context";"=";"context";"}";")";";";"registry";".";"*";"=";"reply";".";"next";";";"return";"reply";".";"status";";"] && + RegistrySource.same unregister ["const";"registry";"=";"r";"orelse";"return";"4";";";"if";"(";"registry";".";"active";")";"return";"6";";";"if";"(";"!";"known";"(";"tag";")";")";"return";"2";";";"const";"slot";":";"state";".";"Slot";"=";"switch";"(";"tag";")";"{";"1";"=>";".";"mcp";",";"9";"=>";".";"rest";",";"else";"=>";"return";"11";",";"}";";";"const";"reply";"=";"state";".";"unregister";"(";"Endpoint";",";"registry";".";"*";",";"slot";")";";";"registry";".";"*";"=";"reply";".";"next";";";"return";"reply";".";"status";";"] + then parse_call call else None + | _ => None end + | None => None end + | None => None end. + +Record header_program := HeaderProgram { initial_state : nat; maximum_state : nat; final_state : nat }. +Definition header_canonical := HeaderProgram 0 1 1. +Definition parse_scan (ts : list string) : option header_program := + match operands [["var";"state";":";"u8";"="]; +[";";"for";"(";"bytes";")";"|";"b";"|";"{";"const";"result";"=";"idris2_trampoline";"(";"Proven_SafeHeader_ByteKernel_headerStep";"(";"bits8";".";"encode";"(";"state";")";",";"bits8";".";"encode";"(";"b";")";")";")";";";"const";"next";"=";"try";"bits8";".";"decode";"(";"result";")";";";"if";"(";"next";">"]; +[")";"return";"error";".";"InvalidRefcResult";";";"state";"=";"next";";";"}";"return";"state";"=="]; +[";"]] ts with + | Some [i;m;f] => Some (HeaderProgram i m f) + | _ => None end. +Definition parse_header (bytes : list nat) : option header_program := + match tokenize bytes with + | Some ts => match RegistrySource.strip ["const";"bits8";"=";"@";"import";"(";"quoted:refc/bits8.zig";")";";";"extern";"fn";"Proven_SafeHeader_ByteKernel_headerStep";"(";"?";"*";"anyopaque";",";"?";"*";"anyopaque";")";"callconv";"(";".";"c";")";"?";"*";"anyopaque";";";"extern";"fn";"idris2_trampoline";"(";"?";"*";"anyopaque";")";"callconv";"(";".";"c";")";"?";"*";"anyopaque";";";"pub";"fn";"detect";"(";"bytes";":";"[";"]";"const";"u8";")";"error";"{";"InvalidRefcResult";"}";"!";"bool";"{"] ts with + | Some tail => match RegistrySource.body (List.length tail) 0 [] tail with + | Some (b,rest) => if RegistrySource.same rest ["test";"{";"_";"=";"bits8";";";"}"] then parse_scan b else None + | None => None end + | None => None end + | None => None end. +Definition registry_eq_dec (a b : registry_program) : {a=b}+{a<>b}. +Proof. decide equality; apply Nat.eq_dec. Defined. +Definition header_eq_dec (a b : header_program) : {a=b}+{a<>b}. +Proof. decide equality; apply Nat.eq_dec. Defined. +Definition check_registry bytes := match parse_registry bytes with + | Some p => if registry_eq_dec p registry_canonical then true else false | None => false end. +Definition check_header bytes := match parse_header bytes with + | Some p => if header_eq_dec p header_canonical then true else false | None => false end. +Lemma registry_bound : forall bytes, check_registry bytes = true -> parse_registry bytes = Some registry_canonical. +Proof. intros bytes H. unfold check_registry in H. destruct (parse_registry bytes) as [p|] eqn:E; [|discriminate]. + destruct (registry_eq_dec p registry_canonical); [now subst|discriminate]. Qed. +Lemma header_bound : forall bytes, check_header bytes = true -> parse_header bytes = Some header_canonical. +Proof. intros bytes H. unfold check_header in H. destruct (parse_header bytes) as [p|] eqn:E; [|discriminate]. + destruct (header_eq_dec p header_canonical); [now subst|discriminate]. Qed. + +(* A heap projection: this record is the registry allocation. The callback's + disjoint context may change freely; this projection must be preserved. + A live readable allocation and serialized access are external premises. *) +Definition observation A := (Z * RegistrySource.state A * option A)%type. +Definition outcome {A} (code : nat) (s : RegistrySource.state A) : observation A := + (Z.of_nat code,s,None). +Definition invoke {A} (p : registry_program) (s : RegistrySource.state A) + (slot : RegistrySource.slot) (span_shape_ok : bool) + (callback : A -> RegistrySource.state A -> RegistrySource.state A * Z) : observation A := + let reply := RegistrySource.begin RegistrySource.canonical s slot in + if negb (Nat.eqb (RegistrySource.status reply) 0) then outcome (RegistrySource.status reply) s else + match RegistrySource.selected reply with + | None => outcome (selected_code p) s + | Some endpoint => + let borrowed := RegistrySource.next reply in + if span_shape_ok then + let '(after,code) := callback endpoint borrowed in + (RegistrySource.sanitize RegistrySource.canonical code, + RegistrySource.finish RegistrySource.canonical after,Some endpoint) + else outcome (span_code p) (RegistrySource.finish RegistrySource.canonical borrowed) + end. +Definition registry_run {A} (p : registry_program) (present : bool) + (s : RegistrySource.state A) (tag : nat) (span_shape_ok : bool) callback : observation A := + if negb present then outcome (null_code p) s else + if RegistrySource.active s then outcome (busy_code p) s else + if negb ((1 <=? tag) && (tag <=? 9)) then outcome (tag_code p) s else + match tag with + | 1 => invoke p s RegistrySource.MCP span_shape_ok callback + | 9 => invoke p s RegistrySource.REST span_shape_ok callback + | _ => outcome (unsupported_code p) s end. +Definition final_registry {A} (out : observation A) := snd (fst out). +Definition callback_frames {A} (callback : A -> RegistrySource.state A -> RegistrySource.state A * Z) := forall (e : A) s, + fst (callback e s) = s. + +Lemma invoke_frames : forall A p (s : RegistrySource.state A) k valid callback, + RegistrySource.active s = false -> callback_frames callback -> + final_registry (invoke p s k valid callback) = s. +Proof. + intros A p [r m busy] k valid callback Hb Hframe. simpl in Hb. subst busy. + destruct k; unfold invoke, RegistrySource.begin, RegistrySource.get, + RegistrySource.canonical, RegistrySource.field_value; simpl; + destruct m as [em|]; try destruct r as [er|]; simpl; + try reflexivity; + destruct valid; simpl; try reflexivity; + match goal with + | |- context [callback ?e ?s] => specialize (Hframe e s); + destruct (callback e s) as [after code] eqn:E; simpl in Hframe; subst after + end; reflexivity. +Qed. +Theorem registry_normal_frame : forall bytes A present (s : RegistrySource.state A) tag valid callback, + check_registry bytes = true -> RegistrySource.active s = false -> + callback_frames callback -> + exists p, parse_registry bytes = Some p /\ + final_registry (registry_run p present s tag valid callback) = s. +Proof. + intros bytes A present s tag valid callback Hsource Hidle Hframe. + exists registry_canonical. split; [now apply registry_bound|]. + unfold registry_run. rewrite Hidle. destruct present; [|reflexivity]. + destruct ((1 <=? tag) && (tag <=? 9)); cbn [negb]; [|reflexivity]. + do 10 (destruct tag as [|tag]; try reflexivity; try (now apply invoke_frames)); reflexivity. +Qed. +Theorem busy_refuses : forall A p (s : RegistrySource.state A) tag valid callback, + RegistrySource.active s = true -> + registry_run p true s tag valid callback = outcome (busy_code p) s. +Proof. intros. unfold registry_run. simpl. now rewrite H. Qed. +Theorem no_callback_for_invalid_span : forall A p (s : RegistrySource.state A) k callback, + snd (invoke p s k false callback) = None. +Proof. + intros. unfold invoke. destruct (negb (Nat.eqb (RegistrySource.status (RegistrySource.begin RegistrySource.canonical s k)) 0)); [reflexivity|]. + destruct (RegistrySource.selected (RegistrySource.begin RegistrySource.canonical s k)); reflexivity. +Qed. +Example raw_alias_counterexample : + final_registry (registry_run registry_canonical true + (RegistrySource.State (Some 9) (Some 1) false) 1 true + (fun _ _ => (RegistrySource.State None (Some 1) true,7%Z))) = + RegistrySource.State None (Some 1) false. +Proof. reflexivity. Qed. + +(* Each loop iteration reads one element of the borrowed immutable list. The + foreign step has no heap authority here; that is an ASSUMED external call + contract, not a conclusion about arbitrary native code or the compiler. *) +Fixpoint scan (p : header_program) (step : nat -> nat -> option nat) + (state : nat) (bytes : list nat) : option nat := + match bytes with + | [] => Some state + | b::bs => match step state b with + | Some next => if next <=? maximum_state p then scan p step next bs else None + | None => None end + end. +Definition header_run p step bytes := + match scan p step (initial_state p) bytes with + | Some state => Some (Nat.eqb state (final_state p)) | None => None end. +Definition encode (s : bool) : nat := if s then 1 else 0. +Fixpoint fold (step : bool -> nat -> bool) (s : bool) (bytes : list nat) : bool := + match bytes with [] => s | b::bs => fold step (step s b) bs end. +Lemma scan_fold : forall (step : bool -> nat -> bool) foreign, + (forall s b, b < 256 -> foreign (encode s) b = Some (encode (step s b))) -> + forall bs s, Forall (fun b => b < 256) bs -> + scan header_canonical foreign (encode s) bs = Some (encode (fold step s bs)). +Proof. + intros step foreign H bs. induction bs as [|b bs IH]; intros s Hbytes; [reflexivity|]. + inversion Hbytes as [|b' bs' Hb Htail]; subst. + simpl. rewrite (H s b Hb). destruct (step s b) eqn:E; simpl; + [apply (IH true Htail)|apply (IH false Htail)]. +Qed. +Theorem header_source_fold : forall bytes step foreign bs, + check_header bytes = true -> + Forall (fun b => b < 256) bs -> + (forall s b, b < 256 -> foreign (encode s) b = Some (encode (step s b))) -> + exists p, parse_header bytes = Some p /\ + header_run p foreign bs = Some (fold step false bs). +Proof. + intros bytes step foreign bs Hsource Hbytes Hcall. exists header_canonical. + split; [now apply header_bound|]. unfold header_run. + change (match scan header_canonical foreign (encode false) bs with + | Some state => Some (Nat.eqb state 1) | None => None end = Some (fold step false bs)). + rewrite (scan_fold step foreign Hcall bs false Hbytes). destruct (fold step false bs); reflexivity. +Qed. +Fixpoint read_count (p : header_program) (step : nat -> nat -> option nat) + (state : nat) (bytes : list nat) : nat := match bytes with + | [] => 0 + | b::bs => S (match step state b with + | Some next => if next <=? maximum_state p then read_count p step next bs else 0 + | None => 0 end) end. +Theorem bounded_reads : forall p step bs s, read_count p step s bs <= List.length bs. +Proof. + intros p step bs. induction bs as [|b bs IH]; intro s; simpl; [lia|]. + destruct (step s b) as [next|]; [destruct (next <=? maximum_state p)|]; simpl; try lia. + specialize (IH next). lia. +Qed. +Theorem checked_state_bound : forall p step bs s out, + s <= maximum_state p -> scan p step s bs = Some out -> out <= maximum_state p. +Proof. + intros p step bs. induction bs as [|b bs IH]; intros s out Hbound Hrun. + - simpl in Hrun. inversion Hrun. subst. exact Hbound. + - simpl in Hrun. destruct (step s b) as [next|] eqn:E; [|discriminate]. + destruct (next <=? maximum_state p) eqn:Hnext; [|discriminate]. + apply Nat.leb_le in Hnext. now apply (IH next out). +Qed. +Print Assumptions registry_normal_frame. +Print Assumptions busy_refuses. +Print Assumptions no_callback_for_invalid_span. +Print Assumptions raw_alias_counterexample. +Print Assumptions header_source_fold. +Print Assumptions bounded_reads. +Print Assumptions checked_state_bound. + +Theorem raw_alias_breaks_frame : + final_registry (registry_run registry_canonical true + (RegistrySource.State (Some 9) (Some 1) false) 1 true + (fun _ _ => (RegistrySource.State None (Some 1) true,7%Z))) <> + RegistrySource.State (Some 9) (Some 1) false. +Proof. discriminate. Qed. +Print Assumptions raw_alias_breaks_frame. diff --git a/verification/atoma/consumer/lean4/WrapperEffects.lean b/verification/atoma/consumer/lean4/WrapperEffects.lean new file mode 100644 index 0000000..0ec6925 --- /dev/null +++ b/verification/atoma/consumer/lean4/WrapperEffects.lean @@ -0,0 +1,40 @@ +-- SPDX-License-Identifier: MPL-2.0 +namespace WrapperEffects +structure Registry (α : Type) where + rest : α + mcp : α + active : Bool +def finish (s : Registry α) : Registry α := ⟨s.rest, s.mcp, false⟩ +theorem normalReturnFrame (r m : α) (after : Registry α) + (frame : after = ⟨r, m, true⟩) : finish after = ⟨r, m, false⟩ := by + cases frame + rfl +theorem invalidSpanCleanup (r m : α) : finish (Registry.mk r m true) = ⟨r, m, false⟩ := rfl +theorem aliasCounterexample : finish (Registry.mk false true true) = ⟨false, true, false⟩ := rfl +theorem aliasBreaksFrame : finish (Registry.mk false true true) ≠ Registry.mk true true false := by + intro h + have bad := congrArg Registry.rest h + cases bad +def fold (step : Bool → β → Bool) (s : Bool) : List β → Bool + | [] => s + | b :: bs => fold step (step s b) bs +def scan (step : Bool → β → Option Bool) (s : Bool) : List β → Option Bool + | [] => some s + | b :: bs => match step s b with + | none => none + | some next => scan step next bs +theorem scanRefinesFold (step : Bool → β → Bool) (foreign : Bool → β → Option Bool) + (contract : ∀ s b, foreign s b = some (step s b)) (bs : List β) : + ∀ s, scan foreign s bs = some (fold step s bs) := by + induction bs with + | nil => intro s; rfl + | cons b bs ih => + intro s + simp only [scan, contract, fold] + exact ih (step s b) +#print axioms normalReturnFrame +#print axioms invalidSpanCleanup +#print axioms aliasCounterexample +#print axioms aliasBreaksFrame +#print axioms scanRefinesFold +end WrapperEffects