omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
GitHub aien-dev/omega-mv#448 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/adc732fcfa463b15.bundle -o adc732fcfa463b15.bundle git fetch adc732fcfa463b15.bundle refs/pull/448/head
Provenance
github-import 1
aien-dev/omega-mv
448
2842aa9544983098feb6efb5321155588c9467e9
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":448,"url":"https://github.com/aien-dev/omega-mv/pull/448","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:54Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 411fc0e88..9937a535e 100644 --- a/.crumb +++ b/.crumb @@ -63,8 +63,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "c6e66e6c62824d71b6b469316281c774dca08241921cefc18d31495f554cfcc7", - "last_commit": "d8273d6f", + "digest": "5f0f4cfb1ef5837569c712847c5f7c8c9c93fe1083a42b582cf2a9cbe27f4d3f", + "last_commit": "4fa52370", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -81,20 +81,20 @@ "purpose": "Directory research. Purpose not yet described by a human." }, { - "digest": "6f273bd316d4a2a8b932ef7d92ea3596b93be2fc0736a055acb111d94e44a8f2", - "last_commit": "e9943ed2", + "digest": "3d892a08078369eebc9a5e2a7ee2b6a24c278f2dbd91db5e7026decb8d8399f8", + "last_commit": "4fa52370", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "56899f232feaddd4ada1458f06aa49f3034d5fa6d52a1fa77f7ecde3cb3c23a2", - "last_commit": "d8273d6f", + "digest": "3b6e68a896d400c0805cc613b9af28ef6709f372a993ba22d48664d550c2557d", + "last_commit": "4fa52370", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "e678609e8a172112a41f3e6a204f6f5adf29aac13bc99fb7413fc89daf40ce6f", - "last_commit": "d8273d6f", + "digest": "51957489c42457c95a8f0c4c0820eebbc36621fd85d2f92624335f8656fe15e5", + "last_commit": "4fa52370", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, @@ -105,15 +105,15 @@ "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:c518c455c3e7cdeff242226266bd2483237361ab4b7c067dc2d620f2d994744d", - "compiled_at": "2026-10-14T17:50:29Z", + "children_root": "sha256:6aaa635cd81112488f715ab2ec322c87285530c08911dc46418ff11373b7a1a8", + "compiled_at": "2026-10-14T18:36:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:7755287f1df197b1ac1cbe651253b19d48bcd962f41341a6a60ddaadd76e6893", + "digest": "sha256:d1156cd6d48e531619a96e8158705760a85065dd0d03d705e80762765db96e6b", "evidence_files": 7338, "evidence_root": "sha256:35fd4dcec251643bc8056425a6b03acdae66c10a6e44d7eaa91761a260358a33", - "files": 9938, - "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", - "source_tree": "sha256:450f69ba47b39f2a65ad2b86e67e53605adec21690fd2da27547c313acd79715" + "files": 9995, + "generated_at_commit": "4fa52370f177d268e4248955dc7adec53519e215", + "source_tree": "sha256:66dbebfbb554c96a050dd707d23b1f9c72c0081ebe0e0d0fa97fdcd3b46d0432" }, "owner_lane": "", "provenance": { diff --git a/.github/workflows/host-suites.yml b/.github/workflows/host-suites.yml index ae2e3e2c4..644db4f60 100644 --- a/.github/workflows/host-suites.yml +++ b/.github/workflows/host-suites.yml @@ -98,12 +98,42 @@ on: - 'src/compiler/**' - 'tests/compiler/**' - 'mk/compiler.mk' + # checker2 + signed realization receipts (one-layer stage 3, omega#446); its differential + # and LRAT gate also run when the compiler, sha256 or the vendored Ed25519 change + - 'src/checker2/**' + - 'tests/checker2/**' + - 'mk/checker2.mk' + - 'spec/one-layer-receipts.md' concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + checker2: + # Independent checker2 (src/checker2), LRAT gate and receipts (spec/one-layer-receipts.md): + # plain + ASan/UBSan unit tests, black-box differential against oscc, 20-program LRAT gate, + # receipt signature tests, and the GUARD-line mutant negative controls. + runs-on: ubuntu-24.04-arm + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Changed-path guard (checker2 inputs only) + id: guard + run: | + if [ "${{ github.event_name }}" != "pull_request" ]; then echo "run=true" >> "$GITHUB_OUTPUT"; exit 0; fi + CHANGED=$(git diff --name-only HEAD^1 HEAD) + if echo "$CHANGED" | grep -Eq '^(src/checker2/|tests/checker2/|mk/checker2\.mk$|spec/one-layer-receipts\.md$|src/compiler/|tests/compiler/|mk/compiler\.mk$|src/sha256\.|src/searchtrace/sig/|\.github/workflows/host-suites\.yml$)'; then + echo "run=true" >> "$GITHUB_OUTPUT" + else + echo "run=false" >> "$GITHUB_OUTPUT"; echo "no checker2 inputs changed; skipping" + fi + - name: checker2 unit, differential, LRAT gate, receipts, mutants (plain + ASan/UBSan) + if: steps.guard.outputs.run == 'true' + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-checker2 + searchtrace: runs-on: ubuntu-24.04-arm timeout-minutes: 15 diff --git a/mk/.crumb b/mk/.crumb index 4018a9094..7b1643d29 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-14T17:50:29Z", + "compiled_at": "2026-10-14T18:36:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:c6e66e6c62824d71b6b469316281c774dca08241921cefc18d31495f554cfcc7", + "digest": "sha256:5f0f4cfb1ef5837569c712847c5f7c8c9c93fe1083a42b582cf2a9cbe27f4d3f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 69, - "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", - "source_tree": "sha256:cfdf2847f618856866730d8a3e70103ab7844e5e6ecce577f0d14b1241cee0ca" + "files": 70, + "generated_at_commit": "4fa52370f177d268e4248955dc7adec53519e215", + "source_tree": "sha256:1eb1827be8d0df76b1b76db2a0a6ea03b519f4fe9817f2c4e796feb213dd4761" }, "owner_lane": "", "provenance": { diff --git a/mk/checker2.mk b/mk/checker2.mk new file mode 100644 index 000000000..e9464a6d2 --- /dev/null +++ b/mk/checker2.mk @@ -0,0 +1,111 @@ +# One-layer stage 3 (omega#446): independent checker2 and signed realization receipts. +# Files: src/checker2/*, tests/checker2/*, spec/one-layer-receipts.md. Picked up by +# `-include mk/*.mk`; not part of `all` or `test`. checker2 links none of src/compiler/*.c: it +# includes no compiler header and shares no parser, evaluator or instruction table with oscc. +# Links only src/sha256.c and the vendored in-house Ed25519 (src/searchtrace/sig, PROVENANCE.txt). +# make checker2 build/checker2/checker2 +# make test-checker2 receipt, checker and LRAT tests (plain and ASan/UBSan), corpus + +# black-box differential against oscc, blaster semantics against oscc's +# compiled code (black box), then the mutant negative controls +# make test-checker2-mutants negative controls only: each GUARD line removed must fail a test +ifndef CHECKER2_MK +CHECKER2_MK := 1 +.PHONY: checker2 test-checker2 test-checker2-lrat test-checker2-unit test-checker2-mutants test-checker2-differential test-checker2-blast-native +C2_DIR = $(OUT_DIR)/checker2 +C2_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -Isrc/checker2 +C2_ASAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all +C2_SIG = src/searchtrace/sig/ed25519.c src/searchtrace/sig/sha512.c src/searchtrace/sig/ct.c +C2_RECEIPT = src/checker2/c2_receipt.c src/sha256.c $(C2_SIG) +C2_HDRS = $(wildcard src/checker2/*.h) src/sha256.h src/searchtrace/sig/aienos_sig.h src/searchtrace/sig/sig_internal.h + +C2_CORE = src/checker2/c2_ir.c src/checker2/c2_check.c src/checker2/c2_lrat.c src/checker2/c2_blast.c +# checker identity input (spec section 5): SHA-256 over the checker2 sources in a fixed order +C2_ID_SRCS = src/checker2/c2_ir.h src/checker2/c2_ir.c src/checker2/c2_check.c src/checker2/c2_receipt.h \ + src/checker2/c2_receipt.c src/checker2/c2_lrat.h src/checker2/c2_lrat.c src/checker2/c2_blast.h src/checker2/c2_blast.c \ + src/checker2/checker2_main.c +C2_SOURCES_SHA256 = $(shell cat $(C2_ID_SRCS) | sha256sum | cut -c1-64) +C2_IRDIR = $(C2_DIR)/differential/ir + +checker2: $(C2_DIR)/checker2 + +$(C2_DIR)/checker2: src/checker2/checker2_main.c $(C2_CORE) $(C2_RECEIPT) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -DC2_SOURCES_SHA256='"$(C2_SOURCES_SHA256)"' -o $@ src/checker2/checker2_main.c $(C2_CORE) $(C2_RECEIPT) + +# the same sources built under another checker identity: receipts it issues must be refused by +# checker2 unless that identity is accepted explicitly (lrat.sh, spec section 6 step 6) +$(C2_DIR)/checker2_other: src/checker2/checker2_main.c $(C2_CORE) $(C2_RECEIPT) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -DC2_SOURCES_SHA256='"other-checker-build-for-tests"' -o $@ src/checker2/checker2_main.c $(C2_CORE) $(C2_RECEIPT) + +$(C2_DIR)/test_c2_ir: tests/checker2/test_c2_ir.c $(C2_CORE) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -o $@ tests/checker2/test_c2_ir.c $(C2_CORE) + +$(C2_DIR)/test_c2_ir_asan: tests/checker2/test_c2_ir.c $(C2_CORE) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) $(C2_ASAN) -o $@ tests/checker2/test_c2_ir.c $(C2_CORE) + +# producer side, used only by the differential (links the producer library, never checker2) +# (own variables: mk/compiler.mk is included after this file, so its variables are empty here) +C2_PRODUCER_LIB = $(filter-out src/compiler/oscc_main.c,$(wildcard src/compiler/*.c)) src/sha256.c +$(C2_DIR)/osc_emit_ir: tests/checker2/producer/osc_emit_ir.c $(C2_PRODUCER_LIB) $(wildcard src/compiler/*.h) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS:-Isrc/checker2=-Isrc/compiler) -o $@ tests/checker2/producer/osc_emit_ir.c $(C2_PRODUCER_LIB) + +test-checker2-differential: $(OUT_DIR)/compiler/oscc $(C2_DIR)/osc_emit_ir $(C2_DIR)/checker2 + sh tests/checker2/differential.sh $(OUT_DIR)/compiler/oscc $(C2_DIR)/osc_emit_ir $(C2_DIR)/checker2 $(C2_DIR)/differential + +$(C2_DIR)/test_c2_receipt: tests/checker2/test_c2_receipt.c $(C2_RECEIPT) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -o $@ tests/checker2/test_c2_receipt.c $(C2_RECEIPT) + +$(C2_DIR)/test_c2_receipt_asan: tests/checker2/test_c2_receipt.c $(C2_RECEIPT) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) $(C2_ASAN) -o $@ tests/checker2/test_c2_receipt.c $(C2_RECEIPT) + +# untrusted SAT solver (not in the checker identity; every UNSAT answer is re-checked by c2_lrat) +$(C2_DIR)/c2sat: src/checker2/untrusted/c2sat.c + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -o $@ src/checker2/untrusted/c2sat.c + +$(C2_DIR)/test_c2_lrat: tests/checker2/test_c2_lrat.c src/checker2/c2_lrat.c $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -o $@ tests/checker2/test_c2_lrat.c src/checker2/c2_lrat.c + +$(C2_DIR)/test_c2_lrat_asan: tests/checker2/test_c2_lrat.c src/checker2/c2_lrat.c $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) $(C2_ASAN) -o $@ tests/checker2/test_c2_lrat.c src/checker2/c2_lrat.c + +$(C2_DIR)/test_c2_blast: tests/checker2/test_c2_blast.c $(C2_CORE) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -o $@ tests/checker2/test_c2_blast.c $(C2_CORE) + +# 20 bounded programs proved by bit-blasting + c2sat + checker2 LRAT replay, plus negative controls +test-checker2-lrat: $(C2_DIR)/osc_emit_ir $(C2_DIR)/checker2 $(C2_DIR)/checker2_other $(C2_DIR)/c2sat $(C2_DIR)/test_c2_lrat $(C2_DIR)/test_c2_lrat_asan $(C2_DIR)/test_c2_blast test-checker2-differential + ./$(C2_DIR)/test_c2_lrat + ./$(C2_DIR)/test_c2_lrat_asan + sh tests/checker2/lrat.sh $(C2_DIR)/osc_emit_ir $(C2_DIR)/checker2 $(C2_DIR)/c2sat $(C2_DIR)/lrat $(C2_DIR)/checker2_other + ./$(C2_DIR)/test_c2_blast $(C2_IRDIR) $(C2_DIR)/lrat + +# blaster semantics against oscc's compiled AArch64 code, run as a black box (no ASan build: +# the harness jumps into mapped machine code and leaves traps with siglongjmp) +$(C2_DIR)/test_c2_blast_native: tests/checker2/test_c2_blast_native.c $(C2_CORE) $(C2_HDRS) + @mkdir -p $(C2_DIR) + $(CC) $(C2_CFLAGS) -o $@ tests/checker2/test_c2_blast_native.c $(C2_CORE) + +test-checker2-blast-native: $(OUT_DIR)/compiler/oscc $(C2_DIR)/test_c2_blast_native + sh tests/checker2/blast_native.sh $(OUT_DIR)/compiler/oscc $(C2_DIR)/test_c2_blast_native $(C2_DIR)/blast_native + +test-checker2-unit: $(C2_DIR)/test_c2_receipt $(C2_DIR)/test_c2_receipt_asan $(C2_DIR)/test_c2_ir $(C2_DIR)/test_c2_ir_asan test-checker2-differential test-checker2-lrat test-checker2-blast-native + ./$(C2_DIR)/test_c2_receipt tests/checker2/fixtures + ./$(C2_DIR)/test_c2_receipt_asan tests/checker2/fixtures + ./$(C2_DIR)/test_c2_ir $(C2_IRDIR) + ./$(C2_DIR)/test_c2_ir_asan $(C2_IRDIR) + +test-checker2-mutants: test-checker2-differential test-checker2-lrat + sh tests/checker2/mutants.sh "$(CC)" "$(C2_DIR)/mutants" "$(C2_IRDIR)" "$(C2_DIR)/lrat" + +test-checker2: test-checker2-unit test-checker2-mutants + +endif diff --git a/spec/.crumb b/spec/.crumb index b1933c2b0..fc2d95592 100644 --- a/spec/.crumb +++ b/spec/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:6834a3241647d3a098283d4eafedbdb1428dfa4d834f9ed5f22025b6d2303093", - "compiled_at": "2026-10-14T17:37:01Z", + "compiled_at": "2026-10-14T18:36:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:6f273bd316d4a2a8b932ef7d92ea3596b93be2fc0736a055acb111d94e44a8f2", + "digest": "sha256:3d892a08078369eebc9a5e2a7ee2b6a24c278f2dbd91db5e7026decb8d8399f8", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 57, - "generated_at_commit": "e9943ed23f0712a7dd1f7248a7d6bb00eabf5ea5", - "source_tree": "sha256:ab760dc10a179ca9d6cc4ec94648609e54d9026c6d6c42d50026b0a941357cb6" + "files": 58, + "generated_at_commit": "4fa52370f177d268e4248955dc7adec53519e215", + "source_tree": "sha256:a1fb731468c43b20acfa4e5a2cde5e3adde0d6ab71b10aba4eaeadffcd2dfec0" }, "owner_lane": "", "provenance": { diff --git a/spec/one-layer-receipts.md b/spec/one-layer-receipts.md new file mode 100644 index 000000000..a4e36eb5f --- /dev/null +++ b/spec/one-layer-receipts.md @@ -0,0 +1,250 @@ +# One-layer receipts v1: signed Omega realization receipts (normative) + +Stage 3 of the one-layer plan (omega#446). Code: `src/checker2/` (receipts `c2_receipt.{h,c}`, +IR decoder `c2_ir.{h,c}`, acceptance rules `c2_check.c`, LRAT checker `c2_lrat.{h,c}`, bit-blaster +`c2_blast.{h,c}`, command line `checker2_main.c`). Tests: `make test-checker2` (section 12). +Pairs with aienos#383 (OSC unit admission), which must verify exactly these bytes. + +## 1. What a receipt says, and what it does not + +A receipt records that **checker2** (the independent checker in `src/checker2/`) judged one +exact set of bytes and accepted them, and that a key of a stated signer class vouches for that +record. The signature establishes provenance only. It never establishes correctness, and a +receipt grants no capability: aienos grants stay separate, revocable authority. + +A receipt is minted only by `checker2 receipt issue`, which runs checker2 on the program bytes +itself and refuses to sign when checker2 rejects. Nothing else in Omega writes receipts. + +## 2. Byte layout (416 bytes, little-endian, no padding, no text, no timestamps) + +| offset | size | field | +|---:|---:|---| +| 0 | 8 | magic `O M R C P T 1 \0` | +| 8 | 2 | format version, = 1 | +| 10 | 2 | signer class: 1 TEST, 2 OWNER (same numbers as aienos `OSC_SIGNER_TEST`/`OSC_SIGNER_OWNER`) | +| 12 | 2 | signature algorithm, = 1 (pure Ed25519, RFC 8032 section 5.1) | +| 14 | 2 | evidence class (section 4) | +| 16 | 32 | requirements: SHA-256 of the requirements object bytes (all zero: none supplied) | +| 48 | 32 | program: SHA-256 of the canonical program bytes (OSC IR; equals `oscc` `ir_sha256`) | +| 80 | 32 | executable: SHA-256 of the realized executable bytes (equals `oscc` `code_sha256`) | +| 112 | 32 | dependencies: SHA-256(`"OMEGA-RECEIPT-DEPS-V1\0"` ‖ u32 count ‖ receipt ids, strictly ascending) | +| 144 | 32 | checker: identity of the checker2 build (section 5) | +| 176 | 32 | producer checker: SHA-256 of the `oscc` binary that produced the bytes | +| 208 | 32 | target: SHA-256(`"OMEGA-TARGET-V1\0"` ‖ target name), e.g. `aarch64-linux-host` | +| 240 | 32 | firmware: SHA-256 of the firmware image; all zero = none (host) | +| 272 | 32 | input: SHA-256 of the input or dataset identity; all zero = none | +| 304 | 8 | policy epoch the receipt was issued under | +| 312 | 8 | expiry epoch: last epoch at which it is fresh; must be >= policy epoch | +| 320 | 32 | key fingerprint: SHA-256 of the signer's 32-byte Ed25519 public key | +| 352 | 64 | Ed25519 signature | + +"\0" is one zero byte, included in the hash. Receipt id = SHA-256 of all 416 bytes. Ed25519 +signatures are deterministic, so the same inputs and key always give the same receipt and id. + +## 3. Signature + +Signed message (65 bytes) = `"OMEGA-REALIZATION-RECEIPT-SIG-V1\0"` ‖ +SHA-256(`"OMEGA-REALIZATION-RECEIPT-V1\0"` ‖ bytes [0, 352)). + +The verifier takes the public key from its own anchor set for the receipt's class, matched by +fingerprint, never from the receipt (same rule as aienos `osc_unit_admit` step 13). + +### Keys + +- **OWNER** (class 2): Drake's owner root from the aienos#380 ceremony, + `578ada3cb0c2d154623ac089191023c8ad4bc5e63b8ccd1a38db2d679b8c9e76`, generated on a YubiKey + (PIV slot 9c). Compiled in as `c2r_owner_root_pk`. Omega never holds the private key: + `checker2 receipt tbs` writes the 65-byte message, the YubiKey signs it, and + `checker2 receipt attach` verifies and attaches the signature. The test suite proves the + constant is the ceremony key by verifying the real ceremony signature + (`tests/checker2/fixtures/owner/`, public data). +- **TEST** (class 1): seed = SHA-256(`"OMEGA-CHECKER2-TEST-KEY-v1 NOT FOR PRODUCTION"`), public + on purpose. `c2r_sign_test` signs with this key only and only TEST class. + +## 4. Evidence class + +| value | name | meaning | +|---:|---|---| +| 1 | IR_CHECKED | checker2 decoded the canonical program bytes and accepted them. The executable is bound by hash only; it is **not** translation-validated against the program. | +| 2 | IR_CHECKED_LRAT | as 1, plus a declared property proved by an LRAT certificate that checker2's own LRAT checker accepted | + +Any other value is refused. + +## 5. Checker identity + +`checker` = SHA-256(`C2_CHECKER_VERSION` including its terminating NUL ‖ the 64 lowercase hex +characters of SHA-256 over the concatenation of the checker2 sources in the fixed order of +`C2_ID_SRCS` in `mk/checker2.mk`). The sources include the IR decoder, the acceptance rules, the +LRAT checker, the bit-blaster, the receipt code and the command line; the untrusted solver +(`src/checker2/untrusted/`) is deliberately outside. `checker2 version` prints the version, +`sources_sha256` and `checker_id`. A changed checker gives a new identity. The verifier holds a list of +accepted checker identities in its policy (`C2ReceiptPolicy.checkers`); the list is required and an +empty list refuses every receipt. `checker2 receipt verify` accepts its own identity plus any given +with `--accept-checker`. + +## 6. Verification order and named reasons + +The verifier stops at the first failure and returns its reason. Codes are stable. + +1. Structure: `SIZE` (1, not exactly 416 bytes), `MAGIC` (2), `VERSION` (3), + `SIGNATURE_ALGORITHM` (4), `SIGNER_CLASS` (5), `EVIDENCE_CLASS` (6), `EPOCH_ORDER` (7). + Code 8 is unassigned. +2. Class policy: in production mode any class other than OWNER is `TEST_SIGNER_IN_PRODUCTION` + (9). The key must be in the anchor set of the receipt's class, else `UNTRUSTED_SIGNER` (10); + in production the only owner anchor honoured is the compiled-in owner root; a key anchored in + both classes is refused (`UNTRUSTED_SIGNER`). +3. Signature: `BAD_SIGNATURE` (11). +4. Revocation: receipt id, then signer key fingerprint, in the verifier's revocation lists: + `REVOKED` (12). +5. Freshness (epochs, no clock): policy epoch below the verifier's floor is a replay of a + superseded receipt, `STALE_EPOCH` (13); current epoch above expiry `EXPIRED` (14); current + epoch below the policy epoch `NOT_YET_VALID` (15). The window is inclusive at both ends. +6. Checker identity: the receipt's `checker` must be in the verifier's list of accepted checker + identities (section 5), else `UNTRUSTED_CHECKER` (22). The list is part of the policy and is + checked with or without expectations. +7. Binding to what is being admitted: `WRONG_TARGET` (16), `WRONG_FIRMWARE` (17), + `PROGRAM_MISMATCH` (18), `EXECUTABLE_MISMATCH` (19), `WRONG_PRODUCER` (23, producer checker + identity), `DEPENDENCIES_MISMATCH` (24, dependency digest). The dependency digest binds the + dependency receipt ids only: v1 does not fetch, resolve or verify the dependency receipts + themselves (section 11). + +`ARGUMENT` (20) and `KEY_CLASS` (21, signing refused) are tool and signing errors. + +The revocation lists, the epoch floor and the current epoch come from the admitting side's +policy (for aienos: its own authority), never from the receipt. + +## 7. Storage: content-addressed, never rewritten + +`checker2 receipt issue --out-dir D` writes `D/<id hex>.rcpt` with exclusive create. If the file +already exists with identical bytes the write is a no-op; any other existing content is an error, +never an overwrite. + +## 8. Command line + + checker2 check <unit.ir> + checker2 version + checker2 receipt issue <unit.ir> <exe> --target T --epoch E --expiry X + (--out-dir D | --owner-draft PATH) + [--firmware F] [--requirements R | --lrat FUNC=PROOF ...] + [--input I] [--producer P] [--dep ID ...] + checker2 receipt tbs <receipt> <out65> + checker2 receipt attach <receipt> <sig64> --out-dir D + checker2 receipt verify <receipt> <unit.ir> <exe> --target T --epoch E [--allow-test-key + [--producer P] [--dep ID ...] [--accept-checker ID ...]| --production] + [--floor N] [--firmware F] [--revoked-id ID ...] [--revoked-key FP ...] + [--lrat FUNC=PROOF ...] + checker2 prove-cnf <unit.ir> <func> <out.cnf> + checker2 prove-check <unit.ir> <func> <proof.lrat> + +Exit 0 accept or done, 1 reject or refused, 2 usage or I/O error. `issue` refuses to sign bytes +checker2 rejects. `verify` applies the production policy by default (fail closed): a TEST-class +receipt is refused as `TEST_SIGNER_IN_PRODUCTION` unless `--allow-test-key` is given, which only +qualification and test runs may do; `--production` states the default, and giving both is a usage +error. `--dep` ids must be strictly ascending (their digest is order-sensitive). `verify` always +compares the producer and dependency digests: no `--producer` means an all-zero producer and no +`--dep` means an empty dependency list, exactly what `issue` writes without them. + +Owner signing, without Omega ever holding the private key: `issue --owner-draft PATH` writes an +OWNER-class receipt with the owner root fingerprint and an all-zero signature; `tbs` writes the +65-byte message of section 3; Drake signs it on the YubiKey (PIV slot 9c); `attach` verifies the +signature against the compiled-in owner root and stores the signed receipt by id (section 7). + +## 9. What checker2 accepts, and what it was written from + +checker2 decodes the canonical OSC IR bytes itself and applies its own acceptance rules. It links +no file of `src/compiler/` and shares no parser, evaluator or instruction table with the producer +(oscc). Its sources were written from these inputs only; no existing checker implementation +(`src/compiler/osc_check.*` or any other) was read: + +- `src/compiler/osc_ir.h`: the IR data structures, opcodes, scalar kinds and trap codes + (lines 152 to 176); the encoder part of `src/compiler/osc_ir.c` (lines 537 to 729), read for the + exact byte layout only, as the IR format has no separate written specification; +- `src/compiler/osc_front.h` (front-end interface, used by the test producer only); +- `docs/osc/` (OSC-1 design, including the semantics in section 5 of `OSC-1-DESIGN.md`); +- `src/omega_receipt.h`, `src/omega_vc_bridge.h`, `src/searchtrace/sig/*.h`, `src/sha256.h`; +- aienos `osc_unit.c` (the admission side's receipt rules, step 13); +- the build files under `mk/`. + +Every rejection names a stable rule (`C2-*`, listed in `c2_check.c`). Acceptance requires, per +function: valid types and operands; well-formed control flow; every use defined on every path; +ownership, arena, pool and handle discipline (a may-set analysis that rejects definite errors); +every loop reducible and bounded by a guarded counter with a constant limit of at most 10^6. + +## 10. Evidence class 2: LRAT proofs + +Property `no-trap-except-requires` of a function F: for every argument value, a run of F that +passes its `requires` clauses ends without any trap (overflow, division, shift, cast, loop bound, +`ensures`, or an explicit trap). checker2 builds the CNF of "some argument reaches a trap" itself, +from the IR bytes (`c2_blast.h`: scalar functions only; calls, memory, division and signed right +shift are refused, never approximated). The solver (`src/checker2/untrusted/c2sat.c`) is +untrusted and outside the checker identity. An UNSAT answer counts only when checker2's own LRAT +checker (`c2_lrat.h`: RUP steps only, RAT hints refused, the empty clause required, +clause ids at most input clauses plus proof lines so a huge id cannot size its tables) accepts the +proof against the CNF checker2 rebuilt. + +With `--lrat FUNC=PROOF` (functions strictly ascending), `issue` checks every proof and sets +evidence class 2 with `requirements` = SHA-256 of the requirements object: + + OMEGA-REQUIREMENTS-V1\n + no-trap-except-requires <FUNC> proof_sha256=<64 hex>\n (one line per proof) + +`verify` replays: a class 2 receipt is valid only when the same proofs are given, each checks +against the IR bytes, and the rebuilt object hashes to `requirements`. Reasons: `LRAT-PROOFS-REQUIRED`, +`LRAT-REPLAY-FAILED`, `LRAT-REQUIREMENTS-MISMATCH`, and `LRAT-NOT-CLAIMED` (proofs offered for a +class 1 receipt). Proofs are deterministic: the solver writes byte-identical proofs on every run. + +## 11. Not covered (open) + +- Translation validation of the executable against the program (plan section 3) is not done; + evidence classes 1 and 2 say so in their definitions. +- Production acceptance of an OWNER receipt is tested only in its refusals; a positive production + case needs one receipt signed on Drake's YubiKey (owner presence, decision D3). UNVERIFIED + until then. +- The admission side (aienos#383) is separate work and must verify exactly these bytes. +- Dependency receipts are not resolved in v1: the `dependencies` digest binds their ids, and a + verifier can require the expected ids (`DEPENDENCIES_MISMATCH`), but no verifier fetches the + dependency receipts or checks their validity, class or freshness. UNVERIFIED for any chain. +- `src/omega_vc_bridge.h` still self-mints HOST_TEST receipts. That route admits OmegaProgram + programs (`omega_program_ir.h`), not OSC IR, and records an aien-proof EvidenceReceiptV1 + (`src/omega_receipt.h`, contract owned by aien-protocols). Replacing it needs checker2 to judge + that IR (or those programs to arrive as OSC) and a change to that shared contract; neither is + in this change. +- A differential of the planted IR defects against the producer's checker needs an IR-bytes entry + point on the producer side (omega#444); until then those 96 defects are judged by checker2 only. +- Bit-blaster semantics are cross-checked against oscc's compiled AArch64 code (section 12, + `blast_native.sh`), not against an independent reference interpreter. Agreement shows checker2's + CNF and the producer's back end read section 5 of OSC-1-DESIGN the same way; a misreading shared + by both would pass. Operands wider than 16 bits are checked on edge values and samples, not + exhaustively; gate programs are compared on trap or no trap only, not on return values. UNVERIFIED + beyond those inputs. + +## 12. Tests + +`make test-checker2` (CI job `checker2` in `.github/workflows/host-suites.yml`): + +- `test_c2_receipt` (plain and ASan/UBSan): signing, every named refusal, tampered bytes, wrong + key, TEST key in production mode, checker identity not in the policy list (and an empty list), + wrong producer and dependency digests, the real owner ceremony signature; +- `differential.sh`: every OSC unit in the repo plus 48 generated units, oscc run as a black box; + both must accept the same 107 units with identical bytes, and the known-bad units must be + refused (138 by the front end); +- `test_c2_ir` (plain and ASan/UBSan): 107 units re-encode identically, every truncation refused, + bit flips never crash, 96 planted defects each refused by its exact rule; +- `test_c2_lrat` (plain and ASan/UBSan): hand-written LRAT cases, each refusal by its exact rule + (including a huge clause id refused as `LRAT-ID-RANGE` without a large allocation), 20000 + corrupted proofs never verify a satisfiable formula; +- `lrat.sh`: 20 bounded programs proved and replayed, 9 trap programs found to trap, 56 receipt and + proof controls (corrupted, substituted or misapplied proofs and receipts refused, including a + TEST receipt under the default production policy, a receipt from another checker identity unless + accepted with `--accept-checker`, and a wrong producer or dependency digest); +- `test_c2_blast`: non-scalar functions refused; every gate program evaluated input by input + without a solver (exhaustive to 16 argument bits), agreeing with its expectation; +- `blast_native.sh` + `test_c2_blast_native` (AArch64 host): 180 one-operation programs (every + blastable operation, comparison, cast pair and unary operation on every integer type and bool) and + the 29 gate programs, compiled by oscc as a black box; for every input (exhaustive to 16 operand + bits, else edge values and 3000 samples) checker2's CNF must agree with the compiled code on the + trap and, through an `ensures result != c` probe, on the exact result value; 8 negative controls + (the CNF of one operation against the code of another) must disagree; +- `mutants.sh`: each line tagged `GUARD:<name>` in the receipt code, decoder, acceptance rules, + LRAT checker and bit-blaster is removed in turn; a test must fail every time (104 of 104); the script also refuses a tag count that differs + from the mutant count. diff --git a/src/.crumb b/src/.crumb index 5cdfd73d1..338a74082 100644 --- a/src/.crumb +++ b/src/.crumb @@ -80,7 +80,7 @@ }, { "digest": "bdc017bf3baddb9034478651fb3f170f045ce8aa27187481d15ac5da7fbfd18c", - "last_commit": "f77bfef7", + "last_commit": "1edf41a5", "name": "compiler", "purpose": "Directory src/compiler. Purpose not yet described by a human." }, @@ -182,14 +182,14 @@ } ], "children_root": "sha256:93f32e91c5b498226d6ef4a040e3fbd2873dfb1f8b2405c26ea63b3a63df5f22", - "compiled_at": "2026-10-14T17:50:29Z", + "compiled_at": "2026-10-14T18:36:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:56899f232feaddd4ada1458f06aa49f3034d5fa6d52a1fa77f7ecde3cb3c23a2", + "digest": "sha256:3b6e68a896d400c0805cc613b9af28ef6709f372a993ba22d48664d550c2557d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 463, - "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", - "source_tree": "sha256:0d9c3cd9dd847013894fb41a508baf5827bd9e3b8019390b6ec5bf51110ee702" + "files": 474, + "generated_at_commit": "4fa52370f177d268e4248955dc7adec53519e215", + "source_tree": "sha256:bef71447164a7d4e733a93ff8c4d1d0619feccead590b0f9c990cde6a1d756e3" }, "owner_lane": "", "provenance": { diff --git a/src/checker2/c2_blast.c b/src/checker2/c2_blast.c new file mode 100644 index 000000000..b9264eea3 --- /dev/null +++ b/src/checker2/c2_blast.c @@ -0,0 +1,423 @@ +/* c2_blast.c: symbolic execution of one IR function into CNF (see c2_blast.h). */ +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_blast.h" + +#define T 1 +#define F (-1) +#define MAXW 128 + +typedef struct { + C2Cnf *cnf; + int nvars; + int oom; +} Bl; + +static int newvar(Bl *b) { return ++b->nvars; } +static void clause(Bl *b, int n, ...) +{ + int32_t l[4]; + va_list ap; + va_start(ap, n); + for (int k = 0; k < n; k++) l[k] = va_arg(ap, int); + va_end(ap); + if (c2_cnf_add(b->cnf, l, n)) b->oom = 1; +} + +static int AND(Bl *b, int x, int y) +{ + if (x == F || y == F || x == -y) return F; + if (x == T) return y; + if (y == T || x == y) return x; + int v = newvar(b); + clause(b, 2, -v, x); + clause(b, 2, -v, y); + clause(b, 3, v, -x, -y); + return v; +} +static int OR(Bl *b, int x, int y) { return -AND(b, -x, -y); } +static int XOR(Bl *b, int x, int y) +{ + if (x == F) return y; + if (y == F) return x; + if (x == T) return -y; + if (y == T) return -x; + if (x == y) return F; + if (x == -y) return T; + int v = newvar(b); + clause(b, 3, -v, x, y); + clause(b, 3, -v, -x, -y); + clause(b, 3, v, -x, y); + clause(b, 3, v, x, -y); + return v; +} +static int MUX(Bl *b, int s, int x, int y) /* s ? x : y */ +{ + if (s == T || x == y) return x; + if (s == F) return y; + return OR(b, AND(b, s, x), AND(b, -s, y)); +} + +/* ------------------------------------------------------------------ bit vectors */ + +static void add(Bl *b, const int *x, const int *y, int cin, int w, int *out, int *cout) +{ + int c = cin; /* out may alias x or y: read bit i of both before writing out[i] */ + for (int i = 0; i < w; i++) { + int p = XOR(b, x[i], y[i]), g = AND(b, x[i], y[i]); + out[i] = XOR(b, p, c); + c = OR(b, g, AND(b, c, p)); + } + if (cout) *cout = c; +} +static void neg_bits(const int *x, int w, int *o) { for (int i = 0; i < w; i++) o[i] = -x[i]; } +static int eq(Bl *b, const int *x, const int *y, int w) +{ + int r = T; + for (int i = 0; i < w; i++) r = AND(b, r, -XOR(b, x[i], y[i])); + return r; +} +static int ult(Bl *b, const int *x, const int *y, int w) /* x < y unsigned: no carry out of x + ~y + 1 */ +{ + int ny[MAXW], s[MAXW], c; + neg_bits(y, w, ny); + add(b, x, ny, T, w, s, &c); + return -c; +} +static int slt(Bl *b, const int *x, const int *y, int w) +{ + int fx[MAXW], fy[MAXW]; + memcpy(fx, x, (size_t)w * sizeof *x); + memcpy(fy, y, (size_t)w * sizeof *y); + fx[w - 1] = -x[w - 1]; + fy[w - 1] = -y[w - 1]; + return ult(b, fx, fy, w); +} +static void mul(Bl *b, const int *x, const int *y, int w, int *out) +{ + int acc[MAXW], part[MAXW]; + for (int i = 0; i < w; i++) acc[i] = F; + for (int i = 0; i < w; i++) { + for (int k = 0; k < w; k++) part[k] = k < i ? F : AND(b, y[i], x[k - i]); + add(b, acc, part, F, w, acc, NULL); + } + memcpy(out, acc, (size_t)w * sizeof *acc); +} +static int all_equal(Bl *b, const int *x, int lo, int hi) /* x[lo..hi] all equal */ +{ + int r = T; + for (int i = lo + 1; i <= hi; i++) r = AND(b, r, -XOR(b, x[i], x[lo])); + return r; +} + +/* ------------------------------------------------------------------ types */ + +static int width(uint8_t s) +{ + static const int w[] = {0, 1, 8, 16, 32, 64, 8, 16, 32, 64}; + return s <= S_I64 ? w[s] : 0; +} +static int is_signed(uint8_t s) { return s >= S_I8 && s <= S_I64; } +static int log2w(int w) { int k = 0; while ((1 << k) < w) k++; return k; } + +/* ------------------------------------------------------------------ symbolic execution */ + +typedef struct { + int block; + int guard; + int **reg; /* nvregs pointers into the value pool (values are immutable once built) */ +} St; + +typedef struct { + Bl b; + const C2Unit *u; + const C2Func *f; + C2BlastInfo *info; + int **pool; /* every allocated value, freed at the end */ + long npool, cappool; + int32_t *bad; + int nbad, capbad; + long steps; +} Ex; + +static int *val(Ex *x, int w) +{ + if (x->npool == x->cappool) { + x->cappool = x->cappool ? x->cappool * 2 : 1024; + int **np = realloc(x->pool, (size_t)x->cappool * sizeof *np); + if (!np) { x->b.oom = 1; return NULL; } + x->pool = np; + } + int *v = calloc((size_t)(w ? w : 1), sizeof *v); + if (!v) { x->b.oom = 1; return NULL; } + x->pool[x->npool++] = v; + return v; +} + +static int refuse(Ex *x, const char *rule, const char *fmt, ...) +{ + x->info->rule = rule; + va_list ap; + va_start(ap, fmt); + vsnprintf(x->info->detail, sizeof x->info->detail, fmt, ap); + va_end(ap); + return -1; +} + +/* a trap can fire on this path when cond holds: record it, return the guard of the run going on */ +static int trap_if(Ex *x, int g, int cond) +{ + int t = AND(&x->b, g, cond); + if (t != F) { + if (x->nbad == x->capbad) { + x->capbad = x->capbad ? x->capbad * 2 : 64; + int32_t *nb = realloc(x->bad, (size_t)x->capbad * sizeof *nb); + if (!nb) { x->b.oom = 1; return F; } + x->bad = nb; + } + x->bad[x->nbad++] = t; + } + return AND(&x->b, g, -cond); +} + +/* run one path to its end; forks are pushed on the stack */ +static int run(Ex *x, St *s, St *stack, int *sp) +{ + const C2Func *f = x->f; + Bl *b = &x->b; + for (;;) { + const C2Block *bk = &f->blk[s->block]; + for (uint32_t i = bk->first; i < bk->first + bk->count; i++) { + const C2Insn *in = &f->in[i]; + if (++x->steps > C2_BLAST_MAX_STEPS) return refuse(x, "BLAST-TOO-LARGE", "more than %ld steps", C2_BLAST_MAX_STEPS); + if (b->oom) return refuse(x, "BLAST-RESOURCE", "out of memory"); + const C2Type *td = in->dst >= 0 ? &f->vt[in->dst] : NULL; + const C2Type *ta = in->a >= 0 ? &f->vt[in->a] : NULL; + int w = td ? width(td->s) : 0; + int *r = NULL; + switch (in->op) { + case C2_CONST: + r = val(x, w); + for (int k = 0; r && k < w; k++) r[k] = (in->imm >> k) & 1 ? T : F; + break; + case C2_MOV: + s->reg[in->dst] = s->reg[in->a]; + continue; + case C2_BIN: { + const int *A = s->reg[in->a], *B = s->reg[in->b]; + int sg = is_signed(td->s); + r = val(x, w); + if (!r) break; + switch (in->sub) { + case B_ADD: case B_SUB: { + int nb[MAXW]; + if (in->sub == B_SUB) neg_bits(B, w, nb); else memcpy(nb, B, (size_t)w * sizeof *nb); + add(b, A, nb, in->sub == B_SUB ? T : F, w, r, NULL); + if (sg) { /* overflow: operands (after negation for SUB) agree in sign, result differs */ + int same = in->sub == B_ADD ? -XOR(b, A[w - 1], B[w - 1]) : XOR(b, A[w - 1], B[w - 1]); + s->guard = trap_if(x, s->guard, AND(b, same, XOR(b, r[w - 1], A[w - 1]))); /* GUARD:add-sub-overflow */ + } + break; + } + case B_MUL: + if (!sg) { mul(b, A, B, w, r); break; } + { + int ax[MAXW], bx[MAXW], p[MAXW]; + for (int k = 0; k < 2 * w; k++) { ax[k] = A[k < w ? k : w - 1]; bx[k] = B[k < w ? k : w - 1]; } + mul(b, ax, bx, 2 * w, p); + memcpy(r, p, (size_t)w * sizeof *r); + s->guard = trap_if(x, s->guard, -all_equal(b, p, w - 1, 2 * w - 1)); /* GUARD:mul-overflow */ + } + break; + case B_AND: for (int k = 0; k < w; k++) r[k] = AND(b, A[k], B[k]); break; + case B_OR: for (int k = 0; k < w; k++) r[k] = OR(b, A[k], B[k]); break; + case B_XOR: for (int k = 0; k < w; k++) r[k] = XOR(b, A[k], B[k]); break; + case B_SHL: case B_SHR: { + if (in->sub == B_SHR && sg) return refuse(x, "BLAST-UNSUPPORTED", "SHR on a signed operand (insn %u)", i); + int wb = width(f->vt[in->b].s), lg = log2w(w); + int big = F; /* amount >= w, or negative (sign bit of a signed amount) */ + for (int k = lg; k < wb; k++) big = OR(b, big, B[k]); + s->guard = trap_if(x, s->guard, big); /* GUARD:shift-range */ + int cur[MAXW], nxt[MAXW]; + memcpy(cur, A, (size_t)w * sizeof *cur); + for (int j = 0; j < lg && j < wb; j++) { + int sh = 1 << j; + for (int k = 0; k < w; k++) { + int from = in->sub == B_SHL ? k - sh : k + sh; + int moved = from >= 0 && from < w ? cur[from] : F; + nxt[k] = MUX(b, B[j], moved, cur[k]); + } + memcpy(cur, nxt, (size_t)w * sizeof *cur); + } + memcpy(r, cur, (size_t)w * sizeof *r); + if (in->sub == B_SHL && sg) { /* a << k representable iff a[w-1-k .. w-1] all equal */ + int ovf = F; + for (int k = 1; k < w; k++) { + int amt = T; + for (int j = 0; j < lg; j++) amt = AND(b, amt, (k >> j) & 1 ? B[j] : -B[j]); + ovf = OR(b, ovf, AND(b, amt, -all_equal(b, A, w - 1 - k, w - 1))); + } + s->guard = trap_if(x, s->guard, ovf); /* GUARD:shl-overflow */ + } + break; + } + default: return refuse(x, "BLAST-UNSUPPORTED", "binary op %u (insn %u)", in->sub, i); + } + break; + } + case C2_UN: { + const int *A = s->reg[in->a]; + r = val(x, w); + if (!r) break; + if (in->sub == U_NEG) { + int zero[MAXW], na[MAXW]; + for (int k = 0; k < w; k++) zero[k] = F; + neg_bits(A, w, na); + add(b, zero, na, T, w, r, NULL); + if (is_signed(td->s)) { /* -MIN is not representable */ + int min = A[w - 1]; + for (int k = 0; k < w - 1; k++) min = AND(b, min, -A[k]); + s->guard = trap_if(x, s->guard, min); /* GUARD:neg-overflow */ + } + } else if (in->sub == U_BNOT) neg_bits(A, w, r); + else r[0] = -A[0]; + break; + } + case C2_CMP: { + const int *A = s->reg[in->a], *B = s->reg[in->b]; + int wa = width(ta->s), sg = is_signed(ta->s); + int lt = sg ? slt(b, A, B, wa) : ult(b, A, B, wa); + int gt = sg ? slt(b, B, A, wa) : ult(b, B, A, wa); + int e = eq(b, A, B, wa), c; + switch (in->sub) { + case CC_EQ: c = e; break; + case CC_NE: c = -e; break; + case CC_LT: c = lt; break; + case CC_LE: c = -gt; break; + case CC_GT: c = gt; break; + default: c = -lt; break; /* CC_GE */ + } + r = val(x, 1); + if (r) r[0] = c; + break; + } + case C2_CAST: { + const int *A = s->reg[in->a]; + int ws = width(ta->s), wt = w, W = (ws > wt ? ws : wt) + 1; + int ext[MAXW + 1]; + for (int k = 0; k < W; k++) ext[k] = k < ws ? A[k] : (is_signed(ta->s) ? A[ws - 1] : F); + int fill = is_signed(td->s) ? ext[wt - 1] : F, fits = T; + for (int k = wt; k < W; k++) fits = AND(b, fits, -XOR(b, ext[k], fill)); + s->guard = trap_if(x, s->guard, -fits); /* GUARD:cast-range */ + r = val(x, wt); + if (r) memcpy(r, ext, (size_t)wt * sizeof *r); + break; + } + case C2_TRAP: + if (in->imm != 9) (void)trap_if(x, s->guard, T); /* 9 = REQUIRES: the caller's fault; GUARD:trap-insn */ + return 0; + case C2_RET: + return 0; + case C2_BR: + s->block = in->t; + goto next_block; + case C2_CBR: { + int c = s->reg[in->a][0]; + int gt = AND(b, s->guard, c), gf = AND(b, s->guard, -c); + if (gt != F && gf != F) { + if (x->info->paths >= C2_BLAST_MAX_PATHS) return refuse(x, "BLAST-TOO-LARGE", "more than %d paths", C2_BLAST_MAX_PATHS); + St *o = &stack[(*sp)++]; + o->block = in->f; + o->guard = gf; + o->reg = malloc((size_t)f->nvregs * sizeof *o->reg); + if (!o->reg) return refuse(x, "BLAST-RESOURCE", "out of memory"); + memcpy(o->reg, s->reg, (size_t)f->nvregs * sizeof *o->reg); + x->info->paths++; + } + if (gt == F && gf == F) return 0; + s->block = gt != F ? in->t : in->f; + s->guard = gt != F ? gt : gf; + goto next_block; + } + default: + return refuse(x, "BLAST-UNSUPPORTED", "opcode %u (insn %u)", in->op, i); + } + if (!r) return refuse(x, "BLAST-RESOURCE", "out of memory"); + s->reg[in->dst] = r; + if (s->guard == F) return 0; /* every run of this path has trapped */ + } + return refuse(x, "BLAST-UNSUPPORTED", "block %d falls through", s->block); + next_block:; + } +} + +int c2_func_index(const C2Unit *u, const char *name) +{ + for (int i = 0; i < u->nfuncs; i++) + if (strcmp(u->fn[i].name, name) == 0) return i; + return -1; +} + +int c2_blast_notrap(const C2Unit *u, int fi, C2Cnf *cnf, C2BlastInfo *info) +{ + memset(cnf, 0, sizeof *cnf); + memset(info, 0, sizeof *info); + info->rule = "BLAST-OK"; + C2Verdict v; + if (c2_check_unit(u, &v)) { + info->rule = "BLAST-UNIT-REJECTED"; + snprintf(info->detail, sizeof info->detail, "%s", v.rule); + return -1; + } + if (fi < 0 || fi >= u->nfuncs) { info->rule = "BLAST-NO-FUNCTION"; return -1; } + const C2Func *f = &u->fn[fi]; + Ex x; + memset(&x, 0, sizeof x); + x.b.cnf = cnf; + x.u = u; + x.f = f; + x.info = info; + int rc = -1; + St *stack = calloc(C2_BLAST_MAX_PATHS + 1, sizeof *stack); + St s = {0, T, calloc((size_t)f->nvregs + 1, sizeof(int *))}; + int sp = 0; + if (!stack || !s.reg) { refuse(&x, "BLAST-RESOURCE", "out of memory"); goto out; } + for (int r = 0; r < f->nvregs; r++) + if (!(f->vt[r].s >= S_BOOL && f->vt[r].s <= S_I64)) { refuse(&x, "BLAST-UNSUPPORTED", "register v%d is not a scalar", r); goto out; } /* GUARD:blast-scalar-only */ + /* variable 1 is TRUE; argument bits are variables 2..inputs+1 */ + x.b.nvars = 1; + clause(&x.b, 1, T); + for (int r = 0; r < f->nparams; r++) { + int w = width(f->vt[r].s); + int *p = val(&x, w); + if (!p) { refuse(&x, "BLAST-RESOURCE", "out of memory"); goto out; } + for (int k = 0; k < w; k++) p[k] = newvar(&x.b); + s.reg[r] = p; + info->inputs += w; + } + info->paths = 1; + if (run(&x, &s, stack, &sp)) goto out; + while (sp > 0) { + St o = stack[--sp]; + int e = run(&x, &o, stack, &sp); + free(o.reg); + if (e) goto out; + } + /* some trap fires: OR of all trap sites (no site: the empty clause, unsatisfiable at once) */ + info->trap_sites = x.nbad; + if (c2_cnf_add(cnf, x.bad, x.nbad) || x.b.oom) { refuse(&x, "BLAST-RESOURCE", "out of memory"); goto out; } + cnf->nvars = x.b.nvars; + rc = 0; +out: + while (sp > 0) free(stack[--sp].reg); + free(stack); + free(s.reg); + for (long i = 0; i < x.npool; i++) free(x.pool[i]); + free(x.pool); + free(x.bad); + if (rc) c2_cnf_free(cnf); + return rc; +} diff --git a/src/checker2/c2_blast.h b/src/checker2/c2_blast.h new file mode 100644 index 000000000..239217c04 --- /dev/null +++ b/src/checker2/c2_blast.h @@ -0,0 +1,44 @@ +/* c2_blast: checker2's bit-blaster for bounded integer programs (omega#446). + * + * Property NO-TRAP for function F of a unit checker2 has accepted: + * for every argument value, a run of F that passes its `requires` clauses (trap code 9 is the + * caller's fault, OSC-2) ends without any trap: no overflow, shift, cast, loop-bound or + * `ensures` (code 10) trap, and no explicit TRAP instruction is reached. + * The CNF is satisfiable exactly when some argument value reaches such a trap, so an LRAT proof + * of unsatisfiability, accepted by c2_lrat_check, proves the property. + * + * Semantics bit-blasted (docs/osc/OSC-1-DESIGN.md section 5): unsigned results reduce modulo 2^w; + * signed ADD/SUB/MUL/NEG/SHL trap OVERFLOW when the result is not representable; a shift amount + * outside 0..w-1 traps SHIFT; CAST traps CAST when the value is not representable in the target; + * CMP is signed for signed operands; bool is one bit. + * + * Supported subset (anything else is refused, never approximated): scalar parameters and + * registers only; CONST MOV BIN(ADD SUB MUL AND OR XOR SHL, SHR on unsigned) UN CMP CAST BR CBR + * RET TRAP. Refused: CALL, memory, handles, slices, DIV, REM, SHR on signed operands. Every path is + * executed symbolically (paths whose branch condition is a constant do not fork, so loops with a + * constant counter unroll exactly); more than C2_BLAST_MAX_PATHS paths or C2_BLAST_MAX_STEPS + * steps is refused as too large. */ +#ifndef C2_BLAST_H +#define C2_BLAST_H + +#include "c2_ir.h" +#include "c2_lrat.h" + +#define C2_BLAST_MAX_PATHS 4096 +#define C2_BLAST_MAX_STEPS 4000000L +#define C2_PROPERTY_NOTRAP "no-trap-except-requires" + +typedef struct { + const char *rule; /* "BLAST-OK" or the refusal reason */ + char detail[160]; + int inputs; /* argument bits (CNF variables 2..inputs+1) */ + int paths, trap_sites; /* explored paths; path points where a trap can fire */ +} C2BlastInfo; + +/* 0: cnf built (caller frees with c2_cnf_free); -1: refused (info->rule). The unit must already be + * accepted by c2_check_unit; c2_blast_notrap runs it again and refuses otherwise. */ +int c2_blast_notrap(const C2Unit *u, int fi, C2Cnf *cnf, C2BlastInfo *info); +/* index of the function called name, or -1 */ +int c2_func_index(const C2Unit *u, const char *name); + +#endif /* C2_BLAST_H */ diff --git a/src/checker2/c2_check.c b/src/checker2/c2_check.c new file mode 100644 index 000000000..eec0c0b94 --- /dev/null +++ b/src/checker2/c2_check.c @@ -0,0 +1,903 @@ +/* c2_check.c: checker2 acceptance rules over a decoded unit (spec/one-layer-receipts.md section 9). + * + * Written from docs/osc/OSC-{1,2,3}-DESIGN.md, OSC-EXT-BYTES-DESIGN.md and the osc_ir.h comments + * only. Rules, in the order applied: + * unit tables -> per-function types -> CFG shape -> per-instruction typing -> calls -> + * handle disciplines -> definite assignment -> loop bounds (termination) -> ownership flow. + * The ownership flow is a may-analysis that rejects only DEFINITE errors (a state that holds on + * every path), so it cannot reject a correct program through imprecision; drop-flag guarded + * releases (OSC-3 item 3) are therefore never refused by it. */ +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_ir.h" + +static int fail(C2Verdict *v, const char *rule, int func, int insn, const char *fmt, ...) +{ + if (v) { + v->ok = 0; + v->rule = rule; + v->func = func; + v->insn = insn; + va_list ap; + va_start(ap, fmt); + vsnprintf(v->detail, sizeof v->detail, fmt, ap); + va_end(ap); + } + return -1; +} + +/* ------------------------------------------------------------------ types */ + +static int is_value(uint8_t s) { return s >= S_BOOL && s <= S_I64; } +static int is_int(uint8_t s) { return s >= S_U8 && s <= S_I64; } +static int is_signed(uint8_t s) { return s >= S_I8 && s <= S_I64; } +static unsigned width(uint8_t s) +{ + switch (s) { + case S_BOOL: return 1; + case S_U8: case S_I8: return 8; + case S_U16: case S_I16: return 16; + case S_U32: case S_I32: return 32; + case S_U64: case S_I64: return 64; + default: return 0; + } +} +static int is_scalar_t(const C2Type *t) { return is_value(t->s); } +static int is_ref(const C2Type *t) { return t->s == S_REF; } +static int is_array_ref(const C2Type *t) { return t->s == S_REF && t->sid == 0; } +static int is_struct_ref(const C2Type *t) { return t->s == S_REF && t->sid != 0; } +static int is_slice(const C2Type *t) { return t->s == S_BYTES || t->s == S_CELLS; } +static int is_u64(const C2Type *t) { return t->s == S_U64; } +static int same_type(const C2Type *a, const C2Type *b) +{ + if (a->s != b->s) return 0; + if (a->s != S_REF) return 1; + return a->kind == b->kind && a->elem == b->elem && a->len == b->len && a->sid == b->sid; +} +/* Same object shape (element, length, struct), any reference kind. */ +static int same_shape(const C2Type *a, const C2Type *b) +{ + return a->s == S_REF && b->s == S_REF && a->elem == b->elem && a->len == b->len && a->sid == b->sid; +} +/* A reference of kind `from` may be bound to a destination of kind `to` (move, borrow, reborrow, + * downgrade): own->own|shared|mut, mut->mut|shared, shared->shared. */ +static int bindable(uint8_t to, uint8_t from) +{ + if (from == K_OWN) return 1; + if (from == K_MUT) return to == K_MUT || to == K_SHARED; + if (from == K_SHARED) return to == K_SHARED; + return 0; +} +/* imm is the canonical 64-bit value of a constant of scalar s */ +static int canonical(uint8_t s, uint64_t imm) +{ + unsigned w = width(s); + if (s == S_BOOL) return imm <= 1; + if (w == 64) return 1; + if (!is_signed(s)) return imm < (1ull << w); + int64_t x = (int64_t)imm; + int64_t lo = -(int64_t)(1ull << (w - 1)), hi = (int64_t)(1ull << (w - 1)) - 1; + return x >= lo && x <= hi; +} + +/* ------------------------------------------------------------------ unit tables */ + +static int check_structs(const C2Unit *u, C2Verdict *v) +{ + for (int k = 0; k < u->nstructs; k++) { + const C2Struct *s = &u->st[k]; + for (int j = 0; j < k; j++) + if (strcmp(u->st[j].name, s->name) == 0) + return fail(v, "C2-STRUCT-NAME", -1, -1, "struct %s defined twice", s->name); + unsigned off = 0; + for (int f = 0; f < s->nfields; f++) { + const C2Field *fd = &s->f[f]; + for (int g = 0; g < f; g++) + if (strcmp(s->f[g].name, fd->name) == 0) + return fail(v, "C2-STRUCT-NAME", -1, -1, "field %s.%s twice", s->name, fd->name); + if (!is_value(fd->s)) return fail(v, "C2-STRUCT-FIELD-TYPE", -1, -1, "%s.%s", s->name, fd->name); + if (fd->alen > C2_MAX_ARRAY) + return fail(v, "C2-STRUCT-FIELD-LEN", -1, -1, "%s.%s length %u", s->name, fd->name, fd->alen); + if (fd->off != off) /* GUARD:struct-offset */ + return fail(v, "C2-STRUCT-LAYOUT", -1, -1, "%s.%s offset %u, prefix sum %u", s->name, fd->name, fd->off, off); + off += fd->alen ? fd->alen : 1; + } + if (s->ncells != off || off < 1 || off > C2_MAX_ARRAY) /* GUARD:struct-cells */ + return fail(v, "C2-STRUCT-LAYOUT", -1, -1, "%s cells %u, fields need %u", s->name, s->ncells, off); + } + return 0; +} + +static int check_type(const C2Unit *u, const C2Type *t) +{ + if (t->s >= S_LIMIT || t->s == S_VOID) return 0; + if (t->s != S_REF) return 1; + if (t->kind < K_OWN || t->kind > K_MUT) return 0; + if (t->elem == S_VOID) { /* struct reference */ + if (t->sid < 1 || t->sid > u->nstructs) return 0; + return t->len == u->st[t->sid - 1].ncells; + } + return is_value(t->elem) && t->sid == 0 && t->len >= 1 && t->len <= C2_MAX_ARRAY; +} + +/* ------------------------------------------------------------------ per-function context */ + +#define BSW 8 /* 512 bits: enough for C2_MAX_VREGS (480) and C2_MAX_BLOCKS (512) */ +typedef struct { uint64_t w[BSW]; } Bits; +static void bset(Bits *b, unsigned i) { b->w[i >> 6] |= 1ull << (i & 63); } +static int btest(const Bits *b, unsigned i) { return (int)((b->w[i >> 6] >> (i & 63)) & 1); } +static void ball(Bits *b) { memset(b, 0xff, sizeof *b); } +static void band(Bits *d, const Bits *s) { for (int i = 0; i < BSW; i++) d->w[i] &= s->w[i]; } +static int beq(const Bits *a, const Bits *b) { return memcmp(a, b, sizeof *a) == 0; } + +typedef struct { + const C2Unit *u; + const C2Func *f; + int fi; + C2Verdict *v; + int nb; + int *blk_of; /* insn -> block */ + int succ[C2_MAX_BLOCKS][2]; + int nsucc[C2_MAX_BLOCKS]; + int reach[C2_MAX_BLOCKS]; + Bits dom[C2_MAX_BLOCKS]; + int ndefs[C2_MAX_VREGS]; + int def_insn[C2_MAX_VREGS]; /* the single definition, or -1 */ + int quiet; /* ownership fixpoint: apply effects, report nothing */ +} Fx; + +static int term(uint8_t op) { return op == C2_BR || op == C2_CBR || op == C2_RET; } + +/* uses of an instruction (vregs read); returns count */ +static int uses(const C2Insn *in, int16_t *o) +{ + int n = 0; + switch (in->op) { + case C2_CONST: case C2_TRAP: case C2_BR: case C2_AOPEN: case C2_POPEN: break; + case C2_MOV: case C2_CAST: case C2_UN: case C2_ALLOC: case C2_RELEASE: case C2_ADESTROY: case C2_PCLOSE: + case C2_CBR: o[n++] = in->a; break; + case C2_RET: if (in->a >= 0) o[n++] = in->a; break; + case C2_BIN: case C2_CMP: case C2_LOAD: case C2_AALLOC: case C2_HALLOC: case C2_HGEN: case C2_SLOAD: + o[n++] = in->a; o[n++] = in->b; break; + case C2_STORE: case C2_HFREE: case C2_HLOAD: case C2_SSTORE: o[n++] = in->a; o[n++] = in->b; o[n++] = in->c; break; + case C2_HSTORE: o[n++] = in->a; o[n++] = in->b; o[n++] = in->c; o[n++] = in->args[0]; break; + case C2_FLOAD: o[n++] = in->a; if (in->b >= 0) o[n++] = in->b; break; + case C2_FSTORE: o[n++] = in->a; if (in->b >= 0) o[n++] = in->b; o[n++] = in->c; break; + case C2_CALL: for (int k = 0; k < in->nargs; k++) o[n++] = in->args[k]; break; + default: break; + } + return n; +} + +static int defines(const C2Insn *in) +{ + switch (in->op) { + case C2_CONST: case C2_MOV: case C2_BIN: case C2_UN: case C2_CMP: case C2_CAST: case C2_ALLOC: case C2_LOAD: + case C2_FLOAD: case C2_AOPEN: case C2_AALLOC: case C2_POPEN: case C2_HALLOC: case C2_HGEN: case C2_HLOAD: + case C2_SLOAD: + return in->dst; + case C2_CALL: return in->dst; /* -1 for a void call */ + default: return -1; + } +} + +#define F(rule, ...) return fail(x->v, rule, x->fi, (int)ii, __VA_ARGS__) + +static const C2Type *T(const Fx *x, int16_t r) { return &x->f->vt[r]; } + +static int check_insn(Fx *x, uint32_t ii) +{ + const C2Func *f = x->f; + const C2Insn *in = &f->in[ii]; + int nv = f->nvregs; + int16_t us[8]; + int nu = uses(in, us); + for (int k = 0; k < nu; k++) { + if (us[k] < 0 || us[k] >= nv) F("C2-OPERAND-RANGE", "operand v%d out of range", us[k]); /* GUARD:operand-range */ + } + int d = defines(in); + int need_dst = !(in->op == C2_CALL && f->in[ii].dst == -1) && d != -1 ? 1 : 0; + if (in->op != C2_CALL && (in->op == C2_CONST || in->op == C2_MOV || in->op == C2_BIN || in->op == C2_UN || + in->op == C2_CMP || in->op == C2_CAST || in->op == C2_ALLOC || in->op == C2_LOAD || + in->op == C2_FLOAD || in->op == C2_AOPEN || in->op == C2_AALLOC || in->op == C2_POPEN || + in->op == C2_HALLOC || in->op == C2_HGEN || in->op == C2_HLOAD || in->op == C2_SLOAD) && + in->dst < 0) + F("C2-OPERAND-RANGE", "missing destination"); + if (need_dst && (d < 0 || d >= nv)) F("C2-OPERAND-RANGE", "destination v%d out of range", d); /* GUARD:dst-range */ + if (d >= 0 && is_slice(T(x, d))) F("C2-SLICE-WRITE", "slice register v%d redefined", d); + if (d >= 0 && d < f->nparams && d > 0 && is_slice(T(x, d - 1))) + F("C2-SLICE-WRITE", "slice length register v%d redefined", d); + + const C2Type *td = d >= 0 ? T(x, d) : NULL; + const C2Type *ta = in->a >= 0 && in->a < nv ? T(x, in->a) : NULL; + const C2Type *tb = in->b >= 0 && in->b < nv ? T(x, in->b) : NULL; + const C2Type *tc = in->c >= 0 && in->c < nv ? T(x, in->c) : NULL; + + switch (in->op) { + case C2_CONST: + if (!is_scalar_t(td)) F("C2-TYPE-CONST", "constant into a non-scalar register"); + if (!canonical(td->s, in->imm)) F("C2-CONST-CANONICAL", "constant %llu not canonical for its type", (unsigned long long)in->imm); /* GUARD:const-canonical */ + break; + case C2_MOV: + if (is_slice(ta) || is_slice(td)) F("C2-SLICE-ESCAPE", "slice copied"); + if (is_ref(td) || is_ref(ta)) { + if (!same_shape(td, ta) || !bindable(td->kind, ta->kind)) F("C2-TYPE-MOV", "reference kinds or shapes do not bind"); /* GUARD:mov-ref */ + } else { + if (!same_type(td, ta) || !is_scalar_t(td)) F("C2-TYPE-MOV", "MOV between different types"); /* GUARD:mov-type */ + } + break; + case C2_BIN: + if (in->sub < B_ADD || in->sub >= B_LIMIT) F("C2-DECODE-SUBOP", "binary op %u", in->sub); + if (in->sub == B_SHL || in->sub == B_SHR) { + if (!is_int(td->s) || !same_type(td, ta) || !is_int(tb->s)) F("C2-TYPE-BIN", "shift operand types"); /* GUARD:bin-shift */ + } else if (in->sub == B_AND || in->sub == B_OR || in->sub == B_XOR) { + if (!is_scalar_t(td) || !same_type(td, ta) || !same_type(td, tb)) F("C2-TYPE-BIN", "bitwise operand types"); + } else { + if (!is_int(td->s) || !same_type(td, ta) || !same_type(td, tb)) F("C2-TYPE-BIN", "arithmetic operand types"); /* GUARD:bin-type */ + } + break; + case C2_UN: + if (in->sub < U_NEG || in->sub >= U_LIMIT) F("C2-DECODE-SUBOP", "unary op %u", in->sub); + if (!same_type(td, ta)) F("C2-TYPE-UN", "unary result type differs from operand"); + if (in->sub == U_LNOT ? td->s != S_BOOL : !is_int(td->s)) F("C2-TYPE-UN", "unary operand type"); /* GUARD:un-type */ + break; + case C2_CMP: + if (in->sub < CC_EQ || in->sub >= CC_LIMIT) F("C2-DECODE-SUBOP", "comparison %u", in->sub); + if (td->s != S_BOOL || !is_scalar_t(ta) || !same_type(ta, tb)) F("C2-TYPE-CMP", "comparison operand types"); /* GUARD:cmp-type */ + break; + case C2_CAST: + if (!is_int(td->s) || !is_int(ta->s)) F("C2-TYPE-CAST", "cast between non-integers (bool casts are refused)"); /* GUARD:cast-type */ + break; + case C2_ALLOC: case C2_AALLOC: + if (!is_ref(td) || td->kind != K_OWN) F("C2-TYPE-ALLOC", "allocation into a non-owner"); /* GUARD:alloc-own */ + if (is_array_ref(td) ? ta->s != td->elem : ta->s != S_U64) F("C2-TYPE-ALLOC", "initial value type"); /* GUARD:alloc-init */ + if (in->op == C2_AALLOC && !is_u64(tb)) F("C2-TYPE-ALLOC", "arena handle is not u64"); + break; + case C2_RELEASE: + if (!is_ref(ta) || ta->kind != K_OWN) F("C2-TYPE-RELEASE", "release of a non-owner"); /* GUARD:release-own */ + break; + case C2_LOAD: case C2_STORE: + if (!is_array_ref(ta)) F("C2-TYPE-INDEX", "indexing a non-array"); /* GUARD:index-array */ + if (!is_int(tb->s)) F("C2-TYPE-INDEX", "index is not an integer"); + if (in->op == C2_LOAD ? td->s != ta->elem : tc->s != ta->elem) F("C2-TYPE-INDEX", "element type"); /* GUARD:index-elem */ + if (in->op == C2_STORE && ta->kind == K_SHARED) F("C2-READ-ONLY", "store through a shared borrow"); /* GUARD:store-shared */ + break; + case C2_FLOAD: case C2_FSTORE: { + if (!is_struct_ref(ta)) F("C2-TYPE-FIELD", "field access on a non-struct"); + const C2Struct *s = &x->u->st[ta->sid - 1]; + if (in->imm >= s->nfields) F("C2-TYPE-FIELD", "field %llu of %s", (unsigned long long)in->imm, s->name); /* GUARD:field-index */ + const C2Field *fd = &s->f[in->imm]; + if (fd->alen ? (!tb || !is_int(tb->s)) : in->b != -1) F("C2-TYPE-FIELD", "element index of field %s.%s", s->name, fd->name); /* GUARD:field-elem-index */ + if (in->op == C2_FLOAD ? td->s != fd->s : tc->s != fd->s) F("C2-TYPE-FIELD", "type of field %s.%s", s->name, fd->name); /* GUARD:field-type */ + if (in->op == C2_FSTORE && ta->kind == K_SHARED) F("C2-READ-ONLY", "field store through a shared borrow"); /* GUARD:fstore-shared */ + break; + } + case C2_AOPEN: + if (!is_u64(td)) F("C2-TYPE-HANDLE", "arena handle is not u64"); + if (in->imm < 1 || in->imm > C2_MAX_ARRAY) F("C2-ARENA-CAPACITY", "arena of %llu cells", (unsigned long long)in->imm); /* GUARD:arena-cap */ + break; + case C2_ADESTROY: case C2_PCLOSE: + if (!is_u64(ta)) F("C2-TYPE-HANDLE", "handle is not u64"); + break; + case C2_POPEN: + if (!is_u64(td)) F("C2-TYPE-HANDLE", "pool id is not u64"); + if (!is_value(in->sub)) F("C2-TYPE-POOL", "pool element type %u", in->sub); + if (in->nargs < 1 || in->nargs > C2_POOL_SLOTS) F("C2-POOL-CAPACITY", "pool of %u slots", in->nargs); /* GUARD:pool-cap */ + break; + case C2_HALLOC: if (!is_u64(td) || !is_u64(tb) || !is_value(ta->s)) F("C2-TYPE-POOL", "pool alloc operand types"); break; + case C2_HGEN: if (!is_u64(td) || !is_u64(ta) || !is_u64(tb)) F("C2-TYPE-POOL", "pool generation operand types"); break; + case C2_HFREE: if (!is_u64(ta) || !is_u64(tb) || !is_u64(tc)) F("C2-TYPE-POOL", "pool free operand types"); break; + case C2_HLOAD: if (!is_value(td->s) || !is_u64(ta) || !is_u64(tb) || !is_u64(tc)) F("C2-TYPE-POOL", "pool load operand types"); break; + case C2_HSTORE: + if (in->args[0] < 0 || in->args[0] >= nv) F("C2-OPERAND-RANGE", "pool store value"); + if (!is_u64(ta) || !is_u64(tb) || !is_u64(tc)) F("C2-TYPE-POOL", "pool store operand types"); + break; + case C2_SLOAD: case C2_SSTORE: + if (!is_slice(ta)) F("C2-TYPE-SLICE", "slice access through a non-slice register"); /* GUARD:slice-ptr */ + if (in->op == C2_SSTORE && ta->s != S_CELLS) F("C2-SLICE-WRITE", "store into a read-only bytes slice"); /* GUARD:slice-bytes-ro */ + if (!is_int(tb->s)) F("C2-TYPE-SLICE", "slice index is not an integer"); + if (in->op == C2_SLOAD ? !is_u64(td) : !is_u64(tc)) F("C2-TYPE-SLICE", "slice element is u64"); + break; + case C2_TRAP: + if (in->imm < 1 || in->imm > C2_TRAP_MAX) F("C2-TRAP-CODE", "trap code %llu", (unsigned long long)in->imm); /* GUARD:trap-code */ + break; + case C2_BR: + if (in->t >= f->nblocks) F("C2-CFG-TARGET", "branch to block %u", in->t); /* GUARD:br-target */ + break; + case C2_CBR: + if (in->t >= f->nblocks || in->f >= f->nblocks) F("C2-CFG-TARGET", "branch to block %u/%u", in->t, in->f); /* GUARD:cbr-target */ + if (ta->s != S_BOOL) F("C2-TYPE-COND", "branch condition is not bool"); /* GUARD:cbr-bool */ + break; + case C2_RET: + if (f->ret.s == S_VOID ? in->a != -1 : (in->a < 0 || !same_type(ta, &f->ret))) F("C2-TYPE-RET", "return value type"); /* GUARD:ret-type */ + break; + case C2_CALL: { + if (in->callee >= x->fi) F("C2-CALL-ORDER", "call to function %u from function %d (no recursion, no forward calls)", in->callee, x->fi); /* GUARD:call-order */ + const C2Func *g = &x->u->fn[in->callee]; + if (in->nargs != g->nparams) F("C2-CALL-ARITY", "%u arguments for %u parameters", in->nargs, g->nparams); /* GUARD:call-arity */ + if (g->ret.s == S_VOID ? in->dst != -1 : (in->dst < 0 || in->dst >= nv || !same_type(T(x, in->dst), &g->ret))) + F("C2-TYPE-CALL", "call result type"); /* GUARD:call-ret */ + for (int k = 0; k < in->nargs; k++) { + const C2Type *pa = T(x, in->args[k]), *pp = &g->vt[k]; + if (is_ref(pp)) { + if (!same_shape(pa, pp) || !bindable(pp->kind, pa->kind)) F("C2-TYPE-CALL", "argument %d does not bind", k); /* GUARD:call-ref */ + } else if (is_slice(pp)) { + if (pa->s != pp->s) F("C2-TYPE-CALL", "slice argument %d type", k); + if (k + 1 >= in->nargs || in->args[k + 1] != in->args[k] + 1) + F("C2-TYPE-CALL", "slice argument %d is not passed with its own length", k); + } else { + if (!same_type(pa, pp)) F("C2-TYPE-CALL", "argument %d type", k); /* GUARD:call-scalar */ + } + /* aliasing: the same register twice where either parameter may write or take it */ + for (int j = 0; j < k; j++) { + int alias = in->args[j] == in->args[k] && (is_ref(pp) || pp->s == S_CELLS) && + (pp->kind != K_SHARED || g->vt[j].kind != K_SHARED); + if (alias) F("C2-CALL-ALIAS", "register v%d passed twice and written", in->args[k]); /* GUARD:call-alias */ + } + } + break; + } + default: F("C2-DECODE-OPCODE", "opcode %u", in->op); + } + return 0; +} + +/* ------------------------------------------------------------------ CFG */ + +static int build_cfg(Fx *x) +{ + const C2Func *f = x->f; + uint32_t pos = 0; + for (int b = 0; b < f->nblocks; b++) { + const C2Block *bk = &f->blk[b]; + if (bk->count < 1 || bk->first != pos || bk->first + bk->count > f->ninsns) /* GUARD:cfg-layout */ + return fail(x->v, "C2-CFG-LAYOUT", x->fi, -1, "block %d is not the next contiguous range", b); + for (uint32_t i = bk->first; i < bk->first + bk->count; i++) { + x->blk_of[i] = b; + int last = i + 1 == bk->first + bk->count; + if (term(f->in[i].op) != last) /* GUARD:cfg-terminator */ + return fail(x->v, "C2-CFG-TERMINATOR", x->fi, (int)i, last ? "block %d does not end in a terminator" : "terminator inside block %d", b); + } + pos += bk->count; + } + if (pos != f->ninsns) return fail(x->v, "C2-CFG-LAYOUT", x->fi, -1, "blocks cover %u of %u instructions", pos, f->ninsns); + return 0; +} + +static void link_cfg(Fx *x) +{ + const C2Func *f = x->f; + for (int b = 0; b < f->nblocks; b++) { + const C2Insn *t = &f->in[f->blk[b].first + f->blk[b].count - 1]; + x->nsucc[b] = 0; + if (t->op == C2_BR) x->succ[b][x->nsucc[b]++] = t->t; + if (t->op == C2_CBR) { + x->succ[b][x->nsucc[b]++] = t->t; + if (t->f != t->t) x->succ[b][x->nsucc[b]++] = t->f; + } + } + int stack[C2_MAX_BLOCKS], sp = 0; + memset(x->reach, 0, sizeof x->reach); + x->reach[0] = 1; + stack[sp++] = 0; + while (sp) { + int b = stack[--sp]; + for (int k = 0; k < x->nsucc[b]; k++) + if (!x->reach[x->succ[b][k]]) { x->reach[x->succ[b][k]] = 1; stack[sp++] = x->succ[b][k]; } + } + /* dominators over reachable blocks */ + for (int b = 0; b < f->nblocks; b++) ball(&x->dom[b]); + memset(&x->dom[0], 0, sizeof x->dom[0]); + bset(&x->dom[0], 0); + int changed = 1; + while (changed) { + changed = 0; + for (int b = 1; b < f->nblocks; b++) { + if (!x->reach[b]) continue; + Bits n; + ball(&n); + for (int p = 0; p < f->nblocks; p++) { + if (!x->reach[p]) continue; + for (int k = 0; k < x->nsucc[p]; k++) + if (x->succ[p][k] == b) band(&n, &x->dom[p]); + } + bset(&n, (unsigned)b); + if (!beq(&n, &x->dom[b])) { x->dom[b] = n; changed = 1; } + } + } +} + +static int dominates(const Fx *x, int a, int b) { return btest(&x->dom[b], (unsigned)a); } + +/* ------------------------------------------------------------------ disciplines */ + +static int count_defs(Fx *x) +{ + const C2Func *f = x->f; + for (int r = 0; r < f->nvregs; r++) { x->ndefs[r] = r < f->nparams ? 1 : 0; x->def_insn[r] = -1; } + for (uint32_t i = 0; i < f->ninsns; i++) { + int d = defines(&f->in[i]); + if (d < 0) continue; + x->ndefs[d]++; + x->def_insn[d] = x->ndefs[d] == 1 ? (int)i : -1; + } + return 0; +} + +/* Arena handles and pool ids: defined exactly once, by AOPEN / POPEN, never a parameter, and used + * only in their handle positions (OSC-2 section 3.3, OSC-3 item 2). */ +static int check_handles(Fx *x) +{ + const C2Func *f = x->f; + for (uint32_t i = 0; i < f->ninsns; i++) { + const C2Insn *in = &f->in[i]; + if (in->op != C2_AOPEN && in->op != C2_POPEN) continue; + int h = in->dst; + if (h < f->nparams || x->ndefs[h] != 1) /* also implied by handle-origin and the leak rule (untagged) */ + return fail(x->v, "C2-HANDLE-DISCIPLINE", x->fi, (int)i, "handle v%d defined more than once or a parameter", h); + for (uint32_t j = 0; j < f->ninsns; j++) { + const C2Insn *o = &f->in[j]; + int16_t us[8]; + int nu = uses(o, us); + for (int k = 0; k < nu; k++) { + if (us[k] != h) continue; + int ok; + if (in->op == C2_AOPEN) + ok = (o->op == C2_AALLOC && o->b == h && o->a != h) || (o->op == C2_ADESTROY && o->a == h); + else + ok = (o->op == C2_PCLOSE && o->a == h) || (o->op == C2_HALLOC && o->b == h && o->a != h) || + ((o->op == C2_HGEN || o->op == C2_HFREE || o->op == C2_HLOAD || o->op == C2_HSTORE) && o->a == h && + o->b != h && o->c != h && o->args[0] != h); + if (!ok) /* GUARD:handle-use */ + return fail(x->v, "C2-HANDLE-DISCIPLINE", x->fi, (int)j, "handle v%d used outside its handle position", h); + } + } + } + /* every handle operand is such a handle, and pool element types agree with the pool */ + for (uint32_t j = 0; j < f->ninsns; j++) { + const C2Insn *o = &f->in[j]; + int h = -1; + if (o->op == C2_AALLOC) h = o->b; + if (o->op == C2_ADESTROY || o->op == C2_PCLOSE || o->op == C2_HGEN || o->op == C2_HFREE || o->op == C2_HLOAD || + o->op == C2_HSTORE) + h = o->a; + if (o->op == C2_HALLOC) h = o->b; + if (h < 0) continue; + int di = x->def_insn[h]; + uint8_t want = (o->op == C2_AALLOC || o->op == C2_ADESTROY) ? C2_AOPEN : C2_POPEN; + if (di < 0 || f->in[di].op != want) /* GUARD:handle-origin */ + return fail(x->v, "C2-HANDLE-DISCIPLINE", x->fi, (int)j, "v%d is not a handle opened by %s", h, want == C2_AOPEN ? "AOPEN" : "POPEN"); + uint8_t es = f->in[di].sub; + if (o->op == C2_HALLOC && f->vt[o->a].s != es) return fail(x->v, "C2-TYPE-POOL", x->fi, (int)j, "pool value type"); + if (o->op == C2_HLOAD && f->vt[o->dst].s != es) return fail(x->v, "C2-TYPE-POOL", x->fi, (int)j, "pool value type"); /* GUARD:pool-elem */ + if (o->op == C2_HSTORE && f->vt[o->args[0]].s != es) return fail(x->v, "C2-TYPE-POOL", x->fi, (int)j, "pool value type"); + } + return 0; +} + +/* ------------------------------------------------------------------ definite assignment */ + +static int check_defined(Fx *x) +{ + const C2Func *f = x->f; + static Bits in[C2_MAX_BLOCKS], out[C2_MAX_BLOCKS]; /* not reentrant; checker2 is single-threaded */ + Bits params; + memset(¶ms, 0, sizeof params); + for (int r = 0; r < f->nparams; r++) bset(¶ms, (unsigned)r); + for (int b = 0; b < f->nblocks; b++) ball(&out[b]); + int changed = 1; + while (changed) { + changed = 0; + for (int b = 0; b < f->nblocks; b++) { + if (!x->reach[b]) continue; + Bits cur; + if (b == 0) cur = params; + else { + ball(&cur); + for (int p = 0; p < f->nblocks; p++) { + if (!x->reach[p]) continue; + for (int k = 0; k < x->nsucc[p]; k++) + if (x->succ[p][k] == b) band(&cur, &out[p]); + } + } + if (b == 0) { + /* the entry block may also be a loop header */ + for (int p = 0; p < f->nblocks; p++) { + if (!x->reach[p]) continue; + for (int k = 0; k < x->nsucc[p]; k++) + if (x->succ[p][k] == 0) band(&cur, &out[p]); + } + } + in[b] = cur; + for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count; i++) { + if (f->in[i].op == C2_TRAP) { ball(&cur); break; } /* a trap ends the path */ + int d = defines(&f->in[i]); + if (d >= 0) bset(&cur, (unsigned)d); + } + if (!beq(&cur, &out[b])) { out[b] = cur; changed = 1; } + } + } + for (int b = 0; b < f->nblocks; b++) { + if (!x->reach[b]) continue; + Bits cur = in[b]; + for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count; i++) { + if (f->in[i].op == C2_TRAP) break; + int16_t us[8]; + int nu = uses(&f->in[i], us); + for (int k = 0; k < nu; k++) { + if (!btest(&cur, (unsigned)us[k])) /* GUARD:definite-assignment */ + return fail(x->v, "C2-UNDEFINED-USE", x->fi, (int)i, "v%d may be read before it is written", us[k]); + } + int d = defines(&f->in[i]); + if (d >= 0) bset(&cur, (unsigned)d); + } + } + return 0; +} + +/* ------------------------------------------------------------------ loop bounds */ + +/* Every loop must be bounded (OSC-1 section 3 "Loops"; OSC-1 section 4 "loops to blocks with an + * explicit counter vreg, CMP and CBR on the bound"). checker2 proves it structurally: the CFG is + * reducible, and each natural loop L contains a guard block G that dominates every latch of L and + * ends in CBR on cond, where + * cond is defined once, in G, by CMP c, K with + * K defined exactly once in the function, by CONST, |K| <= 1,000,000; + * c an integer register whose only definitions inside L are c = BIN ADD c, s with s defined + * exactly once in the function by CONST 1, each in a block that dominates every latch of L; + * CMP GE with the TRUE successor outside L, or CMP LT with the FALSE successor outside L. + * Then every iteration raises c by one and the loop is left once c >= K: at most |K - c0| + 2 + * iterations per entry (an unsigned counter can wrap at most once, on the first iteration; a + * signed one traps on overflow). */ +static int single_const(const Fx *x, int r, uint64_t *val) +{ + if (r < 0 || x->ndefs[r] != 1 || x->def_insn[r] < 0) return 0; + const C2Insn *d = &x->f->in[x->def_insn[r]]; + if (d->op != C2_CONST) return 0; + *val = d->imm; + return 1; +} + +static int loop_guarded(const Fx *x, const int *inloop, const int *latch, int nlatch) +{ + const C2Func *f = x->f; + for (int g = 0; g < f->nblocks; g++) { + if (!inloop[g]) continue; + int domall = 1; + for (int k = 0; k < nlatch; k++) domall &= dominates(x, g, latch[k]); + if (!domall) continue; + const C2Insn *t = &f->in[f->blk[g].first + f->blk[g].count - 1]; + if (t->op != C2_CBR) continue; + int ci = x->def_insn[t->a]; + if (ci < 0 || x->blk_of[ci] != g || f->in[ci].op != C2_CMP) continue; + const C2Insn *cmp = &f->in[ci]; + int exits; + if (cmp->sub == CC_GE) exits = !inloop[t->t]; + else if (cmp->sub == CC_LT) exits = !inloop[t->f]; + else continue; + if (!exits) continue; + uint64_t kv, one; + if (!single_const(x, cmp->b, &kv)) continue; + uint8_t ks = f->vt[cmp->b].s; + int64_t ksig = is_signed(ks) ? (int64_t)kv : (kv > 2000000 ? 2000000 : (int64_t)kv); + if (ksig > 1000000 || ksig < -1000000) continue; + int c = cmp->a; + if (!is_int(f->vt[c].s)) continue; + int incs = 0, bad = 0; + for (uint32_t i = 0; i < f->ninsns && !bad; i++) { + if (!inloop[x->blk_of[i]] || defines(&f->in[i]) != c) continue; + const C2Insn *d = &f->in[i]; + int ok = d->op == C2_BIN && d->sub == B_ADD && d->a == c && single_const(x, d->b, &one) && one == 1; + for (int k = 0; ok && k < nlatch; k++) ok = dominates(x, x->blk_of[i], latch[k]); + if (!ok) bad = 1; + else incs++; + } + if (!bad && incs >= 1) return 1; + } + return 0; +} + +static int check_loops(Fx *x) +{ + const C2Func *f = x->f; + /* reducibility: every edge into a block that does not dominate its source must go forward in a + * DFS without creating a cycle; equivalently, removing back edges (to a dominator) leaves a DAG. */ + static int color[C2_MAX_BLOCKS], stk[C2_MAX_BLOCKS], idx[C2_MAX_BLOCKS]; + memset(color, 0, sizeof color); + int sp = 0; + stk[sp] = 0; idx[sp] = 0; sp++; + color[0] = 1; + while (sp) { + int b = stk[sp - 1]; + if (idx[sp - 1] < x->nsucc[b]) { + int s = x->succ[b][idx[sp - 1]++]; + if (color[s] == 1 && !dominates(x, s, b)) /* GUARD:reducible */ + return fail(x->v, "C2-CFG-IRREDUCIBLE", x->fi, -1, "cycle entered other than through its header (block %d)", s); + if (color[s] == 0) { color[s] = 1; stk[sp] = s; idx[sp] = 0; sp++; } + } else { + color[b] = 2; + sp--; + } + } + /* natural loops, one per header (all its back edges together) */ + for (int h = 0; h < f->nblocks; h++) { + if (!x->reach[h]) continue; + int latch[C2_MAX_BLOCKS], nlatch = 0; + for (int p = 0; p < f->nblocks; p++) { + if (!x->reach[p]) continue; + for (int k = 0; k < x->nsucc[p]; k++) + if (x->succ[p][k] == h && dominates(x, h, p)) latch[nlatch++] = p; + } + if (!nlatch) continue; + static int inloop[C2_MAX_BLOCKS]; + memset(inloop, 0, sizeof inloop); + inloop[h] = 1; + int st[C2_MAX_BLOCKS], n = 0; + for (int k = 0; k < nlatch; k++) + if (!inloop[latch[k]]) { inloop[latch[k]] = 1; st[n++] = latch[k]; } + while (n) { + int b = st[--n]; + for (int p = 0; p < f->nblocks; p++) { + if (!x->reach[p] || inloop[p]) continue; + for (int k = 0; k < x->nsucc[p]; k++) + if (x->succ[p][k] == b) { inloop[p] = 1; st[n++] = p; break; } + } + } + if (!loop_guarded(x, inloop, latch, nlatch)) /* GUARD:loop-bound */ + return fail(x->v, "C2-LOOP-UNBOUNDED", x->fi, (int)f->blk[h].first, "loop at block %d has no counter guard", h); + } + return 0; +} + +/* ------------------------------------------------------------------ ownership flow */ + +/* May-states of a reference-owner register: bit 0 not yet holding, bit 1 live, bit 2 dead + * (released, moved or its arena destroyed). Handles: bit 0 not opened, bit 1 open, bit 2 closed. + * Only a state that excludes "live" on every path is an error. */ +enum { ST_U = 1, ST_L = 2, ST_D = 4 }; + +typedef struct { + int arena_obj[C2_MAX_VREGS]; /* defined by AALLOC: its handle register, else -1 */ + int origin[C2_MAX_VREGS]; /* borrow -> root owner register; -1 none/external; -2 mixed */ + uint8_t in[C2_MAX_BLOCKS][C2_MAX_VREGS]; +} Own; + +static int tracked(const Fx *x, int r) +{ + const C2Type *t = &x->f->vt[r]; + return (t->s == S_REF && t->kind == K_OWN); +} + +#define OF(rule, ...) do { if (!x->quiet) return fail(x->v, rule, x->fi, (int)i, __VA_ARGS__); } while (0) + +static int own_use(const Fx *x, const Own *o, const uint8_t *st, uint32_t i, int r) +{ + if (tracked(x, r) && !(st[r] & ST_L)) /* GUARD:own-use-dead */ + OF("C2-OWN-USE-DEAD", "owner v%d used after it was released or moved (every path)", r); + int g = o->origin[r]; + if (g >= 0 && !(st[g] & ST_L)) /* GUARD:borrow-outlives */ + OF("C2-BORROW-OUTLIVES-OWNER", "borrow v%d used after its owner v%d is gone (every path)", r, g); + return 0; +} + +static int own_kill(const Fx *x, uint8_t *st, uint32_t i, int r, const char *what) +{ + (void)what; + if (!(st[r] & ST_L)) OF("C2-OWN-USE-DEAD", "owner v%d moved after it was released or moved (every path)", r); /* GUARD:own-move-dead */ + st[r] = ST_D; + return 0; +} + +static int own_birth(const Fx *x, uint8_t *st, uint32_t i, int r) +{ + if (st[r] == ST_L) /* GUARD:own-overwrite */ + OF("C2-OWN-LEAK", "owner v%d overwritten while it still holds an object (every path)", r); + st[r] = ST_L; + return 0; +} + +static int own_step(const Fx *x, const Own *o, uint8_t *st, uint32_t i) +{ + const C2Func *f = x->f; + const C2Insn *in = &f->in[i]; + switch (in->op) { + case C2_ALLOC: + return own_birth(x, st, i, in->dst); + case C2_AALLOC: + if (!(st[in->b] & ST_L)) OF("C2-ARENA-DEAD", "allocation from arena v%d after it was destroyed (every path)", in->b); /* GUARD:arena-alloc-dead */ + return own_birth(x, st, i, in->dst); + case C2_RELEASE: + if (o->arena_obj[in->a] >= 0) OF("C2-OWN-RELEASE-ARENA", "release of arena object v%d", in->a); /* GUARD:release-arena */ + if (!(st[in->a] & ST_L)) OF("C2-OWN-DOUBLE-RELEASE", "v%d released when it holds nothing (every path)", in->a); /* GUARD:double-release */ + st[in->a] = ST_D; + return 0; + case C2_MOV: + if (tracked(x, in->a)) { + if (f->vt[in->dst].kind == K_OWN) { + if (o->arena_obj[in->a] >= 0 || o->arena_obj[in->dst] >= 0) + OF("C2-OWN-ARENA-MOVE", "move involving arena object"); /* GUARD:arena-move */ + if (own_kill(x, st, i, in->a, "move")) return -1; + return own_birth(x, st, i, in->dst); + } + return own_use(x, o, st, i, in->a); + } + return is_ref(&f->vt[in->a]) ? own_use(x, o, st, i, in->a) : 0; + case C2_LOAD: case C2_STORE: case C2_FLOAD: case C2_FSTORE: + return own_use(x, o, st, i, in->a); + case C2_CALL: { + const C2Func *g = &x->u->fn[in->callee]; + for (int k = 0; k < in->nargs; k++) { + int r = in->args[k]; + if (!is_ref(&f->vt[r])) continue; + if (own_use(x, o, st, i, r)) return -1; + if (g->vt[k].kind == K_OWN) { + if (o->arena_obj[r] >= 0) OF("C2-OWN-ARENA-MOVE", "arena object v%d passed to an own parameter", r); + if (own_kill(x, st, i, r, "move into call")) return -1; + } + } + return 0; + } + case C2_AOPEN: case C2_POPEN: + if (st[in->dst] & ST_L) OF("C2-HANDLE-REOPEN", "handle v%d reopened while open", in->dst); + st[in->dst] = ST_L; + return 0; + case C2_ADESTROY: case C2_PCLOSE: + if (!(st[in->a] & ST_L)) OF("C2-HANDLE-DOUBLE-CLOSE", "handle v%d closed when not open (every path)", in->a); /* GUARD:double-close */ + st[in->a] = ST_D; + if (in->op == C2_ADESTROY) + for (int r = 0; r < f->nvregs; r++) + if (o->arena_obj[r] == in->a && st[r] != ST_U) st[r] = ST_D; + return 0; + case C2_HALLOC: case C2_HGEN: case C2_HFREE: case C2_HLOAD: case C2_HSTORE: { + int h = in->op == C2_HALLOC ? in->b : in->a; + if (!(st[h] & ST_L)) OF("C2-HANDLE-DEAD", "pool v%d used when not open (every path)", h); /* GUARD:pool-dead */ + return 0; + } + case C2_RET: + for (int r = 0; r < f->nvregs; r++) { + int handle = x->def_insn[r] >= 0 && (f->in[x->def_insn[r]].op == C2_AOPEN || f->in[x->def_insn[r]].op == C2_POPEN); + if (st[r] == ST_L && (handle || (tracked(x, r) && o->arena_obj[r] < 0))) /* GUARD:leak */ + OF(handle ? "C2-HANDLE-LEAK" : "C2-OWN-LEAK", "v%d still %s at return (every path)", r, handle ? "open" : "owns an object"); + } + return 0; + default: + return 0; + } +} + +static int check_ownership(Fx *x) +{ + const C2Func *f = x->f; + Own *o = malloc(sizeof *o); + if (!o) return fail(x->v, "C2-RESOURCE", x->fi, -1, "out of memory"); + for (int r = 0; r < f->nvregs; r++) { o->arena_obj[r] = -1; o->origin[r] = -1; } + for (uint32_t i = 0; i < f->ninsns; i++) { + const C2Insn *in = &f->in[i]; + if (in->op == C2_AALLOC) o->arena_obj[in->dst] = in->b; + } + for (uint32_t i = 0; i < f->ninsns; i++) { + const C2Insn *in = &f->in[i]; + if ((in->op == C2_ALLOC && o->arena_obj[in->dst] >= 0) || + (in->op == C2_AALLOC && o->arena_obj[in->dst] != in->b)) { + free(o); + return fail(x->v, "C2-OWN-ARENA-MOVE", x->fi, (int)i, "register v%d holds both arena and pool objects", in->dst); + } + } + /* borrow origins: flow-insensitive, single root owner or unknown */ + int changed = 1; + while (changed) { + changed = 0; + for (uint32_t i = 0; i < f->ninsns; i++) { + const C2Insn *in = &f->in[i]; + if (in->op != C2_MOV || !is_ref(&f->vt[in->dst]) || f->vt[in->dst].kind == K_OWN) continue; + int root = f->vt[in->a].kind == K_OWN ? in->a : o->origin[in->a]; + int cur = o->origin[in->dst]; + int nw = cur == -1 && root >= 0 ? root : (cur == root ? cur : -2); + if (in->dst < f->nparams) nw = -2; + if (nw != cur && cur != -2) { o->origin[in->dst] = nw; changed = 1; } + } + } + for (int r = 0; r < f->nvregs; r++) + if (o->origin[r] == -2) o->origin[r] = -1; + + /* Fixpoint of the may-states. In-states only grow (bitwise OR over a finite lattice), so this + * terminates. Transfer runs quietly (effects applied, no verdict); a TRAP ends its path, so a + * trapping block propagates nothing. Blocks no non-trapping path reaches are not judged. */ + static int live[C2_MAX_BLOCKS]; + memset(o->in, 0, sizeof o->in); + memset(live, 0, sizeof live); + for (int r = 0; r < f->nvregs; r++) o->in[0][r] = (r < f->nparams && tracked(x, r)) ? ST_L : ST_U; + live[0] = 1; + x->quiet = 1; + changed = 1; + while (changed) { + changed = 0; + for (int b = 0; b < f->nblocks; b++) { + if (!live[b]) continue; + uint8_t st[C2_MAX_VREGS]; + memcpy(st, o->in[b], f->nvregs); + int trapped = 0; + for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count && !trapped; i++) { + if (f->in[i].op == C2_TRAP) trapped = 1; + else (void)own_step(x, o, st, i); + } + if (trapped) continue; + for (int k = 0; k < x->nsucc[b]; k++) { + int s = x->succ[b][k]; + if (!live[s]) { live[s] = 1; changed = 1; } + for (int r = 0; r < f->nvregs; r++) { + uint8_t m = o->in[s][r] | st[r]; + if (m != o->in[s][r]) { o->in[s][r] = m; changed = 1; } + } + } + } + } + x->quiet = 0; + /* report the first definite error */ + for (int b = 0; b < f->nblocks; b++) { + if (!live[b]) continue; + uint8_t st[C2_MAX_VREGS]; + memcpy(st, o->in[b], f->nvregs); + for (uint32_t i = f->blk[b].first; i < f->blk[b].first + f->blk[b].count; i++) { + if (f->in[i].op == C2_TRAP) break; + if (own_step(x, o, st, i)) { free(o); return -1; } + } + } + free(o); + return 0; +} + +/* ------------------------------------------------------------------ driver */ + +static int check_func(const C2Unit *u, int fi, C2Verdict *v) +{ + const C2Func *f = &u->fn[fi]; + for (int g = 0; g < fi; g++) + if (strcmp(u->fn[g].name, f->name) == 0) return fail(v, "C2-FUNC-NAME", fi, -1, "function %s defined twice", f->name); /* GUARD:func-name */ + if (f->nparams > C2_MAX_PARAMS || f->nparams > f->nvregs) /* GUARD:params */ + return fail(v, "C2-FUNC-PARAMS", fi, -1, "%u parameters, %u registers", f->nparams, f->nvregs); + if (!(f->ret.s == S_VOID || is_value(f->ret.s))) /* GUARD:ret-scalar */ + return fail(v, "C2-FUNC-RETURN", fi, -1, "function returns a non-scalar"); + for (int r = 0; r < f->nvregs; r++) { + const C2Type *t = &f->vt[r]; + if (!check_type(u, t)) return fail(v, "C2-TYPE-INVALID", fi, -1, "register v%d has an invalid type", r); /* GUARD:vreg-type */ + if (is_slice(t)) { + if (r + 1 >= f->nparams || f->vt[r + 1].s != S_U64) /* GUARD:slice-param */ + return fail(v, "C2-SLICE-PARAM", fi, -1, "slice register v%d is not a parameter followed by its u64 length", r); + if (r > 0 && is_slice(&f->vt[r - 1])) + return fail(v, "C2-SLICE-PARAM", fi, -1, "slice v%d sits in the length register of v%d", r, r - 1); + } + } + Fx *x = calloc(1, sizeof *x); + if (!x) return fail(v, "C2-RESOURCE", fi, -1, "out of memory"); + x->u = u; x->f = f; x->fi = fi; x->v = v; x->nb = f->nblocks; + x->blk_of = calloc(f->ninsns, sizeof *x->blk_of); + int rc = -1; + if (!x->blk_of) { fail(v, "C2-RESOURCE", fi, -1, "out of memory"); goto out; } + if (build_cfg(x)) goto out; + for (uint32_t i = 0; i < f->ninsns; i++) + if (check_insn(x, i)) goto out; + link_cfg(x); + count_defs(x); + if (check_handles(x)) goto out; + if (check_defined(x)) goto out; + if (check_loops(x)) goto out; + if (check_ownership(x)) goto out; + rc = 0; +out: + free(x->blk_of); + free(x); + return rc; +} + +int c2_check_unit(const C2Unit *u, C2Verdict *v) +{ + if (v) { memset(v, 0, sizeof *v); v->ok = 1; v->func = v->insn = -1; v->rule = "ACCEPT"; } + if (check_structs(u, v)) return -1; + for (int fi = 0; fi < u->nfuncs; fi++) + if (check_func(u, fi, v)) return -1; + return 0; +} diff --git a/src/checker2/c2_ir.c b/src/checker2/c2_ir.c new file mode 100644 index 000000000..cdf75d75e --- /dev/null +++ b/src/checker2/c2_ir.c @@ -0,0 +1,393 @@ +/* c2_ir.c: checker2 decoder, re-encoder and acceptance rules for canonical OSC IR bytes. + * See c2_ir.h for the independence statement and spec/one-layer-receipts.md section 9 for the + * rules. Every rejection names its rule; lines tagged GUARD, colon, name are removed one at a time by + * tests/checker2/mutants.sh and each removal must make a test fail. */ +#include "c2_ir.h" + +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static int fail(C2Verdict *v, const char *rule, int func, int insn, const char *fmt, ...) +{ + if (v) { + v->ok = 0; + v->rule = rule; + v->func = func; + v->insn = insn; + va_list ap; + va_start(ap, fmt); + vsnprintf(v->detail, sizeof v->detail, fmt, ap); + va_end(ap); + } + return -1; +} + +/* ------------------------------------------------------------------ reader */ + +typedef struct { + const uint8_t *p; + size_t n, i; +} Rd; + +static int need(Rd *r, size_t k) { return r->n - r->i >= k; } +static int rd8(Rd *r, uint8_t *o) +{ + if (!need(r, 1)) return -1; + *o = r->p[r->i++]; + return 0; +} +static int rd16(Rd *r, uint16_t *o) +{ + if (!need(r, 2)) return -1; + *o = (uint16_t)(r->p[r->i] | (r->p[r->i + 1] << 8)); + r->i += 2; + return 0; +} +static int rd32(Rd *r, uint32_t *o) +{ + if (!need(r, 4)) return -1; + uint32_t x = 0; + for (int k = 3; k >= 0; k--) x = (x << 8) | r->p[r->i + k]; + r->i += 4; + *o = x; + return 0; +} +static int rd64(Rd *r, uint64_t *o) +{ + if (!need(r, 8)) return -1; + uint64_t x = 0; + for (int k = 7; k >= 0; k--) x = (x << 8) | r->p[r->i + k]; + r->i += 8; + *o = x; + return 0; +} +static int rdvr(Rd *r, int16_t *o) +{ + uint16_t x; + if (rd16(r, &x)) return -1; + *o = (int16_t)x; /* two's complement; 0xFFFF = -1 = "none" */ + return 0; +} + +static int ident_ok(const char *s, size_t n) +{ + if (n == 0) return 0; + for (size_t i = 0; i < n; i++) { + char c = s[i]; + int alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; + int digit = c >= '0' && c <= '9'; + if (!(alpha || (i > 0 && digit))) return 0; + } + return 1; +} + +/* name with a one-byte length (functions, structs, fields) */ +static int rdname(Rd *r, char *out) +{ + uint8_t n; + if (rd8(r, &n)) return -1; + if (n > C2_NAME_MAX || !need(r, n)) return -2; + memcpy(out, r->p + r->i, n); + out[n] = 0; + r->i += n; + return ident_ok(out, n) ? 0 : -2; +} + +static int rdtype(Rd *r, C2Type *t) +{ + memset(t, 0, sizeof *t); + if (rd8(r, &t->s)) return -1; + if (t->s == S_REF) { + if (rd8(r, &t->kind) || rd8(r, &t->elem) || rd16(r, &t->len)) return -1; + /* a struct reference has elem VOID and carries its struct index + 1 */ + if (t->elem == S_VOID && rd8(r, &t->sid)) return -1; + } + return 0; +} + +#define TRUNC(rule) return fail(v, "C2-DECODE-TRUNCATED", fi, -1, "%s", rule) + +static int dec_insn(Rd *r, C2Insn *in, C2Verdict *v, int fi, int ii) +{ + memset(in, 0, sizeof *in); + in->dst = in->a = in->b = in->c = -1; + for (int k = 0; k < C2_MAX_PARAMS; k++) in->args[k] = -1; + if (rd8(r, &in->op)) TRUNC("opcode"); + int bad = 0; + switch (in->op) { + case C2_CONST: bad = rdvr(r, &in->dst) || rd64(r, &in->imm); break; + case C2_MOV: case C2_CAST: case C2_ALLOC: bad = rdvr(r, &in->dst) || rdvr(r, &in->a); break; + case C2_BIN: case C2_CMP: + bad = rd8(r, &in->sub) || rdvr(r, &in->dst) || rdvr(r, &in->a) || rdvr(r, &in->b); + break; + case C2_UN: bad = rd8(r, &in->sub) || rdvr(r, &in->dst) || rdvr(r, &in->a); break; + case C2_RELEASE: case C2_ADESTROY: case C2_PCLOSE: case C2_RET: bad = rdvr(r, &in->a); break; + case C2_AOPEN: { + uint8_t k = 0; + bad = rdvr(r, &in->dst) || rd8(r, &k); + in->imm = k; + break; + } + case C2_AALLOC: case C2_HALLOC: case C2_HGEN: case C2_LOAD: case C2_SLOAD: + bad = rdvr(r, &in->dst) || rdvr(r, &in->a) || rdvr(r, &in->b); + break; + case C2_POPEN: bad = rdvr(r, &in->dst) || rd8(r, &in->sub) || rd8(r, &in->nargs) || rd64(r, &in->imm); break; + case C2_HFREE: case C2_STORE: case C2_SSTORE: bad = rdvr(r, &in->a) || rdvr(r, &in->b) || rdvr(r, &in->c); break; + case C2_HLOAD: bad = rdvr(r, &in->dst) || rdvr(r, &in->a) || rdvr(r, &in->b) || rdvr(r, &in->c); break; + case C2_HSTORE: + bad = rdvr(r, &in->a) || rdvr(r, &in->b) || rdvr(r, &in->c) || rdvr(r, &in->args[0]); + in->nargs = 1; + break; + case C2_FLOAD: case C2_FSTORE: { + uint8_t k = 0; + if (in->op == C2_FLOAD) bad = rdvr(r, &in->dst) || rdvr(r, &in->a) || rdvr(r, &in->b); + else bad = rdvr(r, &in->a) || rdvr(r, &in->b) || rdvr(r, &in->c); + bad = bad || rd8(r, &k); + in->imm = k; + break; + } + case C2_CALL: + bad = rdvr(r, &in->dst) || rd16(r, &in->callee) || rd8(r, &in->nargs); + if (!bad && in->nargs > C2_MAX_PARAMS) + return fail(v, "C2-CALL-ARITY", fi, ii, "call with %u arguments", in->nargs); /* GUARD:call-nargs-limit */ + for (int k = 0; !bad && k < in->nargs; k++) bad = rdvr(r, &in->args[k]); + break; + case C2_TRAP: { + uint8_t k = 0; + bad = rd8(r, &k); + in->imm = k; + break; + } + case C2_BR: bad = rd16(r, &in->t); break; + case C2_CBR: bad = rdvr(r, &in->a) || rd16(r, &in->t) || rd16(r, &in->f); break; + default: return fail(v, "C2-DECODE-OPCODE", fi, ii, "unknown opcode %u", in->op); + } + if (bad) TRUNC("instruction operands"); + return 0; +} + +static int has_op(const C2Unit *u, uint8_t lo, uint8_t hi) +{ + for (int fi = 0; fi < u->nfuncs; fi++) + for (uint32_t i = 0; i < u->fn[fi].ninsns; i++) + if (u->fn[fi].in[i].op >= lo && u->fn[fi].in[i].op <= hi) return 1; + return 0; +} + +static int has_slice(const C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) + for (int k = 0; k < u->fn[fi].nvregs; k++) + if (u->fn[fi].vt[k].s == S_BYTES || u->fn[fi].vt[k].s == S_CELLS) return 1; + return 0; +} + +static int canonical_version(const C2Unit *u) +{ + if (has_slice(u)) return 5; + if (has_op(u, C2_POPEN, C2_HSTORE)) return 4; + if (has_op(u, C2_AOPEN, C2_ADESTROY)) return 3; + if (u->nstructs) return 2; + return 1; +} + +void c2_unit_free(C2Unit *u) +{ + if (!u) return; + for (int i = 0; i < C2_MAX_FUNCS; i++) { + free(u->fn[i].vt); + free(u->fn[i].blk); + free(u->fn[i].in); + u->fn[i].vt = NULL; + u->fn[i].blk = NULL; + u->fn[i].in = NULL; + } +} + +static int rdtext(Rd *r, char *out, uint16_t *len) +{ + if (rd16(r, len)) return -1; + if (*len > C2_CLAUSE_MAX || !need(r, *len)) return -2; + memcpy(out, r->p + r->i, *len); + out[*len] = 0; + r->i += *len; + for (unsigned k = 0; k < *len; k++) + if (out[k] == 0) return -2; /* the producer writes strnlen bytes: an inner NUL is not canonical */ + return 0; +} + +static const uint8_t MAGIC7[7] = {'O', 'S', 'C', '1', 'I', 'R', 0}; + +int c2_decode(const uint8_t *buf, size_t len, C2Unit *u, C2Verdict *v) +{ + int fi = -1; + memset(u, 0, sizeof *u); + if (v) { memset(v, 0, sizeof *v); v->ok = 1; v->func = v->insn = -1; } + Rd rr = {buf, len, 0}, *r = &rr; + if (!buf || len < 8 || memcmp(buf, MAGIC7, 7) != 0) return fail(v, "C2-DECODE-MAGIC", -1, -1, "bad magic"); + u->version = buf[7]; + if (u->version < 1 || u->version > 5) /* GUARD:version-range */ + return fail(v, "C2-DECODE-VERSION", -1, -1, "unknown version %u", u->version); + r->i = 8; + if (u->version >= 2) { + if (rd8(r, &u->nstructs)) TRUNC("struct count"); + if (u->nstructs > C2_MAX_STRUCTS) return fail(v, "C2-LIMIT-STRUCTS", -1, -1, "%u structs", u->nstructs); + for (int k = 0; k < u->nstructs; k++) { + C2Struct *s = &u->st[k]; + int e = rdname(r, s->name); + if (e == -1) TRUNC("struct name"); + if (e) return fail(v, "C2-DECODE-NAME", -1, -1, "struct %d name", k); + if (rd8(r, &s->nfields) || rd16(r, &s->ncells)) TRUNC("struct header"); + if (s->nfields < 1 || s->nfields > C2_MAX_FIELDS) + return fail(v, "C2-STRUCT-FIELDS", -1, -1, "struct %d has %u fields", k, s->nfields); + for (int f = 0; f < s->nfields; f++) { + e = rdname(r, s->f[f].name); + if (e == -1) TRUNC("field name"); + if (e) return fail(v, "C2-DECODE-NAME", -1, -1, "struct %d field %d name", k, f); + if (rd8(r, &s->f[f].s) || rd16(r, &s->f[f].alen) || rd16(r, &s->f[f].off)) TRUNC("field"); + } + } + } + if (rd16(r, &u->nfuncs)) TRUNC("function count"); + if (u->nfuncs < 1 || u->nfuncs > C2_MAX_FUNCS) + return fail(v, "C2-LIMIT-FUNCS", -1, -1, "%u functions", u->nfuncs); + for (fi = 0; fi < u->nfuncs; fi++) { + C2Func *f = &u->fn[fi]; + int e = rdname(r, f->name); + if (e == -1) TRUNC("function name"); + if (e) return fail(v, "C2-DECODE-NAME", fi, -1, "function name"); + if (rd8(r, &f->nparams)) TRUNC("nparams"); + if (rdtype(r, &f->ret)) TRUNC("return type"); + if (rd16(r, &f->nvregs)) TRUNC("nvregs"); + if (f->nvregs > C2_MAX_VREGS) return fail(v, "C2-LIMIT-VREGS", fi, -1, "%u vregs", f->nvregs); + f->vt = calloc(f->nvregs ? f->nvregs : 1, sizeof *f->vt); + if (!f->vt) return fail(v, "C2-RESOURCE", fi, -1, "out of memory"); + for (int k = 0; k < f->nvregs; k++) + if (rdtype(r, &f->vt[k])) TRUNC("vreg type"); + if (rd16(r, &f->nblocks)) TRUNC("nblocks"); + if (f->nblocks < 1 || f->nblocks > C2_MAX_BLOCKS) + return fail(v, "C2-LIMIT-BLOCKS", fi, -1, "%u blocks", f->nblocks); + f->blk = calloc(f->nblocks, sizeof *f->blk); + if (!f->blk) return fail(v, "C2-RESOURCE", fi, -1, "out of memory"); + for (int b = 0; b < f->nblocks; b++) + if (rd32(r, &f->blk[b].first) || rd32(r, &f->blk[b].count)) TRUNC("block"); + if (rd32(r, &f->ninsns)) TRUNC("ninsns"); + if (f->ninsns < 1 || f->ninsns > C2_MAX_INSNS) + return fail(v, "C2-LIMIT-INSNS", fi, -1, "%u instructions", f->ninsns); + f->in = calloc(f->ninsns, sizeof *f->in); + if (!f->in) return fail(v, "C2-RESOURCE", fi, -1, "out of memory"); + for (uint32_t i = 0; i < f->ninsns; i++) + if (dec_insn(r, &f->in[i], v, fi, (int)i)) return -1; + e = rdtext(r, f->req, &f->req_len); + if (e == -1) TRUNC("requires text"); + if (e) return fail(v, "C2-DECODE-TEXT", fi, -1, "requires text"); + e = rdtext(r, f->ens, &f->ens_len); + if (e == -1) TRUNC("ensures text"); + if (e) return fail(v, "C2-DECODE-TEXT", fi, -1, "ensures text"); + } + fi = -1; + if (r->i != r->n) /* GUARD:trailing */ + return fail(v, "C2-DECODE-TRAILING", -1, -1, "%zu bytes after the last function", r->n - r->i); + int cv = canonical_version(u); + if (cv != u->version) /* GUARD:canonical-version */ + return fail(v, "C2-DECODE-VERSION-NONCANONICAL", -1, -1, "version byte %u, content needs %d", u->version, cv); + return 0; +} + +/* ------------------------------------------------------------------ re-encoder (mirror) */ + +typedef struct { + uint8_t *p; + size_t cap, n; +} Wr; + +static void wb(Wr *w, const void *s, size_t k) +{ + if (w->n + k <= w->cap) memcpy(w->p + w->n, s, k); + w->n += k; +} +static void w8(Wr *w, unsigned x) { uint8_t b = (uint8_t)x; wb(w, &b, 1); } +static void w16(Wr *w, unsigned x) { w8(w, x & 0xff); w8(w, (x >> 8) & 0xff); } +static void w32(Wr *w, uint32_t x) { for (int k = 0; k < 4; k++) w8(w, (x >> (8 * k)) & 0xff); } +static void w64(Wr *w, uint64_t x) { for (int k = 0; k < 8; k++) w8(w, (unsigned)((x >> (8 * k)) & 0xff)); } +static void wvr(Wr *w, int16_t x) { w16(w, (uint16_t)x); } +static void wname(Wr *w, const char *s) { size_t n = strlen(s); w8(w, (unsigned)n); wb(w, s, n); } +static void wtype(Wr *w, const C2Type *t) +{ + w8(w, t->s); + if (t->s == S_REF) { + w8(w, t->kind); w8(w, t->elem); w16(w, t->len); + if (t->elem == S_VOID) w8(w, t->sid); + } +} + +size_t c2_encode(const C2Unit *u, uint8_t *buf, size_t cap) +{ + Wr w = {buf, cap, 0}; + wb(&w, MAGIC7, 7); + w8(&w, u->version); + if (u->version >= 2) { + w8(&w, u->nstructs); + for (int k = 0; k < u->nstructs; k++) { + const C2Struct *s = &u->st[k]; + wname(&w, s->name); w8(&w, s->nfields); w16(&w, s->ncells); + for (int f = 0; f < s->nfields; f++) { + wname(&w, s->f[f].name); w8(&w, s->f[f].s); w16(&w, s->f[f].alen); w16(&w, s->f[f].off); + } + } + } + w16(&w, u->nfuncs); + for (int fi = 0; fi < u->nfuncs; fi++) { + const C2Func *f = &u->fn[fi]; + wname(&w, f->name); w8(&w, f->nparams); wtype(&w, &f->ret); + w16(&w, f->nvregs); + for (int k = 0; k < f->nvregs; k++) wtype(&w, &f->vt[k]); + w16(&w, f->nblocks); + for (int b = 0; b < f->nblocks; b++) { w32(&w, f->blk[b].first); w32(&w, f->blk[b].count); } + w32(&w, f->ninsns); + for (uint32_t i = 0; i < f->ninsns; i++) { + const C2Insn *in = &f->in[i]; + w8(&w, in->op); + switch (in->op) { + case C2_CONST: wvr(&w, in->dst); w64(&w, in->imm); break; + case C2_MOV: case C2_CAST: case C2_ALLOC: wvr(&w, in->dst); wvr(&w, in->a); break; + case C2_BIN: case C2_CMP: w8(&w, in->sub); wvr(&w, in->dst); wvr(&w, in->a); wvr(&w, in->b); break; + case C2_UN: w8(&w, in->sub); wvr(&w, in->dst); wvr(&w, in->a); break; + case C2_RELEASE: case C2_ADESTROY: case C2_PCLOSE: case C2_RET: wvr(&w, in->a); break; + case C2_AOPEN: wvr(&w, in->dst); w8(&w, (unsigned)in->imm); break; + case C2_AALLOC: case C2_HALLOC: case C2_HGEN: case C2_LOAD: case C2_SLOAD: + wvr(&w, in->dst); wvr(&w, in->a); wvr(&w, in->b); break; + case C2_POPEN: wvr(&w, in->dst); w8(&w, in->sub); w8(&w, in->nargs); w64(&w, in->imm); break; + case C2_HFREE: case C2_STORE: case C2_SSTORE: wvr(&w, in->a); wvr(&w, in->b); wvr(&w, in->c); break; + case C2_HLOAD: wvr(&w, in->dst); wvr(&w, in->a); wvr(&w, in->b); wvr(&w, in->c); break; + case C2_HSTORE: wvr(&w, in->a); wvr(&w, in->b); wvr(&w, in->c); wvr(&w, in->args[0]); break; + case C2_FLOAD: wvr(&w, in->dst); wvr(&w, in->a); wvr(&w, in->b); w8(&w, (unsigned)in->imm); break; + case C2_FSTORE: wvr(&w, in->a); wvr(&w, in->b); wvr(&w, in->c); w8(&w, (unsigned)in->imm); break; + case C2_CALL: + wvr(&w, in->dst); w16(&w, in->callee); w8(&w, in->nargs); + for (int k = 0; k < in->nargs; k++) wvr(&w, in->args[k]); + break; + case C2_TRAP: w8(&w, (unsigned)in->imm); break; + case C2_BR: w16(&w, in->t); break; + case C2_CBR: wvr(&w, in->a); w16(&w, in->t); w16(&w, in->f); break; + default: break; + } + } + w16(&w, f->req_len); wb(&w, f->req, f->req_len); + w16(&w, f->ens_len); wb(&w, f->ens, f->ens_len); + } + return w.n <= cap ? w.n : 0; +} + +int c2_check_bytes(const uint8_t *buf, size_t len, C2Verdict *v) +{ + C2Unit *u = malloc(sizeof *u); + if (!u) return fail(v, "C2-RESOURCE", -1, -1, "out of memory"); + int rc = c2_decode(buf, len, u, v); + if (rc == 0) rc = c2_check_unit(u, v); + c2_unit_free(u); + free(u); + return rc; +} diff --git a/src/checker2/c2_ir.h b/src/checker2/c2_ir.h new file mode 100644 index 000000000..30ca0cba8 --- /dev/null +++ b/src/checker2/c2_ir.h @@ -0,0 +1,119 @@ +/* c2_ir: checker2's own decoder and acceptance rules for canonical OSC IR bytes. + * + * INDEPENDENCE. Written from the byte layout of the encoder (src/compiler/osc_ir.c, the + * canonical-encoding section only, lines 537-729 at d58023e6) and the meaning stated in + * docs/osc/OSC-1-DESIGN.md, OSC-2-DESIGN.md, OSC-3-DESIGN.md, OSC-EXT-BYTES-DESIGN.md and the + * comments of src/compiler/osc_ir.h. It includes no compiler header, links no compiler object and + * never read osc_check.* or osc_ir_validate. Every constant below is restated here, not imported. + * The rule list is in spec/one-layer-receipts.md section 9. + * + * Fails closed: anything not understood is a rejection with a stable rule name. */ +#ifndef C2_IR_H +#define C2_IR_H + +#include <stddef.h> +#include <stdint.h> + +/* limits restated from the OSC design (osc_ir.h comments) */ +#define C2_MAX_FUNCS 32 +#define C2_MAX_PARAMS 6 +#define C2_MAX_VREGS 480 +#define C2_MAX_INSNS 4096 +#define C2_MAX_BLOCKS 512 +#define C2_MAX_ARRAY 64 +#define C2_NAME_MAX 63 /* bytes, excluding the terminator the producer keeps */ +#define C2_CLAUSE_MAX 255 +#define C2_MAX_STRUCTS 16 +#define C2_MAX_FIELDS 16 +#define C2_POOL_SLOTS 16 +#define C2_TRAP_MAX 14 + +/* scalar codes on the wire */ +enum { S_VOID = 0, S_BOOL, S_U8, S_U16, S_U32, S_U64, S_I8, S_I16, S_I32, S_I64, S_REF, S_BYTES, S_CELLS, + S_LIMIT }; +enum { K_NONE = 0, K_OWN, K_SHARED, K_MUT }; + +/* opcodes on the wire */ +enum { + C2_CONST = 1, C2_MOV, C2_BIN, C2_UN, C2_CMP, C2_CAST, C2_ALLOC, C2_RELEASE, C2_LOAD, C2_STORE, + C2_CALL, C2_TRAP, C2_BR, C2_CBR, C2_RET, C2_FLOAD, C2_FSTORE, C2_AOPEN, C2_AALLOC, C2_ADESTROY, + C2_POPEN, C2_PCLOSE, C2_HALLOC, C2_HGEN, C2_HFREE, C2_HLOAD, C2_HSTORE, C2_SLOAD, C2_SSTORE, + C2_OP_LIMIT +}; +enum { B_ADD = 1, B_SUB, B_MUL, B_DIV, B_REM, B_AND, B_OR, B_XOR, B_SHL, B_SHR, B_LIMIT }; +enum { U_NEG = 1, U_BNOT, U_LNOT, U_LIMIT }; +enum { CC_EQ = 1, CC_NE, CC_LT, CC_LE, CC_GT, CC_GE, CC_LIMIT }; + +typedef struct { + uint8_t s, kind, elem, sid; + uint16_t len; +} C2Type; + +typedef struct { + uint8_t op, sub, nargs; + int16_t dst, a, b, c; + int16_t args[C2_MAX_PARAMS]; + uint16_t t, f, callee; + uint64_t imm; +} C2Insn; + +typedef struct { uint32_t first, count; } C2Block; + +typedef struct { + char name[C2_NAME_MAX + 1]; + uint8_t nparams; + C2Type ret; + uint16_t nvregs, nblocks; + uint32_t ninsns; + C2Type *vt; /* nvregs */ + C2Block *blk; /* nblocks */ + C2Insn *in; /* ninsns */ + uint16_t req_len, ens_len; + char req[C2_CLAUSE_MAX + 1], ens[C2_CLAUSE_MAX + 1]; +} C2Func; + +typedef struct { + char name[C2_NAME_MAX + 1]; + uint8_t s; + uint16_t alen, off; +} C2Field; + +typedef struct { + char name[C2_NAME_MAX + 1]; + uint8_t nfields; + uint16_t ncells; + C2Field f[C2_MAX_FIELDS]; +} C2Struct; + +typedef struct { + uint8_t version; + uint8_t nstructs; + C2Struct st[C2_MAX_STRUCTS]; + uint16_t nfuncs; + C2Func fn[C2_MAX_FUNCS]; +} C2Unit; + +/* Verdict. rule is a stable name ("C2-..."), func / insn locate it (-1 when not applicable). */ +typedef struct { + int ok; + const char *rule; + int func, insn; + char detail[160]; +} C2Verdict; + +/* Strict decode: exact byte layout, canonical version byte, limits, no trailing bytes. + * 0 ok, -1 rejected with v filled. Call c2_unit_free afterwards in both cases. */ +int c2_decode(const uint8_t *buf, size_t len, C2Unit *u, C2Verdict *v); +void c2_unit_free(C2Unit *u); +/* Acceptance rules over a decoded unit (types, operands, CFG, calls, definite assignment, + * handle disciplines, ownership). 0 accept, -1 reject. */ +int c2_check_unit(const C2Unit *u, C2Verdict *v); +/* decode + check. */ +int c2_check_bytes(const uint8_t *buf, size_t len, C2Verdict *v); + +/* checker2's own canonical re-encoding (used by the tests to plant defects structurally and to + * prove decode is the exact inverse on accepted inputs). Returns the length, or 0 if cap is too + * small. */ +size_t c2_encode(const C2Unit *u, uint8_t *buf, size_t cap); + +#endif /* C2_IR_H */ diff --git a/src/checker2/c2_lrat.c b/src/checker2/c2_lrat.c new file mode 100644 index 000000000..1f22a5b5e --- /dev/null +++ b/src/checker2/c2_lrat.c @@ -0,0 +1,282 @@ +/* c2_lrat.c: DIMACS reader and RUP-only LRAT checker (see c2_lrat.h for the format and rules). */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_lrat.h" + +#define C2_LRAT_MAX_VARS 4000000 +#define C2_LRAT_MAX_ID 100000000L + +/* ------------------------------------------------------------------ tokens */ + +typedef struct { + const char *p; + size_t n, i; + long line; +} Lx; + +static void skip_ws(Lx *x) +{ + for (;;) { + while (x->i < x->n && (x->p[x->i] == ' ' || x->p[x->i] == '\t' || x->p[x->i] == '\r' || x->p[x->i] == '\n')) { + if (x->p[x->i] == '\n') x->line++; + x->i++; + } + if (x->i < x->n && x->p[x->i] == 'c') { /* comment to end of line */ + while (x->i < x->n && x->p[x->i] != '\n') x->i++; + continue; + } + return; + } +} + +/* signed decimal integer; -1 on malformed/overflow, 1 at end of input, 0 ok */ +static int rd_int(Lx *x, long *out) +{ + skip_ws(x); + if (x->i >= x->n) return 1; + int neg = 0; + if (x->p[x->i] == '-') { neg = 1; x->i++; } + if (x->i >= x->n || x->p[x->i] < '0' || x->p[x->i] > '9') return -1; + long v = 0; + while (x->i < x->n && x->p[x->i] >= '0' && x->p[x->i] <= '9') { + v = v * 10 + (x->p[x->i] - '0'); + if (v > C2_LRAT_MAX_ID) return -1; + x->i++; + } + if (x->i < x->n && !(x->p[x->i] == ' ' || x->p[x->i] == '\t' || x->p[x->i] == '\n' || x->p[x->i] == '\r')) return -1; + *out = neg ? -v : v; + return 0; +} + +/* ------------------------------------------------------------------ CNF */ + +void c2_cnf_free(C2Cnf *c) +{ + if (!c) return; + free(c->lits); + free(c->start); + memset(c, 0, sizeof *c); +} + +int c2_cnf_add(C2Cnf *c, const int32_t *lits, int n) +{ + size_t need = c->nlits + (size_t)n + 1; + if (need > c->lcap) { + size_t nc = c->lcap ? c->lcap : 1024; + while (nc < need) nc *= 2; + int32_t *nl = realloc(c->lits, nc * sizeof *nl); + if (!nl) return -1; + c->lits = nl; + c->lcap = nc; + } + if ((size_t)c->nclauses + 1 > c->scap) { + size_t nc = c->scap ? c->scap * 2 : 1024; + size_t *ns = realloc(c->start, nc * sizeof *ns); + if (!ns) return -1; + c->start = ns; + c->scap = nc; + } + c->start[c->nclauses++] = c->nlits; + for (int k = 0; k < n; k++) { + int32_t l = lits[k]; + int v = l < 0 ? -l : l; + if (l == 0 || v > C2_LRAT_MAX_VARS) return -1; + if (v > c->nvars) c->nvars = v; + c->lits[c->nlits++] = l; + } + c->lits[c->nlits++] = 0; + return 0; +} + +int c2_cnf_parse(const char *text, size_t len, C2Cnf *c, const char **why) +{ + memset(c, 0, sizeof *c); + Lx x = {text, len, 0, 1}; + skip_ws(&x); + if (len - x.i < 6 || memcmp(text + x.i, "p cnf ", 6) != 0) { *why = "CNF-HEADER"; return -1; } + x.i += 6; + long nv, nc; + if (rd_int(&x, &nv) || rd_int(&x, &nc) || nv < 0 || nc < 0 || nv > C2_LRAT_MAX_VARS) { *why = "CNF-HEADER"; return -1; } + int32_t buf[4096]; + int n = 0; + for (;;) { + long l; + int r = rd_int(&x, &l); + if (r == 1) break; + if (r < 0 || l > nv || -l > nv) { *why = "CNF-LITERAL"; c2_cnf_free(c); return -1; } + if (l == 0) { + if (c2_cnf_add(c, buf, n)) { *why = "CNF-RESOURCE"; c2_cnf_free(c); return -1; } + n = 0; + continue; + } + if (n == 4096) { *why = "CNF-CLAUSE-TOO-LONG"; c2_cnf_free(c); return -1; } + buf[n++] = (int32_t)l; + } + if (n != 0 || c->nclauses != nc) { *why = "CNF-COUNT"; c2_cnf_free(c); return -1; } /* GUARD:cnf-count */ + c->nvars = (int)nv; + return 0; +} + +char *c2_cnf_print(const C2Cnf *c, size_t *len) +{ + size_t cap = 64 + c->nlits * 12, n = 0; + char *s = malloc(cap); + if (!s) return NULL; + n += (size_t)snprintf(s + n, cap - n, "p cnf %d %d\n", c->nvars, c->nclauses); + for (size_t i = 0; i < c->nlits; i++) + n += (size_t)snprintf(s + n, cap - n, c->lits[i] ? "%d " : "%d\n", c->lits[i]); + *len = n; + return s; +} + +/* ------------------------------------------------------------------ LRAT */ + +typedef struct { + int32_t **cl; /* by id; NULL = absent or deleted; each ends with 0 */ + long cap; +} Db; + +static int db_put(Db *d, long id, int32_t *lits) +{ + if (id >= d->cap) { + long nc = d->cap ? d->cap : 1024; + while (nc <= id) nc *= 2; + int32_t **n = realloc(d->cl, (size_t)nc * sizeof *n); + if (!n) return -1; + memset(n + d->cap, 0, (size_t)(nc - d->cap) * sizeof *n); + d->cl = n; + d->cap = nc; + } + d->cl[id] = lits; + return 0; +} + +static int32_t *dup_clause(const int32_t *l, int n) +{ + int32_t *c = malloc(((size_t)n + 1) * sizeof *c); + if (!c) return NULL; + memcpy(c, l, (size_t)n * sizeof *c); + c[n] = 0; + return c; +} + +static int fail(C2LratResult *r, const char *rule, long line) +{ + r->ok = 0; + r->rule = rule; + r->line = line; + return -1; +} + +int c2_lrat_check(const C2Cnf *cnf, const char *proof, size_t len, C2LratResult *r) +{ + memset(r, 0, sizeof *r); + r->rule = "LRAT-OK"; + Db d = {NULL, 0}; + int nv = cnf->nvars; + int8_t *val = calloc((size_t)nv + 1, 1); /* +1 true, -1 false, 0 unassigned (by variable) */ + int32_t *assigned = malloc(((size_t)nv + 1) * sizeof *assigned); + int32_t *lits = malloc(((size_t)nv + 2) * sizeof *lits); + int rc = -1; + if (!val || !assigned || !lits) { fail(r, "LRAT-RESOURCE", 0); goto out; } + for (int i = 0; i < cnf->nclauses; i++) { + const int32_t *c = cnf->lits + cnf->start[i]; + int n = 0; + while (c[n]) n++; + int32_t *k = dup_clause(c, n); + if (!k || db_put(&d, i + 1, k)) { free(k); fail(r, "LRAT-RESOURCE", 0); goto out; } + } + /* Clause ids are capped at (input clauses + proof lines): textual LRAT writes one step per line, + * so an honest proof with dense ids never exceeds it, and a huge id cannot make the clause table huge (the table + * is indexed by id). */ + long max_id = cnf->nclauses + 1; + for (size_t i = 0; i < len; i++) max_id += proof[i] == '\n'; + Lx x = {proof, len, 0, 1}; + long last_id = cnf->nclauses; + for (;;) { + long id; + int t = rd_int(&x, &id); + if (t == 1) break; + long line = x.line; + if (t < 0 || id < 1) { fail(r, "LRAT-SYNTAX", line); goto out; } + skip_ws(&x); + if (x.i < x.n && x.p[x.i] == 'd') { /* deletion */ + x.i++; + for (;;) { + long del; + if (rd_int(&x, &del)) { fail(r, "LRAT-SYNTAX", line); goto out; } + if (del == 0) break; + if (del < 0 || del >= d.cap || !d.cl[del]) { fail(r, "LRAT-DELETE-UNKNOWN", line); goto out; } /* GUARD:delete-unknown */ + free(d.cl[del]); + d.cl[del] = NULL; + r->deletions++; + } + continue; + } + if (id <= last_id) { fail(r, "LRAT-ID-ORDER", line); goto out; } /* GUARD:id-order */ + if (id > max_id) { fail(r, "LRAT-ID-RANGE", line); goto out; } /* GUARD:id-range */ + last_id = id; + /* clause literals */ + int n = 0, na = 0, ok = 0; + for (;;) { + long l; + if (rd_int(&x, &l)) { fail(r, "LRAT-SYNTAX", line); goto out; } + if (l == 0) break; + if (l > nv || -l > nv) { fail(r, "LRAT-LITERAL", line); goto out; } /* GUARD:lrat-literal */ + if (n > nv) { fail(r, "LRAT-SYNTAX", line); goto out; } + lits[n++] = (int32_t)l; + } + /* assign every literal of the new clause false */ + int taut = 0; + for (int k = 0; k < n; k++) { + int v = lits[k] < 0 ? -lits[k] : lits[k]; + int8_t want = lits[k] < 0 ? 1 : -1; + if (val[v] == -want) taut = 1; + if (!val[v]) { val[v] = want; assigned[na++] = v; } + } + ok = taut; /* a tautology is implied by anything */ + /* hints */ + for (;;) { + long h; + if (rd_int(&x, &h)) { fail(r, "LRAT-SYNTAX", line); goto undo_fail; } + if (h == 0) break; + if (ok) continue; /* trailing hints after the conflict are allowed and ignored */ + if (h < 0) { fail(r, "LRAT-RAT-UNSUPPORTED", line); goto undo_fail; } /* GUARD:rat-refused */ + if (h >= d.cap || !d.cl[h]) { fail(r, "LRAT-HINT-UNKNOWN", line); goto undo_fail; } /* GUARD:hint-unknown */ + const int32_t *c = d.cl[h]; + int32_t unit = 0; + int nfree = 0, sat = 0; + for (int k = 0; c[k]; k++) { + int v = c[k] < 0 ? -c[k] : c[k]; + int8_t s = val[v] == 0 ? 0 : ((c[k] > 0) == (val[v] > 0) ? 1 : -1); + if (s == 1) { sat = 1; break; } + if (s == 0) { nfree++; unit = c[k]; } + } + if (sat || nfree > 1) { fail(r, "LRAT-HINT-NOT-UNIT", line); goto undo_fail; } /* GUARD:hint-not-unit */ + if (nfree == 0) { ok = 1; continue; } /* falsified: the step is proved */ + int v = unit < 0 ? -unit : unit; + val[v] = unit > 0 ? 1 : -1; + assigned[na++] = v; + } + for (int k = 0; k < na; k++) val[assigned[k]] = 0; + if (!ok) { fail(r, "LRAT-NO-CONFLICT", line); goto out; } /* GUARD:no-conflict */ + int32_t *k = dup_clause(lits, n); + if (!k || db_put(&d, id, k)) { free(k); fail(r, "LRAT-RESOURCE", line); goto out; } + r->steps++; + if (n == 0) { r->ok = 1; rc = 0; goto out; } /* empty clause: unsatisfiable */ + continue; + undo_fail: + for (int k = 0; k < na; k++) val[assigned[k]] = 0; + goto out; + } + fail(r, "LRAT-NO-EMPTY-CLAUSE", x.line); /* GUARD:no-empty-clause */ +out: + for (long i = 0; i < d.cap; i++) free(d.cl[i]); + free(d.cl); + free(val); + free(assigned); + free(lits); + return rc; +} diff --git a/src/checker2/c2_lrat.h b/src/checker2/c2_lrat.h new file mode 100644 index 000000000..cc0427b0c --- /dev/null +++ b/src/checker2/c2_lrat.h @@ -0,0 +1,49 @@ +/* c2_lrat: checker2's own DIMACS CNF reader and LRAT proof checker (omega#446). + * + * Trusted part of checker2. The SAT solver that writes proofs is NOT trusted and is not linked here. + * Written from the published formats only: DIMACS CNF ("p cnf V C", clauses of nonzero literals + * ended by 0, "c" comment lines) and textual LRAT (Cruz-Filipe, Heule, Hunt, Kaufmann, Schneider-Kamp, + * "Efficient certified RAT verification", CADE 2017): + * <id> <lit>* 0 <hint>* 0 add a clause, justified by reverse unit propagation (RUP) + * <id> d <id>* 0 delete clauses + * checker2 accepts RUP steps only: a negative hint (a RAT step) is refused, never interpreted. + * Each added clause is checked by assigning all its literals false and walking the hints in order: + * every hint must be unit (then its last literal is assigned) or falsified (then the step is + * proved). A hint that is neither, or a hint list that ends without a conflict, fails the proof. + * The proof is accepted only if it adds the empty clause. Added clause ids must be strictly + * increasing and at most (input clauses + proof lines), LRAT-ID-RANGE otherwise, so the id-indexed + * clause table stays proportional to the input. Fails closed on any malformed input. */ +#ifndef C2_LRAT_H +#define C2_LRAT_H + +#include <stddef.h> +#include <stdint.h> + +typedef struct { + int nvars; + int nclauses; + int32_t *lits; /* all clause literals, each clause ended by 0 */ + size_t nlits; + size_t *start; /* nclauses offsets into lits */ + size_t lcap, scap; /* allocated entries of lits / start */ +} C2Cnf; + +typedef struct { + int ok; /* 1: the empty clause was derived, the formula is unsatisfiable */ + const char *rule; /* stable failure name, "LRAT-OK" on success */ + long line; /* proof line of the failure, 0 if none */ + long steps, deletions; +} C2LratResult; + +/* 0 ok, -1 malformed (rule in *why). Caller frees with c2_cnf_free. */ +int c2_cnf_parse(const char *text, size_t len, C2Cnf *cnf, const char **why); +void c2_cnf_free(C2Cnf *cnf); +/* Append clause (lits[0..n), 0 excluded) to an in-memory formula (used by the bit-blaster). */ +int c2_cnf_add(C2Cnf *cnf, const int32_t *lits, int n); +/* DIMACS text of cnf into a malloc'd buffer. */ +char *c2_cnf_print(const C2Cnf *cnf, size_t *len); + +/* 0 proof accepted (empty clause derived), -1 refused (r->rule says why). */ +int c2_lrat_check(const C2Cnf *cnf, const char *proof, size_t len, C2LratResult *r); + +#endif /* C2_LRAT_H */ diff --git a/src/checker2/c2_receipt.c b/src/checker2/c2_receipt.c new file mode 100644 index 000000000..6d89bb3e6 --- /dev/null +++ b/src/checker2/c2_receipt.c @@ -0,0 +1,292 @@ +/* c2_receipt.c: signed Omega realization receipts v1. Normative layout: spec/one-layer-receipts.md. + * + * Signature code: the vendored in-house Ed25519 (src/searchtrace/sig, aienos native/sig @ 913b962, + * PROVENANCE.txt there). SHA-256: src/sha256.c. No other dependency. */ +#include "c2_receipt.h" + +#include <string.h> + +#include "sha256.h" +#include "searchtrace/sig/aienos_sig.h" + +static const uint8_t MAGIC[8] = {'O', 'M', 'R', 'C', 'P', 'T', '1', 0}; + +/* 578ada3c...9e76: aienos-owner-ceremony/20261014T114310Z/slot-9c-public.pem and + * owner-pubkeys.txt (aienos#380). Public data; tests/checker2/fixtures/owner holds the ceremony + * statement and its real signature, which test_c2_receipt verifies against this key. */ +const uint8_t c2r_owner_root_pk[32] = { + 0x57, 0x8a, 0xda, 0x3c, 0xb0, 0xc2, 0xd1, 0x54, 0x62, 0x3a, 0xc0, 0x89, 0x19, 0x10, 0x23, 0xc8, + 0xad, 0x4b, 0xc5, 0xe6, 0x3b, 0x8c, 0xcd, 0x1a, 0x38, 0xdb, 0x2d, 0x67, 0x9b, 0x8c, 0x9e, 0x76}; + +/* Derived from c2r_test_seed by aienos_ed25519_public_key; test_c2_receipt re-derives and compares. */ +const uint8_t c2r_test_pk[32] = { + 0x60, 0x28, 0x10, 0xd4, 0x3c, 0x01, 0x15, 0xdf, 0x87, 0x7b, 0x0c, 0xf8, 0xc3, 0x27, 0x01, 0x0e, + 0x5a, 0x7e, 0x57, 0x04, 0x90, 0xc8, 0x5e, 0x31, 0x46, 0x6c, 0x0c, 0xff, 0x6c, 0xa3, 0x74, 0xc5}; + +void c2r_test_seed(uint8_t seed[32]) +{ + static const char s[] = "OMEGA-CHECKER2-TEST-KEY-v1 NOT FOR PRODUCTION"; + sha256_hash((const uint8_t *)s, sizeof s - 1, seed); +} + +const char *c2r_reason(int code) +{ + switch (code) { + case C2R_OK: return "OK"; + case C2R_E_SIZE: return "SIZE"; + case C2R_E_MAGIC: return "MAGIC"; + case C2R_E_VERSION: return "VERSION"; + case C2R_E_ALG: return "SIGNATURE_ALGORITHM"; + case C2R_E_CLASS: return "SIGNER_CLASS"; + case C2R_E_EVIDENCE: return "EVIDENCE_CLASS"; + case C2R_E_EPOCH_ORDER: return "EPOCH_ORDER"; + case C2R_E_TEST_IN_PRODUCTION: return "TEST_SIGNER_IN_PRODUCTION"; + case C2R_E_UNTRUSTED_SIGNER: return "UNTRUSTED_SIGNER"; + case C2R_E_BAD_SIGNATURE: return "BAD_SIGNATURE"; + case C2R_E_REVOKED: return "REVOKED"; + case C2R_E_STALE: return "STALE_EPOCH"; + case C2R_E_EXPIRED: return "EXPIRED"; + case C2R_E_NOT_YET_VALID: return "NOT_YET_VALID"; + case C2R_E_WRONG_TARGET: return "WRONG_TARGET"; + case C2R_E_WRONG_FIRMWARE: return "WRONG_FIRMWARE"; + case C2R_E_PROGRAM_MISMATCH: return "PROGRAM_MISMATCH"; + case C2R_E_EXECUTABLE_MISMATCH: return "EXECUTABLE_MISMATCH"; + case C2R_E_ARG: return "ARGUMENT"; + case C2R_E_KEY_CLASS: return "KEY_CLASS"; + case C2R_E_UNTRUSTED_CHECKER: return "UNTRUSTED_CHECKER"; + case C2R_E_WRONG_PRODUCER: return "WRONG_PRODUCER"; + case C2R_E_DEPS_MISMATCH: return "DEPENDENCIES_MISMATCH"; + default: return "UNKNOWN"; + } +} + +static void put16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } +static void put64(uint8_t *p, uint64_t v) +{ + for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); +} +static uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); } +static uint64_t get64(const uint8_t *p) +{ + uint64_t v = 0; + for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; + return v; +} + +void c2r_target_id(const char *name, uint8_t out[32]) +{ + static const char tag[] = "OMEGA-TARGET-V1"; /* sizeof includes the NUL */ + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)tag, sizeof tag); + sha256_update(&c, (const uint8_t *)name, strlen(name)); + sha256_final(&c, out); +} + +int c2r_deps_digest(const uint8_t (*ids)[32], unsigned n, uint8_t out[32]) +{ + static const char tag[] = "OMEGA-RECEIPT-DEPS-V1"; + for (unsigned i = 1; i < n; i++) + if (memcmp(ids[i - 1], ids[i], 32) >= 0) return -1; + uint8_t cnt[4] = {(uint8_t)n, (uint8_t)(n >> 8), (uint8_t)(n >> 16), (uint8_t)(n >> 24)}; + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)tag, sizeof tag); + sha256_update(&c, cnt, 4); + for (unsigned i = 0; i < n; i++) sha256_update(&c, ids[i], 32); + sha256_final(&c, out); + return 0; +} + +/* Offsets (spec/one-layer-receipts.md section 2). */ +enum { + O_MAGIC = 0, O_VER = 8, O_CLASS = 10, O_ALG = 12, O_EV = 14, + O_REQ = 16, O_PROG = 48, O_EXE = 80, O_DEPS = 112, O_CHK = 144, O_PCHK = 176, + O_TGT = 208, O_FW = 240, O_IN = 272, O_EPOCH = 304, O_EXP = 312, O_KFP = 320, O_SIG = 352 +}; + +void c2r_encode(const C2Receipt *r, uint8_t out[C2R_SIZE]) +{ + memcpy(out + O_MAGIC, MAGIC, 8); + put16(out + O_VER, r->version); + put16(out + O_CLASS, r->signer_class); + put16(out + O_ALG, r->alg); + put16(out + O_EV, r->evidence_class); + memcpy(out + O_REQ, r->requirements, 32); + memcpy(out + O_PROG, r->program, 32); + memcpy(out + O_EXE, r->executable, 32); + memcpy(out + O_DEPS, r->dependencies, 32); + memcpy(out + O_CHK, r->checker, 32); + memcpy(out + O_PCHK, r->producer_checker, 32); + memcpy(out + O_TGT, r->target, 32); + memcpy(out + O_FW, r->firmware, 32); + memcpy(out + O_IN, r->input, 32); + put64(out + O_EPOCH, r->policy_epoch); + put64(out + O_EXP, r->expiry_epoch); + memcpy(out + O_KFP, r->key_fp, 32); + memcpy(out + O_SIG, r->sig, 64); +} + +int c2r_decode(const uint8_t *b, size_t len, C2Receipt *r) +{ + if (!b || !r) return C2R_E_ARG; + if (len != C2R_SIZE) return C2R_E_SIZE; + if (memcmp(b, MAGIC, 8) != 0) return C2R_E_MAGIC; /* GUARD:magic */ + r->version = get16(b + O_VER); + r->signer_class = get16(b + O_CLASS); + r->alg = get16(b + O_ALG); + r->evidence_class = get16(b + O_EV); + if (r->version != C2R_FORMAT_VERSION) return C2R_E_VERSION; + if (r->alg != C2R_ALG_ED25519) return C2R_E_ALG; + if (r->signer_class != C2R_CLASS_TEST && r->signer_class != C2R_CLASS_OWNER) return C2R_E_CLASS; + if (r->evidence_class != C2R_EV_IR_CHECKED && r->evidence_class != C2R_EV_IR_CHECKED_LRAT) + return C2R_E_EVIDENCE; + memcpy(r->requirements, b + O_REQ, 32); + memcpy(r->program, b + O_PROG, 32); + memcpy(r->executable, b + O_EXE, 32); + memcpy(r->dependencies, b + O_DEPS, 32); + memcpy(r->checker, b + O_CHK, 32); + memcpy(r->producer_checker, b + O_PCHK, 32); + memcpy(r->target, b + O_TGT, 32); + memcpy(r->firmware, b + O_FW, 32); + memcpy(r->input, b + O_IN, 32); + r->policy_epoch = get64(b + O_EPOCH); + r->expiry_epoch = get64(b + O_EXP); + if (r->expiry_epoch < r->policy_epoch) return C2R_E_EPOCH_ORDER; /* GUARD:epoch-order */ + memcpy(r->key_fp, b + O_KFP, 32); + memcpy(r->sig, b + O_SIG, 64); + return C2R_OK; +} + +void c2r_id(const uint8_t buf[C2R_SIZE], uint8_t out[32]) { sha256_hash(buf, C2R_SIZE, out); } + +void c2r_signed_message(const uint8_t buf[C2R_SIZE], uint8_t msg[C2R_SIGNED_MSG_LEN]) +{ + static const char body_tag[] = "OMEGA-REALIZATION-RECEIPT-V1"; + static const char sig_tag[] = "OMEGA-REALIZATION-RECEIPT-SIG-V1"; + _Static_assert(sizeof sig_tag + 32 == C2R_SIGNED_MSG_LEN, "signed message length"); + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)body_tag, sizeof body_tag); + sha256_update(&c, buf, C2R_SIGNED_LEN); + memcpy(msg, sig_tag, sizeof sig_tag); + sha256_final(&c, msg + sizeof sig_tag); +} + +static int fields_ok(const C2Receipt *r) +{ + uint8_t tmp[C2R_SIZE]; + C2Receipt chk; + C2Receipt copy = *r; + memset(copy.key_fp, 0, 32); + memset(copy.sig, 0, 64); + c2r_encode(©, tmp); + return c2r_decode(tmp, C2R_SIZE, &chk); +} + +int c2r_sign_test(C2Receipt *r, const uint8_t seed[32], uint8_t out[C2R_SIZE]) +{ + if (!r || !seed || !out) return C2R_E_ARG; + if (r->signer_class != C2R_CLASS_TEST) return C2R_E_KEY_CLASS; /* GUARD:sign-test-class-only */ + uint8_t pk[32]; + if (aienos_ed25519_public_key(pk, seed) != AIENOS_SIG_OK) return C2R_E_ARG; + /* Only the TEST key may sign TEST class here; any other secret is refused, so a stray key can + * never mint a receipt that a TEST-anchored verifier would also take. */ + if (memcmp(pk, c2r_test_pk, 32) != 0) return C2R_E_KEY_CLASS; /* GUARD:sign-test-key-only */ + int e = fields_ok(r); + if (e) return e; + sha256_hash(pk, 32, r->key_fp); + memset(r->sig, 0, 64); + c2r_encode(r, out); + uint8_t msg[C2R_SIGNED_MSG_LEN]; + c2r_signed_message(out, msg); + if (aienos_ed25519_sign(r->sig, msg, sizeof msg, seed) != AIENOS_SIG_OK) return C2R_E_ARG; + memcpy(out + O_SIG, r->sig, 64); + return C2R_OK; +} + +int c2r_attach(C2Receipt *r, const uint8_t pk[32], const uint8_t sig[64], uint8_t out[C2R_SIZE]) +{ + if (!r || !pk || !sig || !out) return C2R_E_ARG; + int e = fields_ok(r); + if (e) return e; + sha256_hash(pk, 32, r->key_fp); + memcpy(r->sig, sig, 64); + c2r_encode(r, out); + uint8_t msg[C2R_SIGNED_MSG_LEN]; + c2r_signed_message(out, msg); + if (aienos_ed25519_verify(sig, msg, sizeof msg, pk) != AIENOS_SIG_OK) return C2R_E_BAD_SIGNATURE; + return C2R_OK; +} + +/* The anchor of the receipt's class whose fingerprint matches, or NULL. */ +static const uint8_t *anchor_for(const uint8_t (*set)[32], unsigned n, const uint8_t fp[32]) +{ + for (unsigned i = 0; set && i < n; i++) { + uint8_t h[32]; + sha256_hash(set[i], 32, h); + if (memcmp(h, fp, 32) == 0) return set[i]; + } + return NULL; +} + +static int in_set(const uint8_t (*set)[32], unsigned n, const uint8_t v[32]) +{ + for (unsigned i = 0; set && i < n; i++) + if (memcmp(set[i], v, 32) == 0) return 1; + return 0; +} + +int c2r_verify(const uint8_t *buf, size_t len, const C2ReceiptPolicy *pol, const C2ReceiptExpect *ex, + C2Receipt *out) +{ + C2Receipt r; + if (!pol) return C2R_E_ARG; + /* 1. structure */ + int e = c2r_decode(buf, len, &r); + if (e) return e; + /* 2. class policy: production takes OWNER only, and only Drake's root */ + if (pol->production && r.signer_class != C2R_CLASS_OWNER) return C2R_E_TEST_IN_PRODUCTION; /* GUARD:production-class */ + const uint8_t *key; + if (r.signer_class == C2R_CLASS_TEST) { + key = anchor_for(pol->test_anchors, pol->n_test, r.key_fp); + } else { + key = anchor_for(pol->owner_anchors, pol->n_owner, r.key_fp); + /* production: an owner anchor that is not the compiled-in root is not an owner */ + if (key && pol->production && memcmp(key, c2r_owner_root_pk, 32) != 0) key = NULL; /* GUARD:production-root */ + } + if (!key) return C2R_E_UNTRUSTED_SIGNER; /* GUARD:anchor */ + /* a TEST-class receipt signed by an owner anchor key (or the reverse) is refused: the key + * must not be an anchor of the other class either */ + int other = r.signer_class == C2R_CLASS_TEST ? anchor_for(pol->owner_anchors, pol->n_owner, r.key_fp) != NULL + : anchor_for(pol->test_anchors, pol->n_test, r.key_fp) != NULL; + if (other) return C2R_E_UNTRUSTED_SIGNER; /* GUARD:cross-class */ + /* 3. signature over the domain-separated digest */ + uint8_t msg[C2R_SIGNED_MSG_LEN]; + c2r_signed_message(buf, msg); + if (aienos_ed25519_verify(r.sig, msg, sizeof msg, key) != AIENOS_SIG_OK) return C2R_E_BAD_SIGNATURE; /* GUARD:signature */ + /* 4. revocation (receipt id, then signer key) */ + uint8_t id[32]; + c2r_id(buf, id); + if (in_set(pol->revoked_ids, pol->n_revoked_ids, id)) return C2R_E_REVOKED; /* GUARD:revoked-id */ + if (in_set(pol->revoked_keys, pol->n_revoked_keys, r.key_fp)) return C2R_E_REVOKED; /* GUARD:revoked-key */ + /* 5. freshness */ + if (r.policy_epoch < pol->epoch_floor) return C2R_E_STALE; /* GUARD:stale */ + if (pol->current_epoch < r.policy_epoch) return C2R_E_NOT_YET_VALID; /* GUARD:not-yet-valid */ + if (pol->current_epoch > r.expiry_epoch) return C2R_E_EXPIRED; /* GUARD:expired */ + /* 6. checker identity: only verdicts of a checker2 build the verifier anchors count; an empty + * or missing list refuses everything */ + if (!in_set(pol->checkers, pol->n_checkers, r.checker)) return C2R_E_UNTRUSTED_CHECKER; /* GUARD:checker-identity */ + /* 7. binding to what is being admitted */ + if (ex) { + if (ex->target && memcmp(ex->target, r.target, 32) != 0) return C2R_E_WRONG_TARGET; /* GUARD:target */ + if (ex->firmware && memcmp(ex->firmware, r.firmware, 32) != 0) return C2R_E_WRONG_FIRMWARE; /* GUARD:firmware */ + if (ex->program && memcmp(ex->program, r.program, 32) != 0) return C2R_E_PROGRAM_MISMATCH; /* GUARD:program */ + if (ex->executable && memcmp(ex->executable, r.executable, 32) != 0) return C2R_E_EXECUTABLE_MISMATCH; /* GUARD:executable */ + if (ex->producer_checker && memcmp(ex->producer_checker, r.producer_checker, 32) != 0) return C2R_E_WRONG_PRODUCER; /* GUARD:producer */ + /* the dependency ids are bound by digest only; v1 does not resolve dependency receipts */ + if (ex->dependencies && memcmp(ex->dependencies, r.dependencies, 32) != 0) return C2R_E_DEPS_MISMATCH; /* GUARD:dependencies */ + } + if (out) *out = r; + return C2R_OK; +} diff --git a/src/checker2/c2_receipt.h b/src/checker2/c2_receipt.h new file mode 100644 index 000000000..b695f5585 --- /dev/null +++ b/src/checker2/c2_receipt.h @@ -0,0 +1,145 @@ +/* c2_receipt: signed Omega realization receipts, format v1 (spec/one-layer-receipts.md, normative). + * + * A receipt is 416 bytes, fixed layout, little-endian, no text, no timestamps. It binds one + * checker2 verdict to the exact bytes it judged (requirements, canonical program bytes, executable + * bytes, dependencies, checker identities, evidence class, target, firmware, input identity) and a + * policy-epoch window, and carries a pure Ed25519 signature (RFC 8032 section 5.1) made by a key of + * one signer class: TEST (class 1, automated tests only) or OWNER (class 2, Drake's owner root, held + * on a YubiKey; this code never sees that private key). The class numbers equal aienos + * native/kernel/artifact/osc_unit.h OSC_SIGNER_TEST / OSC_SIGNER_OWNER. + * + * A signature establishes provenance (who vouched), never correctness. A receipt grants no + * capability. Receipt identity = SHA-256 of all 416 bytes; a receipt is never rewritten. + * + * No heap, no clock, no I/O in this file (the store and the tool live in c2_receipt_tool.c). */ +#ifndef C2_RECEIPT_H +#define C2_RECEIPT_H + +#include <stddef.h> +#include <stdint.h> + +#define C2R_SIZE 416u +#define C2R_SIGNED_LEN 352u /* bytes [0, 352) are covered by the signature */ +#define C2R_FORMAT_VERSION 1u +#define C2R_ALG_ED25519 1u + +enum { C2R_CLASS_TEST = 1, C2R_CLASS_OWNER = 2 }; + +/* Evidence class: what checker2 actually did before the receipt was signed. */ +enum { + C2R_EV_IR_CHECKED = 1, /* checker2 decoded the canonical bytes and accepted them; + the executable is bound by hash, NOT translation-validated */ + C2R_EV_IR_CHECKED_LRAT = 2 /* as 1, plus an LRAT-checked proof of the declared property */ +}; + +typedef struct { + uint16_t version; /* C2R_FORMAT_VERSION */ + uint16_t signer_class; /* C2R_CLASS_* */ + uint16_t alg; /* C2R_ALG_ED25519 */ + uint16_t evidence_class; /* C2R_EV_* */ + uint8_t requirements[32]; /* SHA-256 of the requirements object bytes */ + uint8_t program[32]; /* SHA-256 of the canonical program bytes (OSC IR) */ + uint8_t executable[32]; /* SHA-256 of the realized executable bytes */ + uint8_t dependencies[32]; /* c2r_deps_digest over the dependency receipt ids */ + uint8_t checker[32]; /* identity of the checker2 build that judged */ + uint8_t producer_checker[32]; /* identity of the producer's checker (oscc binary hash) */ + uint8_t target[32]; /* c2r_target_id(target name) */ + uint8_t firmware[32]; /* SHA-256 of the firmware image, all zero = none (host) */ + uint8_t input[32]; /* SHA-256 of the input / dataset identity, zero = none */ + uint64_t policy_epoch; /* epoch the receipt was issued under */ + uint64_t expiry_epoch; /* last epoch at which it is fresh (>= policy_epoch) */ + uint8_t key_fp[32]; /* SHA-256 of the signer's 32-byte Ed25519 public key */ + uint8_t sig[64]; +} C2Receipt; + +/* Named verdicts. 0 is the only acceptance. Values are part of the spec; never renumbered. */ +enum { + C2R_OK = 0, + C2R_E_SIZE = 1, /* not exactly 416 bytes */ + C2R_E_MAGIC = 2, + C2R_E_VERSION = 3, + C2R_E_ALG = 4, + C2R_E_CLASS = 5, /* signer class not TEST or OWNER */ + C2R_E_EVIDENCE = 6, /* unknown evidence class */ + C2R_E_EPOCH_ORDER = 7, /* expiry_epoch < policy_epoch */ + /* 8 is unassigned (format v1 has no reserved bytes) */ + C2R_E_TEST_IN_PRODUCTION = 9, + C2R_E_UNTRUSTED_SIGNER = 10, /* key fingerprint not in the anchor set of its class */ + C2R_E_BAD_SIGNATURE = 11, + C2R_E_REVOKED = 12, /* receipt id or signer key fingerprint is revoked */ + C2R_E_STALE = 13, /* policy_epoch below the verifier's floor: replay of a superseded receipt */ + C2R_E_EXPIRED = 14, /* current epoch past expiry_epoch */ + C2R_E_NOT_YET_VALID = 15, /* current epoch before policy_epoch */ + C2R_E_WRONG_TARGET = 16, + C2R_E_WRONG_FIRMWARE = 17, + C2R_E_PROGRAM_MISMATCH = 18, + C2R_E_EXECUTABLE_MISMATCH = 19, + C2R_E_ARG = 20, + C2R_E_KEY_CLASS = 21, /* signing: key not allowed for the requested class */ + C2R_E_UNTRUSTED_CHECKER = 22, /* checker identity not in the verifier's checker list */ + C2R_E_WRONG_PRODUCER = 23, /* producer checker identity differs from the expected one */ + C2R_E_DEPS_MISMATCH = 24 /* dependency digest differs from the expected one */ +}; +const char *c2r_reason(int code); + +/* Verifier policy. Anchors are raw 32-byte Ed25519 public keys; the key used is always taken from + * the anchor set of the receipt's class, never from the receipt. production = 1 refuses TEST class + * outright and accepts only the anchors in owner_anchors. */ +typedef struct { + int production; + const uint8_t (*test_anchors)[32]; unsigned n_test; + const uint8_t (*owner_anchors)[32]; unsigned n_owner; + const uint8_t (*revoked_ids)[32]; unsigned n_revoked_ids; /* receipt ids */ + const uint8_t (*revoked_keys)[32]; unsigned n_revoked_keys; /* key fingerprints */ + /* checker2 identities (section 5) whose verdicts this verifier accepts. Required: an empty or + * NULL list refuses every receipt (C2R_E_UNTRUSTED_CHECKER), so a policy cannot forget it. */ + const uint8_t (*checkers)[32]; unsigned n_checkers; + uint64_t epoch_floor; /* receipts issued under an older epoch are refused (C2R_E_STALE) */ + uint64_t current_epoch; +} C2ReceiptPolicy; + +/* What the admitting side expects the receipt to be about. NULL fields are not checked. */ +typedef struct { + const uint8_t *target; /* 32 bytes: c2r_target_id of the launching target */ + const uint8_t *firmware; /* 32 bytes */ + const uint8_t *program; /* 32 bytes: SHA-256 of the program bytes being admitted */ + const uint8_t *executable; /* 32 bytes: SHA-256 of the executable bytes being admitted */ + const uint8_t *producer_checker; /* 32 bytes: identity of the producer's checker (oscc hash) */ + const uint8_t *dependencies; /* 32 bytes: c2r_deps_digest of the expected dependency receipt ids. + Format v1 binds the ids only: the dependency receipts themselves + are NOT fetched, resolved or verified here. */ +} C2ReceiptExpect; + +/* Drake's owner root public key (aienos#380 ceremony, YubiKey PIV slot 9c). */ +extern const uint8_t c2r_owner_root_pk[32]; +/* The TEST-tier key: secret seed = SHA-256("OMEGA-CHECKER2-TEST-KEY-v1 NOT FOR PRODUCTION"). + * Public on purpose: anything it signs is TEST class and refused in production. */ +void c2r_test_seed(uint8_t seed[32]); +extern const uint8_t c2r_test_pk[32]; + +void c2r_target_id(const char *target_name, uint8_t out[32]); +/* SHA-256("OMEGA-RECEIPT-DEPS-V1\0" || u32 count || ids in ascending byte order). ids must be + * strictly ascending (sorted, unique); returns -1 otherwise. count 0 is allowed. */ +int c2r_deps_digest(const uint8_t (*ids)[32], unsigned n, uint8_t out[32]); + +void c2r_encode(const C2Receipt *r, uint8_t out[C2R_SIZE]); +/* Structural decode only (size, magic, version, alg, class, evidence, epoch order). */ +int c2r_decode(const uint8_t *buf, size_t len, C2Receipt *r); +void c2r_id(const uint8_t buf[C2R_SIZE], uint8_t out[32]); +/* The exact bytes the Ed25519 signature covers (65 bytes): + * "OMEGA-REALIZATION-RECEIPT-SIG-V1\0" || SHA-256("OMEGA-REALIZATION-RECEIPT-V1\0" || buf[0,352)). */ +#define C2R_SIGNED_MSG_LEN 65u +void c2r_signed_message(const uint8_t buf[C2R_SIZE], uint8_t msg[C2R_SIGNED_MSG_LEN]); + +/* Sign r (fills key_fp and sig, then encodes into out). TEST class only takes the TEST key; + * OWNER class is refused here (the owner key never leaves the YubiKey: use c2r_attach). */ +int c2r_sign_test(C2Receipt *r, const uint8_t seed[32], uint8_t out[C2R_SIZE]); +/* Attach a signature made elsewhere (YubiKey) over c2r_signed_message for public key pk. + * Verifies it before returning 0. */ +int c2r_attach(C2Receipt *r, const uint8_t pk[32], const uint8_t sig[64], uint8_t out[C2R_SIZE]); + +/* Full admission check, in spec order. Returns C2R_OK or the first failing named reason. */ +int c2r_verify(const uint8_t *buf, size_t len, const C2ReceiptPolicy *pol, const C2ReceiptExpect *ex, + C2Receipt *out); + +#endif /* C2_RECEIPT_H */ diff --git a/src/checker2/checker2_main.c b/src/checker2/checker2_main.c new file mode 100644 index 000000000..adbfbd23a --- /dev/null +++ b/src/checker2/checker2_main.c @@ -0,0 +1,517 @@ +/* checker2: the independent checker's command line (omega#446, spec/one-layer-receipts.md). + * + * checker2 check <unit.ir> judge canonical OSC IR bytes + * checker2 version print the checker identity + * checker2 prove-cnf <unit.ir> <func> <out.cnf> NO-TRAP formula of func (c2_blast.h) + * checker2 prove-check <unit.ir> <func> <proof> rebuild that formula, check an LRAT proof + * checker2 receipt issue <unit.ir> <exe> --target T --epoch E --expiry X --out-dir D + * [--firmware F.bin] [--requirements R] [--input I] [--producer P] + * [--dep ID]... [--lrat FUNC=PROOF]... (proofs checked, evidence class 2) + * check, sign with the TEST key, store by id + * checker2 receipt tbs <receipt> <out65> write the 65-byte message an owner key signs + * checker2 receipt attach <receipt> <sig64> --out-dir D + * verify an OWNER signature, store by id + * checker2 receipt verify <receipt> <unit.ir> <exe> --target T --epoch E + * [--allow-test-key | --production] [--floor N] [--firmware F.bin] [--revoked-id HEX]... + * [--revoked-key HEX]... [--lrat FUNC=PROOF]... (required for evidence class 2) + * [--producer P] [--dep ID]... [--accept-checker ID]... + * the receipt's checker must be this build or an --accept-checker identity; + * producer and dependency digests must equal the given ones (none = none) + * production policy by default: a TEST receipt is refused unless + * --allow-test-key is given (qualification and test runs only) + * + * Exit: 0 accept / done, 1 reject / refused, 2 usage or I/O error. */ +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +#include "c2_blast.h" +#include "c2_ir.h" +#include "c2_lrat.h" +#include "c2_receipt.h" +#include "sha256.h" + +#define C2_CHECKER_VERSION "checker2 1 (omega#446)" +#ifndef C2_SOURCES_SHA256 +#define C2_SOURCES_SHA256 "unset" +#endif + +static void hex(const uint8_t *b, size_t n, char *out) +{ + static const char d[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { out[2 * i] = d[b[i] >> 4]; out[2 * i + 1] = d[b[i] & 15]; } + out[2 * n] = 0; +} + +static int unhex32(const char *s, uint8_t out[32]) +{ + if (strlen(s) != 64) return -1; + for (int i = 0; i < 32; i++) { + unsigned v = 0; + for (int k = 0; k < 2; k++) { + char c = s[2 * i + k]; + v <<= 4; + if (c >= '0' && c <= '9') v |= (unsigned)(c - '0'); + else if (c >= 'a' && c <= 'f') v |= (unsigned)(c - 'a' + 10); + else return -1; + } + out[i] = (uint8_t)v; + } + return 0; +} + +static uint8_t *slurp(const char *path, size_t *len) +{ + FILE *f = fopen(path, "rb"); + if (!f) { fprintf(stderr, "checker2: cannot open %s: %s\n", path, strerror(errno)); return NULL; } + size_t cap = 1 << 16, n = 0; + uint8_t *b = malloc(cap); + while (b) { + size_t r = fread(b + n, 1, cap - n, f); + n += r; + if (n < cap) break; + if (cap >= (1u << 28)) { free(b); b = NULL; break; } + uint8_t *nb = realloc(b, cap * 2); + if (!nb) { free(b); b = NULL; break; } + b = nb; + cap *= 2; + } + int err = ferror(f); + fclose(f); + if (!b || err) { free(b); fprintf(stderr, "checker2: cannot read %s\n", path); return NULL; } + *len = n; + return b; +} + +static int file_sha(const char *path, uint8_t out[32]) +{ + size_t n; + uint8_t *b = slurp(path, &n); + if (!b) return -1; + sha256_hash(b, n, out); + free(b); + return 0; +} + +/* identity = SHA-256(version string ‖ 0 ‖ sources digest hex) (spec section 5) */ +static void checker_id(uint8_t out[32]) +{ + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)C2_CHECKER_VERSION, sizeof C2_CHECKER_VERSION); + sha256_update(&c, (const uint8_t *)C2_SOURCES_SHA256, strlen(C2_SOURCES_SHA256)); + sha256_final(&c, out); +} + +static int judge(const char *path, uint8_t ir_sha[32], int quiet) +{ + size_t n; + uint8_t *b = slurp(path, &n); + if (!b) return 2; + sha256_hash(b, n, ir_sha); + C2Verdict v; + int rc = c2_check_bytes(b, n, &v); + free(b); + char h[65]; + hex(ir_sha, 32, h); + if (rc == 0) { + if (!quiet) printf("checker2=ACCEPT ir_sha256=%s\n", h); + return 0; + } + printf("checker2=REJECT rule=%s func=%d insn=%d ir_sha256=%s detail=%s\n", v.rule, v.func, v.insn, h, v.detail); + return 1; +} + +/* create a new file with exactly these bytes; never overwrite */ +static int write_new(const char *path, const uint8_t *b, size_t n) +{ + int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0444); + if (fd < 0) { fprintf(stderr, "checker2: cannot create %s: %s\n", path, strerror(errno)); return 2; } + ssize_t w = write(fd, b, n); + if (w < 0 || (size_t)w != n || fsync(fd) != 0 || close(fd) != 0) { fprintf(stderr, "checker2: write %s failed\n", path); return 2; } + return 0; +} + +/* write bytes to D/<id>.rcpt: exclusive create; identical existing bytes is a no-op */ +static int store(const char *dir, const uint8_t r[C2R_SIZE]) +{ + uint8_t id[32]; + char h[65], path[4096]; + c2r_id(r, id); + hex(id, 32, h); + if (snprintf(path, sizeof path, "%s/%s.rcpt", dir, h) >= (int)sizeof path) return 2; + int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0444); + if (fd < 0 && errno == EEXIST) { + size_t n; + uint8_t *old = slurp(path, &n); + int same = old && n == C2R_SIZE && memcmp(old, r, C2R_SIZE) == 0; + free(old); + if (same) { printf("receipt=%s unchanged\n", path); return 0; } + fprintf(stderr, "checker2: %s exists with different bytes; receipts are never rewritten\n", path); + return 1; + } + if (fd < 0) { fprintf(stderr, "checker2: cannot create %s: %s\n", path, strerror(errno)); return 2; } + ssize_t w = write(fd, r, C2R_SIZE); + if (w != C2R_SIZE || fsync(fd) != 0 || close(fd) != 0) { fprintf(stderr, "checker2: write %s failed\n", path); return 2; } + printf("receipt=%s\n", path); + return 0; +} + +static const char *opt(int argc, char **argv, const char *name) +{ + for (int i = 0; i + 1 < argc; i++) + if (strcmp(argv[i], name) == 0) return argv[i + 1]; + return NULL; +} + +static int flag(int argc, char **argv, const char *name) +{ + for (int i = 0; i < argc; i++) + if (strcmp(argv[i], name) == 0) return 1; + return 0; +} + +static int opt_u64(int argc, char **argv, const char *name, uint64_t *out, int required) +{ + const char *s = opt(argc, argv, name); + if (!s) { + if (required) fprintf(stderr, "checker2: %s is required\n", name); + return required ? -1 : 0; + } + char *end; + errno = 0; + unsigned long long v = strtoull(s, &end, 10); + if (errno || *end || !*s || s[0] == '-') { fprintf(stderr, "checker2: bad number for %s\n", name); return -1; } + *out = v; + return 0; +} + +static int opt_sha_file(int argc, char **argv, const char *name, uint8_t out[32]) +{ + const char *s = opt(argc, argv, name); + memset(out, 0, 32); + return s ? file_sha(s, out) : 0; +} + +static int property_cnf(const char *ir, const char *func, C2Cnf *cnf, C2BlastInfo *bi, uint8_t ir_sha[32]); + +/* Every "--lrat FUNC=PROOF" pair: rebuild FUNC's NO-TRAP formula from the IR bytes and check the + * proof. The requirements object (spec section 10) is + * "OMEGA-REQUIREMENTS-V1\n" then per pair, FUNC strictly ascending: + * "no-trap-except-requires <FUNC> proof_sha256=<hex>\n" + * Returns 0 with *count pairs and req = SHA-256 of the object (object text in obj, may be NULL), + * 1 if a proof is refused or the order is wrong, 2 on usage or I/O error. */ +static int lrat_requirements(int argc, char **argv, const char *ir, uint8_t req[32], int *count, char *obj, size_t objcap) +{ + char text[8192], prev[256] = ""; + size_t tn = (size_t)snprintf(text, sizeof text, "OMEGA-REQUIREMENTS-V1\n"); + *count = 0; + for (int i = 0; i + 1 < argc; i++) { + if (strcmp(argv[i], "--lrat") != 0) continue; + const char *arg = argv[i + 1], *eq = strchr(arg, '='); + if (!eq || eq == arg || (size_t)(eq - arg) >= sizeof prev) { fprintf(stderr, "checker2: --lrat wants FUNC=PROOF\n"); return 2; } + char func[256]; + memcpy(func, arg, (size_t)(eq - arg)); + func[eq - arg] = 0; + if (*count && strcmp(prev, func) >= 0) { fprintf(stderr, "checker2: --lrat functions must be strictly ascending\n"); return 1; } + snprintf(prev, sizeof prev, "%s", func); + C2Cnf cnf; + C2BlastInfo bi; + uint8_t s[32], ps[32]; + int rc = property_cnf(ir, func, &cnf, &bi, s); + if (rc) return rc; + size_t n; + uint8_t *p = slurp(eq + 1, &n); + if (!p) { c2_cnf_free(&cnf); return 2; } + sha256_hash(p, n, ps); + C2LratResult r; + int e = c2_lrat_check(&cnf, (const char *)p, n, &r); + free(p); + c2_cnf_free(&cnf); + if (e) { printf("lrat=REFUSED func=%s rule=%s line=%ld\n", func, r.rule, r.line); return 1; } + char h[65]; + hex(ps, 32, h); + int k = snprintf(text + tn, sizeof text - tn, "%s %s proof_sha256=%s\n", C2_PROPERTY_NOTRAP, func, h); + if (k < 0 || (size_t)k >= sizeof text - tn) { fprintf(stderr, "checker2: too many --lrat\n"); return 2; } + tn += (size_t)k; + (*count)++; + } + sha256_hash((const uint8_t *)text, tn, req); + if (obj) snprintf(obj, objcap, "%s", text); + return 0; +} + +static int receipt_issue(int argc, char **argv) +{ + if (argc < 2) return 2; + const char *ir = argv[0], *exe = argv[1], *target = opt(argc, argv, "--target"), *dir = opt(argc, argv, "--out-dir"); + const char *draft = opt(argc, argv, "--owner-draft"); + if (!target || (!dir == !draft)) { fprintf(stderr, "checker2: --target and exactly one of --out-dir / --owner-draft are required\n"); return 2; } + C2Receipt r; + memset(&r, 0, sizeof r); + r.version = C2R_FORMAT_VERSION; + r.signer_class = C2R_CLASS_TEST; + r.alg = C2R_ALG_ED25519; + r.evidence_class = C2R_EV_IR_CHECKED; + int rc = judge(ir, r.program, 1); + if (rc) { fprintf(stderr, "checker2: refusing to issue a receipt for bytes checker2 does not accept\n"); return rc; } + if (file_sha(exe, r.executable)) return 2; + if (opt_u64(argc, argv, "--epoch", &r.policy_epoch, 1) || opt_u64(argc, argv, "--expiry", &r.expiry_epoch, 1)) return 2; + if (opt_sha_file(argc, argv, "--firmware", r.firmware) || opt_sha_file(argc, argv, "--requirements", r.requirements) || + opt_sha_file(argc, argv, "--input", r.input) || opt_sha_file(argc, argv, "--producer", r.producer_checker)) + return 2; + if (opt(argc, argv, "--lrat")) { + if (opt(argc, argv, "--requirements")) { fprintf(stderr, "checker2: --lrat and --requirements are exclusive\n"); return 2; } + int nproofs; + char obj[8192]; + rc = lrat_requirements(argc, argv, ir, r.requirements, &nproofs, obj, sizeof obj); + if (rc) { fprintf(stderr, "checker2: refusing to issue: a proof did not check\n"); return rc; } + r.evidence_class = C2R_EV_IR_CHECKED_LRAT; + char h[65]; + hex(r.requirements, 32, h); + printf("requirements_sha256=%s proofs=%d\n%s", h, nproofs, obj); + } + uint8_t deps[64][32]; + unsigned nd = 0; + for (int i = 0; i + 1 < argc; i++) + if (strcmp(argv[i], "--dep") == 0) { + if (nd == 64 || unhex32(argv[i + 1], deps[nd])) { fprintf(stderr, "checker2: bad --dep\n"); return 2; } + nd++; + } + if (c2r_deps_digest((const uint8_t (*)[32])deps, nd, r.dependencies)) { fprintf(stderr, "checker2: --dep ids must be strictly ascending\n"); return 2; } + c2r_target_id(target, r.target); + checker_id(r.checker); + uint8_t buf[C2R_SIZE], seed[32]; + if (draft) { + /* OWNER draft: class OWNER, key fingerprint of the owner root, signature all zero. The + * owner signs `receipt tbs` output on the YubiKey; `receipt attach` verifies and stores. */ + r.signer_class = C2R_CLASS_OWNER; + sha256_hash(c2r_owner_root_pk, 32, r.key_fp); + c2r_encode(&r, buf); + return write_new(draft, buf, C2R_SIZE); + } + c2r_test_seed(seed); + int e = c2r_sign_test(&r, seed, buf); + if (e) { fprintf(stderr, "checker2: signing refused: %s\n", c2r_reason(e)); return 1; } + return store(dir, buf); +} + +static int read_receipt(const char *path, uint8_t buf[C2R_SIZE], C2Receipt *r) +{ + size_t n; + uint8_t *b = slurp(path, &n); + if (!b) return 2; + int e = c2r_decode(b, n, r); + if (!e) memcpy(buf, b, C2R_SIZE); + free(b); + if (e) { fprintf(stderr, "checker2: not a receipt: %s\n", c2r_reason(e)); return 1; } + return 0; +} + +static int receipt_tbs(int argc, char **argv) +{ + if (argc < 2) return 2; + uint8_t buf[C2R_SIZE], msg[C2R_SIGNED_MSG_LEN]; + C2Receipt r; + int rc = read_receipt(argv[0], buf, &r); + if (rc) return rc; + c2r_signed_message(buf, msg); + return write_new(argv[1], msg, sizeof msg); +} + +static int receipt_attach(int argc, char **argv) +{ + if (argc < 2) return 2; + const char *dir = opt(argc, argv, "--out-dir"); + if (!dir) { fprintf(stderr, "checker2: --out-dir is required\n"); return 2; } + uint8_t buf[C2R_SIZE], out[C2R_SIZE]; + C2Receipt r; + int rc = read_receipt(argv[0], buf, &r); + if (rc) return rc; + if (r.signer_class != C2R_CLASS_OWNER) { fprintf(stderr, "checker2: attach is for OWNER receipts\n"); return 1; } + size_t ns; + uint8_t *s = slurp(argv[1], &ns); + if (!s) return 2; + if (ns != 64) { free(s); fprintf(stderr, "checker2: signature must be 64 bytes\n"); return 2; } + int e = c2r_attach(&r, c2r_owner_root_pk, s, out); + free(s); + if (e) { fprintf(stderr, "checker2: attach refused: %s\n", c2r_reason(e)); return 1; } + return store(dir, out); +} + +static int receipt_verify(int argc, char **argv) +{ + if (argc < 3) return 2; + const char *target = opt(argc, argv, "--target"); + if (!target) { fprintf(stderr, "checker2: --target is required\n"); return 2; } + uint8_t tgt[32], fw[32], prog[32], exe[32], prod[32], depd[32]; + c2r_target_id(target, tgt); + int rc = judge(argv[1], prog, 1); + if (rc == 0 && file_sha(argv[2], exe)) rc = 2; + if (rc == 0 && opt_sha_file(argc, argv, "--firmware", fw)) rc = 2; + /* producer and dependencies are always compared, like firmware: absent options mean "none" + * (all-zero producer, empty dependency list), exactly what `issue` writes without them */ + if (rc == 0 && opt_sha_file(argc, argv, "--producer", prod)) rc = 2; + static uint8_t deps[64][32]; + unsigned nd = 0; + for (int i = 0; rc == 0 && i + 1 < argc; i++) + if (strcmp(argv[i], "--dep") == 0) rc = nd < 64 && !unhex32(argv[i + 1], deps[nd]) ? (nd++, 0) : 2; + if (rc == 0 && c2r_deps_digest((const uint8_t (*)[32])deps, nd, depd)) { fprintf(stderr, "checker2: --dep ids must be strictly ascending\n"); rc = 2; } + C2ReceiptExpect ex = {.target = tgt, .firmware = fw, .program = prog, .executable = exe, + .producer_checker = prod, .dependencies = depd}; + C2ReceiptPolicy p; + memset(&p, 0, sizeof p); + /* production is the default (fail closed): TEST receipts are refused unless the caller asks + * for a qualification run with --allow-test-key. --production states the default explicitly; + * giving both is a usage error. */ + int allow_test = flag(argc, argv, "--allow-test-key"); + if (allow_test && flag(argc, argv, "--production")) { + fprintf(stderr, "checker2: --production and --allow-test-key are exclusive\n"); + return 2; + } + p.production = !allow_test; + if (!p.production) { p.test_anchors = &c2r_test_pk; p.n_test = 1; } + p.owner_anchors = &c2r_owner_root_pk; + p.n_owner = 1; + /* checker identities: this build's own, plus any given with --accept-checker */ + static uint8_t checkers[16][32]; + unsigned nchk = 1; + checker_id(checkers[0]); + for (int i = 0; rc == 0 && i + 1 < argc; i++) + if (strcmp(argv[i], "--accept-checker") == 0) rc = nchk < 16 && !unhex32(argv[i + 1], checkers[nchk]) ? (nchk++, 0) : 2; + p.checkers = (const uint8_t (*)[32])checkers; + p.n_checkers = nchk; + static uint8_t ids[16][32], keys[16][32]; + unsigned nid = 0, nkey = 0; + for (int i = 0; rc == 0 && i + 1 < argc; i++) { + if (strcmp(argv[i], "--revoked-id") == 0) rc = nid < 16 && !unhex32(argv[i + 1], ids[nid]) ? (nid++, 0) : 2; + if (strcmp(argv[i], "--revoked-key") == 0) rc = nkey < 16 && !unhex32(argv[i + 1], keys[nkey]) ? (nkey++, 0) : 2; + } + p.revoked_ids = (const uint8_t (*)[32])ids; + p.n_revoked_ids = nid; + p.revoked_keys = (const uint8_t (*)[32])keys; + p.n_revoked_keys = nkey; + if (rc == 0 && (opt_u64(argc, argv, "--epoch", &p.current_epoch, 1) || opt_u64(argc, argv, "--floor", &p.epoch_floor, 0))) rc = 2; + if (rc) return rc; + size_t n; + uint8_t *b = slurp(argv[0], &n); + if (!b) return 2; + C2Receipt got; + int e = c2r_verify(b, n, &p, &ex, &got); + free(b); + if (e) { printf("receipt=%s\n", c2r_reason(e)); return 1; } + /* LRAT evidence is replayed, never taken on trust: the proofs must be given, must check + * against these IR bytes, and must hash to the receipt's requirements digest. */ + if (got.evidence_class == C2R_EV_IR_CHECKED_LRAT || opt(argc, argv, "--lrat")) { + uint8_t req[32]; + int nproofs; + rc = lrat_requirements(argc, argv, argv[1], req, &nproofs, NULL, 0); + if (rc) { printf("receipt=LRAT-REPLAY-FAILED\n"); return rc; } + if (got.evidence_class != C2R_EV_IR_CHECKED_LRAT) { printf("receipt=LRAT-NOT-CLAIMED\n"); return 1; } + if (nproofs == 0) { printf("receipt=LRAT-PROOFS-REQUIRED\n"); return 1; } + if (memcmp(req, got.requirements, 32)) { printf("receipt=LRAT-REQUIREMENTS-MISMATCH\n"); return 1; } + } + printf("receipt=VALID\n"); + return 0; +} + +/* decode + accept the unit, locate the function, build its NO-TRAP formula (never read from disk) */ +static int property_cnf(const char *ir, const char *func, C2Cnf *cnf, C2BlastInfo *bi, uint8_t ir_sha[32]) +{ + size_t n; + uint8_t *b = slurp(ir, &n); + if (!b) return 2; + sha256_hash(b, n, ir_sha); + C2Unit *u = malloc(sizeof *u); + C2Verdict v; + int rc = 1; + if (!u) { free(b); return 2; } + if (c2_decode(b, n, u, &v)) printf("checker2=REJECT rule=%s detail=%s\n", v.rule, v.detail); + else if (c2_blast_notrap(u, c2_func_index(u, func), cnf, bi)) printf("prove=REFUSED rule=%s detail=%s\n", bi->rule, bi->detail); + else rc = 0; + c2_unit_free(u); + free(u); + free(b); + return rc; +} + +static int prove_cnf(const char *ir, const char *func, const char *out) +{ + C2Cnf cnf; + C2BlastInfo bi; + uint8_t s[32]; + int rc = property_cnf(ir, func, &cnf, &bi, s); + if (rc) return rc; + size_t n; + char *t = c2_cnf_print(&cnf, &n); + rc = t ? write_new(out, (const uint8_t *)t, n) : 2; + if (!rc) printf("property=%s func=%s inputs=%d paths=%d trap_sites=%d vars=%d clauses=%d\n", C2_PROPERTY_NOTRAP, func, + bi.inputs, bi.paths, bi.trap_sites, cnf.nvars, cnf.nclauses); + free(t); + c2_cnf_free(&cnf); + return rc; +} + +static int prove_check(const char *ir, const char *func, const char *proof) +{ + C2Cnf cnf; + C2BlastInfo bi; + uint8_t s[32], ps[32]; + int rc = property_cnf(ir, func, &cnf, &bi, s); + if (rc) return rc; + size_t n; + uint8_t *p = slurp(proof, &n); + if (!p) { c2_cnf_free(&cnf); return 2; } + sha256_hash(p, n, ps); + C2LratResult r; + int e = c2_lrat_check(&cnf, (const char *)p, n, &r); + free(p); + c2_cnf_free(&cnf); + char h1[65], h2[65]; + hex(s, 32, h1); + hex(ps, 32, h2); + if (e) { printf("lrat=REFUSED rule=%s line=%ld\n", r.rule, r.line); return 1; } + printf("lrat=VERIFIED property=%s func=%s ir_sha256=%s proof_sha256=%s steps=%ld\n", C2_PROPERTY_NOTRAP, func, h1, h2, r.steps); + return 0; +} + +static int usage(void) +{ + fprintf(stderr, "usage: checker2 check <unit.ir> | version | receipt issue|tbs|attach|verify ... (see source header)\n"); + return 2; +} + +int main(int argc, char **argv) +{ + if (argc < 2) return usage(); + if (strcmp(argv[1], "version") == 0) { + uint8_t id[32]; + char h[65]; + checker_id(id); + hex(id, 32, h); + printf("%s\nsources_sha256=%s\nchecker_id=%s\n", C2_CHECKER_VERSION, C2_SOURCES_SHA256, h); + return 0; + } + if (strcmp(argv[1], "prove-cnf") == 0 && argc == 5) return prove_cnf(argv[2], argv[3], argv[4]); + if (strcmp(argv[1], "prove-check") == 0 && argc == 5) return prove_check(argv[2], argv[3], argv[4]); + if (strcmp(argv[1], "check") == 0 && argc == 3) { + uint8_t s[32]; + return judge(argv[2], s, 0); + } + if (strcmp(argv[1], "receipt") == 0 && argc >= 3) { + int (*fn)(int, char **) = NULL; + if (strcmp(argv[2], "issue") == 0) fn = receipt_issue; + if (strcmp(argv[2], "tbs") == 0) fn = receipt_tbs; + if (strcmp(argv[2], "attach") == 0) fn = receipt_attach; + if (strcmp(argv[2], "verify") == 0) fn = receipt_verify; + if (fn) { + int rc = fn(argc - 3, argv + 3); + return rc == 2 && argc - 3 < 2 ? usage() : rc; + } + } + return usage(); +} diff --git a/src/checker2/untrusted/c2sat.c b/src/checker2/untrusted/c2sat.c new file mode 100644 index 000000000..2072e6aba --- /dev/null +++ b/src/checker2/untrusted/c2sat.c @@ -0,0 +1,215 @@ +/* c2sat: small DPLL SAT solver that writes LRAT proofs (omega#446). UNTRUSTED. + * + * Not part of checker2's trusted base and not in its identity hash: every UNSAT answer is only + * believed after checker2's own LRAT checker (src/checker2/c2_lrat.c) accepts the proof. Shares no + * code with that checker (own parser, own data structures). + * + * Method: DPLL with unit propagation over occurrence lists, decisions on the lowest unassigned + * variable, conflict-directed backjumping. Every refuted subtree yields a clause that is the + * negation of the decisions that mattered: + * leaf : RUP with hints = the propagation reasons the conflict depends on, in trail order, + * then the conflicting clause; + * inner : if the first branch's clause does not mention the decision it is returned as is, + * likewise the second; otherwise their resolvent on the decision, hints [first, second]. + * At the root the clause is empty. No learned clause is reused for propagation (simple, slow). + * + * Usage: c2sat <in.cnf> <out.lrat> [max-decisions] + * Exit: 20 UNSAT (proof written), 10 SAT (model on stdout as "v ..."), 1 limit hit, 2 usage/I/O. */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +typedef struct { int *l; int n; } Cl; + +static int nv, ncl; +static Cl *cls; /* original clauses, then learned ones (index = id - 1) */ +static int ncls, capcls; +static int **occ, *nocc, *capocc; /* occ[lit + nv] */ +static signed char *val; +static int *reason, *trail, ntrail, *seen; +static long decisions, max_decisions; +static FILE *out; + +static int lit_true(int l) { return val[abs(l)] == (l > 0 ? 1 : -1); } +static int lit_false(int l) { return val[abs(l)] == (l > 0 ? -1 : 1); } + +static int add_clause(const int *l, int n) +{ + if (ncls == capcls) { + capcls = capcls ? capcls * 2 : 1024; + cls = realloc(cls, (size_t)capcls * sizeof *cls); + if (!cls) exit(2); + } + cls[ncls].l = malloc(((size_t)n + 1) * sizeof(int)); + if (!cls[ncls].l) exit(2); + memcpy(cls[ncls].l, l, (size_t)n * sizeof(int)); + cls[ncls].n = n; + return ++ncls; /* id */ +} + +static void assign(int l, int why) +{ + val[abs(l)] = l > 0 ? 1 : -1; + reason[abs(l)] = why; + trail[ntrail++] = l; +} + +/* propagate from trail position q; returns the id of a falsified clause or 0 */ +static int propagate(int q) +{ + while (q < ntrail) { + int t = trail[q++]; + int f = -t; /* clauses containing f may now be unit or false */ + int *o = occ[f + nv]; + for (int k = 0; k < nocc[f + nv]; k++) { + Cl *c = &cls[o[k] - 1]; + int nfree = 0, last = 0, sat = 0; + for (int j = 0; j < c->n; j++) { + if (lit_true(c->l[j])) { sat = 1; break; } + if (!lit_false(c->l[j])) { nfree++; last = c->l[j]; } + } + if (sat) continue; + if (nfree == 0) return o[k]; + if (nfree == 1) assign(last, o[k]); + } + } + return 0; +} + +static void undo_to(int n) +{ + while (ntrail > n) { + int l = trail[--ntrail]; + val[abs(l)] = 0; + reason[abs(l)] = 0; + } +} + +static int emit(const int *l, int n, const int *hints, int nh) +{ + int id = add_clause(l, n); + fprintf(out, "%d ", id); + for (int k = 0; k < n; k++) fprintf(out, "%d ", l[k]); + fprintf(out, "0 "); + for (int k = 0; k < nh; k++) fprintf(out, "%d ", hints[k]); + fprintf(out, "0\n"); + return id; +} + +/* clause from a conflict: negated relevant decisions, hints = relevant reasons in trail order */ +static int analyze(int conflict) +{ + int *lits = malloc(((size_t)ntrail + 1) * sizeof(int)); + int *hints = malloc(((size_t)ntrail + 2) * sizeof(int)); + int nl = 0, nh = 0; + Cl *c = &cls[conflict - 1]; + for (int j = 0; j < c->n; j++) seen[abs(c->l[j])] = 1; + for (int i = ntrail - 1; i >= 0; i--) { + int v = abs(trail[i]); + if (!seen[v]) continue; + seen[v] = 0; + if (reason[v] == 0) { lits[nl++] = -trail[i]; continue; } + hints[nh++] = reason[v]; + Cl *r = &cls[reason[v] - 1]; + for (int j = 0; j < r->n; j++) + if (abs(r->l[j]) != v) seen[abs(r->l[j])] = 1; + } + for (int a = 0, b = nh - 1; a < b; a++, b--) { int t = hints[a]; hints[a] = hints[b]; hints[b] = t; } + hints[nh++] = conflict; + int id = emit(lits, nl, hints, nh); + free(lits); + free(hints); + return id; +} + +static int mentions(int id, int l) +{ + Cl *c = &cls[id - 1]; + for (int j = 0; j < c->n; j++) if (c->l[j] == l) return 1; + return 0; +} + +/* returns the id of a clause refuting the current trail, 0 if SAT, -1 if the limit was hit */ +static int solve(int q) +{ + int conflict = propagate(q); + if (conflict) return analyze(conflict); + int v = 0; + for (int i = 1; i <= nv; i++) if (!val[i]) { v = i; break; } + if (!v) return 0; + if (++decisions > max_decisions) return -1; + int mark = ntrail, id[2]; + for (int side = 0; side < 2; side++) { + int d = side ? -v : v; + assign(d, 0); + id[side] = solve(ntrail - 1); + if (id[side] <= 0) return id[side]; /* SAT keeps its model on the trail */ + undo_to(mark); + if (!mentions(id[side], -d)) return id[side]; /* backjump: the decision did not matter */ + } + /* resolve on v */ + Cl *a = &cls[id[0] - 1], *b = &cls[id[1] - 1]; + int *r = malloc(((size_t)a->n + (size_t)b->n) * sizeof(int)), n = 0; + for (int j = 0; j < a->n; j++) if (a->l[j] != -v) r[n++] = a->l[j]; + for (int j = 0; j < b->n; j++) { + if (b->l[j] == v) continue; + int dup = 0; + for (int k = 0; k < n; k++) dup |= r[k] == b->l[j]; + if (!dup) r[n++] = b->l[j]; + } + int h[2] = {id[0], id[1]}; + int rid = emit(r, n, h, 2); + free(r); + return rid; +} + +int main(int argc, char **argv) +{ + if (argc < 3) { fprintf(stderr, "usage: c2sat <in.cnf> <out.lrat> [max-decisions]\n"); return 2; } + max_decisions = argc > 3 ? atol(argv[3]) : 2000000; + FILE *in = fopen(argv[1], "r"); + if (!in) return 2; + int ch; + while ((ch = fgetc(in)) == 'c') while ((ch = fgetc(in)) != '\n' && ch != EOF) {} + ungetc(ch, in); + if (fscanf(in, " p cnf %d %d", &nv, &ncl) != 2 || nv < 0 || ncl < 0) return 2; + int *buf = malloc(((size_t)nv * 2 + 2) * sizeof(int)), n = 0, x; + while (fscanf(in, "%d", &x) == 1) { + if (x == 0) { add_clause(buf, n); n = 0; } + else if (n < 2 * nv + 1) buf[n++] = x; + } + fclose(in); + if (ncls != ncl) return 2; + occ = calloc((size_t)nv * 2 + 1, sizeof *occ); + nocc = calloc((size_t)nv * 2 + 1, sizeof *nocc); + capocc = calloc((size_t)nv * 2 + 1, sizeof *capocc); + val = calloc((size_t)nv + 1, 1); + reason = calloc((size_t)nv + 1, sizeof *reason); + seen = calloc((size_t)nv + 1, sizeof *seen); + trail = malloc(((size_t)nv + 1) * sizeof *trail); + for (int i = 0; i < ncls; i++) + for (int j = 0; j < cls[i].n; j++) { + int s = cls[i].l[j] + nv; + if (nocc[s] == capocc[s]) { capocc[s] = capocc[s] ? capocc[s] * 2 : 4; occ[s] = realloc(occ[s], (size_t)capocc[s] * sizeof(int)); } + occ[s][nocc[s]++] = i + 1; + } + out = fopen(argv[2], "w"); + if (!out) return 2; + /* level 0: empty and unit clauses */ + int conflict = 0; + for (int i = 0; i < ncl && !conflict; i++) { + if (cls[i].n == 0) conflict = i + 1; + else if (cls[i].n == 1) { + if (lit_false(cls[i].l[0])) conflict = i + 1; + else if (!lit_true(cls[i].l[0])) assign(cls[i].l[0], i + 1); + } + } + int r = conflict ? analyze(conflict) : solve(0); + fclose(out); + if (r > 0) { printf("s UNSATISFIABLE\n"); return 20; } + if (r < 0) { printf("s UNKNOWN (decision limit)\n"); return 1; } + printf("s SATISFIABLE\nv"); + for (int i = 1; i <= nv; i++) printf(" %d", val[i] >= 0 ? i : -i); + printf(" 0\n"); + return 10; +} diff --git a/tests/.crumb b/tests/.crumb index b3dd9b367..9950952d5 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -134,7 +134,7 @@ }, { "digest": "f041b7daf38c51e8db72834bb764cef7741637981223039d89731a30aa91e224", - "last_commit": "e9943ed2", + "last_commit": "1edf41a5", "name": "compiler", "purpose": "Directory tests/compiler. Purpose not yet described by a human." }, @@ -296,14 +296,14 @@ } ], "children_root": "sha256:007780788467b076e31455e97b09ed7fb861af2e96184fd750995606dac0dc60", - "compiled_at": "2026-10-14T17:50:29Z", + "compiled_at": "2026-10-14T18:36:27Z", "compiler": "crumb-compile/1", - "digest": "sha256:e678609e8a172112a41f3e6a204f6f5adf29aac13bc99fb7413fc89daf40ce6f", + "digest": "sha256:51957489c42457c95a8f0c4c0820eebbc36621fd85d2f92624335f8656fe15e5", "evidence_files": 16, "evidence_root": "sha256:96d08097822ad95f4e562c19e0ba5df5a035774c48632f1832912c40a27bd27a", - "files": 1103, - "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", - "source_tree": "sha256:2dacede8ba425b11dc4c3fad304426c94b64a16c1327fdaec5e1d08a03bb5451" + "files": 1147, + "generated_at_commit": "4fa52370f177d268e4248955dc7adec53519e215", + "source_tree": "sha256:ca2266b0415c722f85da9e9bf8e47ab15d605fd39e419d5a42fb65270e500781" }, "owner_lane": "", "provenance": { diff --git a/tests/checker2/blast_native.sh b/tests/checker2/blast_native.sh new file mode 100644 index 000000000..122ab543c --- /dev/null +++ b/tests/checker2/blast_native.sh @@ -0,0 +1,61 @@ +#!/bin/sh +# Bit-blaster semantics against the producer's compiled code (omega#446, finding 4 of the PR #448 +# review). Writes one tiny OSC program per blastable operation and type, compiles each with oscc +# (run as a black box: IR bytes, AArch64 code and entry table), adds the LRAT gate programs, and +# runs test_c2_blast_native, which compares checker2's CNF with the code input by input (see that +# file for the method and the negative controls). +# op_<op>_<T> fn f(a: T, b: T, c: T) -> T ensures result != c { return a <op> b; } +# add sub mul and or xor shl (all 8 integer types), shr (unsigned only) +# op_<cmp>_<T> fn f(a: T, b: T, c: bool) -> bool ensures result != c { return a <cmp> b; } +# op_neg_<T> (signed), op_bnot_<T>, op_lnot_bool, op_land_bool, op_lor_bool, op_beq_bool +# op_cast_<S>_<T> every ordered pair of distinct integer types +# Any program oscc refuses, or that checker2 does not blast, fails the run. +# Usage: blast_native.sh <oscc> <test_c2_blast_native> <work-dir> +set -u +OSCC=$1 H=$2 W=$3 +D=$(dirname "$0")/lrat +rm -rf "$W" && mkdir -p "$W/src" || exit 2 +types="u8 u16 u32 u64 i8 i16 i32 i64" +fail=0 +gen() { # gen <name> <params> <ret> <expr> + printf 'fn f(%s) -> %s ensures result != c {\n return %s;\n}\n' "$2" "$3" "$4" >"$W/src/$1.osc" +} +for t in $types; do + for op in add:+ sub:- mul:'*' and:'&' or:'|' xor:'^' shl:'<<' shr:'>>'; do + n=${op%%:*} s=${op#*:} + case "$n:$t" in shr:i*) continue ;; esac + gen "op_${n}_$t" "a: $t, b: $t, c: $t" "$t" "a $s b" + done + for op in eq:== ne:!= lt:'<' le:'<=' gt:'>' ge:'>='; do + gen "op_${op%%:*}_$t" "a: $t, b: $t, c: bool" bool "a ${op#*:} b" + done + case $t in i*) gen "op_neg_$t" "a: $t, c: $t" "$t" "-a" ;; esac + gen "op_bnot_$t" "a: $t, c: $t" "$t" "~a" + for t2 in $types; do + [ "$t" = "$t2" ] || gen "op_cast_${t}_$t2" "a: $t, c: $t2" "$t2" "a as $t2" + done +done +gen op_lnot_bool "a: bool, c: bool" bool "!a" +gen op_land_bool "a: bool, b: bool, c: bool" bool "a && b" +gen op_lor_bool "a: bool, b: bool, c: bool" bool "a || b" +gen op_beq_bool "a: bool, b: bool, c: bool" bool "a == b" +cp "$D"/*.osc "$W/src/" +for src in "$W"/src/*.osc; do + b=$(basename "$src" .osc) + "$OSCC" "$src" "$W/$b" >"$W/src/$b.log" 2>&1 || { echo "blast_native: FAIL oscc refused $b: $(head -c 300 "$W/src/$b.log")"; fail=$((fail + 1)); } +done +# negative controls: CNF of the first program against the code of the second (same signature) +cat >"$W/controls" <<'CTL' +op_add_u8 op_sub_u8 +op_and_u16 op_or_u16 +op_shl_u8 op_shr_u8 +op_lt_i8 op_le_i8 +op_mul_i64 op_add_i64 +op_neg_i32 op_bnot_i32 +op_eq_u64 op_ne_u64 +op_cast_i8_u16 op_cast_i8_i16 +CTL +echo "blast_native: $(ls "$W"/src/*.osc | wc -l) programs written, $fail refused by oscc" +"$H" "$W" || fail=$((fail + 1)) +[ "$fail" -eq 0 ] || { echo "blast_native: FAIL"; exit 1; } +echo "blast_native: PASS" diff --git a/tests/checker2/differential.sh b/tests/checker2/differential.sh new file mode 100644 index 000000000..1fa04c87c --- /dev/null +++ b/tests/checker2/differential.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# Black-box differential: the producer's checker (oscc, run as a program; its source is not read by +# checker2) against checker2, over every OSC unit in the repo plus the generated valid units. +# oscc accepts -> osc_emit_ir must write the same bytes (same ir_sha256) and checker2 must ACCEPT +# oscc rejects -> the unit never becomes bytes (front-end refusal); osc_emit_ir must agree +# Disagreement fails. Gate (omega#446): at least 100 units accepted by both checkers. +# The accepted IR files are left in <work>/ir for test_c2_ir. +# Usage: sh tests/checker2/differential.sh <oscc> <osc_emit_ir> <checker2> <work-dir> +set -u +OSCC=$1; EMIT=$2; C2=$3; WORK=$4 +rm -rf "$WORK" +mkdir -p "$WORK/ir" "$WORK/gen" +sh tests/checker2/gen_valid.sh "$WORK/gen" 48 || { echo "differential: generator failed"; exit 1; } + +both=0; fe_reject=0; neg=0; bad=0 +check_unit() { # <file.osc> <expect: any|reject> + src=$1; expect=$2 + name=$(echo "$src" | sed 's|^\./||; s|/|_|g; s|\.osc$||') + out=$("$OSCC" "$src" 2>/dev/null); orc=$? + erc=0; eout=$("$EMIT" "$src" "$WORK/ir/$name.ir" 2>/dev/null) || erc=$? + if [ "$orc" -ne 0 ]; then + fe_reject=$((fe_reject + 1)) + [ "$expect" = reject ] && neg=$((neg + 1)) + if [ "$erc" -eq 0 ]; then echo "DISAGREE $src: oscc rejects, producer library accepts"; bad=$((bad + 1)); fi + rm -f "$WORK/ir/$name.ir" + return + fi + if [ "$expect" = reject ]; then echo "DISAGREE $src: known-bad unit accepted by oscc"; bad=$((bad + 1)); return; fi + osha=$(echo "$out" | sed -n 's/^ir_sha256=//p') + esha=$(echo "$eout" | sed -n 's/.*ir_sha256=//p') + if [ "$erc" -ne 0 ] || [ -z "$osha" ] || [ "$osha" != "$esha" ]; then + echo "DISAGREE $src: emitted bytes are not oscc's bytes ($osha vs $esha)"; bad=$((bad + 1)); return + fi + c=$("$C2" check "$WORK/ir/$name.ir") + case "$c" in + "checker2=ACCEPT ir_sha256=$osha") both=$((both + 1)) ;; + *) echo "DISAGREE $src: oscc accepts, $c"; bad=$((bad + 1)) ;; + esac +} + +for f in tests/compiler/progs/*.osc tests/compiler/slices/*.osc src/osh/*.osc tests/physics0/osc/*.osc "$WORK"/gen/*.osc; do + [ -f "$f" ] && check_unit "$f" any +done +for f in tests/compiler/neg/*.osc; do + [ -f "$f" ] && check_unit "$f" reject +done + +# negative control: the comparison must be able to fail. A truncated copy of an accepted unit has +# to be refused by checker2; otherwise this script could never report a disagreement. +first=$(ls "$WORK"/ir/*.ir | head -n 1) +size=$(wc -c < "$first") +head -c $((size - 1)) "$first" > "$WORK/control.ir" +case $("$C2" check "$WORK/control.ir") in +checker2=REJECT*) ;; +*) echo "differential: negative control failed (truncated unit accepted)"; bad=$((bad + 1)) ;; +esac + +echo "differential: accepted by both=$both front-end refusals=$fe_reject (known-bad neg units=$neg) disagreements=$bad" +[ "$bad" -eq 0 ] || exit 1 +[ "$both" -ge 100 ] || { echo "differential: gate needs >= 100 units accepted by both"; exit 1; } +[ "$neg" -ge 100 ] || { echo "differential: expected the known-bad neg units to be refused"; exit 1; } +exit 0 diff --git a/tests/checker2/fixtures/owner/ceremony-signature b/tests/checker2/fixtures/owner/ceremony-signature new file mode 100644 index 000000000..4c1b3cd71 --- /dev/null +++ b/tests/checker2/fixtures/owner/ceremony-signature @@ -0,0 +1 @@ +tRûâd_WŽ˜_]LÓz•nþX]eD#+§ñ' vOÇo(Ó¡‘½6fQû1‹ïsçÄvÙË®¢½Ê”xE \ No newline at end of file diff --git a/tests/checker2/fixtures/owner/ceremony-statement b/tests/checker2/fixtures/owner/ceremony-statement new file mode 100644 index 000000000..98e4e0375 --- /dev/null +++ b/tests/checker2/fixtures/owner/ceremony-statement @@ -0,0 +1,4 @@ +AIENOS-OWNER-STATEMENT-V1 +purpose pi5-8-receipts-manifest +manifest_bytes 90 +manifest_sha256 c1da13bc35aa8bd10ea89a65158851b125f6ff648603ef832a352707fd996e33 diff --git a/tests/checker2/fixtures/owner/owner-pubkeys.txt b/tests/checker2/fixtures/owner/owner-pubkeys.txt new file mode 100644 index 000000000..ec9e07379 --- /dev/null +++ b/tests/checker2/fixtures/owner/owner-pubkeys.txt @@ -0,0 +1,3 @@ +# AIENOS owner public key. PUBLIC material only (the private key never leaves the YubiKey). +# Ed25519 key generated on YubiKey serial 39017074, PIV slot 9c +owner_root_ed25519 578ada3cb0c2d154623ac089191023c8ad4bc5e63b8ccd1a38db2d679b8c9e76 diff --git a/tests/checker2/fixtures/owner/slot-9c-public.pem b/tests/checker2/fixtures/owner/slot-9c-public.pem new file mode 100644 index 000000000..d51eccedf --- /dev/null +++ b/tests/checker2/fixtures/owner/slot-9c-public.pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEAV4raPLDC0VRiOsCJGRAjyK1LxeY7jM0aONstZ5uMnnY= +-----END PUBLIC KEY----- diff --git a/tests/checker2/gen_valid.sh b/tests/checker2/gen_valid.sh new file mode 100644 index 000000000..f9684b923 --- /dev/null +++ b/tests/checker2/gen_valid.sh @@ -0,0 +1,105 @@ +#!/bin/sh +# Deterministic generator of valid OSC units for the checker2 gate (omega#446): writes +# <out>/gen_NN.osc for NN in 00..(count-1). Each unit varies the scalar type, array length, loop +# bound and shape (loops, borrows, structs, drop-flag moves, casts, contracts) by its index. No +# randomness: the same count gives the same files. The producer (oscc) must accept every one; +# that is checked by tests/checker2/differential.sh, not assumed here. +# Usage: sh tests/checker2/gen_valid.sh <out-dir> [count] +set -eu +OUT=$1 +N=${2:-48} +mkdir -p "$OUT" +set -- u8 u16 u32 u64 i8 i16 i32 i64 +i=0 +while [ "$i" -lt "$N" ]; do + k=$((i % 8 + 1)) + T=$(eval echo "\${$k}") + L=$((i % 7 + 2)) + B=$((10 + i * 3)) + C=$((i % 5 + 1)) + f=$(printf '%s/gen_%02d.osc' "$OUT" "$i") + case $((i % 6)) in + 0) cat > "$f" <<EOF +// entry: main +// generated shape 0: owned array, for loop, while-bound loop ($T, len $L, bound $B) +fn main(x: $T) -> $T { + let a: own [$T; $L] = alloc(x); + for j in 0 .. $L { a[j] = a[j] ^ (j as $T); } + let mut n: u32 = 0; + while n < $C bound $B { n = n + 1; } + let r: $T = a[0] | a[$((L - 1))]; + return r; +} +EOF + ;; + 1) cat > "$f" <<EOF +// entry: main +// generated shape 1: shared and mutable borrows into helpers ($T, len $L) +fn fill(a: &mut [$T; $L], v: $T) { + for j in 0 .. $L { a[j] = v; } +} +fn first(a: &[$T; $L]) -> $T { return a[0]; } +fn main(v: $T) -> $T { + let a: own [$T; $L] = alloc(v); + fill(&mut a, v); + let r: $T = first(&a); + return r; +} +EOF + ;; + 2) cat > "$f" <<EOF +// entry: main +// generated shape 2: struct with scalar and array fields ($T, len $L) +struct S$i { tag: u8, vals: [$T; $L], ok: bool } +fn main(v: $T, t: u8) -> $T { + let s: own S$i = S$i { tag: t, vals: [v; $L], ok: t > $C }; + if s.ok { s.vals[0] = v & v; } + s.tag = s.tag | 1; + return s.vals[$((L - 1))]; +} +EOF + ;; + 3) cat > "$f" <<EOF +// entry: main +// generated shape 3: conditional move with a drop flag ($T, len $L) +fn take(x: own [$T; $L]) -> $T { return x[0]; } +fn main(c: bool, v: $T) -> $T { + let a: own [$T; $L] = alloc(v); + let mut r: $T = v; + if c { r = take(a); } + return r; +} +EOF + ;; + 4) cat > "$f" <<EOF +// entry: main +// generated shape 4: casts, shifts, comparisons and a counted loop ($T, bound $B) +fn main(x: $T, s: u8) -> u64 { + let mut acc: u64 = 0; + let mut n: u16 = 0; + while n < $C bound $B { + acc = acc + ((x as u64) >> (s & 7)); + n = n + 1; + } + if (x as u64) >= acc { return acc; } + return acc << 1; +} +EOF + ;; + 5) cat > "$f" <<EOF +// entry: main +// generated shape 5: contracts and a chain of calls ($T) +fn clamp(v: $T, hi: $T) -> $T requires hi >= 0 ensures result <= hi { + if v > hi { return hi; } + return v; +} +fn main(v: $T) -> $T { + let a: $T = clamp(v, $C); + let b: $T = clamp(a, $((C + 1))); + return a + b; +} +EOF + ;; + esac + i=$((i + 1)) +done diff --git a/tests/checker2/lrat.sh b/tests/checker2/lrat.sh new file mode 100644 index 000000000..d19382d21 --- /dev/null +++ b/tests/checker2/lrat.sh @@ -0,0 +1,124 @@ +#!/bin/sh +# LRAT gate (omega#446): bounded integer programs proved trap-free by checker2. +# For every tests/checker2/lrat/*.osc (header lines "// prove: <func>", "// expect: holds|trap"): +# producer emits the IR bytes; checker2 bit-blasts the property NO-TRAP of <func> to CNF; +# the UNTRUSTED solver c2sat runs under a timeout; +# holds -> c2sat must answer UNSAT (exit 20) and checker2 must replay the LRAT proof (VERIFIED); +# trap -> c2sat must answer SAT (exit 10): the program really can trap. +# Any disagreement with the expectation, any timeout or any refused proof fails the gate. +# At least 20 "holds" programs must end VERIFIED. +# Negative controls (each must be REFUSED, or the gate fails): +# every proof with its final (empty clause) line removed; +# every proof whose final step has its hints removed; +# the abs8 proof replayed against the unguarded abs8 IR (a proof binds to one program). +# Receipts (evidence class 2): issue checks the proofs; verify replays them and refuses missing, +# corrupted, substituted or misapplied proofs, and proofs offered for a class 1 receipt. +# verify is production by default: a TEST receipt is refused unless --allow-test-key is given. +# Replay: c2sat is run twice per program; the two proofs must be byte-identical. +# Checker identity: a receipt issued by <checker2-other> (same sources, another identity) is refused +# as UNTRUSTED_CHECKER unless verify names that identity with --accept-checker; producer and +# dependency digests that differ from the given ones are refused. +# Usage: lrat.sh <osc_emit_ir> <checker2> <c2sat> <work-dir> <checker2-other> [timeout-seconds] +set -u +EMIT=$1 C2=$2 SAT=$3 W=$4 C2O=$5 T=${6:-60} +D=$(dirname "$0")/lrat +rm -rf "$W" && mkdir -p "$W" || exit 2 +fail=0 verified=0 traps=0 ctl=0 +bad() { echo "lrat: FAIL $*"; fail=$((fail + 1)); } + +for src in "$D"/*.osc; do + b=$(basename "$src" .osc) + f=$(sed -n 's,^// prove: *,,p' "$src") + e=$(sed -n 's,^// expect: *,,p' "$src") + [ -n "$f" ] && [ -n "$e" ] || { bad "$b: missing prove/expect header"; continue; } + "$EMIT" "$src" "$W/$b.ir" >/dev/null 2>&1 || { bad "$b: producer refused"; continue; } + "$C2" prove-cnf "$W/$b.ir" "$f" "$W/$b.cnf" >"$W/$b.info" 2>&1 || { bad "$b: prove-cnf: $(cat "$W/$b.info")"; continue; } + timeout "$T" "$SAT" "$W/$b.cnf" "$W/$b.lrat" >"$W/$b.sat" 2>&1 + r=$? + case "$e:$r" in + holds:20) + timeout "$T" "$SAT" "$W/$b.cnf" "$W/$b.lrat2" >/dev/null 2>&1 + cmp -s "$W/$b.lrat" "$W/$b.lrat2" || bad "$b: proof not reproducible" + out=$("$C2" prove-check "$W/$b.ir" "$f" "$W/$b.lrat" 2>&1) + case "$out" in + lrat=VERIFIED*) verified=$((verified + 1)); echo "lrat: $b $f VERIFIED $(grep -o 'vars=[0-9]* clauses=[0-9]*' "$W/$b.info") steps=${out##*steps=}" ;; + *) bad "$b: proof refused: $out"; continue ;; + esac + # control 1: drop the final line (the empty clause) + sed '$d' "$W/$b.lrat" >"$W/$b.cut" + "$C2" prove-check "$W/$b.ir" "$f" "$W/$b.cut" 2>&1 | grep -q '^lrat=REFUSED' && ctl=$((ctl + 1)) || bad "$b: truncated proof accepted" + # control 2: final step without hints + sed '$s/^\([0-9]*\) 0 .*/\1 0 0/' "$W/$b.lrat" >"$W/$b.nohint" + "$C2" prove-check "$W/$b.ir" "$f" "$W/$b.nohint" 2>&1 | grep -q '^lrat=REFUSED' && ctl=$((ctl + 1)) || bad "$b: hintless proof accepted" + ;; + trap:10) traps=$((traps + 1)); echo "lrat: $b $f can trap (counterexample found, as expected)" ;; + *:124) bad "$b: solver timeout after ${T}s" ;; + *) bad "$b: expected $e, solver exit $r" ;; + esac +done + +# control 3: a valid proof for one program must not verify another program +if [ -f "$W/p01_abs8.lrat" ] && [ -f "$W/n01_abs8_unguarded.ir" ]; then + "$C2" prove-check "$W/n01_abs8_unguarded.ir" abs8 "$W/p01_abs8.lrat" 2>&1 | grep -q '^lrat=REFUSED' && ctl=$((ctl + 1)) || bad "abs8 proof verified the unguarded program" +else + bad "cross-program control inputs missing" +fi + +# receipts with LRAT evidence (class 2): proofs are checked at issue and replayed at verify +R=$W/rcpt +mkdir -p "$R/out" "$R/out1" +printf 'exe\n' >"$R/exe" +iss() { "$C2" receipt issue "$1" "$R/exe" --target lrat-gate --epoch 5 --expiry 9 --out-dir "$2" "$3" "$4" >/dev/null 2>&1; } +want() { # want <expected receipt= line> <name> <verify args...> + w=$1 n=$2 + shift 2 + got=$("$C2" receipt verify "$@" 2>/dev/null | grep '^receipt=') + [ "$got" = "receipt=$w" ] && ctl=$((ctl + 1)) || bad "receipt $n: got '$got', want receipt=$w" +} +if iss "$W/p01_abs8.ir" "$R/out" --lrat "abs8=$W/p01_abs8.lrat"; then + rc2=$(ls "$R/out"/*.rcpt) + V="$rc2 $W/p01_abs8.ir $R/exe --target lrat-gate --epoch 6 --allow-test-key" + # production is the default: without --allow-test-key a TEST-signed receipt is refused + want TEST_SIGNER_IN_PRODUCTION default-refuses-test "$rc2" "$W/p01_abs8.ir" "$R/exe" --target lrat-gate --epoch 6 --lrat "abs8=$W/p01_abs8.lrat" + want TEST_SIGNER_IN_PRODUCTION explicit-production-refuses-test "$rc2" "$W/p01_abs8.ir" "$R/exe" --target lrat-gate --epoch 6 --production --lrat "abs8=$W/p01_abs8.lrat" + "$C2" receipt verify $V --production --lrat "abs8=$W/p01_abs8.lrat" >/dev/null 2>&1 + [ $? -eq 2 ] && ctl=$((ctl + 1)) || bad "--production with --allow-test-key not refused as usage" + { cat "$W/p01_abs8.lrat"; echo "c same proof, different bytes"; } >"$W/p01_abs8.other" + want VALID class2-replayed $V --lrat "abs8=$W/p01_abs8.lrat" + want LRAT-PROOFS-REQUIRED class2-without-proofs $V + want LRAT-REPLAY-FAILED class2-bad-proof $V --lrat "abs8=$W/p01_abs8.cut" + want LRAT-REQUIREMENTS-MISMATCH class2-other-proof $V --lrat "abs8=$W/p01_abs8.other" + want PROGRAM_MISMATCH class2-wrong-program "$rc2" "$W/n01_abs8_unguarded.ir" "$R/exe" --target lrat-gate --epoch 6 --allow-test-key --lrat "abs8=$W/p01_abs8.lrat" +else + bad "receipt issue with a verified proof failed" +fi +iss "$W/n01_abs8_unguarded.ir" "$R/out" --lrat "abs8=$W/p01_abs8.lrat" && bad "receipt issued for a program its proof does not cover" || ctl=$((ctl + 1)) +if iss "$W/p02_avg_u8.ir" "$R/out1" --input "$R/exe"; then + rc1=$(ls "$R/out1"/*.rcpt) + V1="$rc1 $W/p02_avg_u8.ir $R/exe --target lrat-gate --epoch 6 --allow-test-key" + want VALID class1-control $V1 + want WRONG_PRODUCER class1-other-producer $V1 --producer "$R/exe" + want DEPENDENCIES_MISMATCH class1-unexpected-dep $V1 --dep 0000000000000000000000000000000000000000000000000000000000000001 + want LRAT-NOT-CLAIMED class1-with-proof "$(ls "$R/out1"/*.rcpt)" "$W/p02_avg_u8.ir" "$R/exe" --target lrat-gate --epoch 6 --allow-test-key --lrat "avg=$W/p02_avg_u8.lrat" +else + bad "class 1 receipt issue failed" +fi + +# checker identity: same sources under another identity; its receipts are not checker2's verdicts +mkdir -p "$R/out2" +if "$C2O" receipt issue "$W/p02_avg_u8.ir" "$R/exe" --target lrat-gate --epoch 5 --expiry 9 --out-dir "$R/out2" >/dev/null 2>&1; then + rco=$(ls "$R/out2"/*.rcpt) + oid=$("$C2O" version | sed -n 's/^checker_id=//p') + sid=$("$C2" version | sed -n 's/^checker_id=//p') + [ -n "$oid" ] && [ "$oid" != "$sid" ] || bad "checker2-other has no distinct identity" + VO="$rco $W/p02_avg_u8.ir $R/exe --target lrat-gate --epoch 6 --allow-test-key" + want UNTRUSTED_CHECKER other-checker-refused $VO + want VALID other-checker-accepted-explicitly $VO --accept-checker "$oid" +else + bad "receipt issue by checker2-other failed" +fi + +echo "lrat: verified=$verified expected-traps=$traps controls-refused=$ctl failures=$fail" +[ "$verified" -ge 20 ] || bad "only $verified programs verified (need 20)" +[ "$fail" -eq 0 ] || exit 1 +echo "lrat: PASS" diff --git a/tests/checker2/lrat/n01_abs8_unguarded.osc b/tests/checker2/lrat/n01_abs8_unguarded.osc new file mode 100644 index 000000000..259ec8b20 --- /dev/null +++ b/tests/checker2/lrat/n01_abs8_unguarded.osc @@ -0,0 +1,7 @@ +// prove: abs8 +// expect: trap +// negative control: without the precondition -(-128) overflows. +fn abs8(x: i8) -> i8 { + if x < 0 { return -x; } + return x; +} diff --git a/tests/checker2/lrat/n02_add8.osc b/tests/checker2/lrat/n02_add8.osc new file mode 100644 index 000000000..64b02c9ba --- /dev/null +++ b/tests/checker2/lrat/n02_add8.osc @@ -0,0 +1,6 @@ +// prove: add8 +// expect: trap +// negative control: unchecked i8 addition can overflow. +fn add8(a: i8, b: i8) -> i8 { + return a + b; +} diff --git a/tests/checker2/lrat/n03_shl.osc b/tests/checker2/lrat/n03_shl.osc new file mode 100644 index 000000000..280dffae4 --- /dev/null +++ b/tests/checker2/lrat/n03_shl.osc @@ -0,0 +1,6 @@ +// prove: shl +// expect: trap +// negative control: a shift amount of 8 or more traps SHIFT. +fn shl(x: u8, s: u8) -> u8 { + return x << s; +} diff --git a/tests/checker2/lrat/n04_count.osc b/tests/checker2/lrat/n04_count.osc new file mode 100644 index 000000000..5c1455c47 --- /dev/null +++ b/tests/checker2/lrat/n04_count.osc @@ -0,0 +1,8 @@ +// prove: count +// expect: trap +// negative control: n > 20 exceeds the loop bound. +fn count(n: u8) -> u8 { + let mut i: u8 = 0; + while i < n bound 20 { i = i + 1; } + return i; +} diff --git a/tests/checker2/lrat/n05_ensures.osc b/tests/checker2/lrat/n05_ensures.osc new file mode 100644 index 000000000..81aae5eea --- /dev/null +++ b/tests/checker2/lrat/n05_ensures.osc @@ -0,0 +1,6 @@ +// prove: avg_bad +// expect: trap +// negative control: a false ensures clause (the plain sum wraps). +fn avg_bad(a: u8, b: u8) -> u8 ensures result >= a { + return a + b; +} diff --git a/tests/checker2/lrat/n06_square.osc b/tests/checker2/lrat/n06_square.osc new file mode 100644 index 000000000..67328b1bc --- /dev/null +++ b/tests/checker2/lrat/n06_square.osc @@ -0,0 +1,6 @@ +// prove: sq +// expect: trap +// negative control: without the range precondition x * x overflows i8. +fn sq(x: i8) -> i8 { + return x * x; +} diff --git a/tests/checker2/lrat/n07_cast.osc b/tests/checker2/lrat/n07_cast.osc new file mode 100644 index 000000000..08cdb2258 --- /dev/null +++ b/tests/checker2/lrat/n07_cast.osc @@ -0,0 +1,6 @@ +// prove: narrow +// expect: trap +// negative control: narrowing i16 to i8 without a range check traps CAST. +fn narrow(x: i16) -> i8 { + return x as i8; +} diff --git a/tests/checker2/lrat/n08_mul_wide.osc b/tests/checker2/lrat/n08_mul_wide.osc new file mode 100644 index 000000000..4b5af8a9c --- /dev/null +++ b/tests/checker2/lrat/n08_mul_wide.osc @@ -0,0 +1,6 @@ +// prove: m +// expect: trap +// negative control: a u16 product of two full bytes exceeds the ensures bound 225. +fn m(a: u8, b: u8) -> u16 ensures result <= 225 { + return (a as u16) * (b as u16); +} diff --git a/tests/checker2/lrat/n09_signed_shl.osc b/tests/checker2/lrat/n09_signed_shl.osc new file mode 100644 index 000000000..eeb300243 --- /dev/null +++ b/tests/checker2/lrat/n09_signed_shl.osc @@ -0,0 +1,6 @@ +// prove: sshl +// expect: trap +// negative control: a signed left shift that leaves the i8 range traps OVERFLOW. +fn sshl(x: i8) -> i8 { + return x << 2; +} diff --git a/tests/checker2/lrat/p01_abs8.osc b/tests/checker2/lrat/p01_abs8.osc new file mode 100644 index 000000000..22c91d9b5 --- /dev/null +++ b/tests/checker2/lrat/p01_abs8.osc @@ -0,0 +1,7 @@ +// prove: abs8 +// expect: holds +// |x| never overflows once x = -128 is excluded, and the result is non-negative. +fn abs8(x: i8) -> i8 requires x != -128 ensures result >= 0 { + if x < 0 { return -x; } + return x; +} diff --git a/tests/checker2/lrat/p02_avg_u8.osc b/tests/checker2/lrat/p02_avg_u8.osc new file mode 100644 index 000000000..66c666c19 --- /dev/null +++ b/tests/checker2/lrat/p02_avg_u8.osc @@ -0,0 +1,6 @@ +// prove: avg +// expect: holds +// overflow-free average of two bytes; never below their common bits. +fn avg(a: u8, b: u8) -> u8 ensures result >= (a & b) { + return (a & b) + ((a ^ b) >> 1); +} diff --git a/tests/checker2/lrat/p03_clamp.osc b/tests/checker2/lrat/p03_clamp.osc new file mode 100644 index 000000000..f41a69441 --- /dev/null +++ b/tests/checker2/lrat/p03_clamp.osc @@ -0,0 +1,8 @@ +// prove: clamp +// expect: holds +// narrowing cast is in range on every path. +fn clamp(x: i16) -> i8 ensures result <= 100 { + if x > 100 { return 100; } + if x < -100 { return -100; } + return x as i8; +} diff --git a/tests/checker2/lrat/p04_sat_add.osc b/tests/checker2/lrat/p04_sat_add.osc new file mode 100644 index 000000000..5b1f362a4 --- /dev/null +++ b/tests/checker2/lrat/p04_sat_add.osc @@ -0,0 +1,7 @@ +// prove: sat_add +// expect: holds +// saturating byte add never wraps below its first operand. +fn sat_add(a: u8, b: u8) -> u8 ensures result >= a { + if a > 255 - b { return 255; } + return a + b; +} diff --git a/tests/checker2/lrat/p05_sub8.osc b/tests/checker2/lrat/p05_sub8.osc new file mode 100644 index 000000000..bf3283891 --- /dev/null +++ b/tests/checker2/lrat/p05_sub8.osc @@ -0,0 +1,6 @@ +// prove: sub8 +// expect: holds +// checked i8 subtraction stays in range under its precondition. +fn sub8(a: i8, b: i8) -> i8 requires b >= 0 && b <= 50 && a >= -70 ensures result <= a { + return a - b; +} diff --git a/tests/checker2/lrat/p06_popcount.osc b/tests/checker2/lrat/p06_popcount.osc new file mode 100644 index 000000000..d8f7f0a61 --- /dev/null +++ b/tests/checker2/lrat/p06_popcount.osc @@ -0,0 +1,10 @@ +// prove: popcount +// expect: holds +// loop with a constant trip count; the count never exceeds 8. +fn popcount(x: u8) -> u8 ensures result <= 8 { + let mut n: u8 = 0; + for i in 0 .. 8 { + if (x >> (i as u8)) & 1 == 1 { n = n + 1; } + } + return n; +} diff --git a/tests/checker2/lrat/p07_pop_swar.osc b/tests/checker2/lrat/p07_pop_swar.osc new file mode 100644 index 000000000..2919be67f --- /dev/null +++ b/tests/checker2/lrat/p07_pop_swar.osc @@ -0,0 +1,10 @@ +// prove: pop8 +// expect: holds +// SWAR population count of a byte is at most 8. +fn pop8(x: u8) -> u8 ensures result <= 8 { + let mut v: u8 = x; + v = (v & 0x55) + ((v >> 1) & 0x55); + v = (v & 0x33) + ((v >> 2) & 0x33); + v = (v & 0x0f) + ((v >> 4) & 0x0f); + return v; +} diff --git a/tests/checker2/lrat/p08_sum10.osc b/tests/checker2/lrat/p08_sum10.osc new file mode 100644 index 000000000..f4cf99d2e --- /dev/null +++ b/tests/checker2/lrat/p08_sum10.osc @@ -0,0 +1,8 @@ +// prove: sum10 +// expect: holds +// ten additions of an i8 never overflow an i16 accumulator. +fn sum10(x: i8) -> i16 ensures result <= 1270 { + let mut s: i16 = 0; + for i in 0 .. 10 { s = s + (x as i16); } + return s; +} diff --git a/tests/checker2/lrat/p09_roundtrip.osc b/tests/checker2/lrat/p09_roundtrip.osc new file mode 100644 index 000000000..16246af66 --- /dev/null +++ b/tests/checker2/lrat/p09_roundtrip.osc @@ -0,0 +1,7 @@ +// prove: rt +// expect: holds +// widening then narrowing a byte is the identity and never traps CAST. +fn rt(x: u8) -> u8 ensures result == x { + let y: i16 = x as i16; + return y as u8; +} diff --git a/tests/checker2/lrat/p10_square.osc b/tests/checker2/lrat/p10_square.osc new file mode 100644 index 000000000..55706f48e --- /dev/null +++ b/tests/checker2/lrat/p10_square.osc @@ -0,0 +1,6 @@ +// prove: sq +// expect: holds +// i8 square in range for |x| <= 11, and non-negative. +fn sq(x: i8) -> i8 requires x >= -11 && x <= 11 ensures result >= 0 { + return x * x; +} diff --git a/tests/checker2/lrat/p11_shl.osc b/tests/checker2/lrat/p11_shl.osc new file mode 100644 index 000000000..a5775e253 --- /dev/null +++ b/tests/checker2/lrat/p11_shl.osc @@ -0,0 +1,6 @@ +// prove: shl +// expect: holds +// unsigned shift with the amount kept below the width never traps SHIFT. +fn shl(x: u8, s: u8) -> u8 requires s < 8 { + return x << s; +} diff --git a/tests/checker2/lrat/p12_max.osc b/tests/checker2/lrat/p12_max.osc new file mode 100644 index 000000000..c92477b2b --- /dev/null +++ b/tests/checker2/lrat/p12_max.osc @@ -0,0 +1,7 @@ +// prove: max8 +// expect: holds +// the maximum is at least both arguments. +fn max8(a: i8, b: i8) -> i8 ensures result >= a && result >= b { + if a > b { return a; } + return b; +} diff --git a/tests/checker2/lrat/p13_widen_add.osc b/tests/checker2/lrat/p13_widen_add.osc new file mode 100644 index 000000000..b1e13834b --- /dev/null +++ b/tests/checker2/lrat/p13_widen_add.osc @@ -0,0 +1,6 @@ +// prove: widen +// expect: holds +// widened byte sum is bounded. +fn widen(a: u8, b: u8) -> u16 ensures result <= 510 { + return (a as u16) + (b as u16); +} diff --git a/tests/checker2/lrat/p14_signed_shl.osc b/tests/checker2/lrat/p14_signed_shl.osc new file mode 100644 index 000000000..304ec0216 --- /dev/null +++ b/tests/checker2/lrat/p14_signed_shl.osc @@ -0,0 +1,6 @@ +// prove: sshl +// expect: holds +// signed shift left that stays representable. +fn sshl(x: i8) -> i8 requires x >= -16 && x < 16 ensures result >= -64 { + return x << 2; +} diff --git a/tests/checker2/lrat/p15_bool.osc b/tests/checker2/lrat/p15_bool.osc new file mode 100644 index 000000000..d21aac96d --- /dev/null +++ b/tests/checker2/lrat/p15_bool.osc @@ -0,0 +1,6 @@ +// prove: band +// expect: holds +// a conjunction implies its first operand. +fn band(a: bool, b: bool) -> bool ensures result == false || a == true { + return a && b; +} diff --git a/tests/checker2/lrat/p16_count.osc b/tests/checker2/lrat/p16_count.osc new file mode 100644 index 000000000..835a4cab2 --- /dev/null +++ b/tests/checker2/lrat/p16_count.osc @@ -0,0 +1,8 @@ +// prove: count +// expect: holds +// data-dependent loop: with n <= 20 the bound 20 is never exceeded. +fn count(n: u8) -> u8 requires n <= 20 ensures result == n { + let mut i: u8 = 0; + while i < n bound 20 { i = i + 1; } + return i; +} diff --git a/tests/checker2/lrat/p17_negneg.osc b/tests/checker2/lrat/p17_negneg.osc new file mode 100644 index 000000000..dceb3fdd6 --- /dev/null +++ b/tests/checker2/lrat/p17_negneg.osc @@ -0,0 +1,7 @@ +// prove: nn +// expect: holds +// double negation is the identity away from -128. +fn nn(x: i8) -> i8 requires x != -128 ensures result == x { + let y: i8 = -x; + return -y; +} diff --git a/tests/checker2/lrat/p18_xor_swap.osc b/tests/checker2/lrat/p18_xor_swap.osc new file mode 100644 index 000000000..78f52fed6 --- /dev/null +++ b/tests/checker2/lrat/p18_xor_swap.osc @@ -0,0 +1,11 @@ +// prove: xs +// expect: holds +// three XORs swap two bytes. +fn xs(a: u8, b: u8) -> u8 ensures result == b { + let mut x: u8 = a; + let mut y: u8 = b; + x = x ^ y; + y = x ^ y; + x = x ^ y; + return x; +} diff --git a/tests/checker2/lrat/p19_gray.osc b/tests/checker2/lrat/p19_gray.osc new file mode 100644 index 000000000..5cc0f2ddb --- /dev/null +++ b/tests/checker2/lrat/p19_gray.osc @@ -0,0 +1,11 @@ +// prove: gray +// expect: holds +// Gray encode then decode is the identity. +fn gray(x: u8) -> u8 ensures result == x { + let g: u8 = x ^ (x >> 1); + let mut y: u8 = g; + y = y ^ (y >> 4); + y = y ^ (y >> 2); + y = y ^ (y >> 1); + return y; +} diff --git a/tests/checker2/lrat/p20_mul_wide.osc b/tests/checker2/lrat/p20_mul_wide.osc new file mode 100644 index 000000000..a61751342 --- /dev/null +++ b/tests/checker2/lrat/p20_mul_wide.osc @@ -0,0 +1,6 @@ +// prove: m +// expect: holds +// product of two nibbles widened to u16 never exceeds 225. +fn m(a: u8, b: u8) -> u16 requires a < 16 && b < 16 ensures result <= 225 { + return (a as u16) * (b as u16); +} diff --git a/tests/checker2/mutants.sh b/tests/checker2/mutants.sh new file mode 100644 index 000000000..6b61fe669 --- /dev/null +++ b/tests/checker2/mutants.sh @@ -0,0 +1,85 @@ +#!/bin/sh +# Negative controls for checker2 (omega#446): every line tagged GUARD:<name> in a checker2 source +# is removed, one at a time, in a scratch copy; the matching test is rebuilt against that copy and +# MUST fail. A mutant that survives means the test cannot see that check, and this script fails. +# Also requires the unmutated build to pass first (otherwise "fails" proves nothing). +# Usage: sh tests/checker2/mutants.sh <cc> <scratch-dir> <ir-dir from differential.sh> <work-dir from lrat.sh> +set -u +CC=${1:-cc} +OUT=${2:-build/checker2/mutants} +IRDIR=${3:-build/checker2/differential/ir} +LRATDIR=${4:-build/checker2/lrat} +CFLAGS="-std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O1 -Isrc -Isrc/checker2" +SIG="src/searchtrace/sig/ed25519.c src/searchtrace/sig/sha512.c src/searchtrace/sig/ct.c" +mkdir -p "$OUT" +total=0 +tagged=0 +killed=0 +survived="" + +# run_family <source under test> <test .c> <other sources> <test args> +run_family() { + src=$1; test_c=$2; others=$3; targs=$4 + base="$OUT/$(basename "$src" .c)" + # shellcheck disable=SC2086 + if ! $CC $CFLAGS -o "$base.orig" "$test_c" "$src" $others 2>"$base.orig.log"; then + echo "mutants: baseline build failed for $src"; cat "$base.orig.log"; exit 1 + fi + # shellcheck disable=SC2086 + if ! "$base.orig" $targs >/dev/null 2>&1; then + echo "mutants: baseline test fails for $src; negative controls are meaningless"; exit 1 + fi + # every "GUARD:" occurrence must be exactly one well-formed, unique tag on its own line, so the + # number of mutants run equals the number of tags (an empty, malformed, repeated or doubled + # tag would otherwise be skipped silently) + occ=$(grep -o "GUARD:" "$src" | wc -l) + names=$(grep -o "GUARD:[a-z0-9-]*" "$src" | sed "s/GUARD://" | grep -c . ) + uniq_names=$(grep -o "GUARD:[a-z0-9-]*" "$src" | sed "s/GUARD://" | grep . | sort -u | wc -l) + lines=$(grep -c "GUARD:" "$src") + if [ "$occ" -ne "$names" ] || [ "$names" -ne "$uniq_names" ] || [ "$names" -ne "$lines" ]; then + echo "mutants: $src has $occ GUARD: occurrences on $lines lines but $uniq_names distinct well-formed tags" + exit 1 + fi + tagged=$((tagged + occ)) + for name in $(grep -o "GUARD:[a-z0-9-]*" "$src" | sed "s/GUARD://" | sort -u); do + total=$((total + 1)) + m="$base.$name.c" + # drop the tagged line; a tagged "if (...)" line without ";" also drops its one-line body + awk -v tag="GUARD:$name" ' + skip { skip = 0; next } + index($0, tag) && substr($0, index($0, tag) + length(tag)) ~ /^([^a-z0-9-]|$)/ { if ($0 !~ /;/) skip = 1; next } + { print }' "$src" > "$m" + # shellcheck disable=SC2086 + if ! $CC $CFLAGS -Wno-unused-function -Wno-unused-variable -Wno-unused-but-set-variable \ + -Wno-error -o "$base.$name" "$test_c" "$m" $others 2>"$base.$name.log"; then + echo "mutants: $src GUARD:$name does not build (counts as killed)" + killed=$((killed + 1)) + continue + fi + # shellcheck disable=SC2086 + if timeout 120 "$base.$name" $targs >/dev/null 2>&1; then + survived="$survived $src:$name" + else + killed=$((killed + 1)) + fi + done +} + +run_family src/checker2/c2_receipt.c tests/checker2/test_c2_receipt.c "src/sha256.c $SIG" tests/checker2/fixtures +run_family src/checker2/c2_ir.c tests/checker2/test_c2_ir.c src/checker2/c2_check.c "$IRDIR" +run_family src/checker2/c2_check.c tests/checker2/test_c2_ir.c src/checker2/c2_ir.c "$IRDIR" +run_family src/checker2/c2_lrat.c tests/checker2/test_c2_lrat.c "" "" +run_family src/checker2/c2_blast.c tests/checker2/test_c2_blast.c "src/checker2/c2_ir.c src/checker2/c2_check.c src/checker2/c2_lrat.c" "$IRDIR $LRATDIR" + +echo "checker2 mutants: $killed of $total killed" +# every GUARD tag in the checker2 sources is covered by a family above (none silently skipped) +all=$(cat src/checker2/*.c src/checker2/*.h | grep -o "GUARD:" | wc -l) +if [ "$all" -ne "$total" ] || [ "$tagged" -ne "$total" ]; then + echo "mutants: $all GUARD tags in src/checker2 but $total mutants run"; exit 1 +fi +if [ -n "$survived" ]; then + echo "SURVIVED (a test cannot see this check):$survived" + exit 1 +fi +[ "$total" -gt 0 ] || { echo "mutants: no GUARD lines found"; exit 1; } +exit 0 diff --git a/tests/checker2/producer/osc_emit_ir.c b/tests/checker2/producer/osc_emit_ir.c new file mode 100644 index 000000000..811c5a1e2 --- /dev/null +++ b/tests/checker2/producer/osc_emit_ir.c @@ -0,0 +1,43 @@ +/* osc_emit_ir: PRODUCER-side helper for the checker2 tests (omega#446). Not part of checker2. + * + * `oscc <file> OUT` writes IR bytes only when the unit also fits an aienos unit container, which + * refuses reference parameters; this helper writes the canonical IR bytes of every unit the + * producer front end accepts, through the producer's public API only (osc_compile, osc_ir_encode + * from src/compiler/osc_front.h and osc_ir.h). It is linked with the producer library, never with + * checker2. The test compares its digest line with `oscc <file>` ir_sha256 so both are the same bytes. + * + * Usage: osc_emit_ir <file.osc> <out.ir> exit 0 written, 1 producer rejected, 2 usage / I/O. */ +#include <stdio.h> +#include <stdlib.h> + +#include "osc_front.h" +#include "sha256.h" + +int main(int argc, char **argv) +{ + if (argc != 3) { fprintf(stderr, "usage: osc_emit_ir <file.osc> <out.ir>\n"); return 2; } + FILE *f = fopen(argv[1], "rb"); + if (!f) { perror(argv[1]); return 2; } + static char src[1 << 20]; + size_t n = fread(src, 1, sizeof src - 1, f); + fclose(f); + src[n] = 0; + OscUnit *u = calloc(1, sizeof *u); + OscDiag d; + if (!u) return 2; + if (osc_compile(src, n, u, &d, NULL) != 0) { printf("producer=REJECT\n"); free(u); return 1; } + size_t len = 0; + if (osc_ir_encode(u, NULL, 0, &len) != 0 && len == 0) { free(u); return 2; } + uint8_t *buf = malloc(len); + if (!buf || osc_ir_encode(u, buf, len, &len) != 0) { free(u); free(buf); return 2; } + uint8_t h[32]; + sha256_hash(buf, len, h); + printf("producer=ACCEPT ir_sha256="); + for (int i = 0; i < 32; i++) printf("%02x", h[i]); + printf("\n"); + FILE *o = fopen(argv[2], "wb"); + if (!o || fwrite(buf, 1, len, o) != len || fclose(o) != 0) { perror(argv[2]); return 2; } + free(buf); + free(u); + return 0; +} diff --git a/tests/checker2/test_c2_blast.c b/tests/checker2/test_c2_blast.c new file mode 100644 index 000000000..3ab0e5fda --- /dev/null +++ b/tests/checker2/test_c2_blast.c @@ -0,0 +1,224 @@ +/* test_c2_blast: checker2's bit-blaster without any SAT solver (omega#446). + * A. Every function of every corpus unit that has a non-scalar register (slice, handle, arena, + * struct) is refused as BLAST-UNSUPPORTED "not a scalar", never approximated. + * B. Every program of the LRAT gate (tests/checker2/lrat, IR written by lrat.sh): the CNF is + * evaluated input by input with unit propagation alone (the encoding is full Tseitin, so fixing + * the argument bits fixes every gate). p* programs ("holds") must conflict on every input; + * n* programs ("trap") must have an input that satisfies it. Exhaustive up to 16 argument bits. + * This cross-checks the CNF against the expectation independently of c2sat and of the proof. + * Usage: test_c2_blast <corpus-ir-dir> <lrat-work-dir> */ +#include <dirent.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_blast.h" + +static int fails; + +static uint8_t *slurp(const char *path, size_t *n) +{ + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t *b = malloc((size_t)len + 1); + if (b && fread(b, 1, (size_t)len, f) != (size_t)len) { free(b); b = NULL; } + fclose(f); + *n = (size_t)len; + return b; +} + +static int load(const char *path, C2Unit *u) +{ + size_t n; + uint8_t *b = slurp(path, &n); + C2Verdict v; + int rc = !b || c2_decode(b, n, u, &v) || c2_check_unit(u, &v); + free(b); + return rc ? -1 : 0; +} + +/* ------------------------------------------------------------------ propagation evaluator */ + +typedef struct { + const C2Cnf *c; + int **occ, *nocc; /* clauses containing literal l at occ[l + nvars] */ + signed char *val; + int *trail, ntrail; +} Ev; + +static void ev_init(Ev *e, const C2Cnf *c) +{ + int nv = c->nvars; + e->c = c; + e->occ = calloc((size_t)nv * 2 + 1, sizeof *e->occ); + e->nocc = calloc((size_t)nv * 2 + 1, sizeof *e->nocc); + int *cap = calloc((size_t)nv * 2 + 1, sizeof *cap); + e->val = calloc((size_t)nv + 1, 1); + e->trail = malloc(((size_t)nv + 1) * sizeof *e->trail); + for (int i = 0; i < c->nclauses; i++) + for (const int32_t *l = c->lits + c->start[i]; *l; l++) { + int s = *l + nv; + if (e->nocc[s] == cap[s]) { cap[s] = cap[s] ? cap[s] * 2 : 4; e->occ[s] = realloc(e->occ[s], (size_t)cap[s] * sizeof(int)); } + e->occ[s][e->nocc[s]++] = i; + } + free(cap); +} + +static void ev_free(Ev *e) +{ + for (int i = 0; i < e->c->nvars * 2 + 1; i++) free(e->occ[i]); + free(e->occ); + free(e->nocc); + free(e->val); + free(e->trail); +} + +static int lval(const Ev *e, int l) { int v = e->val[abs(l)]; return l > 0 ? v : -v; } +static void set(Ev *e, int l) { e->val[abs(l)] = l > 0 ? 1 : -1; e->trail[e->ntrail++] = l; } + +/* 1 conflict, 0 every variable assigned without conflict, -1 propagation left variables open */ +static int ev_run(Ev *e, int inputs, unsigned long a) +{ + const C2Cnf *c = e->c; + while (e->ntrail) e->val[abs(e->trail[--e->ntrail])] = 0; + for (int i = 0; i < c->nclauses; i++) /* unit and empty input clauses */ + if (c->lits[c->start[i]] == 0) return 1; + for (int i = 0; i < c->nclauses; i++) { + const int32_t *l = c->lits + c->start[i]; + if (l[1] == 0) { + if (lval(e, l[0]) < 0) return 1; + if (!lval(e, l[0])) set(e, l[0]); + } + } + for (int k = 0; k < inputs; k++) { + int v = 2 + k, l = (a >> k) & 1 ? v : -v; + if (lval(e, l) < 0) return 1; + if (!lval(e, l)) set(e, l); + } + for (int q = 0; q < e->ntrail; q++) { + int f = -e->trail[q]; + for (int k = 0; k < e->nocc[f + c->nvars]; k++) { + const int32_t *l = c->lits + c->start[e->occ[f + c->nvars][k]]; + int open = 0, last = 0, sat = 0; + for (; *l; l++) { + int s = lval(e, *l); + if (s > 0) { sat = 1; break; } + if (!s) { open++; last = *l; } + } + if (sat) continue; + if (!open) return 1; + if (open == 1) set(e, last); + } + } + return e->ntrail == c->nvars ? 0 : -1; +} + +/* ------------------------------------------------------------------ main */ + +static int has_nonscalar(const C2Func *f) +{ + for (int r = 0; r < f->nvregs; r++) + if (!(f->vt[r].s >= S_BOOL && f->vt[r].s <= S_I64)) return 1; + return 0; +} + +static int by_name(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } + +static int list(const char *dir, const char *suffix, char ***out) +{ + DIR *d = opendir(dir); + if (!d) return -1; + int n = 0, cap = 0; + char **v = NULL; + struct dirent *de; + while ((de = readdir(d))) { + size_t l = strlen(de->d_name), s = strlen(suffix); + if (l <= s || strcmp(de->d_name + l - s, suffix)) continue; + if (n == cap) { cap = cap ? cap * 2 : 64; v = realloc(v, (size_t)cap * sizeof *v); } + v[n] = malloc(strlen(dir) + l + 2); + sprintf(v[n++], "%s/%s", dir, de->d_name); + } + closedir(d); + qsort(v, (size_t)n, sizeof *v, by_name); + *out = v; + return n; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { fprintf(stderr, "usage: test_c2_blast <corpus-ir-dir> <lrat-work-dir>\n"); return 2; } + char **files; + int nf = list(argv[1], ".ir", &files), refused_nonscalar = 0, scalar_ok = 0, scalar_refused = 0; + if (nf <= 0) { printf("FAIL no corpus IR in %s\n", argv[1]); return 1; } + for (int i = 0; i < nf; i++) { + C2Unit u; + if (load(files[i], &u)) { printf("FAIL %s: not accepted\n", files[i]); fails++; free(files[i]); continue; } + for (int fi = 0; fi < u.nfuncs; fi++) { + C2Cnf cnf; + C2BlastInfo bi; + memset(&cnf, 0, sizeof cnf); + int rc = c2_blast_notrap(&u, fi, &cnf, &bi); + if (rc == 0) c2_cnf_free(&cnf); + if (has_nonscalar(&u.fn[fi])) { + if (rc == 0 || strcmp(bi.rule, "BLAST-UNSUPPORTED") || !strstr(bi.detail, "not a scalar")) { + printf("FAIL %s fn %d: non-scalar function not refused as such (rc=%d rule=%s detail=%s)\n", + files[i], fi, rc, rc ? bi.rule : "-", rc ? bi.detail : "-"); + fails++; + } else refused_nonscalar++; + } else if (rc == 0) scalar_ok++; + else scalar_refused++; + } + c2_unit_free(&u); + free(files[i]); + } + free(files); + if (refused_nonscalar == 0) { printf("FAIL corpus has no non-scalar function to refuse\n"); fails++; } + printf("test_c2_blast: corpus %d units: %d scalar functions blasted, %d scalar refused (calls, division, memory), %d non-scalar refused\n", + nf, scalar_ok, scalar_refused, refused_nonscalar); + + int np = list(argv[2], ".ir", &files), holds = 0, traps = 0, checked = 0; + if (np <= 0) { printf("FAIL no LRAT gate IR in %s\n", argv[2]); return 1; } + for (int i = 0; i < np; i++) { + const char *base = strrchr(files[i], '/') + 1; + int want_trap = base[0] == 'n'; + if (base[0] != 'n' && base[0] != 'p') { free(files[i]); continue; } + C2Unit u; + C2Cnf cnf; + C2BlastInfo bi; + memset(&cnf, 0, sizeof cnf); + if (load(files[i], &u) || u.nfuncs != 1 || c2_blast_notrap(&u, 0, &cnf, &bi)) { + printf("FAIL %s: not blasted\n", base); + fails++; + free(files[i]); + continue; + } + Ev e; + memset(&e, 0, sizeof e); + ev_init(&e, &cnf); + int ok = 1; + unsigned long total = bi.inputs <= 16 ? 1UL << bi.inputs : 65536, sat = 0, open = 0; + unsigned long x = 99; + for (unsigned long a = 0; a < total; a++) { + unsigned long in = a; + if (bi.inputs > 16) { x = x * 6364136223846793005UL + 1442695040888963407UL; in = x >> 7; } + int r = ev_run(&e, bi.inputs, in); + if (r == 0) sat++; + if (r < 0) open++; + } + if (open) { printf("FAIL %s: %lu inputs left gates undetermined\n", base, open); ok = 0; } + if (want_trap && !sat) { printf("FAIL %s: expected a trapping input, none of %lu traps\n", base, total); ok = 0; } + if (!want_trap && sat) { printf("FAIL %s: %lu of %lu inputs trap but the program is expected to hold\n", base, sat, total); ok = 0; } + if (ok) { checked++; if (want_trap) traps++; else holds++; } else fails++; + ev_free(&e); + c2_cnf_free(&cnf); + c2_unit_free(&u); + free(files[i]); + } + free(files); + if (holds < 20) { printf("FAIL only %d holding programs checked (need 20)\n", holds); fails++; } + printf("test_c2_blast: %d gate programs evaluated input by input (%d hold, %d trap), %d failures\n", checked, holds, traps, fails); + return fails ? 1 : 0; +} diff --git a/tests/checker2/test_c2_blast_native.c b/tests/checker2/test_c2_blast_native.c new file mode 100644 index 000000000..fd8338b77 --- /dev/null +++ b/tests/checker2/test_c2_blast_native.c @@ -0,0 +1,464 @@ +/* test_c2_blast_native: checker2's bit-blaster against the producer's compiled code (omega#446). + * + * Independent cross-check of the blaster's semantics. The other side is NOT checker2 code and NOT + * a hand-written label: it is the AArch64 machine code oscc emits (`oscc file.osc OUT` writes + * OUT.ir, OUT.code, OUT.entries), mapped executable and called as a black box per the documented + * native ABI (docs/osc/OSC-1-DESIGN.md section 7: params in x0..x5, return in x0, runtime pointer + * in x7). Every runtime entry the code reaches is a trap here (the blastable subset has no calls, + * memory or handles), and the trap code is read from the second argument register. Nothing of + * src/compiler is linked or read; only oscc's output bytes are used. + * + * The CNF side is the formula checker2 builds from oscc's own IR bytes, evaluated with unit + * propagation after fixing the argument bits as units (full Tseitin encoding: fixing the inputs + * fixes every gate, so the answer is exact; an undetermined gate fails the test). + * + * Two kinds of program, by file name: + * op_* fn f(<operands>, c: T) -> T ensures result != c { return <one operation>; } + * The ensures clause exposes the operation's value to the CNF. For each operand vector: + * run the code with c = 0. If it returns r (or traps ENSURES with c = 0, then r = 0, and a + * rerun with c = 1 must return 0), the CNF must be satisfiable at c = r (the ensures trap) + * and unsatisfiable at c = r ^ 1. If the code traps with any other code, the operation + * itself traps and the CNF must be satisfiable at c = 0 and at c = 1. + * other (the LRAT gate programs): the code traps with a code other than REQUIRES (9) exactly on + * the inputs at which the CNF is satisfiable. + * Inputs: exhaustive up to 16 operand bits; otherwise edge values of each operand type (0, 1, 2, + * -1, -2, MIN, MIN+1, MAX, MAX-1, the sign bit, every shift amount 0..w+1) in all combinations, + * plus 3000 pseudo-random vectors. + * + * Negative controls (file "controls" in the work directory, lines "<ir-name> <code-name>"): the + * CNF of one program checked against the code of a different operation of the same signature must + * disagree on at least one input, so the comparison can tell the operations apart. + * + * AArch64 Linux only (the documented native ABI); the harness refuses to run elsewhere. + * Usage: test_c2_blast_native <work-dir> (written by tests/checker2/blast_native.sh) */ +#include <dirent.h> +#include <setjmp.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mman.h> + +#include "c2_blast.h" + +#if !defined(__aarch64__) || !defined(__linux__) +int main(void) +{ + printf("test_c2_blast_native: FAIL not an AArch64 Linux host; the native cross-check cannot run\n"); + return 1; +} +#else + +#define TRAP_REQUIRES 9 +#define TRAP_ENSURES 10 + +static int fails; + +static uint8_t *slurp(const char *path, size_t *n) +{ + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t *b = len >= 0 ? malloc((size_t)len + 1) : NULL; + if (b && fread(b, 1, (size_t)len, f) != (size_t)len) { free(b); b = NULL; } + fclose(f); + if (b) b[len] = 0; + *n = (size_t)len; + return b; +} + +/* ------------------------------------------------------------------ CNF side */ + +typedef struct { + const C2Cnf *c; + int **occ, *nocc; /* clauses containing literal l at occ[l + nvars] */ + signed char *val; + int *trail, ntrail; +} Ev; + +static void ev_init(Ev *e, const C2Cnf *c) +{ + int nv = c->nvars; + e->c = c; + e->occ = calloc((size_t)nv * 2 + 1, sizeof *e->occ); + e->nocc = calloc((size_t)nv * 2 + 1, sizeof *e->nocc); + int *cap = calloc((size_t)nv * 2 + 1, sizeof *cap); + e->val = calloc((size_t)nv + 1, 1); + e->trail = malloc(((size_t)nv + 1) * sizeof *e->trail); + e->ntrail = 0; + for (int i = 0; i < c->nclauses; i++) + for (const int32_t *l = c->lits + c->start[i]; *l; l++) { + int s = *l + nv; + if (e->nocc[s] == cap[s]) { cap[s] = cap[s] ? cap[s] * 2 : 4; e->occ[s] = realloc(e->occ[s], (size_t)cap[s] * sizeof(int)); } + e->occ[s][e->nocc[s]++] = i; + } + free(cap); +} + +static void ev_free(Ev *e) +{ + for (int i = 0; i < e->c->nvars * 2 + 1; i++) free(e->occ[i]); + free(e->occ); + free(e->nocc); + free(e->val); + free(e->trail); +} + +static int lval(const Ev *e, int l) { int v = e->val[abs(l)]; return l > 0 ? v : -v; } +static void set(Ev *e, int l) { e->val[abs(l)] = l > 0 ? 1 : -1; e->trail[e->ntrail++] = l; } + +/* bits[k] is argument bit k (CNF variable 2 + k). 1 satisfiable (a trap is reachable), 0 conflict, + * -1 propagation left gates undetermined. */ +static int ev_sat(Ev *e, const uint8_t *bits, int inputs) +{ + const C2Cnf *c = e->c; + while (e->ntrail) e->val[abs(e->trail[--e->ntrail])] = 0; + for (int i = 0; i < c->nclauses; i++) + if (c->lits[c->start[i]] == 0) return 0; + for (int i = 0; i < c->nclauses; i++) { + const int32_t *l = c->lits + c->start[i]; + if (l[1] == 0) { + if (lval(e, l[0]) < 0) return 0; + if (!lval(e, l[0])) set(e, l[0]); + } + } + for (int k = 0; k < inputs; k++) { + int l = bits[k] ? 2 + k : -(2 + k); + if (lval(e, l) < 0) return 0; + if (!lval(e, l)) set(e, l); + } + for (int q = 0; q < e->ntrail; q++) { + int f = -e->trail[q]; + for (int k = 0; k < e->nocc[f + c->nvars]; k++) { + const int32_t *l = c->lits + c->start[e->occ[f + c->nvars][k]]; + int open = 0, last = 0, sat = 0; + for (; *l; l++) { + int s = lval(e, *l); + if (s > 0) { sat = 1; break; } + if (!s) { open++; last = *l; } + } + if (sat) continue; + if (!open) return 0; + if (open == 1) set(e, last); + } + } + return e->ntrail == c->nvars ? 1 : -1; +} + +/* ------------------------------------------------------------------ native side */ + +static sigjmp_buf jb; +static volatile uint64_t trap_code; +static void *rt_table[512]; + +static void rt_entry(uint64_t x0, uint64_t x1) +{ + (void)x0; + trap_code = x1; + siglongjmp(jb, 1); +} + +typedef uint64_t (*NativeFn)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, void *); + +typedef struct { + uint8_t *map; + size_t maplen; + NativeFn fn; +} Native; + +static int native_load(const char *code_path, const char *entries_path, const char *fname, Native *nt) +{ + size_t n, en; + uint8_t *code = slurp(code_path, &n); + uint8_t *ent = slurp(entries_path, &en); + long off = -1; + if (code && ent) { + for (char *line = strtok((char *)ent, "\n"); line; line = strtok(NULL, "\n")) { + char *name = strrchr(line, ' '); + if (name && strcmp(name + 1, fname) == 0) off = strtol(line, NULL, 10); + } + } + free(ent); + if (!code || off < 0 || (size_t)off >= n) { free(code); return -1; } + nt->maplen = (n + 4095) & ~(size_t)4095; + nt->map = mmap(NULL, nt->maplen, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (nt->map == MAP_FAILED) { free(code); return -1; } + memcpy(nt->map, code, n); + free(code); + if (mprotect(nt->map, nt->maplen, PROT_READ | PROT_EXEC)) { munmap(nt->map, nt->maplen); return -1; } + __builtin___clear_cache((char *)nt->map, (char *)nt->map + n); + nt->fn = (NativeFn)(void *)(nt->map + off); + return 0; +} + +/* 0 returned (*ret), 1 trapped (*code) */ +static int native_run(const Native *nt, const uint64_t *a, int na, uint64_t *ret, uint64_t *code) +{ + uint64_t x[6] = {0}; + for (int i = 0; i < na && i < 6; i++) x[i] = a[i]; + if (sigsetjmp(jb, 0) == 0) { + *ret = nt->fn(x[0], x[1], x[2], x[3], x[4], x[5], 0, rt_table); + return 0; + } + *code = trap_code; + return 1; +} + +/* ------------------------------------------------------------------ values */ + +static int width(uint8_t s) +{ + static const int w[] = {0, 1, 8, 16, 32, 64, 8, 16, 32, 64}; + return s <= S_I64 ? w[s] : 0; +} +static int is_signed(uint8_t s) { return s >= S_I8 && s <= S_I64; } +static uint64_t mask(int w) { return w == 64 ? ~0ULL : (1ULL << w) - 1; } + +/* canonical 64-bit register value of the low w bits of v */ +static uint64_t canon(uint64_t v, uint8_t s) +{ + int w = width(s); + v &= mask(w); + if (is_signed(s) && w < 64 && (v >> (w - 1)) & 1) v |= ~mask(w); + return v; +} + +/* edge values of a type, as low-w-bit patterns */ +static int edges(uint8_t s, uint64_t *out) +{ + int w = width(s), n = 0; + if (w == 1) { out[0] = 0; out[1] = 1; return 2; } + uint64_t m = mask(w), msb = 1ULL << (w - 1); + uint64_t base[] = {0, 1, 2, 3, m, m - 1, msb, msb + 1, msb - 1, msb - 2}; + for (unsigned i = 0; i < sizeof base / sizeof *base; i++) out[n++] = base[i] & m; + for (int k = 4; k <= w + 1; k++) out[n++] = (uint64_t)k & m; /* every shift amount */ + return n; +} + +static uint64_t rng = 88172645463325252ULL; +static uint64_t rnd(void) +{ + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + return rng; +} + +/* operand vectors for params 0..np-1: exhaustive up to 16 bits, else edges x edges + random */ +typedef struct { + uint64_t (*v)[6]; + long n, cap; +} Vecs; + +static void push(Vecs *vs, const uint64_t *x, int np) +{ + if (vs->n == vs->cap) { vs->cap = vs->cap ? vs->cap * 2 : 1024; vs->v = realloc(vs->v, (size_t)vs->cap * sizeof *vs->v); } + for (int i = 0; i < 6; i++) vs->v[vs->n][i] = i < np ? x[i] : 0; + vs->n++; +} + +static void vectors(const C2Func *f, int np, Vecs *vs) +{ + int bits = 0; + for (int i = 0; i < np; i++) bits += width(f->vt[i].s); + uint64_t x[6] = {0}; + if (bits <= 16) { + for (uint64_t a = 0; a < (1ULL << bits); a++) { + int sh = 0; + for (int i = 0; i < np; i++) { int w = width(f->vt[i].s); x[i] = (a >> sh) & mask(w); sh += w; } + push(vs, x, np); + } + return; + } + uint64_t e[6][80]; + int ne[6], idx[6] = {0}; + long combos = 1; + for (int i = 0; i < np; i++) { ne[i] = edges(f->vt[i].s, e[i]); combos *= ne[i]; } + if (combos <= 20000) + for (long c = 0; c < combos; c++) { + long r = c; + for (int i = 0; i < np; i++) { idx[i] = (int)(r % ne[i]); r /= ne[i]; x[i] = e[i][idx[i]]; } + push(vs, x, np); + } + for (int k = 0; k < 3000; k++) { + for (int i = 0; i < np; i++) { + /* mix: sometimes an edge value, sometimes a uniform pattern */ + uint64_t r = rnd(); + x[i] = (r & 3) == 0 ? e[i][(r >> 8) % (uint64_t)ne[i]] : rnd() & mask(width(f->vt[i].s)); + } + push(vs, x, np); + } +} + +static void put_bits(uint8_t *bits, int *at, uint64_t v, int w) +{ + for (int k = 0; k < w; k++) bits[(*at)++] = (uint8_t)((v >> k) & 1); +} + +/* ------------------------------------------------------------------ one program */ + +typedef struct { + long vectors, native_traps, mismatches, undetermined; + char first[200]; +} Stat; + +static void note(Stat *st, const char *what, const uint64_t *x, int np, uint64_t extra) +{ + st->mismatches++; + if (st->first[0]) return; + int k = snprintf(st->first, sizeof st->first, "%s at", what); + for (int i = 0; i < np && k < (int)sizeof st->first; i++) + k += snprintf(st->first + k, sizeof st->first - (size_t)k, " %#llx", (unsigned long long)x[i]); + if (k < (int)sizeof st->first) snprintf(st->first + k, sizeof st->first - (size_t)k, " (%#llx)", (unsigned long long)extra); +} + +/* compare the CNF of irfile with the code of codebase; value mode for op_* programs */ +static int compare(const char *dir, const char *irname, const char *codename, Stat *st) +{ + char p[1024], q[1024]; + memset(st, 0, sizeof *st); + snprintf(p, sizeof p, "%s/%s.ir", dir, irname); + size_t n; + uint8_t *b = slurp(p, &n); + C2Unit *u = calloc(1, sizeof *u); + C2Verdict v; + if (!b || !u || c2_decode(b, n, u, &v) || c2_check_unit(u, &v) || u->nfuncs != 1) { + printf("FAIL %s: IR not accepted by checker2\n", irname); + free(b); + free(u); + return -1; + } + free(b); + C2Cnf cnf; + C2BlastInfo bi; + memset(&cnf, 0, sizeof cnf); + if (c2_blast_notrap(u, 0, &cnf, &bi)) { + printf("FAIL %s: not blasted (%s %s)\n", irname, bi.rule, bi.detail); + c2_unit_free(u); + free(u); + return -1; + } + Native nt; + snprintf(p, sizeof p, "%s/%s.code", dir, codename); + snprintf(q, sizeof q, "%s/%s.entries", dir, codename); + const C2Func *f = &u->fn[0]; + int rc = -1; + if (native_load(p, q, f->name, &nt)) { + printf("FAIL %s: cannot load native code %s\n", irname, codename); + goto out; + } + Ev e; + ev_init(&e, &cnf); + int value_mode = strncmp(irname, "op_", 3) == 0; + int np = f->nparams, nops = value_mode ? np - 1 : np; + uint8_t cs = f->vt[np - 1].s; + int cw = width(cs); + Vecs vs = {0}; + vectors(f, nops, &vs); + uint8_t *bits = malloc((size_t)bi.inputs + 1); + for (long i = 0; i < vs.n; i++) { + uint64_t a[6], ret = 0, code = 0; + int at = 0; + for (int k = 0; k < nops; k++) { a[k] = canon(vs.v[i][k], f->vt[k].s); put_bits(bits, &at, vs.v[i][k], width(f->vt[k].s)); } + st->vectors++; + if (!value_mode) { + int t = native_run(&nt, a, np, &ret, &code); + int native_trap = t && code != TRAP_REQUIRES; + st->native_traps += native_trap; + int s = ev_sat(&e, bits, bi.inputs); + if (s < 0) { st->undetermined++; continue; } + if (s != native_trap) note(st, native_trap ? "code traps, CNF holds" : "CNF traps, code holds", vs.v[i], nops, code); + continue; + } + /* value mode: last parameter c of the result type */ + a[np - 1] = 0; + int t = native_run(&nt, a, np, &ret, &code); + int optrap = 0; + uint64_t r = 0; + if (!t) r = ret & mask(cw); + else if (code == TRAP_ENSURES) { + a[np - 1] = canon(1, cs); + if (native_run(&nt, a, np, &ret, &code) || (ret & mask(cw)) != 0) { note(st, "ENSURES trap at c=0 not confirmed at c=1", vs.v[i], nops, code); continue; } + r = 0; + } else optrap = 1; + st->native_traps += optrap; + uint64_t cvals[2] = {optrap ? 0 : r, optrap ? 1 : (r ^ 1) & mask(cw)}; + int want[2] = {1, optrap}; + for (int j = 0; j < 2; j++) { + int at2 = at; + put_bits(bits, &at2, cvals[j], cw); + int s = ev_sat(&e, bits, bi.inputs); + if (s < 0) { st->undetermined++; continue; } + if (s != want[j]) + note(st, optrap ? "code traps, CNF does not" : (j ? "CNF disagrees: traps at c = r^1" : "CNF disagrees: no trap at c = r"), + vs.v[i], nops, optrap ? code : r); + } + } + free(bits); + free(vs.v); + ev_free(&e); + munmap(nt.map, nt.maplen); + rc = 0; +out: + c2_cnf_free(&cnf); + c2_unit_free(u); + free(u); + return rc; +} + +static int by_name(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } + +int main(int argc, char **argv) +{ + if (argc != 2) { fprintf(stderr, "usage: test_c2_blast_native <work-dir>\n"); return 2; } + const char *dir = argv[1]; + for (unsigned i = 0; i < sizeof rt_table / sizeof *rt_table; i++) rt_table[i] = (void *)rt_entry; + DIR *d = opendir(dir); + if (!d) { printf("FAIL cannot open %s\n", dir); return 1; } + char **names = NULL; + int nn = 0, cap = 0; + struct dirent *de; + while ((de = readdir(d))) { + size_t l = strlen(de->d_name); + if (l <= 3 || strcmp(de->d_name + l - 3, ".ir")) continue; + if (nn == cap) { cap = cap ? cap * 2 : 64; names = realloc(names, (size_t)cap * sizeof *names); } + names[nn] = strndup(de->d_name, l - 3); + nn++; + } + closedir(d); + qsort(names, (size_t)nn, sizeof *names, by_name); + long vec = 0, ntraps = 0; + int ops = 0, gates = 0; + for (int i = 0; i < nn; i++) { + Stat st; + if (compare(dir, names[i], names[i], &st)) { fails++; free(names[i]); continue; } + vec += st.vectors; + ntraps += st.native_traps; + if (st.mismatches || st.undetermined) { + printf("FAIL %s: %ld of %ld vectors disagree, %ld undetermined; first: %s\n", names[i], st.mismatches, st.vectors, + st.undetermined, st.first); + fails++; + } else if (strncmp(names[i], "op_", 3) == 0) ops++; + else gates++; + free(names[i]); + } + free(names); + /* negative controls: the CNF of one operation against the code of another must disagree */ + char cp[1024]; + snprintf(cp, sizeof cp, "%s/controls", dir); + FILE *cf = fopen(cp, "r"); + int controls = 0; + char a[256], b[256]; + while (cf && fscanf(cf, "%255s %255s", a, b) == 2) { + Stat st; + if (compare(dir, a, b, &st) == 0 && st.mismatches > 0) controls++; + else { printf("FAIL control %s vs code of %s: no disagreement found\n", a, b); fails++; } + } + if (cf) fclose(cf); + if (ops < 180 || gates < 29 || controls < 8) { printf("FAIL too little coverage: %d operations, %d gate programs, %d controls\n", ops, gates, controls); fails++; } + printf("test_c2_blast_native: %d operation programs and %d gate programs agree with oscc's code on %ld vectors " + "(%ld native traps); %d controls disagree as required; %d failures\n", ops, gates, vec, ntraps, controls, fails); + return fails ? 1 : 0; +} +#endif diff --git a/tests/checker2/test_c2_ir.c b/tests/checker2/test_c2_ir.c new file mode 100644 index 000000000..5f19f2a7e --- /dev/null +++ b/tests/checker2/test_c2_ir.c @@ -0,0 +1,1016 @@ +/* test_c2_ir: checker2's decoder and acceptance rules (omega#446). + * + * Usage: test_c2_ir <dir of producer-emitted .ir files> (tests/checker2/differential.sh fills it) + * + * 1. Every unit in the dir: strict decode, ACCEPT, and checker2's own re-encoding is byte-identical. + * 2. Robustness: truncated prefixes are refused; deterministic bit flips never crash (run under + * ASan/UBSan by the make target). + * 3. Planted defects: each named defect is applied to the first unit (sorted by name) where it + * fits, and checker2 must refuse the mutated unit with the expected rule, and refuse its bytes. + * A defect that fits no unit fails the test (no silent skips). + * 4. Hand-built units for the control-flow defects no producer output contains. */ +#include <dirent.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_ir.h" + +static int fails, checks; +#define CHECK(cond, ...) \ + do { \ + checks++; \ + if (!(cond)) { \ + fails++; \ + fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + } \ + } while (0) + +typedef struct { char *name; uint8_t *b; size_t n; } Unit; +static Unit corpus[512]; +static int ncorpus; + +static int load(const char *dir) +{ + struct dirent **ents; + int n = scandir(dir, &ents, NULL, alphasort); + if (n < 0) { perror(dir); return -1; } + for (int i = 0; i < n; i++) { + size_t l = strlen(ents[i]->d_name); + if (l > 3 && strcmp(ents[i]->d_name + l - 3, ".ir") == 0 && ncorpus < 512) { + char path[4096]; + snprintf(path, sizeof path, "%s/%s", dir, ents[i]->d_name); + FILE *f = fopen(path, "rb"); + if (f) { + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + Unit *u = &corpus[ncorpus]; + u->b = malloc((size_t)sz + 1); + u->n = fread(u->b, 1, (size_t)sz, f); + u->name = strdup(ents[i]->d_name); + fclose(f); + ncorpus++; + } + } + free(ents[i]); + } + free(ents); + return 0; +} + +/* ------------------------------------------------------------------ mutation helpers */ + +static int isval(uint8_t s) { return s >= S_BOOL && s <= S_I64; } +static int isint(uint8_t s) { return s >= S_U8 && s <= S_I64; } +static unsigned widthof(uint8_t s) +{ + static const unsigned w[] = {0, 1, 8, 16, 32, 64, 8, 16, 32, 64}; + return s <= S_I64 ? w[s] : 0; +} + +/* first register >= from with a value type, matching want (0 any value, else that scalar) and + * differing from not (0 = no restriction); int_only restricts to integers. -1 if none. */ +static int reg_val(const C2Func *f, int from, uint8_t want, uint8_t not, int int_only) +{ + for (int r = from; r < f->nvregs; r++) { + uint8_t s = f->vt[r].s; + if (!isval(s) || (want && s != want) || (not && s == not) || (int_only && !isint(s))) continue; + if (r > 0 && r - 1 < f->nparams && (f->vt[r - 1].s == S_BYTES || f->vt[r - 1].s == S_CELLS)) continue; + return r; + } + return -1; +} +static int reg_ref(const C2Func *f, int from) +{ + for (int r = from; r < f->nvregs; r++) + if (f->vt[r].s == S_REF) return r; + return -1; +} +static int newreg(C2Func *f, C2Type t) +{ + C2Type *nv = realloc(f->vt, (f->nvregs + 1u) * sizeof *nv); + if (!nv) abort(); + f->vt = nv; + f->vt[f->nvregs] = t; + return f->nvregs++; +} +static void ins(C2Func *f, uint32_t pos, C2Insn in) +{ + C2Insn *ni = realloc(f->in, (f->ninsns + 1u) * sizeof *ni); + if (!ni) abort(); + f->in = ni; + memmove(&f->in[pos + 1], &f->in[pos], (f->ninsns - pos) * sizeof *f->in); + f->in[pos] = in; + f->ninsns++; + for (int b = 0; b < f->nblocks; b++) { + C2Block *k = &f->blk[b]; + if (pos >= k->first && pos < k->first + k->count) k->count++; + else if (k->first > pos) k->first++; + } +} +static void del(C2Func *f, uint32_t pos) +{ + memmove(&f->in[pos], &f->in[pos + 1], (f->ninsns - pos - 1) * sizeof *f->in); + f->ninsns--; + for (int b = 0; b < f->nblocks; b++) { + C2Block *k = &f->blk[b]; + if (pos >= k->first && pos < k->first + k->count) k->count--; + else if (k->first > pos) k->first--; + } +} +static C2Insn mk(uint8_t op, int16_t a) +{ + C2Insn in; + memset(&in, 0, sizeof in); + in.op = op; + in.dst = in.b = in.c = -1; + for (int k = 0; k < C2_MAX_PARAMS; k++) in.args[k] = -1; + in.a = a; + return in; +} +static int block_of(const C2Func *f, uint32_t i) +{ + for (int b = 0; b < f->nblocks; b++) + if (i >= f->blk[b].first && i < f->blk[b].first + f->blk[b].count) return b; + return -1; +} +static int block_ends_ret(const C2Func *f, int b) { return f->in[f->blk[b].first + f->blk[b].count - 1].op == C2_RET; } +static int single_def_const(const C2Func *f, int r, uint32_t *at) +{ + int n = r < f->nparams ? 1 : 0; + for (uint32_t i = 0; i < f->ninsns; i++) { + const C2Insn *in = &f->in[i]; + int d = -1; + switch (in->op) { + case C2_BR: case C2_CBR: case C2_RET: case C2_TRAP: case C2_STORE: case C2_FSTORE: case C2_RELEASE: + case C2_ADESTROY: case C2_PCLOSE: case C2_HFREE: case C2_HSTORE: case C2_SSTORE: break; + default: d = in->dst; + } + if (d == r) { n++; *at = i; } + } + return n == 1 && f->in[*at].op == C2_CONST; +} +/* a CBR closing a loop header: some block at or after it branches back to it */ +static int is_loop_header(const C2Func *f, int h) +{ + for (int b = h; b < f->nblocks; b++) { + const C2Insn *t = &f->in[f->blk[b].first + f->blk[b].count - 1]; + if ((t->op == C2_BR && t->t == h) || (t->op == C2_CBR && (t->t == h || t->f == h))) return 1; + } + return 0; +} + +#define EACH_INSN(op_) \ + for (int fi = 0; fi < u->nfuncs; fi++) \ + for (uint32_t i = 0; i < u->fn[fi].ninsns; i++) \ + if (u->fn[fi].in[i].op == (op_)) +#define FN (&u->fn[fi]) +#define IN (&u->fn[fi].in[i]) + +/* ------------------------------------------------------------------ the defects */ + +static int d_const_noncanon(C2Unit *u) +{ + EACH_INSN(C2_CONST) { + uint8_t s = FN->vt[IN->dst].s; + if (s == S_BOOL) { IN->imm = 2; return 1; } + if (widthof(s) && widthof(s) < 64) { IN->imm = 1ull << widthof(s); return 1; } + } + return 0; +} +static int d_const_into_ref(C2Unit *u) +{ + EACH_INSN(C2_CONST) { int r = reg_ref(FN, FN->nparams); if (r >= 0) { IN->dst = (int16_t)r; return 1; } } + return 0; +} +static int d_mov_scalar_mismatch(C2Unit *u) +{ + EACH_INSN(C2_MOV) { + uint8_t s = FN->vt[IN->dst].s; + if (!isval(s)) continue; + int r = reg_val(FN, 0, 0, s, 0); + if (r >= 0) { IN->a = (int16_t)r; return 1; } + } + return 0; +} +static int d_mov_ref_from_scalar(C2Unit *u) +{ + EACH_INSN(C2_MOV) { + if (FN->vt[IN->dst].s != S_REF) continue; + int r = reg_val(FN, 0, 0, 0, 0); + if (r >= 0) { IN->a = (int16_t)r; return 1; } + } + return 0; +} +static int d_mov_kind_widen(C2Unit *u) /* shared borrow into a mut or own destination */ +{ + EACH_INSN(C2_MOV) { + const C2Type *td = &FN->vt[IN->dst]; + if (td->s != S_REF || td->kind == K_SHARED) continue; + for (int r = 0; r < FN->nvregs; r++) { + const C2Type *t = &FN->vt[r]; + if (t->s == S_REF && t->kind == K_SHARED && t->elem == td->elem && t->len == td->len && t->sid == td->sid) { + IN->a = (int16_t)r; + return 1; + } + } + } + return 0; +} +static int d_bin_subop(C2Unit *u) { EACH_INSN(C2_BIN) { IN->sub = B_LIMIT; return 1; } return 0; } +static int d_bin_mismatch(C2Unit *u) +{ + EACH_INSN(C2_BIN) { + if (IN->sub == B_SHL || IN->sub == B_SHR) continue; + uint8_t s = FN->vt[IN->dst].s; + int r = reg_val(FN, 0, 0, s, 1); + if (isint(s) && r >= 0) { IN->b = (int16_t)r; return 1; } + } + return 0; +} +static int d_shift_bool(C2Unit *u) +{ + EACH_INSN(C2_BIN) { + if (IN->sub != B_SHL && IN->sub != B_SHR) continue; + int r = reg_val(FN, 0, S_BOOL, 0, 0); + if (r >= 0) { IN->b = (int16_t)r; return 1; } + } + return 0; +} +static int d_bin_bool_arith(C2Unit *u) +{ + EACH_INSN(C2_BIN) { if (FN->vt[IN->dst].s == S_BOOL) { IN->sub = B_ADD; return 1; } } + EACH_INSN(C2_CMP) { /* no bool BIN in the corpus: make one from a comparison result */ + int16_t d = IN->dst; + for (uint32_t j = i + 1; j < FN->ninsns; j++) + if (FN->in[j].op == C2_BIN && isint(FN->vt[FN->in[j].dst].s) && FN->in[j].sub == B_ADD) { + FN->in[j].dst = FN->in[j].a = FN->in[j].b = d; + return 1; + } + } + return 0; +} +static int d_un_subop(C2Unit *u) { EACH_INSN(C2_UN) { IN->sub = U_LIMIT; return 1; } return 0; } +static int d_un_lnot_int(C2Unit *u) +{ + EACH_INSN(C2_UN) { if (IN->sub != U_LNOT) { IN->sub = U_LNOT; return 1; } } + return 0; +} +static int d_un_neg_bool(C2Unit *u) +{ + EACH_INSN(C2_UN) { if (IN->sub == U_LNOT) { IN->sub = U_NEG; return 1; } } + return 0; +} +static int d_cmp_nonbool(C2Unit *u) +{ + EACH_INSN(C2_CMP) { int r = reg_val(FN, FN->nparams, 0, S_BOOL, 1); if (r >= 0) { IN->dst = (int16_t)r; return 1; } } + return 0; +} +static int d_cmp_subop(C2Unit *u) { EACH_INSN(C2_CMP) { IN->sub = CC_LIMIT; return 1; } return 0; } +static int d_cmp_mixed(C2Unit *u) +{ + EACH_INSN(C2_CMP) { + int r = reg_val(FN, 0, 0, FN->vt[IN->a].s, 0); + if (r >= 0) { IN->b = (int16_t)r; return 1; } + } + return 0; +} +static int d_cast_bool(C2Unit *u) +{ + EACH_INSN(C2_CAST) { int r = reg_val(FN, 0, S_BOOL, 0, 0); if (r >= 0) { IN->a = (int16_t)r; return 1; } } + return 0; +} +static int d_alloc_nonowner(C2Unit *u) +{ + EACH_INSN(C2_ALLOC) { int r = reg_val(FN, FN->nparams, 0, 0, 0); if (r >= 0) { IN->dst = (int16_t)r; return 1; } } + return 0; +} +static int d_alloc_init(C2Unit *u) +{ + EACH_INSN(C2_ALLOC) { + const C2Type *t = &FN->vt[IN->dst]; + uint8_t want = t->sid ? S_U64 : t->elem; + int r = reg_val(FN, 0, 0, want, 0); + if (r >= 0) { IN->a = (int16_t)r; return 1; } + } + return 0; +} +static int d_release_scalar(C2Unit *u) +{ + EACH_INSN(C2_RELEASE) { int r = reg_val(FN, 0, 0, 0, 0); if (r >= 0) { IN->a = (int16_t)r; return 1; } } + return 0; +} +static int d_load_index_bool(C2Unit *u) +{ + EACH_INSN(C2_LOAD) { int r = reg_val(FN, 0, S_BOOL, 0, 0); if (r >= 0) { IN->b = (int16_t)r; return 1; } } + return 0; +} +static int d_load_nonarray(C2Unit *u) +{ + EACH_INSN(C2_LOAD) { int r = reg_val(FN, 0, 0, 0, 0); if (r >= 0) { IN->a = (int16_t)r; return 1; } } + return 0; +} +static int d_load_elem(C2Unit *u) +{ + EACH_INSN(C2_LOAD) { + int r = reg_val(FN, FN->nparams, 0, FN->vt[IN->a].elem, 0); + if (r >= 0) { IN->dst = (int16_t)r; return 1; } + } + return 0; +} +static int d_store_shared(C2Unit *u) +{ + EACH_INSN(C2_STORE) { if (FN->vt[IN->a].kind == K_MUT) { FN->vt[IN->a].kind = K_SHARED; return 1; } } + return 0; +} +static int d_fload_field_range(C2Unit *u) +{ + EACH_INSN(C2_FLOAD) { IN->imm = u->st[FN->vt[IN->a].sid - 1].nfields; return 1; } + return 0; +} +static int d_fload_type(C2Unit *u) +{ + EACH_INSN(C2_FLOAD) { + uint8_t s = u->st[FN->vt[IN->a].sid - 1].f[IN->imm].s; + int r = reg_val(FN, FN->nparams, 0, s, 0); + if (r >= 0) { IN->dst = (int16_t)r; return 1; } + } + return 0; +} +static int d_fstore_elem_index(C2Unit *u) +{ + EACH_INSN(C2_FSTORE) { + if (IN->b != -1) continue; + int r = reg_val(FN, 0, 0, 0, 1); + if (r >= 0) { IN->b = (int16_t)r; return 1; } + } + return 0; +} +static int d_fstore_shared(C2Unit *u) +{ + EACH_INSN(C2_FSTORE) { if (FN->vt[IN->a].kind == K_MUT) { FN->vt[IN->a].kind = K_SHARED; return 1; } } + return 0; +} +static int d_arena_cap0(C2Unit *u) { EACH_INSN(C2_AOPEN) { IN->imm = 0; return 1; } return 0; } +static int d_arena_cap65(C2Unit *u) { EACH_INSN(C2_AOPEN) { IN->imm = C2_MAX_ARRAY + 1; return 1; } return 0; } +static int d_pool_cap17(C2Unit *u) { EACH_INSN(C2_POPEN) { IN->nargs = C2_POOL_SLOTS + 1; return 1; } return 0; } +static int d_pool_cap0(C2Unit *u) { EACH_INSN(C2_POPEN) { IN->nargs = 0; return 1; } return 0; } +static int d_pool_elem_ref(C2Unit *u) { EACH_INSN(C2_POPEN) { IN->sub = S_REF; return 1; } return 0; } +static int d_trap0(C2Unit *u) { EACH_INSN(C2_TRAP) { IN->imm = 0; return 1; } return 0; } +static int d_trap15(C2Unit *u) { EACH_INSN(C2_TRAP) { IN->imm = C2_TRAP_MAX + 1; return 1; } return 0; } +static int d_br_range(C2Unit *u) { EACH_INSN(C2_BR) { IN->t = FN->nblocks; return 1; } return 0; } +static int d_cbr_range(C2Unit *u) { EACH_INSN(C2_CBR) { IN->f = FN->nblocks; return 1; } return 0; } +static int d_cbr_nonbool(C2Unit *u) +{ + EACH_INSN(C2_CBR) { int r = reg_val(FN, 0, 0, 0, 1); if (r >= 0) { IN->a = (int16_t)r; return 1; } } + return 0; +} +static int d_ret_type(C2Unit *u) +{ + EACH_INSN(C2_RET) { + if (IN->a < 0) continue; + int r = reg_val(FN, 0, 0, FN->ret.s, 0); + if (r >= 0) { IN->a = (int16_t)r; return 1; } + } + return 0; +} +static int d_ret_void_value(C2Unit *u) +{ + EACH_INSN(C2_RET) { if (IN->a < 0 && FN->nvregs > 0) { IN->a = 0; return 1; } } + return 0; +} +static int d_call_self(C2Unit *u) { EACH_INSN(C2_CALL) { IN->callee = (uint16_t)fi; return 1; } return 0; } +static int d_call_arity(C2Unit *u) +{ + EACH_INSN(C2_CALL) { if (IN->nargs > 0) { IN->nargs--; return 1; } } + return 0; +} +static int d_call_arg_type(C2Unit *u) +{ + EACH_INSN(C2_CALL) { + const C2Func *g = &u->fn[IN->callee]; + for (int k = 0; k < IN->nargs; k++) { + if (!isval(g->vt[k].s)) continue; + if (k > 0 && (g->vt[k - 1].s == S_BYTES || g->vt[k - 1].s == S_CELLS)) continue; + int r = reg_val(FN, 0, 0, g->vt[k].s, 0); + if (r >= 0) { IN->args[k] = (int16_t)r; return 1; } + } + } + return 0; +} +static int d_call_ref_kind(C2Unit *u) /* shared borrow passed to a mut parameter */ +{ + EACH_INSN(C2_CALL) { + const C2Func *g = &u->fn[IN->callee]; + for (int k = 0; k < IN->nargs; k++) { + const C2Type *p = &g->vt[k]; + if (p->s != S_REF || p->kind != K_MUT) continue; + for (int r = 0; r < FN->nvregs; r++) { + const C2Type *t = &FN->vt[r]; + if (t->s == S_REF && t->kind == K_SHARED && t->elem == p->elem && t->len == p->len && t->sid == p->sid) { + IN->args[k] = (int16_t)r; + return 1; + } + } + } + } + return 0; +} +static int d_call_ret_type(C2Unit *u) +{ + EACH_INSN(C2_CALL) { + if (IN->dst < 0) continue; + int r = reg_val(FN, FN->nparams, 0, FN->vt[IN->dst].s, 0); + if (r >= 0) { IN->dst = (int16_t)r; return 1; } + } + return 0; +} +static int d_call_alias(C2Unit *u) /* one register bound to two parameters, one of them writable */ +{ + EACH_INSN(C2_CALL) { + const C2Func *g = &u->fn[IN->callee]; + for (int k = 0; k < IN->nargs; k++) + for (int j = 0; j < IN->nargs; j++) { + const C2Type *pk = &g->vt[k], *pj = &g->vt[j]; + if (j == k || pk->s != S_REF || pj->s != S_REF || pk->kind != K_MUT) continue; + if (pk->elem != pj->elem || pk->len != pj->len || pk->sid != pj->sid) continue; + IN->args[j] = IN->args[k]; + return 1; + } + } + return 0; +} +static int d_term_missing(C2Unit *u) +{ + EACH_INSN(C2_BR) { IN->op = C2_TRAP; IN->imm = 1; return 1; } + return 0; +} +static int d_term_inside(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) + for (int b = 0; b < FN->nblocks; b++) + if (FN->blk[b].count >= 2) { + C2Insn *in = &FN->in[FN->blk[b].first]; + *in = mk(C2_BR, -1); + in->t = 0; + return 1; + } + return 0; +} +static int d_block_gap(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) + if (FN->nblocks >= 2 && FN->blk[1].count >= 2) { FN->blk[1].first++; FN->blk[1].count--; return 1; } + return 0; +} +static int d_undefined_use(C2Unit *u) +{ + EACH_INSN(C2_BIN) { IN->a = (int16_t)newreg(FN, FN->vt[IN->a]); return 1; } + return 0; +} +static int d_operand_range(C2Unit *u) { EACH_INSN(C2_BIN) { IN->a = (int16_t)FN->nvregs; return 1; } return 0; } +static int slice_param(const C2Func *f, uint8_t s) +{ + for (int r = 0; r + 1 < f->nparams; r++) + if (f->vt[r].s == s || (!s && (f->vt[r].s == S_BYTES || f->vt[r].s == S_CELLS))) return r; + return -1; +} +static int d_slice_len_write(C2Unit *u) +{ + EACH_INSN(C2_CONST) { + int p = slice_param(FN, 0); + if (p >= 0 && FN->vt[IN->dst].s == S_U64) { IN->dst = (int16_t)(p + 1); return 1; } + } + return 0; +} +static int d_slice_ptr_write(C2Unit *u) +{ + EACH_INSN(C2_CONST) { int p = slice_param(FN, 0); if (p >= 0) { IN->dst = (int16_t)p; return 1; } } + return 0; +} +static int d_sstore_bytes(C2Unit *u) +{ + EACH_INSN(C2_SSTORE) { FN->vt[IN->a].s = S_BYTES; return 1; } + return 0; +} +static int d_slice_len_type(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { int p = slice_param(FN, 0); if (p >= 0) { FN->vt[p + 1].s = S_U32; return 1; } } + return 0; +} +static int d_slice_nonparam(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { int p = slice_param(FN, 0); if (p >= 0) { FN->nparams = (uint8_t)p; return 1; } } + return 0; +} +static int d_double_release(C2Unit *u) { EACH_INSN(C2_RELEASE) { ins(FN, i + 1, *IN); return 1; } return 0; } +static int d_use_after_release(C2Unit *u) +{ + EACH_INSN(C2_LOAD) { + int16_t a = IN->a; + if (FN->vt[a].kind != K_OWN || a < FN->nparams) continue; + ins(FN, i, mk(C2_RELEASE, a)); + return 1; + } + return 0; +} +static int d_leak(C2Unit *u) +{ + EACH_INSN(C2_RELEASE) { + if (!block_ends_ret(FN, block_of(FN, i))) continue; + del(FN, i); + return 1; + } + return 0; +} +static int d_owner_overwrite(C2Unit *u) { EACH_INSN(C2_ALLOC) { ins(FN, i + 1, *IN); return 1; } return 0; } +static int d_release_arena_obj(C2Unit *u) { EACH_INSN(C2_AALLOC) { ins(FN, i + 1, mk(C2_RELEASE, IN->dst)); return 1; } return 0; } +static int d_arena_alloc_after_destroy(C2Unit *u) { EACH_INSN(C2_AALLOC) { ins(FN, i, mk(C2_ADESTROY, IN->b)); return 1; } return 0; } +static int d_arena_double_destroy(C2Unit *u) { EACH_INSN(C2_ADESTROY) { ins(FN, i + 1, *IN); return 1; } return 0; } +static int d_pool_double_close(C2Unit *u) { EACH_INSN(C2_PCLOSE) { ins(FN, i + 1, *IN); return 1; } return 0; } +static int d_pool_use_after_close(C2Unit *u) { EACH_INSN(C2_HALLOC) { ins(FN, i, mk(C2_PCLOSE, IN->b)); return 1; } return 0; } +static int d_arena_leak(C2Unit *u) +{ + EACH_INSN(C2_ADESTROY) { if (block_ends_ret(FN, block_of(FN, i))) { del(FN, i); return 1; } } + return 0; +} +static int d_pool_leak(C2Unit *u) +{ + EACH_INSN(C2_PCLOSE) { if (block_ends_ret(FN, block_of(FN, i))) { del(FN, i); return 1; } } + return 0; +} +static int d_handle_as_data(C2Unit *u) +{ + EACH_INSN(C2_AOPEN) { + int16_t h = IN->dst; + for (uint32_t j = 0; j < FN->ninsns; j++) { + C2Insn *o = &FN->in[j]; + if (o->op == C2_BIN && FN->vt[o->a].s == S_U64) { o->a = h; return 1; } + if (o->op == C2_CMP && FN->vt[o->a].s == S_U64) { o->a = h; return 1; } + } + C2Insn c = mk(C2_CMP, h); /* no u64 arithmetic nearby: compare the handle with itself */ + c.sub = CC_EQ; + c.b = h; + c.dst = (int16_t)newreg(FN, (C2Type){.s = S_BOOL}); + ins(FN, i + 1, c); + return 1; + } + return 0; +} +static int d_handle_forged(C2Unit *u) +{ + EACH_INSN(C2_AALLOC) { IN->b = (int16_t)newreg(FN, (C2Type){.s = S_U64}); return 1; } + return 0; +} +static int d_pool_value_type(C2Unit *u) +{ + EACH_INSN(C2_HLOAD) { + int r = newreg(FN, (C2Type){.s = FN->vt[IN->dst].s == S_U8 ? S_U16 : S_U8}); + if (r >= 0) { IN->dst = (int16_t)r; return 1; } + } + return 0; +} +/* the CMP feeding the CBR that ends a loop header block, with its bound K a single-def CONST */ +static int loop_guard(C2Func *f, uint32_t *cmp_at, uint32_t *k_at, int *hdr) +{ + for (int h = 0; h < f->nblocks; h++) { + if (!is_loop_header(f, h)) continue; + for (int g = h; g < f->nblocks; g++) { + C2Insn *t = &f->in[f->blk[g].first + f->blk[g].count - 1]; + if (t->op != C2_CBR) continue; + for (uint32_t i = f->blk[g].first; i < f->blk[g].first + f->blk[g].count; i++) { + C2Insn *c = &f->in[i]; + if (c->op == C2_CMP && c->dst == t->a && (c->sub == CC_GE || c->sub == CC_LT) && + single_def_const(f, c->b, k_at)) { + *cmp_at = i; + *hdr = g; + return 1; + } + } + } + } + return 0; +} +static int d_loop_bound_huge(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { + uint32_t c, k; + int g; + if (!loop_guard(FN, &c, &k, &g)) continue; + uint8_t s = FN->vt[FN->in[c].b].s; + if (widthof(s) < 32) continue; + FN->in[k].imm = 2000000; + return 1; + } + return 0; +} +static int d_loop_counter_down(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { + uint32_t c, k; + int g; + if (!loop_guard(FN, &c, &k, &g)) continue; + int16_t ctr = FN->in[c].a; + for (uint32_t i = 0; i < FN->ninsns; i++) + if (IN->op == C2_BIN && IN->dst == ctr && IN->a == ctr && IN->sub == B_ADD) { IN->sub = B_SUB; return 1; } + } + return 0; +} +static int d_loop_guard_swapped(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { + uint32_t c, k; + int g; + if (!loop_guard(FN, &c, &k, &g)) continue; + C2Insn *t = &FN->in[FN->blk[g].first + FN->blk[g].count - 1]; + uint16_t x = t->t; + t->t = t->f; + t->f = x; + return 1; + } + return 0; +} +static int d_struct_offset(C2Unit *u) +{ + for (int s = 0; s < u->nstructs; s++) if (u->st[s].nfields >= 2) { u->st[s].f[1].off++; return 1; } + return 0; +} +static int d_struct_cells(C2Unit *u) { if (u->nstructs) { u->st[0].ncells++; return 1; } return 0; } +static int d_struct_dup_field(C2Unit *u) +{ + for (int s = 0; s < u->nstructs; s++) + if (u->st[s].nfields >= 2) { strcpy(u->st[s].f[1].name, u->st[s].f[0].name); return 1; } + return 0; +} +static int d_struct_field_ref(C2Unit *u) { if (u->nstructs) { u->st[0].f[0].s = S_REF; return 1; } return 0; } +static int d_func_dup_name(C2Unit *u) { if (u->nfuncs >= 2) { strcpy(u->fn[1].name, u->fn[0].name); return 1; } return 0; } +static int d_func_ret_ref(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { + int r = reg_ref(FN, 0); + if (r >= 0) { FN->ret = FN->vt[r]; return 1; } + } + return 0; +} +static int d_vreg_kind(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) { int r = reg_ref(FN, 0); if (r >= 0) { FN->vt[r].kind = 4; return 1; } } + return 0; +} +static int d_vreg_len0(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) + for (int r = 0; r < FN->nvregs; r++) + if (FN->vt[r].s == S_REF && !FN->vt[r].sid) { FN->vt[r].len = 0; return 1; } + return 0; +} +static int d_vreg_sid(C2Unit *u) +{ + for (int fi = 0; fi < u->nfuncs; fi++) + for (int r = 0; r < FN->nvregs; r++) + if (FN->vt[r].s == S_REF && FN->vt[r].sid) { FN->vt[r].sid = (uint8_t)(u->nstructs + 1); return 1; } + return 0; +} +static int d_params_over(C2Unit *u) { u->fn[0].nparams = C2_MAX_PARAMS + 1; return u->fn[0].nvregs > C2_MAX_PARAMS; } +static int d_borrow_outlives(C2Unit *u) +{ + EACH_INSN(C2_MOV) { + int16_t b = IN->dst, o = IN->a; + if (FN->vt[b].s != S_REF || FN->vt[b].kind == K_OWN || FN->vt[o].kind != K_OWN || o < FN->nparams) continue; + int arena = 0; + for (uint32_t j = 0; j < FN->ninsns; j++) arena |= FN->in[j].op == C2_AALLOC && FN->in[j].dst == o; + if (arena) continue; + for (uint32_t j = i + 1; j < FN->ninsns && block_of(FN, j) == block_of(FN, i); j++) { + uint8_t op = FN->in[j].op; + if ((op == C2_LOAD || op == C2_STORE || op == C2_FLOAD || op == C2_FSTORE) && FN->in[j].a == b) { + ins(FN, j, mk(C2_RELEASE, o)); + return 1; + } + } + } + return 0; +} +static int d_use_after_move(C2Unit *u) +{ + EACH_INSN(C2_CALL) { + const C2Func *g = &u->fn[IN->callee]; + for (int k = 0; k < IN->nargs; k++) + if (g->vt[k].s == S_REF && g->vt[k].kind == K_OWN) { ins(FN, i + 1, *IN); return 1; } + } + return 0; +} +static int d_mov_after_move(C2Unit *u) /* own -> own move, then the moved-from owner moved again */ +{ + EACH_INSN(C2_MOV) { + if (FN->vt[IN->dst].kind != K_OWN || FN->vt[IN->a].s != S_REF || FN->vt[IN->a].kind != K_OWN) continue; + C2Insn again = *IN; + again.dst = (int16_t)newreg(FN, FN->vt[IN->dst]); + ins(FN, i + 1, again); + return 1; + } + return 0; +} + +static int d_alloc_into_borrow(C2Unit *u) +{ + EACH_INSN(C2_ALLOC) { + C2Type t = FN->vt[IN->dst]; + t.kind = K_MUT; + IN->dst = (int16_t)newreg(FN, t); + return 1; + } + return 0; +} +/* a table slot past nfields holding a plausible field: the field index must still be refused */ +static int d_field_stale_slot(C2Unit *u) +{ + EACH_INSN(C2_FLOAD) { + C2Struct *s = &u->st[FN->vt[IN->a].sid - 1]; + if (s->nfields >= C2_MAX_FIELDS) continue; + s->f[s->nfields] = s->f[IN->imm]; + IN->imm = s->nfields; + return 1; + } + return 0; +} +/* a scalar register whose unused element byte happens to match: indexing it must be refused */ +static int d_index_scalar_stale_elem(C2Unit *u) +{ + EACH_INSN(C2_LOAD) { + if (FN->vt[IN->a].sid) continue; + int r = reg_val(FN, 0, S_U64, 0, 0); + if (r < 0) continue; + FN->vt[r].elem = FN->vt[IN->a].elem; + IN->a = (int16_t)r; + return 1; + } + return 0; +} +static int d_sload_non_slice(C2Unit *u) +{ + EACH_INSN(C2_SLOAD) { + int r = reg_val(FN, 0, S_U64, 0, 0); + IN->a = (int16_t)(r >= 0 ? r : newreg(FN, (C2Type){.s = S_U64})); + return 1; + } + return 0; +} + +/* hand-built function bodies replacing fn[0] (control-flow shapes no producer emits) */ +static void replace_fn0(C2Unit *u, int nblocks, const C2Insn *code, int ncode, const int *counts) +{ + C2Func *f = &u->fn[0]; + free(f->in); + free(f->blk); + f->in = calloc((size_t)ncode, sizeof *f->in); + f->blk = calloc((size_t)nblocks, sizeof *f->blk); + memcpy(f->in, code, (size_t)ncode * sizeof *code); + f->ninsns = (uint32_t)ncode; + f->nblocks = (uint16_t)nblocks; + uint32_t at = 0; + for (int b = 0; b < nblocks; b++) { f->blk[b].first = at; f->blk[b].count = (uint32_t)counts[b]; at += (uint32_t)counts[b]; } + f->ret.s = S_VOID; +} +static int d_irreducible(C2Unit *u) +{ + /* v_bool <- param or const; B0: CBR c B1 B2; B1: BR B2; B2: BR B1 (two entries into one cycle) */ + C2Func *f = &u->fn[0]; + int c = reg_val(f, 0, S_BOOL, 0, 0); + if (c < 0 || c >= f->nparams) return 0; + C2Insn code[3] = {mk(C2_CBR, (int16_t)c), mk(C2_BR, -1), mk(C2_BR, -1)}; + code[0].t = 1; code[0].f = 2; code[1].t = 2; code[2].t = 1; + int counts[3] = {1, 1, 1}; + replace_fn0(u, 3, code, 3, counts); + return 1; +} +static int d_endless_loop(C2Unit *u) +{ + C2Insn code[2] = {mk(C2_BR, -1), mk(C2_BR, -1)}; + code[0].t = 1; code[1].t = 1; + int counts[2] = {1, 1}; + if (u->fn[0].ret.s != S_VOID) return 0; + replace_fn0(u, 2, code, 2, counts); + return 1; +} + +typedef struct { const char *name, *rule; int (*apply)(C2Unit *); } Defect; +static const Defect defects[] = { + {"const-noncanonical", "C2-CONST-CANONICAL", d_const_noncanon}, + {"const-into-reference", "C2-TYPE-CONST", d_const_into_ref}, + {"mov-scalar-mismatch", "C2-TYPE-MOV", d_mov_scalar_mismatch}, + {"mov-reference-from-scalar", "C2-TYPE-MOV", d_mov_ref_from_scalar}, + {"mov-shared-widened", "C2-TYPE-MOV", d_mov_kind_widen}, + {"bin-subop", "C2-DECODE-SUBOP", d_bin_subop}, + {"bin-operand-mismatch", "C2-TYPE-BIN", d_bin_mismatch}, + {"shift-by-bool", "C2-TYPE-BIN", d_shift_bool}, + {"bool-arithmetic", "C2-TYPE-BIN", d_bin_bool_arith}, + {"un-subop", "C2-DECODE-SUBOP", d_un_subop}, + {"lnot-on-int", "C2-TYPE-UN", d_un_lnot_int}, + {"neg-on-bool", "C2-TYPE-UN", d_un_neg_bool}, + {"cmp-result-not-bool", "C2-TYPE-CMP", d_cmp_nonbool}, + {"cmp-subop", "C2-DECODE-SUBOP", d_cmp_subop}, + {"cmp-mixed-types", "C2-TYPE-CMP", d_cmp_mixed}, + {"cast-from-bool", "C2-TYPE-CAST", d_cast_bool}, + {"alloc-into-scalar", "C2-TYPE-ALLOC", d_alloc_nonowner}, + {"alloc-init-type", "C2-TYPE-ALLOC", d_alloc_init}, + {"release-scalar", "C2-TYPE-RELEASE", d_release_scalar}, + {"index-by-bool", "C2-TYPE-INDEX", d_load_index_bool}, + {"index-non-array", "C2-TYPE-INDEX", d_load_nonarray}, + {"load-element-type", "C2-TYPE-INDEX", d_load_elem}, + {"store-through-shared", "C2-READ-ONLY", d_store_shared}, + {"field-out-of-range", "C2-TYPE-FIELD", d_fload_field_range}, + {"field-load-type", "C2-TYPE-FIELD", d_fload_type}, + {"field-scalar-indexed", "C2-TYPE-FIELD", d_fstore_elem_index}, + {"field-store-through-shared", "C2-READ-ONLY", d_fstore_shared}, + {"arena-capacity-0", "C2-ARENA-CAPACITY", d_arena_cap0}, + {"arena-capacity-65", "C2-ARENA-CAPACITY", d_arena_cap65}, + {"pool-slots-17", "C2-POOL-CAPACITY", d_pool_cap17}, + {"pool-slots-0", "C2-POOL-CAPACITY", d_pool_cap0}, + {"pool-of-references", "C2-TYPE-POOL", d_pool_elem_ref}, + {"trap-code-0", "C2-TRAP-CODE", d_trap0}, + {"trap-code-15", "C2-TRAP-CODE", d_trap15}, + {"branch-out-of-range", "C2-CFG-TARGET", d_br_range}, + {"cond-branch-out-of-range", "C2-CFG-TARGET", d_cbr_range}, + {"branch-on-int", "C2-TYPE-COND", d_cbr_nonbool}, + {"return-type", "C2-TYPE-RET", d_ret_type}, + {"void-returns-value", "C2-TYPE-RET", d_ret_void_value}, + {"recursive-call", "C2-CALL-ORDER", d_call_self}, + {"call-arity", "C2-CALL-ARITY", d_call_arity}, + {"call-argument-type", "C2-TYPE-CALL", d_call_arg_type}, + {"call-shared-to-mut", "C2-TYPE-CALL", d_call_ref_kind}, + {"call-result-type", "C2-TYPE-CALL", d_call_ret_type}, + {"call-aliased-mut", "C2-CALL-ALIAS", d_call_alias}, + {"block-without-terminator", "C2-CFG-TERMINATOR", d_term_missing}, + {"terminator-mid-block", "C2-CFG-TERMINATOR", d_term_inside}, + {"block-layout-gap", "C2-CFG-LAYOUT", d_block_gap}, + {"read-before-write", "C2-UNDEFINED-USE", d_undefined_use}, + {"operand-out-of-range", "C2-OPERAND-RANGE", d_operand_range}, + {"slice-length-written", "C2-SLICE-WRITE", d_slice_len_write}, + {"slice-pointer-written", "C2-SLICE-WRITE", d_slice_ptr_write}, + {"store-into-bytes-slice", "C2-SLICE-WRITE", d_sstore_bytes}, + {"slice-length-not-u64", "C2-SLICE-PARAM", d_slice_len_type}, + {"slice-not-a-parameter", "C2-SLICE-PARAM", d_slice_nonparam}, + {"double-release", "C2-OWN-DOUBLE-RELEASE", d_double_release}, + {"use-after-release", "C2-OWN-USE-DEAD", d_use_after_release}, + {"leak-at-return", "C2-OWN-LEAK", d_leak}, + {"owner-overwritten", "C2-OWN-LEAK", d_owner_overwrite}, + {"release-arena-object", "C2-OWN-RELEASE-ARENA", d_release_arena_obj}, + {"alloc-from-destroyed-arena", "C2-ARENA-DEAD", d_arena_alloc_after_destroy}, + {"arena-destroyed-twice", "C2-HANDLE-DOUBLE-CLOSE", d_arena_double_destroy}, + {"pool-closed-twice", "C2-HANDLE-DOUBLE-CLOSE", d_pool_double_close}, + {"pool-use-after-close", "C2-HANDLE-DEAD", d_pool_use_after_close}, + {"arena-never-destroyed", "C2-HANDLE-LEAK", d_arena_leak}, + {"pool-never-closed", "C2-HANDLE-LEAK", d_pool_leak}, + {"handle-used-as-data", "C2-HANDLE-DISCIPLINE", d_handle_as_data}, + {"forged-arena-handle", "C2-HANDLE-DISCIPLINE", d_handle_forged}, + {"pool-value-type", "C2-TYPE-POOL", d_pool_value_type}, + {"loop-bound-too-large", "C2-LOOP-UNBOUNDED", d_loop_bound_huge}, + {"loop-counter-decrements", "C2-LOOP-UNBOUNDED", d_loop_counter_down}, + {"loop-guard-inverted", "C2-LOOP-UNBOUNDED", d_loop_guard_swapped}, + {"struct-field-offset", "C2-STRUCT-LAYOUT", d_struct_offset}, + {"struct-cell-count", "C2-STRUCT-LAYOUT", d_struct_cells}, + {"struct-duplicate-field", "C2-STRUCT-NAME", d_struct_dup_field}, + {"struct-field-reference", "C2-STRUCT-FIELD-TYPE", d_struct_field_ref}, + {"duplicate-function", "C2-FUNC-NAME", d_func_dup_name}, + {"function-returns-reference", "C2-FUNC-RETURN", d_func_ret_ref}, + {"reference-kind-4", "C2-TYPE-INVALID", d_vreg_kind}, + {"array-length-0", "C2-TYPE-INVALID", d_vreg_len0}, + {"struct-id-out-of-range", "C2-TYPE-INVALID", d_vreg_sid}, + {"seven-parameters", "C2-FUNC-PARAMS", d_params_over}, + {"borrow-outlives-owner", "C2-BORROW-OUTLIVES-OWNER", d_borrow_outlives}, + {"use-after-move-into-call", "C2-OWN-USE-DEAD", d_use_after_move}, + {"move-after-move", "C2-OWN-USE-DEAD", d_mov_after_move}, + {"irreducible-cycle", "C2-CFG-IRREDUCIBLE", d_irreducible}, + {"endless-loop", "C2-LOOP-UNBOUNDED", d_endless_loop}, + {"alloc-into-borrow", "C2-TYPE-ALLOC", d_alloc_into_borrow}, + {"field-index-past-table", "C2-TYPE-FIELD", d_field_stale_slot}, + {"index-scalar-register", "C2-TYPE-INDEX", d_index_scalar_stale_elem}, + {"slice-load-from-scalar", "C2-TYPE-SLICE", d_sload_non_slice}, +}; +#define NDEFECTS ((int)(sizeof defects / sizeof defects[0])) + +/* ------------------------------------------------------------------ byte-level defects */ + +static int bytes_reject(const uint8_t *b, size_t n, const char *want_rule, const char *what) +{ + C2Verdict v; + int rc = c2_check_bytes(b, n, &v); + CHECK(rc != 0, "%s: bytes accepted", what); + if (rc != 0 && want_rule) CHECK(strcmp(v.rule, want_rule) == 0, "%s: rule %s, want %s", what, v.rule, want_rule); + return rc != 0; +} + +static int byte_defects(void) +{ + int planted = 0; + const Unit *s = NULL, *plain = NULL; + for (int i = 0; i < ncorpus; i++) { + if (!s && corpus[i].b[7] >= 2) s = &corpus[i]; + if (!plain && corpus[i].b[7] == 1) plain = &corpus[i]; + } + CHECK(s && plain, "corpus needs a version-1 and a version>=2 unit"); + if (!s || !plain) return 0; + uint8_t *b = malloc(s->n + 1); + memcpy(b, s->b, s->n); + b[0] ^= 1; + planted += bytes_reject(b, s->n, "C2-DECODE-MAGIC", "bad-magic"); + memcpy(b, s->b, s->n); + b[7] = 6; + planted += bytes_reject(b, s->n, "C2-DECODE-VERSION", "unknown-version"); + memcpy(b, s->b, s->n); + b[s->n] = 0; + planted += bytes_reject(b, s->n + 1, "C2-DECODE-TRAILING", "trailing-byte"); + planted += bytes_reject(s->b, s->n - 1, NULL, "truncated-by-one"); + free(b); + /* a version-1 unit relabelled as version 2 needs a struct table it does not have */ + b = malloc(plain->n + 1); + memcpy(b, plain->b, 7); + b[7] = 2; + b[8] = 0; /* empty struct table: well formed but the canonical version for no structs is 1 */ + memcpy(b + 9, plain->b + 8, plain->n - 8); + planted += bytes_reject(b, plain->n + 1, "C2-DECODE-VERSION-NONCANONICAL", "version-not-canonical"); + free(b); + return planted; +} + +/* ------------------------------------------------------------------ main */ + +int main(int argc, char **argv) +{ + if (argc != 2) { fprintf(stderr, "usage: test_c2_ir <ir-dir>\n"); return 2; } + if (load(argv[1]) || ncorpus == 0) { fprintf(stderr, "test_c2_ir: no .ir files in %s\n", argv[1]); return 2; } + static uint8_t enc[1 << 20]; + C2Unit *u = malloc(sizeof *u); + C2Verdict v; + + /* 1. accept and round-trip */ + int accepted = 0; + for (int i = 0; i < ncorpus; i++) { + int d = c2_decode(corpus[i].b, corpus[i].n, u, &v); + CHECK(d == 0, "%s: decode refused: %s %s", corpus[i].name, v.rule, v.detail); + if (d == 0) { + int c = c2_check_unit(u, &v); + CHECK(c == 0, "%s: rejected: %s f%d i%d %s", corpus[i].name, v.rule, v.func, v.insn, v.detail); + size_t n = c2_encode(u, enc, sizeof enc); + CHECK(n == corpus[i].n && memcmp(enc, corpus[i].b, n) == 0, "%s: re-encoding differs", corpus[i].name); + accepted += c == 0; + } + c2_unit_free(u); + } + CHECK(accepted == ncorpus, "accepted %d of %d", accepted, ncorpus); + + /* 2. robustness: truncations refused; bit flips never crash */ + int truncs = 0, flips = 0, flip_rejects = 0; + for (int i = 0; i < ncorpus; i++) { + size_t n = corpus[i].n; + for (size_t k = 0; k < 72; k++) { + size_t cut = k < 64 ? n * k / 64 : n - (72 - k); + if (cut >= n) continue; + truncs++; + CHECK(c2_check_bytes(corpus[i].b, cut, &v) != 0, "%s: prefix of %zu bytes accepted", corpus[i].name, cut); + } + uint8_t *b = malloc(n); + for (int k = 0; k < 96; k++) { + memcpy(b, corpus[i].b, n); + size_t pos = (size_t)(((uint64_t)k * 2654435761u + (uint64_t)i * 40503u) % n); + b[pos] ^= (uint8_t)(1u << (k & 7)); + flips++; + flip_rejects += c2_check_bytes(b, n, &v) != 0; + } + free(b); + } + + /* 3. planted defects */ + int planted = 0; + for (int d = 0; d < NDEFECTS; d++) { + int applied = 0; + for (int i = 0; i < ncorpus && !applied; i++) { + if (c2_decode(corpus[i].b, corpus[i].n, u, &v)) { c2_unit_free(u); continue; } + if (defects[d].apply(u)) { + applied = 1; + int c = c2_check_unit(u, &v); + CHECK(c != 0, "defect %s on %s: accepted", defects[d].name, corpus[i].name); + if (c != 0) + CHECK(strcmp(v.rule, defects[d].rule) == 0, "defect %s on %s: rule %s (%s), want %s", defects[d].name, + corpus[i].name, v.rule, v.detail, defects[d].rule); + int ok = c != 0 && strcmp(v.rule, defects[d].rule) == 0; + size_t n = c2_encode(u, enc, sizeof enc); + if (n) CHECK(c2_check_bytes(enc, n, &v) != 0, "defect %s on %s: its bytes are accepted", defects[d].name, corpus[i].name); + planted += ok; + } + c2_unit_free(u); + } + CHECK(applied, "defect %s fits no corpus unit", defects[d].name); + } + planted += byte_defects(); + CHECK(planted >= 50, "gate needs >= 50 planted defects refused, got %d", planted); + free(u); + + printf("test_c2_ir: %d units accepted and re-encoded identically, %d truncations refused, %d bit flips (%d refused), " + "%d planted defects refused; %d checks, %d failed\n", + accepted, truncs, flips, flip_rejects, planted, checks, fails); + return fails ? 1 : 0; +} diff --git a/tests/checker2/test_c2_lrat.c b/tests/checker2/test_c2_lrat.c new file mode 100644 index 000000000..815020f37 --- /dev/null +++ b/tests/checker2/test_c2_lrat.c @@ -0,0 +1,124 @@ +/* test_c2_lrat: checker2's DIMACS reader and LRAT checker on hand-written cases (omega#446). + * Every refusal is checked by its exact rule name, so removing any GUARD line in c2_lrat.c fails + * a case here (tests/checker2/mutants.sh). Also: 20000 single-byte corruptions of a valid proof + * never crash and never make a satisfiable formula "unsatisfiable". */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_lrat.h" + +static int fails, cases; + +/* (1 2)(1 -2)(-1 2)(-1 -2): unsatisfiable */ +static const char *UNSAT4 = "c four clauses over two variables\np cnf 2 4\n1 2 0\n1 -2 0\n-1 2 0\n-1 -2 0\n"; +static const char *GOOD = "5 1 0 1 2 0\n6 0 5 3 4 0\n"; + +static void lrat(const char *name, const char *cnf_text, const char *proof, const char *want_rule) +{ + cases++; + C2Cnf cnf; + const char *why = ""; + if (c2_cnf_parse(cnf_text, strlen(cnf_text), &cnf, &why)) { + printf("FAIL %s: cnf refused (%s)\n", name, why); + fails++; + return; + } + C2LratResult r; + int rc = c2_lrat_check(&cnf, proof, strlen(proof), &r); + int want_ok = strcmp(want_rule, "LRAT-OK") == 0; + if ((rc == 0) != want_ok || r.ok != want_ok || strcmp(r.rule, want_rule) != 0) { + printf("FAIL %s: rc=%d ok=%d rule=%s line=%ld, want %s\n", name, rc, r.ok, r.rule, r.line, want_rule); + fails++; + } + c2_cnf_free(&cnf); +} + +static void cnf(const char *name, const char *text, const char *want) +{ + cases++; + C2Cnf c; + const char *why = "CNF-OK"; + int rc = c2_cnf_parse(text, strlen(text), &c, &why); + if (rc == 0) c2_cnf_free(&c); + if ((rc == 0) != (strcmp(want, "CNF-OK") == 0) || strcmp(why, want) != 0) { + printf("FAIL %s: rc=%d why=%s, want %s\n", name, rc, why, want); + fails++; + } +} + +int main(void) +{ + /* accepted */ + lrat("valid", UNSAT4, GOOD, "LRAT-OK"); + lrat("valid-with-deletions", UNSAT4, "5 1 0 1 2 0\n5 d 1 2 0\n6 0 5 3 4 0\n", "LRAT-OK"); + lrat("valid-comments", UNSAT4, "c proof\n5 1 0 1 2 0\n\nc next\n6 0 5 3 4 0\n", "LRAT-OK"); + lrat("valid-trailing-hints", UNSAT4, "5 1 0 1 2 3 0\n6 0 5 3 4 0\n", "LRAT-OK"); + lrat("valid-tautology-step", UNSAT4, "5 1 -1 0 0\n6 1 0 1 2 0\n7 0 6 3 4 0\n", "LRAT-OK"); + lrat("valid-empty-input-clause", "p cnf 1 2\n1 0\n0\n", "3 0 2 0\n", "LRAT-OK"); + /* refused, one per rule */ + lrat("hint-satisfied", UNSAT4, "5 1 0 3 0\n", "LRAT-HINT-NOT-UNIT"); + lrat("hint-two-free", UNSAT4, "5 0 1 0\n", "LRAT-HINT-NOT-UNIT"); + lrat("hint-unknown", UNSAT4, "5 1 0 1 9 0\n", "LRAT-HINT-UNKNOWN"); + lrat("hint-deleted", UNSAT4, "4 d 2 0\n5 1 0 1 2 0\n6 0 5 3 4 0\n", "LRAT-HINT-UNKNOWN"); + lrat("rat-hint", UNSAT4, "5 1 0 -1 2 0\n", "LRAT-RAT-UNSUPPORTED"); + lrat("no-conflict", UNSAT4, "5 1 0 1 0\n", "LRAT-NO-CONFLICT"); + lrat("no-hints", UNSAT4, "5 0 0\n", "LRAT-NO-CONFLICT"); + lrat("no-empty-clause", UNSAT4, "5 1 0 1 2 0\n", "LRAT-NO-EMPTY-CLAUSE"); + lrat("empty-proof", UNSAT4, "", "LRAT-NO-EMPTY-CLAUSE"); + lrat("id-repeat", UNSAT4, "5 1 0 1 2 0\n5 0 5 3 4 0\n", "LRAT-ID-ORDER"); + lrat("id-input-range", UNSAT4, "4 1 0 1 2 0\n", "LRAT-ID-ORDER"); + /* ids are capped at (input clauses + proof lines): a huge id must not size the clause table */ + lrat("id-huge", UNSAT4, "5 1 0 1 2 0\n99999999 0 5 3 4 0\n", "LRAT-ID-RANGE"); + lrat("id-huge-first", UNSAT4, "100000000 1 0 1 2 0\n", "LRAT-ID-RANGE"); + lrat("id-at-cap", UNSAT4, "5 1 0 1 2 0\n7 0 5 3 4 0\n", "LRAT-OK"); + lrat("id-past-cap", UNSAT4, "5 1 0 1 2 0\n8 0 5 3 4 0\n", "LRAT-ID-RANGE"); + lrat("literal-range", UNSAT4, "5 7 0 1 2 0\n", "LRAT-LITERAL"); + lrat("literal-range-neg", UNSAT4, "5 -3 0 1 2 0\n", "LRAT-LITERAL"); + lrat("truncated", UNSAT4, "5 1 0 1 2", "LRAT-SYNTAX"); + lrat("garbage", UNSAT4, "5 x 0\n", "LRAT-SYNTAX"); + lrat("id-zero", UNSAT4, "0 1 0 1 2 0\n", "LRAT-SYNTAX"); + lrat("delete-unknown", UNSAT4, "4 d 9 0\n5 1 0 1 2 0\n6 0 5 3 4 0\n", "LRAT-DELETE-UNKNOWN"); + lrat("delete-twice", UNSAT4, "4 d 1 1 0\n", "LRAT-DELETE-UNKNOWN"); + lrat("satisfiable-formula", "p cnf 2 2\n1 2 0\n-1 -2 0\n", "3 0 1 2 0\n", "LRAT-HINT-NOT-UNIT"); + lrat("conclusion-on-wrong-formula", "p cnf 2 3\n1 2 0\n1 -2 0\n-1 2 0\n", "4 1 0 1 2 0\n5 0 4 3 0\n", + "LRAT-NO-CONFLICT"); + + /* DIMACS reader */ + cnf("cnf-ok", UNSAT4, "CNF-OK"); + cnf("cnf-no-header", "1 2 0\n", "CNF-HEADER"); + cnf("cnf-bad-header", "p cnf x 2\n", "CNF-HEADER"); + cnf("cnf-count-high", "p cnf 2 3\n1 2 0\n", "CNF-COUNT"); + cnf("cnf-count-low", "p cnf 2 1\n1 2 0\n-1 0\n", "CNF-COUNT"); + cnf("cnf-unterminated", "p cnf 2 1\n1 2\n", "CNF-COUNT"); + cnf("cnf-literal-range", "p cnf 2 1\n1 3 0\n", "CNF-LITERAL"); + cnf("cnf-garbage", "p cnf 2 1\n1 y 0\n", "CNF-LITERAL"); + + /* robustness: byte corruptions of a valid proof against a satisfiable twin never verify, and + * against the unsatisfiable formula never crash */ + const char *sat2 = "p cnf 2 4\n1 2 0\n1 -2 0\n-1 2 0\n2 0\n"; + C2Cnf u, s; + const char *why; + if (c2_cnf_parse(UNSAT4, strlen(UNSAT4), &u, &why) || c2_cnf_parse(sat2, strlen(sat2), &s, &why)) return 2; + char buf[64]; + size_t n = strlen(GOOD); + unsigned long x = 12345; + long sat_accepts = 0, runs = 0; + for (int it = 0; it < 20000; it++) { + memcpy(buf, GOOD, n + 1); + x = x * 6364136223846793005UL + 1442695040888963407UL; + size_t at = (x >> 33) % n; + buf[at] = " 0123456789-d\nc"[(x >> 20) % 15]; + C2LratResult r; + c2_lrat_check(&u, buf, n, &r); + if (c2_lrat_check(&s, buf, n, &r) == 0) sat_accepts++; + runs++; + } + cases++; + if (sat_accepts) { printf("FAIL corruption: %ld proofs verified a satisfiable formula\n", sat_accepts); fails++; } + c2_cnf_free(&u); + c2_cnf_free(&s); + + printf("test_c2_lrat: %d cases, %ld corruptions, %d failures\n", cases, runs, fails); + return fails ? 1 : 0; +} diff --git a/tests/checker2/test_c2_receipt.c b/tests/checker2/test_c2_receipt.c new file mode 100644 index 000000000..add9bf10b --- /dev/null +++ b/tests/checker2/test_c2_receipt.c @@ -0,0 +1,411 @@ +/* test_c2_receipt: signed realization receipts (spec/one-layer-receipts.md). + * + * Every refusal case starts from a receipt that this same test shows is accepted under the same + * policy, changes one thing, and requires the exact named reason. tests/checker2/mutants.sh removes + * each GUARD line of src/checker2/c2_receipt.c in turn and requires this test to fail (negative + * control: the test can see each check). + * + * Argument 1 (optional): directory holding owner/ceremony-statement and owner/ceremony-signature + * (default tests/checker2/fixtures). */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "c2_receipt.h" +#include "sha256.h" +#include "searchtrace/sig/aienos_sig.h" + +static int fails, checks; +#define CHECK(cond, ...) \ + do { \ + checks++; \ + if (!(cond)) { \ + fails++; \ + fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + } \ + } while (0) +#define EXPECT(got, want, what) \ + CHECK((got) == (want), "%s: got %s, want %s", what, c2r_reason(got), c2r_reason(want)) + +static const char *fixdir = "tests/checker2/fixtures"; + +static size_t slurp(const char *rel, uint8_t *buf, size_t cap) +{ + char path[512]; + snprintf(path, sizeof path, "%s/%s", fixdir, rel); + FILE *f = fopen(path, "rb"); + if (!f) { fprintf(stderr, "cannot open %s\n", path); exit(2); } + size_t n = fread(buf, 1, cap, f); + fclose(f); + return n; +} + +static void fill(uint8_t out[32], const char *label) +{ + sha256_hash((const uint8_t *)label, strlen(label), out); +} + +static C2Receipt base(void) +{ + C2Receipt r; + memset(&r, 0, sizeof r); + r.version = C2R_FORMAT_VERSION; + r.signer_class = C2R_CLASS_TEST; + r.alg = C2R_ALG_ED25519; + r.evidence_class = C2R_EV_IR_CHECKED; + fill(r.requirements, "requirements"); + fill(r.program, "program bytes"); + fill(r.executable, "executable bytes"); + c2r_deps_digest(NULL, 0, r.dependencies); + fill(r.checker, "checker2"); + fill(r.producer_checker, "oscc"); + c2r_target_id("aarch64-linux-host", r.target); + /* firmware all zero: host */ + fill(r.input, "input"); + r.policy_epoch = 5; + r.expiry_epoch = 9; + return r; +} + +static uint8_t seed[32]; +static uint8_t checker_ok[32]; /* fill(.., "checker2"): the identity base() puts in a receipt */ +static const uint8_t (*test_anchor)[32] = &c2r_test_pk; +static const uint8_t (*owner_anchor)[32] = &c2r_owner_root_pk; + +static C2ReceiptPolicy qual(void) +{ + C2ReceiptPolicy p; + memset(&p, 0, sizeof p); + p.production = 0; + p.test_anchors = test_anchor; p.n_test = 1; + p.owner_anchors = owner_anchor; p.n_owner = 1; + p.checkers = (const uint8_t (*)[32])checker_ok; p.n_checkers = 1; + p.epoch_floor = 5; + p.current_epoch = 7; + return p; +} + +static C2ReceiptExpect expect_of(const C2Receipt *r) +{ + C2ReceiptExpect e = {r->target, r->firmware, r->program, r->executable, r->producer_checker, r->dependencies}; + return e; +} + +static void test_keys(void) +{ + uint8_t pk[32]; + c2r_test_seed(seed); + CHECK(aienos_ed25519_public_key(pk, seed) == AIENOS_SIG_OK, "derive test pk"); + CHECK(memcmp(pk, c2r_test_pk, 32) == 0, "c2r_test_pk is the public key of c2r_test_seed"); + CHECK(memcmp(c2r_test_pk, c2r_owner_root_pk, 32) != 0, "test key differs from owner root"); + + /* The owner root is Drake's real key: its ceremony signature (made on the YubiKey) verifies + * under the compiled-in constant, and a one-byte change of the statement does not. */ + uint8_t msg[4096], sig[64]; + size_t n = slurp("owner/ceremony-statement", msg, sizeof msg); + CHECK(slurp("owner/ceremony-signature", sig, sizeof sig) == 64, "ceremony signature is 64 bytes"); + CHECK(aienos_ed25519_verify(sig, msg, n, c2r_owner_root_pk) == AIENOS_SIG_OK, + "real owner ceremony signature verifies under c2r_owner_root_pk"); + msg[n - 1] ^= 1; + CHECK(aienos_ed25519_verify(sig, msg, n, c2r_owner_root_pk) != AIENOS_SIG_OK, + "control: altered ceremony statement is refused"); + msg[n - 1] ^= 1; + CHECK(aienos_ed25519_verify(sig, msg, n, c2r_test_pk) != AIENOS_SIG_OK, + "control: ceremony signature does not verify under the TEST key"); +} + +static void test_valid_and_deterministic(void) +{ + C2Receipt r = base(), r2 = base(), got; + uint8_t a[C2R_SIZE], b[C2R_SIZE], ida[32], idb[32]; + EXPECT(c2r_sign_test(&r, seed, a), C2R_OK, "sign"); + EXPECT(c2r_sign_test(&r2, seed, b), C2R_OK, "sign again"); + CHECK(memcmp(a, b, C2R_SIZE) == 0, "identical inputs give identical receipt bytes"); + c2r_id(a, ida); + c2r_id(b, idb); + CHECK(memcmp(ida, idb, 32) == 0, "identical ids"); + C2ReceiptPolicy p = qual(); + C2ReceiptExpect e = expect_of(&r); + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, &got), C2R_OK, "valid TEST receipt, qualification policy"); + CHECK(memcmp(got.program, r.program, 32) == 0 && got.policy_epoch == 5 && got.expiry_epoch == 9, + "decoded fields round-trip"); + /* epoch window edges are inclusive */ + p.current_epoch = 5; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_OK, "current == policy epoch"); + p.current_epoch = 9; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_OK, "current == expiry epoch"); +} + +/* Altered: every single-bit change anywhere in the 416 bytes is refused. */ +static void test_altered(void) +{ + C2Receipt r = base(); + uint8_t a[C2R_SIZE]; + c2r_sign_test(&r, seed, a); + C2ReceiptPolicy p = qual(); + C2ReceiptExpect e = expect_of(&r); + unsigned accepted = 0; + for (unsigned i = 0; i < C2R_SIZE * 8; i++) { + uint8_t m[C2R_SIZE]; + memcpy(m, a, C2R_SIZE); + m[i / 8] ^= (uint8_t)(1u << (i % 8)); + if (c2r_verify(m, C2R_SIZE, &p, &e, NULL) == C2R_OK) accepted++; + } + CHECK(accepted == 0, "every one of %u single-bit alterations refused (accepted %u)", C2R_SIZE * 8, accepted); + + /* named reasons for the structural fields */ + uint8_t m[C2R_SIZE]; + memcpy(m, a, C2R_SIZE); m[0] ^= 1; + EXPECT(c2r_verify(m, C2R_SIZE, &p, &e, NULL), C2R_E_MAGIC, "altered magic"); + memcpy(m, a, C2R_SIZE); m[8] = 2; + EXPECT(c2r_verify(m, C2R_SIZE, &p, &e, NULL), C2R_E_VERSION, "altered version"); + memcpy(m, a, C2R_SIZE); m[10] = 3; + EXPECT(c2r_verify(m, C2R_SIZE, &p, &e, NULL), C2R_E_CLASS, "altered class"); + memcpy(m, a, C2R_SIZE); m[12] = 2; + EXPECT(c2r_verify(m, C2R_SIZE, &p, &e, NULL), C2R_E_ALG, "altered algorithm"); + memcpy(m, a, C2R_SIZE); m[14] = 9; + EXPECT(c2r_verify(m, C2R_SIZE, &p, &e, NULL), C2R_E_EVIDENCE, "altered evidence class"); + memcpy(m, a, C2R_SIZE); m[48] ^= 0x80; + EXPECT(c2r_verify(m, C2R_SIZE, &p, NULL, NULL), C2R_E_BAD_SIGNATURE, "altered program hash"); + memcpy(m, a, C2R_SIZE); m[400] ^= 0x01; + EXPECT(c2r_verify(m, C2R_SIZE, &p, &e, NULL), C2R_E_BAD_SIGNATURE, "altered signature"); + EXPECT(c2r_verify(a, C2R_SIZE - 1, &p, &e, NULL), C2R_E_SIZE, "truncated"); + uint8_t big[C2R_SIZE + 1]; + memcpy(big, a, C2R_SIZE); big[C2R_SIZE] = 0; + EXPECT(c2r_verify(big, sizeof big, &p, &e, NULL), C2R_E_SIZE, "trailing byte"); + + /* epoch order: an expiry before the issue epoch is refused at decode and at signing */ + C2Receipt bad = base(); + bad.expiry_epoch = 4; + EXPECT(c2r_sign_test(&bad, seed, m), C2R_E_EPOCH_ORDER, "sign refuses expiry < policy epoch"); +} + +static void test_wrong_key(void) +{ + C2Receipt r = base(); + uint8_t a[C2R_SIZE], other_seed[32], other_pk[32]; + fill(other_seed, "some other key"); + aienos_ed25519_public_key(other_pk, other_seed); + EXPECT(c2r_sign_test(&r, other_seed, a), C2R_E_KEY_CLASS, "signing refuses a key that is not the TEST key"); + + /* a receipt signed by an unknown key (attached signature) is refused: not an anchor */ + C2Receipt r2 = base(); + uint8_t tbs[C2R_SIZE], msg[C2R_SIGNED_MSG_LEN], sig[64]; + sha256_hash(other_pk, 32, r2.key_fp); + c2r_encode(&r2, tbs); + c2r_signed_message(tbs, msg); + aienos_ed25519_sign(sig, msg, sizeof msg, other_seed); + EXPECT(c2r_attach(&r2, other_pk, sig, a), C2R_OK, "attach a valid foreign signature"); + C2ReceiptPolicy p = qual(); + C2ReceiptExpect e = expect_of(&r2); + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_UNTRUSTED_SIGNER, "wrong key"); + + /* the right key fingerprint with a signature made by another key */ + C2Receipt r3 = base(); + sha256_hash(c2r_test_pk, 32, r3.key_fp); + c2r_encode(&r3, tbs); + c2r_signed_message(tbs, msg); + aienos_ed25519_sign(sig, msg, sizeof msg, other_seed); + EXPECT(c2r_attach(&r3, c2r_test_pk, sig, a), C2R_E_BAD_SIGNATURE, "attach refuses a signature by the wrong key"); + memcpy(a + 352, sig, 64); + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_BAD_SIGNATURE, "TEST fingerprint, foreign signature"); + + /* swap two equally valid receipts' signatures: refused */ + C2Receipt x = base(), y = base(); + y.policy_epoch = 6; + uint8_t bx[C2R_SIZE], by[C2R_SIZE]; + c2r_sign_test(&x, seed, bx); + c2r_sign_test(&y, seed, by); + memcpy(bx + 352, by + 352, 64); + EXPECT(c2r_verify(bx, C2R_SIZE, &p, &e, NULL), C2R_E_BAD_SIGNATURE, "signature of another receipt"); +} + +static void test_production(void) +{ + C2Receipt r = base(); + uint8_t a[C2R_SIZE]; + c2r_sign_test(&r, seed, a); + C2ReceiptPolicy p = qual(); + C2ReceiptExpect e = expect_of(&r); + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_OK, "control: accepted in qualification"); + p.production = 1; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_TEST_IN_PRODUCTION, "TEST receipt in production"); + + /* the TEST key relabelled OWNER class: production refuses it even if a careless policy lists + * the TEST key as an owner anchor */ + C2Receipt o = base(); + o.signer_class = C2R_CLASS_OWNER; + EXPECT(c2r_sign_test(&o, seed, a), C2R_E_KEY_CLASS, "TEST key cannot sign OWNER class"); + uint8_t tbs[C2R_SIZE], msg[C2R_SIGNED_MSG_LEN], sig[64]; + sha256_hash(c2r_test_pk, 32, o.key_fp); + c2r_encode(&o, tbs); + c2r_signed_message(tbs, msg); + aienos_ed25519_sign(sig, msg, sizeof msg, seed); + EXPECT(c2r_attach(&o, c2r_test_pk, sig, a), C2R_OK, "attach (OWNER class, TEST key)"); + const uint8_t sloppy[2][32] = {{0}, {0}}; + uint8_t (*sl)[32] = (uint8_t (*)[32])sloppy; + memcpy(sl[0], c2r_owner_root_pk, 32); + memcpy(sl[1], c2r_test_pk, 32); + C2ReceiptPolicy q = qual(); + q.production = 1; + q.owner_anchors = (const uint8_t (*)[32])sl; + q.n_owner = 2; + q.test_anchors = NULL; + q.n_test = 0; + EXPECT(c2r_verify(a, C2R_SIZE, &q, &e, NULL), C2R_E_UNTRUSTED_SIGNER, + "production pins the owner root: TEST key listed as owner anchor is refused"); + /* control for the pin: the same sloppy policy outside production takes it */ + q.production = 0; + EXPECT(c2r_verify(a, C2R_SIZE, &q, &e, NULL), C2R_OK, "control: non-production takes listed owner anchor"); + /* cross-class: the same key may not be anchored in both classes */ + q.test_anchors = test_anchor; + q.n_test = 1; + EXPECT(c2r_verify(a, C2R_SIZE, &q, &e, NULL), C2R_E_UNTRUSTED_SIGNER, "key anchored in both classes"); + + /* an OWNER-class receipt claiming the owner fingerprint but signed by the TEST key */ + C2Receipt f = base(); + f.signer_class = C2R_CLASS_OWNER; + sha256_hash(c2r_owner_root_pk, 32, f.key_fp); + c2r_encode(&f, tbs); + c2r_signed_message(tbs, msg); + aienos_ed25519_sign(sig, msg, sizeof msg, seed); + memcpy(tbs + 352, sig, 64); + EXPECT(c2r_attach(&f, c2r_owner_root_pk, sig, a), C2R_E_BAD_SIGNATURE, "attach refuses forged owner signature"); + p = qual(); + p.production = 1; + EXPECT(c2r_verify(tbs, C2R_SIZE, &p, &e, NULL), C2R_E_BAD_SIGNATURE, "forged owner receipt in production"); +} + +static void test_revoked_replayed_fresh(void) +{ + C2Receipt r = base(); + uint8_t a[C2R_SIZE], id[32], fp[32], other[32]; + c2r_sign_test(&r, seed, a); + c2r_id(a, id); + sha256_hash(c2r_test_pk, 32, fp); + fill(other, "unrelated id"); + C2ReceiptExpect e = expect_of(&r); + C2ReceiptPolicy p = qual(); + const uint8_t (*ids)[32] = (const uint8_t (*)[32])id; + const uint8_t (*oth)[32] = (const uint8_t (*)[32])other; + const uint8_t (*fps)[32] = (const uint8_t (*)[32])fp; + p.revoked_ids = oth; p.n_revoked_ids = 1; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_OK, "control: unrelated revocation"); + p.revoked_ids = ids; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_REVOKED, "revoked receipt id"); + p = qual(); + p.revoked_keys = fps; p.n_revoked_keys = 1; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_REVOKED, "revoked signer key"); + + /* replay of a superseded receipt: policy moved its floor past the receipt's epoch */ + p = qual(); + p.epoch_floor = 6; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_STALE, "replayed after epoch floor moved"); + p = qual(); + p.current_epoch = 10; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_EXPIRED, "expired"); + p = qual(); + p.epoch_floor = 0; + p.current_epoch = 4; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_NOT_YET_VALID, "not yet valid"); +} + +static void test_binding(void) +{ + C2Receipt r = base(); + uint8_t a[C2R_SIZE], x[32]; + c2r_sign_test(&r, seed, a); + C2ReceiptPolicy p = qual(); + C2ReceiptExpect e = expect_of(&r); + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_OK, "control: all bindings match"); + + c2r_target_id("gb10-aienos", x); + e = expect_of(&r); e.target = x; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_WRONG_TARGET, "wrong target"); + fill(x, "firmware v2"); + e = expect_of(&r); e.firmware = x; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_WRONG_FIRMWARE, "wrong firmware"); + fill(x, "other program"); + e = expect_of(&r); e.program = x; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_PROGRAM_MISMATCH, "program mismatch"); + fill(x, "other executable"); + e = expect_of(&r); e.executable = x; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_EXECUTABLE_MISMATCH, "executable mismatch"); +} + +/* Checker identity is a policy anchor list: a receipt judged by any other checker build is refused, + * an empty list refuses everything (fail closed). Producer and dependency digests are bound like + * the other fields. */ +static void test_checker_identity(void) +{ + C2Receipt r = base(), o = base(); + uint8_t a[C2R_SIZE], b[C2R_SIZE], x[32], two[2][32]; + fill(o.checker, "checker2 built from other sources"); + c2r_sign_test(&r, seed, a); + c2r_sign_test(&o, seed, b); + C2ReceiptPolicy p = qual(); + C2ReceiptExpect e = expect_of(&r); + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_OK, "control: receipt from the anchored checker"); + EXPECT(c2r_verify(b, C2R_SIZE, &p, &e, NULL), C2R_E_UNTRUSTED_CHECKER, "receipt from a different checker identity"); + EXPECT(c2r_verify(b, C2R_SIZE, &p, NULL, NULL), C2R_E_UNTRUSTED_CHECKER, "checker identity checked without expectations"); + memcpy(two[0], checker_ok, 32); + memcpy(two[1], o.checker, 32); + p.checkers = (const uint8_t (*)[32])two; + p.n_checkers = 2; + EXPECT(c2r_verify(b, C2R_SIZE, &p, &e, NULL), C2R_OK, "control: second identity anchored"); + p.n_checkers = 0; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_UNTRUSTED_CHECKER, "empty checker list refuses everything"); + p.checkers = NULL; + p.n_checkers = 1; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_UNTRUSTED_CHECKER, "NULL checker list refuses everything"); + + p = qual(); + fill(x, "another oscc binary"); + e = expect_of(&r); e.producer_checker = x; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_WRONG_PRODUCER, "wrong producer checker"); + uint8_t ids[1][32]; + fill(ids[0], "some dependency receipt"); + c2r_deps_digest((const uint8_t (*)[32])ids, 1, x); + e = expect_of(&r); e.dependencies = x; + EXPECT(c2r_verify(a, C2R_SIZE, &p, &e, NULL), C2R_E_DEPS_MISMATCH, "dependency digest mismatch"); +} + +static void test_deps(void) +{ + uint8_t ids[3][32], d1[32], d2[32]; + fill(ids[0], "a"); fill(ids[1], "b"); fill(ids[2], "c"); + /* sort ascending */ + for (int i = 0; i < 3; i++) + for (int j = i + 1; j < 3; j++) + if (memcmp(ids[i], ids[j], 32) > 0) { + uint8_t t[32]; + memcpy(t, ids[i], 32); memcpy(ids[i], ids[j], 32); memcpy(ids[j], t, 32); + } + CHECK(c2r_deps_digest((const uint8_t (*)[32])ids, 3, d1) == 0, "sorted deps accepted"); + CHECK(c2r_deps_digest((const uint8_t (*)[32])ids, 2, d2) == 0 && memcmp(d1, d2, 32) != 0, + "dependency count is bound"); + uint8_t swapped[2][32]; + memcpy(swapped[0], ids[1], 32); memcpy(swapped[1], ids[0], 32); + CHECK(c2r_deps_digest((const uint8_t (*)[32])swapped, 2, d2) == -1, "unsorted deps refused"); + memcpy(swapped[1], ids[1], 32); + CHECK(c2r_deps_digest((const uint8_t (*)[32])swapped, 2, d2) == -1, "duplicate deps refused"); +} + +int main(int argc, char **argv) +{ + if (argc > 1) fixdir = argv[1]; + fill(checker_ok, "checker2"); + test_keys(); + test_valid_and_deterministic(); + test_altered(); + test_wrong_key(); + test_production(); + test_revoked_replayed_fresh(); + test_binding(); + test_checker_identity(); + test_deps(); + printf("test_c2_receipt: %d checks, %d failed\n", checks, fails); + return fails ? 1 : 0; +}