From 0c2095078e259ed0220f93cb8c3eb6d4c59ee7f2 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Wed, 30 Sep 2026 21:47:29 -0500 Subject: [PATCH 1/2] chore: remove Python from physics repo (shell/C rewrites); AR2 status lines - Delete the five legacy M2 Python files (generate_physics_audit.py, m2_build.py, run_milestone2_gates.py, seam1_physics_audit.py, seam2_physics_harness.py). Superseded by m2_build.sh, run_m2_gates.sh and tools/m2tool.c (physics#8). Verified before deletion on d52759d: both runners print the same 15 gates, all PASS; both rebuild physics.bin and atlas_m2.bin byte-identical to the committed files; the Python audit generator reproduced the committed audit artifacts byte-identically (physics.decode differs only in objdump's path line). - tests/run_m16_requalification.sh: replace the inline python3 /proc maps capture with a bash function. It now polls for the whole run and checks every snapshot for libcuda (the Python helper stopped at the first read, which can precede the dynamic loader mapping any library). - README, docs/native-frame-authority.md: point at ./run_m2_gates.sh. - TRANSITION_PLAN_M2.md: Phase 3 complete; no-Python regeneration recipe for the committed M2 audit artifacts. qualification_receipt.json is untouched historical evidence (it pins the old .py hashes). - docs/FORGE_SUBSTRATE_V2_SPEC.md: AR2 is covered by physics#21 (d52759d), simulated only. Reviewed-by: Codex gpt-6-astra (codex review, no findings) Co-Authored-By: Drake Stapleton Co-Authored-By: Codex gpt-6-astra Co-Authored-By: Claude Opus 5.5 --- README.md | 12 +- TRANSITION_PLAN_M2.md | 28 +- docs/FORGE_SUBSTRATE_V2_SPEC.md | 4 +- docs/native-frame-authority.md | 2 +- generate_physics_audit.py | 440 ------------------------ m2_build.py | 115 ------- run_milestone2_gates.py | 198 ----------- seam1_physics_audit.py | 394 --------------------- seam2_physics_harness.py | 570 ------------------------------- tests/run_m16_requalification.sh | 54 +-- 10 files changed, 67 insertions(+), 1750 deletions(-) delete mode 100755 generate_physics_audit.py delete mode 100644 m2_build.py delete mode 100755 run_milestone2_gates.py delete mode 100755 seam1_physics_audit.py delete mode 100644 seam2_physics_harness.py diff --git a/README.md b/README.md index 8c47365..45f8f88 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ AIEN OBSERVES, THINKS, HYPOTHESIZES, SEARCHES, DISCOVERS, AND INVENTS. ## Qualification Architecture (Dual Verification Seams) -### Seam 1: Independent Artifact-Audit Seam (`seam1_physics_audit.py`) +### Seam 1: Independent Artifact-Audit Seam (`tools/m2tool audit-verify`) Validates static artifact properties without requiring execution: 1. `PHYSICS_ARTIFACT_IDENTITY_PASS`: `physics.bin` matches `physics.sha256`. 2. `PHYSICS_MACHINE_CONTRACT_PASS`: Code size $\le 32\text{ KiB}$ (actual: 1,856 B), total image $\le 64\text{ KiB}$ (actual: 6,144 B), anti-bloat law satisfied. @@ -66,8 +66,8 @@ Validates static artifact properties without requiring execution: 6. `PHYSICS_MEMORY_DISJOINTNESS_PASS`: Static mathematical proof that all 7 physical memory regions (`IMAGE`, `VBAR`, `STACK`, `STATE`, `CAP_TABLE`, `STATIC_DATA`, `FREE_FRAME_REGION`) are pairwise disjoint. 7. `PHYSICS_STATIC_MEMORY_BOUNDS_PASS`: Memory operations confined strictly to declared regions; initial kernel SP is `0x40205800`. -### Seam 2: External Execution Seam (`seam2_physics_harness.py`) -Boots PHYSICS in QEMU virt (AArch64, cortex-a57, 128 MiB) and qualifies it by reading guest memory over QMP (`xp`), not by trusting UART strings. Every image is rebuilt from source on every run (`m2_build.py`); nothing is cached. +### Seam 2: External Execution Seam (`run_m2_gates.sh` + `tools/qemu_inspect.sh`) +Boots PHYSICS in QEMU virt (AArch64, cortex-a57, 128 MiB) and qualifies it by reading guest memory over QMP (`pmemsave`), not by trusting UART strings. Every image is rebuilt from source on every run (`m2_build.sh`); nothing is cached. 1. `PHYSICS_ENTRY_EL_PASS`: recorded `CurrentEL` (boot state +0x40) equals the contract's `expected_entry_el_value` (EL1); a real EL2 entry (`virt,virtualization=on`) is refused with `PANIC_UNCONTRACTED_EL` before any authority exists. 2. `PHYSICS_DESCRIPTOR_INGRESS_PASS`: the PHYSICS-owned 64-byte descriptor copy equals the contract descriptor word for word; every header (magic, version, length, reserved) and machine-profile violation is refused before bitmap initialization. 3. `PHYSICS_BOOT_QEMU_PASS`: `physics.bin` and `atlas_m2.bin` rebuild byte-identically; telemetry is exactly the golden sequence; allocator header is exactly `DRAM_END=0x48000000`, 32,248 frames; no exception taken. @@ -77,7 +77,7 @@ Boots PHYSICS in QEMU virt (AArch64, cortex-a57, 128 MiB) and qualifies it by re 7. `PHYSICS_EXCEPTION_STATE_CAPTURE_PASS`: two faults (BRK and an alignment Data Abort) with sentinel values in x0..x30; the trap frame at `0x40205880` holds every sentinel, the interrupted SP, vector slot 4, `CurrentEL`, ESR, ELR (== fault site symbol), SPSR `0x3C5`, FAR and FAR_VALID (0 for BRK, 1 with the faulting address for the abort). 8. `PHYSICS_CORRUPTION_REFUSAL_PASS`: 23 hostile cases (cookie, payload size, descriptor pointer, magic, version, length, reserved bits, zero/overflowing/oversized/undersized/shifted/out-of-profile RAM, UART, PHYSICS base/size, EL2 entry) each end in the expected panic with the entry record, allocator header and CAP_ROOT slot still zero in memory. -`run_milestone2_gates.py` deletes `build/`, regenerates every artifact from source, runs both seams, and writes `qualification_receipt.json` bound to the SHA-256 of the contract, audit, gate scripts, sources and both artifacts, plus the QEMU version and base commit. +`run_m2_gates.sh` (also reachable as `run_milestone2_gates.sh`) rebuilds every artifact from source via `m2_build.sh`, checks the rebuilt binaries against the committed ones, and runs both seams. It leaves the committed `qualification_receipt.json` untouched unless `--write-receipt` is passed. That committed receipt is historical evidence from the retired Python harness (it pins the SHA-256 of the old `.py` scripts, retrievable from git history; see `TRANSITION_PLAN_M2.md`). --- @@ -91,6 +91,6 @@ Boots PHYSICS in QEMU virt (AArch64, cortex-a57, 128 MiB) and qualifies it by re ## Reproduction & Verification To execute the complete Milestone 2 qualification suite: ```bash -python3 run_milestone2_gates.py +./run_m2_gates.sh ``` -Outputs formal qualification receipt to `qualification_receipt.json`. +Prints all 15 gate results. `./run_m2_gates.sh --write-receipt` also rewrites `qualification_receipt.json` (only on a recorded requalification decision, aien-architecture#12). diff --git a/TRANSITION_PLAN_M2.md b/TRANSITION_PLAN_M2.md index e5f6817..2842dbf 100644 --- a/TRANSITION_PLAN_M2.md +++ b/TRANSITION_PLAN_M2.md @@ -44,8 +44,34 @@ All 15 gates complete execution in ~16.2 seconds with zero Python dependencies. 1. **Phase 1 (Dual-Track Availability - Present)**: - Pure C and shell tooling (`tools/m2tool.c`, `tools/qemu_inspect.sh`, `m2_build.sh`, `run_m2_gates.sh`) are active. - Developers and automated CI can build and verify all gates using `./run_m2_gates.sh` without Python. - - Legacy Python scripts remain available as historical reference. + - Legacy Python scripts were kept as historical reference until Phase 3 (below). 2. **Phase 2 (Formal Requalification Decision)**: - When recorded in `aien-architecture#12`, `run_m2_gates.sh --write-receipt` generates a refreshed receipt reflecting the pure C/shell verification toolchain. 3. **Phase 3 (Python Retirement & Archival)**: - Legacy Python files are moved to `history/legacy-python/` or deleted, completing total retirement of Python from the sovereign path. + +## Phase 3 Status: COMPLETE (2026-09-30) +The five legacy Python files (`generate_physics_audit.py`, `m2_build.py`, `run_milestone2_gates.py`, +`seam1_physics_audit.py`, `seam2_physics_harness.py`) are deleted. They remain in git history at +`d52759d` and earlier; `qualification_receipt.json` (historical evidence, untouched) pins their SHA-256. + +Equivalence check before deletion (scratch copies of `d52759d`, QEMU on the Spark): +- `python3 run_milestone2_gates.py` and `./run_m2_gates.sh` print the same 15 gate names, all PASS, no FAIL. +- Both rebuild `physics.bin` (`4b22a08c...f4aed3bd`) and `atlas_m2.bin` (`1d6d75a6...7b09012`) byte-identical + to the committed files. +- The Python audit generator regenerated `physics.audit`, `physics.manifest`, `physics.memory-map`, + `physics.control-flow` and `physics.sha256` byte-identical to the committed files; `physics.decode` differed + only in objdump's file-path header line. + +### Regeneration recipe for the committed M2 audit artifacts (no Python) +Run `./m2_build.sh` first (produces `build/canonical/physics.elf` and `physics.bin`). +- `physics.sha256`: `(cd build/canonical && sha256sum physics.bin)`; byte-identical to the committed file. +- `physics.decode`: `aarch64-linux-gnu-objdump -d build/canonical/physics.elf`; identical to the committed + file except line 2, which names the ELF path of the machine that generated it. +- `physics.audit`, `physics.manifest`, `physics.memory-map`, `physics.control-flow`: frozen M2 evidence, last + generated by `generate_physics_audit.py` (`git show d52759d:generate_physics_audit.py`). They are not + regenerated; `tools/m2tool audit-verify` re-checks `physics.audit`, `physics.manifest` and `physics.decode` + against `physics.bin` on every `./run_m2_gates.sh` run. If `physics.s` ever changes, these files need a + C/shell generator first (none exists yet). +- `physics_pin.inc`: `tools/m2tool pin-inc build/canonical/physics.bin physics_pin.inc` reproduces it except + the header comment (the committed copy still says it came from `m2_build.py`; left as committed). diff --git a/docs/FORGE_SUBSTRATE_V2_SPEC.md b/docs/FORGE_SUBSTRATE_V2_SPEC.md index dba8bd9..f9b98b9 100644 --- a/docs/FORGE_SUBSTRATE_V2_SPEC.md +++ b/docs/FORGE_SUBSTRATE_V2_SPEC.md @@ -36,7 +36,7 @@ Non-goals: - FORGE MACHINE DESCRIPTOR V1 remains **the qualified first implementation** on GB10. V2 does not replace, modify or re-qualify it. No v1 type, file or receipt changes. Historical receipts stay historical. - No hardware access, no driver calls, no submission path. V2 here is a data contract plus a host-only - reference serializer. Realization on a V2-described substrate is later work (AR2 onward). + reference serializer. Realization on a V2-described substrate starts at AR2 (simulated analog provider, merged in physics #21, `d52759d`; see `forge/analog-sim/`). - No change to the Omega runtime (R16 owns it until it closes) and no ARGUS ABI change. ## 2. Wire format @@ -465,7 +465,7 @@ exact strings the test prints. | AR1 | stale calibration refused | `stale_calibration_rejected`, `missing_calibration_rejected`, `calibration_from_future_rejected`, `calibration_window_capped_by_substrate`, `calibration_for_other_substrate_rejected`, `out_of_envelope_conditions_rejected` | covered | | AR1 | v1 generation refused | `v1_32bit_generation_refused`, `legacy_version_1_object_refused`, `stale_generation_high_bits_refused` | covered | | AR1 | `SIMULATED_DEVELOPMENT` provenance explicit | `evidence_encode_without_provenance_refused`, `evidence_decode_missing_provenance_refused`, `evidence_decode_zero_provenance_refused`, `simulated_provenance_explicit_in_kat_evidence` | covered | -| AR2 | analog simulation provider with digital oracle parity | contract/profile/evidence data model only; anchors in §6.4 | **not covered** (needs the simulation provider) | +| AR2 | analog simulation provider with digital oracle parity | `forge/analog-sim/forge_analog_sim.{h,c}`, `tests/test_forge_analog_sim.c`, `tests/run_forge_analog_sim_gates.sh`, receipt `evidence/AR2/`; anchors in §6.4 | **covered by physics #21** (`d52759d`), simulated only (`SIMULATED_DEVELOPMENT`); not by this V2 gate script | | AR3 | staleness ⇒ ineligible; uncertainty propagates into the contract check; evidence complete | `fresh_calibration_eligible`, `stale_calibration_rejected`, `substrate_bound_looser_than_contract_rejected`, `stochastic_substrate_not_eligible_for_exact_contract`, `recalibration_changes_realization_identity` | partial (data model + eligibility; no live evidence completeness audit) | | AR4 | first physical analog operation; clean digital fallback (a digital realization of the same contract exists somewhere in the eligible set, on any Machine); faulted device cannot corrupt World; no authority bypass; no vendor identity | `faulted_substrate_excluded`, `digital_fallback_eligible_for_bounded_and_exact`, `analog_only_machine_roundtrip_strict`, `eligible_set_analog_only_has_no_digital_fallback`, `digital_candidate_for_other_contract_not_a_fallback`, `eligible_set_digital_on_other_machine_is_fallback`, `irreversible_config_without_right_refused`, `irreversible_config_with_right_and_generation_allowed`, `authorize_pure_current_generation`, `reference_range_overflow_refused`, `no_vendor_names_in_v2_identifiers` | preconditions only; **no physical device exists** and none is claimed | diff --git a/docs/native-frame-authority.md b/docs/native-frame-authority.md index 8df532e..0726fae 100644 --- a/docs/native-frame-authority.md +++ b/docs/native-frame-authority.md @@ -457,7 +457,7 @@ scheduling). | `PHYSICS_DETERMINISTIC_ALLOCATION_PASS` | Two independent runs with the same profile and call sequence produce identical address sequences and identical metadata SHA-256; grants are ascending lowest-free. | | `PHYSICS_RELEASE_INTEGRITY_PASS` | Double, unaligned, reserved, hole and out-of-range releases refused with no state change; release without an SMMU-unmap + TLBI-sync receipt refused. | | `PHYSICS_NO_DISCRETE_VRAM_ASSUMPTION_PASS` | Static audit: no VRAM/HBM class or constant; the accelerator pool is carved from DRAM; a contract with `ACCEL_COHERENT_POOL` size 0 boots and qualifies. | -| `PHYSICS_QEMU_M2_REGRESSION_PASS` | `physics.bin` SHA-256 unchanged and the M2 suite (`run_milestone2_gates.py`) passes unchanged. | +| `PHYSICS_QEMU_M2_REGRESSION_PASS` | `physics.bin` SHA-256 unchanged and the M2 suite (`run_m2_gates.sh`) passes unchanged. | | `PHYSICS_RECEIPT_SEPARATION_PASS` | Native receipts live in their own namespace; the checker rejects a QEMU receipt for a native gate and vice versa. | | `PHYSICS_BOOT_NATIVE_PASS` | **Pending.** Physical DGX Spark boot, ATLAS to PHYSICS with the real UEFI-derived profile, every native gate above re-run with `evidence_class = native_hardware`, profile and metadata digests recorded. | diff --git a/generate_physics_audit.py b/generate_physics_audit.py deleted file mode 100755 index 453af7f..0000000 --- a/generate_physics_audit.py +++ /dev/null @@ -1,440 +0,0 @@ -#!/usr/bin/env python3 -""" -generate_physics_audit.py - Milestone 2 (PHYSICS_BOOT) Evidence Generation Tooling -Sovereign Machine Trusted Machine Authority - -Performs: -1. Toolchain linking of physics.o, vector_table.o, memory_alloc.o, capability.o - via linker script physics.ld (-Ttext=0x40200000). -2. Binary extraction (physics.bin via aarch64-linux-gnu-objcopy). -3. Disassembly dump (physics.decode via aarch64-linux-gnu-objdump -d). -4. Cryptographic SHA-256 calculation (physics.sha256). -5. Mathematical 8-column markdown ledger generation (physics.audit) - reconciling CODE_BYTES + RODATA_BYTES + CANONICAL_PADDING_BYTES + VECTOR_TABLE_BYTES == BINARY_SIZE - with exact 0-byte discrepancy. -6. Manifest generation (physics.manifest). -7. Normative memory map generation (physics.memory-map). -8. Textual / Mermaid control flow graph generation (physics.control-flow). -""" - -import hashlib -import json -import os -import re -import subprocess -import sys - -def build_physics_binary(base_dir="."): - """Build physics.bin, physics_pin.inc and atlas_m2.bin from source via - m2_build (no cached objects), returning the physics ELF and binary.""" - from m2_build import build_canonical - physics_elf, physics_bin = build_canonical(base_dir) - print(f"Built {physics_bin} and atlas_m2.bin from source (intermediates in build/canonical)") - return physics_elf, physics_bin - -def generate_decode(physics_elf, base_dir="."): - decode_path = os.path.join(base_dir, "physics.decode") - cmd = ["aarch64-linux-gnu-objdump", "-d", physics_elf] - proc = subprocess.run(cmd, stdout=subprocess.PIPE, text=True, check=True) - with open(decode_path, "w") as f: - f.write(proc.stdout) - print(f"Generated {decode_path} ({len(proc.stdout.splitlines())} lines)") - return proc.stdout - -def compute_sha256(physics_bin, base_dir="."): - sha_path = os.path.join(base_dir, "physics.sha256") - with open(physics_bin, "rb") as f: - data = f.read() - digest = hashlib.sha256(data).hexdigest() - with open(sha_path, "w") as f: - f.write(f"{digest} physics.bin\n") - print(f"Computed SHA-256: {digest} -> {sha_path}") - return digest, data - -def parse_section_headers(physics_elf): - cmd = ["aarch64-linux-gnu-objdump", "-h", physics_elf] - proc = subprocess.run(cmd, stdout=subprocess.PIPE, text=True, check=True) - sections = {} - for line in proc.stdout.splitlines(): - parts = line.strip().split() - if len(parts) >= 6 and parts[0].isdigit(): - idx = int(parts[0]) - name = parts[1] - size = int(parts[2], 16) - vma = int(parts[3], 16) - lma = int(parts[4], 16) - sections[name] = {"idx": idx, "size": size, "vma": vma, "lma": lma} - return sections - -def generate_audit_ledger(physics_bin, physics_elf, decode_text, sections, base_dir="."): - audit_file = os.path.join(base_dir, "physics.audit") - bin_size = os.path.getsize(physics_bin) - assert bin_size % 4 == 0, f"Binary size {bin_size} is not 4-byte aligned!" - total_words = bin_size // 4 - - # Map addresses to decoded disassembly lines - decoded_ops = {} - for line in decode_text.splitlines(): - line = line.strip() - m = re.match(r"^([0-9a-f]+):\s+([0-9a-f]{8})\s+(.*)$", line) - if m: - addr = int(m.group(1), 16) - raw_hex = m.group(2) - op = m.group(3).strip() - decoded_ops[addr] = (raw_hex, op) - - # Read binary bytes - with open(physics_bin, "rb") as f: - raw_bytes = f.read() - - text_info = sections.get(".text", {"vma": 0x40200000, "size": 0}) - rodata_info = sections.get(".rodata", {"vma": text_info["vma"] + text_info["size"], "size": 0}) - vectors_info = sections.get(".vectors", {"vma": 0x40201000, "size": 0x800}) - - text_start = text_info["vma"] - text_end = text_start + text_info["size"] - rodata_start = rodata_info["vma"] - rodata_end = rodata_start + rodata_info["size"] - vectors_start = vectors_info["vma"] - vectors_end = vectors_start + vectors_info["size"] - - audit_rows = [ - "# PHYSICS MACHINE OPERATION AUDIT LEDGER", - "## Normative Mathematical Accounting: 100% Byte Reconciliation", - "Milestone 2: Physics Authority Nucleus (PHYSICS_BOOT)", - "", - f"- **Binary Artifact:** `physics.bin` ({bin_size} bytes)", - f"- **Total 32-bit Words:** {total_words} words", - f"- **Base Physical Address:** `0x40200000`", - f"- **Vector Table Base:** `0x{vectors_start:08x}`", - "", - "| Offset | Raw Bytes | Decoded Operation / Content | Inputs | Outputs | Branch Target | Memory Accessed | Classification |", - "| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |" - ] - - code_words = 0 - rodata_words = 0 - padding_words = 0 - vector_words = 0 - - base_addr = 0x40200000 - - for i in range(total_words): - offset = i * 4 - addr = base_addr + offset - offset_str = f"0x{offset:04x}" - addr_str = f"0x{addr:08x}" - word_bytes = raw_bytes[offset:offset+4] - # Little-endian 32-bit hex - raw_hex = "".join(f"{b:02x}" for b in reversed(word_bytes)) - - inputs = "-" - outputs = "-" - branch_target = "-" - mem_access = "-" - - # Determine classification - if addr in decoded_ops: - raw_dump, op_text = decoded_ops[addr] - if addr >= vectors_start and addr < vectors_end: - classification = "VECTOR_ENTRY" - vector_words += 1 - else: - classification = "INSTRUCTION" - code_words += 1 - - # Disassemble semantics - if "msr" in op_text: - parts = op_text.replace(",", "").split() - if len(parts) >= 3: - outputs = parts[1] - inputs = parts[2] - elif "mrs" in op_text: - parts = op_text.replace(",", "").split() - if len(parts) >= 3: - outputs = parts[1] - inputs = parts[2] - elif "mov\tsp" in op_text or "mov sp" in op_text: - parts = op_text.replace(",", "").split() - inputs = parts[-1] - outputs = "SP" - elif "str" in op_text or "stp" in op_text: - classification_extra = "Write" - m_str = re.search(r"str[b]?\s+([w|x][0-9]+),\s+\[([a-z0-9,\s#+-]+)\]", op_text) - if m_str: - inputs = m_str.group(1) - mem_access = f"Write [{m_str.group(2)}]" - m_stp = re.search(r"stp\s+([w|x][0-9]+),\s+([w|x][0-9]+),\s+\[([a-z0-9,\s#+-]+)\]", op_text) - if m_stp: - inputs = f"{m_stp.group(1)}, {m_stp.group(2)}" - mem_access = f"Write [{m_stp.group(3)}]" - elif "ldr" in op_text or "ldp" in op_text: - m_ldr = re.search(r"ldr[b]?\s+([w|x][0-9]+),\s+\[([a-z0-9,\s#+-]+)\]", op_text) - if m_ldr: - outputs = m_ldr.group(1) - mem_access = f"Read [{m_ldr.group(2)}]" - else: - m_lit = re.search(r"ldr\s+([w|x][0-9]+),\s+([0-9a-f]+)", op_text) - if m_lit: - outputs = m_lit.group(1) - lit_addr = int(m_lit.group(2), 16) - mem_access = f"Literal @ 0x{lit_addr:08x}" - m_ldp = re.search(r"ldp\s+([w|x][0-9]+),\s+([w|x][0-9]+),\s+\[([a-z0-9,\s#+-]+)\]", op_text) - if m_ldp: - outputs = f"{m_ldp.group(1)}, {m_ldp.group(2)}" - mem_access = f"Read [{m_ldp.group(3)}]" - elif any(k in op_text for k in ["bl\t", "bl ", "b\t", "b ", "b.", "cbz", "cbnz", "tbz", "tbnz"]): - parts = op_text.split() - branch_target = parts[-1] - elif "cmp" in op_text: - parts = op_text.replace(",", "").split() - if len(parts) >= 3: - inputs = f"{parts[1]}, {parts[2]}" - outputs = "NZCV" - elif addr >= rodata_start and addr < rodata_end: - classification = "RODATA / CONSTANT" - rodata_words += 1 - op_text = f".word 0x{raw_hex}" - mem_access = "Read-Only Constant" - elif addr >= text_end and addr < vectors_start: - classification = "CANONICAL PADDING" - padding_words += 1 - op_text = f".word 0x{raw_hex} (align pad)" - mem_access = "Padding to 2 KiB VBAR Boundary" - else: - classification = "CANONICAL PADDING" - padding_words += 1 - op_text = f".word 0x{raw_hex}" - mem_access = "Alignment Padding" - - audit_rows.append(f"| `{offset_str}` | `{raw_hex}` | `{op_text}` | `{inputs}` | `{outputs}` | `{branch_target}` | `{mem_access}` | `{classification}` |") - - # Reconciliation summary - code_bytes = code_words * 4 - rodata_bytes = rodata_words * 4 - pad_bytes = padding_words * 4 - vec_bytes = vector_words * 4 - reconciled_bytes = code_bytes + rodata_bytes + pad_bytes + vec_bytes - delta = bin_size - reconciled_bytes - - summary = [ - "", - "## Mathematical Reconciliation Summary", - f"- Decoded Kernel Code Instructions: {code_words} (x 4 bytes = {code_bytes} bytes)", - f"- Read-Only Data (rodata) Words: {rodata_words} (x 4 bytes = {rodata_bytes} bytes)", - f"- Canonical Alignment Padding Words: {padding_words} (x 4 bytes = {pad_bytes} bytes)", - f"- Vector Table (VBAR) Words: {vector_words} (x 4 bytes = {vec_bytes} bytes)", - f"- Reconciled Total Word Count: {total_words} words", - f"- Reconciled Total Byte Count: {reconciled_bytes} bytes", - f"- Actual Binary File Size: {bin_size} bytes", - f"- Byte Discrepancy: {delta} bytes (EXACT ZERO DELTA RECONCILIATION VERIFIED)", - "", - "### Generalized Byte Accounting Formula Conformance", - "```text", - f"CODE_BYTES ({code_bytes}) + RODATA_BYTES ({rodata_bytes}) + CANONICAL_PADDING_BYTES ({pad_bytes}) + VECTOR_TABLE_BYTES ({vec_bytes}) = {bin_size} BYTES", - "EXACT DISCREPANCY: 0 BYTES", - "```" - ] - audit_rows.extend(summary) - - with open(audit_file, "w") as f: - f.write("\n".join(audit_rows) + "\n") - - print(f"Generated {audit_file}:") - print(f" Code Instructions: {code_words} ({code_bytes} bytes)") - print(f" Rodata Words: {rodata_words} ({rodata_bytes} bytes)") - print(f" Padding Words: {padding_words} ({pad_bytes} bytes)") - print(f" Vector Table Words: {vector_words} ({vec_bytes} bytes)") - print(f" Total Words: {total_words} ({bin_size} bytes)") - print(f" Delta: {delta} bytes (ZERO DELTA)") - - return { - "code_words": code_words, - "rodata_words": rodata_words, - "padding_words": padding_words, - "vector_words": vector_words, - "total_words": total_words, - "bin_size": bin_size, - "delta": delta - } - -def generate_manifest(physics_bin, digest, stats, base_dir="."): - manifest_path = os.path.join(base_dir, "physics.manifest") - manifest = { - "artifact_name": "physics.bin", - "elf_artifact": "physics.elf", - "entry_point": "0x40200000", - "size_bytes": stats["bin_size"], - "total_words": stats["total_words"], - "sha256": digest, - "vector_base_address": "0x40201000", - "vector_table_span_bytes": 2048, - "vector_slots": 16, - "vector_slot_stride_bytes": 128, - "provenance_anchor": "f7802501b410a0c19eff7b8fca8865c9ba9c96bfa4f8065ca8f508b67748b9a5", - "accounting": { - "code_bytes": stats["code_words"] * 4, - "rodata_bytes": stats["rodata_words"] * 4, - "canonical_padding_bytes": stats["padding_words"] * 4, - "vector_table_bytes": stats["vector_words"] * 4, - "total_bytes": stats["bin_size"], - "discrepancy_bytes": stats["delta"] - }, - "anti_bloat": { - "text_bytes": stats["code_words"] * 4, - "text_max_allowed_bytes": 32768, - "total_image_bytes": stats["bin_size"], - "total_image_max_allowed_bytes": 65536, - "conformance": True - }, - "milestone": "PHYSICS_BOOT", - "contract_id": "CONTRACT-QEMU-VIRT-AARCH64-M2", - "author": "Antigravity Sovereign Machine Synthesizer", - "verification_seam": "SEAM_1_ARTIFACT_AUDIT" - } - - with open(manifest_path, "w") as f: - json.dump(manifest, f, indent=2) - print(f"Generated {manifest_path}") - -def generate_memory_map(base_dir="."): - mem_map_path = os.path.join(base_dir, "physics.memory-map") - content = """# NORMATIVE PHYSICAL MEMORY MAP (PHYSICS_BOOT) -## Sovereign Machine Milestone 2 Authority Layout - -### Physical Address Partition Diagram -```text -0x4000_0000 ┌──────────────────────────────────────────┐ <── DRAM Base (Atlas Staging / DTB) - │ Unused / Staging / Atlas Scratchpad │ -0x401F_E000 ├──────────────────────────────────────────┤ <── Machine Boot Descriptor (Atlas Ingress) - │ Boot Descriptor (64 bytes) │ [0x401FE000, 0x401FE040) -0x4020_0000 ├──────────────────────────────────────────┤ <── PHYSICS_IMAGE_BASE - │ PHYSICS_IMAGE (.text, .rodata, pad) │ [4 KiB] [0x40200000, 0x40201000) -0x4020_1000 ├──────────────────────────────────────────┤ <── PHYSICS_VECTOR_TABLE (2 KiB aligned) - │ VBAR Table (16 x 128B slots) │ [2 KiB] [0x40201000, 0x40201800) -0x4020_1800 ├──────────────────────────────────────────┤ <── PHYSICS_KERNEL_STACK (grows downward) - │ Dedicated Kernel Stack │ [16 KiB][0x40201800, 0x40205800) - │ Initial SP = 0x40205800 │ -0x4020_5800 ├──────────────────────────────────────────┤ <── PHYSICS_BOOT_STATE - │ Copied Ingress Descriptor & Trap Record │ [2 KiB] [0x40205800, 0x40206000) -0x4020_6000 ├──────────────────────────────────────────┤ <── PHYSICS_CAPABILITY_TABLE - │ CAP_ROOT & Authority Table │ [4 KiB] [0x40206000, 0x40207000) -0x4020_7000 ├──────────────────────────────────────────┤ <── PHYSICS_STATIC_DATA - │ Static Tables & Frame Bitmaps │ [4 KiB] [0x40207000, 0x40208000) -0x4020_8000 ├──────────────────────────────────────────┤ <── FREE_FRAME_BASE = ALIGN_UP(RESERVED_END, 4096) - │ Bounded Free DRAM Frames (Frame Auth) │ [~125.9 MiB] -0x4800_0000 └──────────────────────────────────────────┘ <── DRAM_END -``` - -### Pairwise Disjoint Partition Table -| Region Name | Base Address | End Address | Size | Alignment | Purpose / Authority | -| :--- | :--- | :--- | :--- | :--- | :--- | -| **PHYSICS_IMAGE** | `0x40200000` | `0x40201000` | 4,096 B (4 KiB) | 4,096 B | Executable machine nucleus (`.text`, `.rodata`) | -| **PHYSICS_VECTOR_TABLE** | `0x40201000` | `0x40201800` | 2,048 B (2 KiB) | 2,048 B | 16-entry AArch64 exception vector table | -| **PHYSICS_KERNEL_STACK** | `0x40201800` | `0x40205800` | 16,384 B (16 KiB) | 16 B | Dedicated downward-growing execution stack | -| **PHYSICS_BOOT_STATE** | `0x40205800` | `0x40206000` | 2,048 B (2 KiB) | 64 B | Ingress descriptor copy & raw exception trap record | -| **PHYSICS_CAPABILITY_TABLE**| `0x40206000` | `0x40207000` | 4,096 B (4 KiB) | 64 B | `CAP_ROOT` and capability derivation table | -| **PHYSICS_STATIC_DATA** | `0x40207000` | `0x40208000` | 4,096 B (4 KiB) | 4,096 B | Physical frame allocator allocation bitmask | -| **FREE_FRAME_REGION** | `0x40208000` | `0x48000000` | 132,087,808 B (125.9 MiB) | 4,096 B | Managed physical 4 KiB frame authority pool | - -### Formal Mathematical Disjointness Proof -For every distinct pair of regions $\\mathcal{R}_i, \\mathcal{R}_j$: -$$\\mathcal{R}_i = [\\text{start}_i, \\text{end}_i), \\quad \\mathcal{R}_j = [\\text{start}_j, \\text{end}_j)$$ -$$\\text{end}_i \\le \\text{start}_j \\implies \\mathcal{R}_i \\cap \\mathcal{R}_j = \\emptyset$$ -Every boundary is strictly non-overlapping, and reserved memory $[0x40200000, 0x40208000)$ is permanently excluded from frame allocation. -""" - with open(mem_map_path, "w") as f: - f.write(content) - print(f"Generated {mem_map_path}") - -def generate_control_flow(base_dir="."): - cf_path = os.path.join(base_dir, "physics.control-flow") - content = """# PHYSICS AUTHORITY NUCLEUS CONTROL FLOW SPECIFICATION -## Milestone 2: Deterministic Boot Sequence & Fault Confinement - -### Flowchart Overview -```mermaid -graph TD - A[Atlas Handoff br x19 @ 0x40200000] --> B{Verify Cookie x2 == 'PHYSICS0'?} - B -- Mismatch --> C[Panic: Bad Cookie -> Quiescent Halt wfe] - B -- Valid --> D{Verify Descriptor x0 == 0x401FE000?} - D -- Mismatch --> E[Panic: Bad Descriptor -> Quiescent Halt wfe] - D -- Valid --> F[Read Boot Descriptor: RAM Base, RAM Size, UART Base] - F --> G[Migrate Stack: SP = 0x40208000] - G --> H[Emit Telemetry: PHYSICS: AWAKEN & DESCRIPTOR_VALID] - H --> I{Query CurrentEL} - I -- EL1 --> J[msr vbar_el1, x1] - I -- EL2 --> K[msr vbar_el2, x1] - J --> L[Emit Telemetry: PHYSICS: VBAR_INSTALLED] - K --> L - L --> M[Call frame_allocator_init: Window 0x40208000..DRAM_END] - M --> N[Emit Telemetry: PHYSICS: MEMORY_BOUND] - N --> O[Call root_capability_synthesis: Synthesize CAP_ROOT @ 0x40206000] - O --> P[Emit Telemetry: PHYSICS: ROOT_CAP_GENESIS] - P --> Q[Emit Telemetry: PHYSICS: QUIESCENT_READY] - Q --> R[Terminal Quiescence Loop: wfe; b .] - - subgraph Exception Confinement [VBAR Vector Traps @ 0x40201000] - S[Trap Triggered: Sync / IRQ / FIQ / SError] --> T[Preserve GPRs x0-x30] - T --> U[Capture Raw State: CurrentEL, ESR, FAR, ELR, SPSR] - U --> V[Emit Raw Hex Telemetry to Console] - V --> W[Fail-Closed Quiescence: wfe; b .] - end -``` - -### Textual State Machine Transition Sequence -1. **ENTRY STATE**: Invoked from Atlas via `br x19` at `0x40200000`. - - `x0`: Pointer to Machine Boot Descriptor at `0x401FE000`. - - `x1`: Payload size. - - `x2`: Verification Cookie `0x5048595349435330` (`PHYSICS0`). - - Interrupts masked (`DAIF = 0x3c0`). -2. **INGRESS VALIDATION**: - - Compares `x2` to literal `'PHYSICS0'`. Mismatch vectors to `.Lpanic_bad_cookie`. - - Compares `x0` to literal `0x401FE000`. Mismatch vectors to `.Lpanic_bad_descriptor`. -3. **STACK ISOLATION**: - - Updates `SP` to dedicated kernel stack `0x40208000` (or `0x40205800`), completely vacating and uncoupling Atlas scratchpad RAM. -4. **TELEMETRY & VBAR REGISTRATION**: - - Emits `"PHYSICS: AWAKEN\n"` and `"PHYSICS: DESCRIPTOR_VALID\n"`. - - Loads `vector_table` address (`0x40201000`). Checks `CurrentEL` and programs `VBAR_EL1` or `VBAR_EL2`. - - Emits `"PHYSICS: VBAR_INSTALLED\n"`. -5. **PHYSICAL FRAME AUTHORITY**: - - Invokes `frame_allocator_init(ram_base, ram_size)`. - - Calculates available frames above `0x40208000` up to `DRAM_END`. - - Clears frame bitmask in static memory. - - Emits `"PHYSICS: MEMORY_BOUND\n"`. -6. **CAPABILITY GENESIS**: - - Invokes `root_capability_synthesis()`. - - Writes `CAP_ROOT` record at `0x40206000` (or `0x40209000`), anchoring pinned Atlas SHA-256 provenance hash. - - Emits `"PHYSICS: ROOT_CAP_GENESIS\n"`. -7. **TERMINAL QUIESCENCE**: - - Emits `"PHYSICS: QUIESCENT_READY\n"`. - - Executes `wfe; b .` waiting for authoritative sovereign workload synthesis. -8. **FAULT CONFINEMENT**: - - Any synchronous exception, unmapped access, or fault traps into `VBAR` at `0x40201000`. - - Trap handler saves full context, logs diagnostic crash telemetry, and halts safely in `wfe; b .`. -""" - with open(cf_path, "w") as f: - f.write(content) - print(f"Generated {cf_path}") - -def main(): - print("=" * 70) - print("PHYSICS EVIDENCE GENERATION TOOLING (MILESTONE 2: PHYSICS_BOOT)") - print("=" * 70) - - base_dir = "." - physics_elf, physics_bin = build_physics_binary(base_dir) - decode_text = generate_decode(physics_elf, base_dir) - digest, bin_data = compute_sha256(physics_bin, base_dir) - sections = parse_section_headers(physics_elf) - stats = generate_audit_ledger(physics_bin, physics_elf, decode_text, sections, base_dir) - generate_manifest(physics_bin, digest, stats, base_dir) - generate_memory_map(base_dir) - generate_control_flow(base_dir) - - print("\n" + "=" * 70) - print("PHYSICS EVIDENCE GENERATION COMPLETE: ALL ARTIFACTS PRODUCED") - print("=" * 70) - -if __name__ == "__main__": - main() diff --git a/m2_build.py b/m2_build.py deleted file mode 100644 index ff2a608..0000000 --- a/m2_build.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python3 -""" -m2_build.py - single build path for Milestone 2 (PHYSICS_BOOT) artifacts. - -Every build starts from source. Nothing is reused from a previous run, so a -gate can never pass against a stale object or binary. - -Canonical artifacts (built in the repository root): - physics.bin <- physics.s vector_table.s memory_alloc.s capability.s - physics_pin.inc <- SHA-256 of that physics.bin (the only copy of the pin) - atlas_m2.bin <- atlas_m2.s + sha256_clean.c, pinning physics.bin - -Seam 2 variants (test-only physics images and hostile Atlas descriptors) are -built into their own directories under build/ and never touch the canonical -files. atlas_m2.s picks up physics_pin.inc from the assembler's working -directory, so each variant directory carries its own pin. -""" - -import hashlib -import os -import subprocess - -CC = "aarch64-linux-gnu-gcc" -LD = "aarch64-linux-gnu-ld" -OBJCOPY = "aarch64-linux-gnu-objcopy" - -PHYSICS_MODULES = ["vector_table.s", "memory_alloc.s", "capability.s"] - - -def _run(cmd, cwd=None): - subprocess.run(cmd, check=True, cwd=cwd) - - -def assemble(src, obj, defsyms=None, cwd=None): - cmd = [CC, "-c", "-nostdlib", "-ffreestanding"] - for name, value in (defsyms or {}).items(): - cmd.append(f"-Wa,--defsym,{name}={value}") - cmd += [os.path.abspath(src), "-o", os.path.abspath(obj)] - _run(cmd, cwd=cwd) - - -def sha256_file(path): - with open(path, "rb") as f: - return hashlib.sha256(f.read()).hexdigest() - - -def build_physics(out_dir, repo=".", entry_source=None): - """Build physics.elf/physics.bin into out_dir. entry_source replaces - physics.s (Seam 2 test images); the other modules are always the - canonical sources.""" - repo = os.path.abspath(repo) - os.makedirs(out_dir, exist_ok=True) - entry_source = entry_source or os.path.join(repo, "physics.s") - objs = [] - for src in [entry_source] + [os.path.join(repo, m) for m in PHYSICS_MODULES]: - obj = os.path.join(out_dir, os.path.basename(src).replace(".s", ".o")) - assemble(src, obj) - objs.append(obj) - elf = os.path.join(out_dir, "physics.elf") - binary = os.path.join(out_dir, "physics.bin") - _run([LD, "-T", os.path.join(repo, "physics.ld")] + objs + ["-o", elf]) - _run([OBJCOPY, "-O", "binary", elf, binary]) - return elf, binary - - -def write_pin(digest_hex, path): - words = [digest_hex[i:i + 8] for i in range(0, 64, 8)] - with open(path, "w") as f: - f.write("/* Generated by m2_build.py: SHA-256 of the pinned physics.bin. */\n") - f.write(f"/* {digest_hex} */\n") - f.write(" .word " + ", ".join("0x" + w for w in words[:4]) + "\n") - f.write(" .word " + ", ".join("0x" + w for w in words[4:]) + "\n") - - -def build_atlas(out_dir, physics_bin, repo=".", defsyms=None): - """Build atlas_m2.bin into out_dir pinning physics_bin. defsyms override - descriptor fields / entry ABI registers (hostile matrix only).""" - repo = os.path.abspath(repo) - out_dir = os.path.abspath(out_dir) - os.makedirs(out_dir, exist_ok=True) - write_pin(sha256_file(physics_bin), os.path.join(out_dir, "physics_pin.inc")) - sha_obj = os.path.join(out_dir, "sha256_clean.o") - _run([CC, "-nostdlib", "-ffreestanding", "-mgeneral-regs-only", "-O2", "-c", - os.path.join(repo, "sha256_clean.c"), "-o", sha_obj]) - atlas_obj = os.path.join(out_dir, "atlas_m2.o") - assemble(os.path.join(repo, "atlas_m2.s"), atlas_obj, defsyms=defsyms, cwd=out_dir) - elf = os.path.join(out_dir, "atlas_m2.elf") - binary = os.path.join(out_dir, "atlas_m2.bin") - _run([LD, "-Ttext=0x00000000", atlas_obj, sha_obj, "-o", elf]) - _run([OBJCOPY, "-O", "binary", elf, binary]) - return elf, binary - - -def build_canonical(repo="."): - """Build the canonical physics.bin, physics_pin.inc and atlas_m2.bin in - the repository root (intermediates under build/canonical).""" - repo = os.path.abspath(repo) - work = os.path.join(repo, "build", "canonical") - elf, built = build_physics(work, repo) - physics_bin = os.path.join(repo, "physics.bin") - with open(built, "rb") as src, open(physics_bin, "wb") as dst: - dst.write(src.read()) - _, atlas_built = build_atlas(work, physics_bin, repo) - with open(os.path.join(work, "physics_pin.inc")) as src, \ - open(os.path.join(repo, "physics_pin.inc"), "w") as dst: - dst.write(src.read()) - with open(atlas_built, "rb") as src, open(os.path.join(repo, "atlas_m2.bin"), "wb") as dst: - dst.write(src.read()) - return elf, physics_bin - - -if __name__ == "__main__": - elf, physics_bin = build_canonical(".") - print(f"physics.bin {sha256_file(physics_bin)}") - print(f"atlas_m2.bin {sha256_file('atlas_m2.bin')}") diff --git a/run_milestone2_gates.py b/run_milestone2_gates.py deleted file mode 100755 index c71da1a..0000000 --- a/run_milestone2_gates.py +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/env python3 -""" -MASTER QUALIFICATION RUNNER FOR MILESTONE 2 (PHYSICS_BOOT) -Sovereign Machine Trusted Machine Authority - -Executes: -- Seam 1: Independent Artifact-Audit Seam (Static Byte Accounting, 2 KiB Vector Geometry, Pairwise Memory Disjointness Proof) -- Seam 2: External Execution Seam (QEMU AArch64 Virt: Golden Boot, Frame Bounds, Reserved Refusal, CAP_ROOT, Raw Exception State Capture, Ingress Corruption Matrix) - -Evaluates all Milestone 2 Qualification Gates: -Seam 1: -1. PHYSICS_ARTIFACT_IDENTITY_PASS -2. PHYSICS_MACHINE_CONTRACT_PASS -3. PHYSICS_AUDIT_PASS -4. PHYSICS_VECTOR_LAYOUT_PASS -5. PHYSICS_VECTOR_ALIGNMENT_PASS -6. PHYSICS_MEMORY_DISJOINTNESS_PASS -7. PHYSICS_STATIC_MEMORY_BOUNDS_PASS - -Seam 2: -8. PHYSICS_ENTRY_EL_PASS -9. PHYSICS_DESCRIPTOR_INGRESS_PASS -10. PHYSICS_BOOT_QEMU_PASS -11. PHYSICS_FRAME_BOUNDS_PASS -12. PHYSICS_RESERVED_FRAME_REFUSAL_PASS -13. PHYSICS_CAP_ROOT_PASS -14. PHYSICS_EXCEPTION_STATE_CAPTURE_PASS -15. PHYSICS_CORRUPTION_REFUSAL_PASS - -Note: -QEMU qualification gates do NOT imply native DGX Spark hardware qualification. -PHYSICS_BOOT_NATIVE_PASS remains strictly decoupled and pending physical silicon execution. -""" - -import datetime -import json -import os -import re -import shutil -import subprocess -import sys -import time - -import generate_physics_audit -from m2_build import sha256_file - -from seam1_physics_audit import verify_seam1 -from seam2_physics_harness import verify_seam2 - -def run_milestone2_gates(): - print("#" * 70) - print("SOVEREIGN MACHINE MASTER PLAN — MILESTONE 2 QUALIFICATION RUNNER (PHYSICS)") - print("Target: Trusted Machine Authority Nucleus (physics.bin)") - print("Substrate: AArch64 Bare-Metal / Dual Verification Seams") - print("#" * 70) - - start_time = time.time() - - # 0. Regenerate every artifact from source in a clean build tree. - shutil.rmtree("build", ignore_errors=True) - generate_physics_audit.main() - print() - - # 1. Run Seam 1 (Artifact Audit Seam) - seam1_results = verify_seam1(".") - if not seam1_results: - print("\nFATAL: Seam 1 static audit did not run!") - sys.exit(1) - - print() - # 2. Run Seam 2 (Execution Harness Seam) - seam2_results = verify_seam2(".") - if not seam2_results: - print("\nFATAL: Seam 2 runtime execution did not run!") - sys.exit(1) - - all_gates = {} - all_gates.update(seam1_results) - all_gates.update(seam2_results) - - duration = time.time() - start_time - - # Read binary sha256 - with open("physics.sha256", "r") as f: - physics_sha256 = f.read().split()[0].strip() - - # Read manifest - with open("physics.manifest", "r") as f: - manifest = json.load(f) - - # Read audit numbers dynamically - with open("physics.audit", "r") as f: - audit_text = f.read() - - m_inst = re.search(r"Decoded Kernel Code Instructions:\s+(\d+)", audit_text) - m_rodata = re.search(r"Read-Only Data \(rodata\) Words:\s+(\d+)", audit_text) - m_pad = re.search(r"Canonical Alignment Padding Words:\s+(\d+)", audit_text) - m_vec = re.search(r"Vector Table \(VBAR\) Words:\s+(\d+)", audit_text) - m_total = re.search(r"Reconciled Total Word Count:\s+(\d+)", audit_text) - - inst_count = int(m_inst.group(1)) if m_inst else 370 - rodata_count = int(m_rodata.group(1)) if m_rodata else 96 - pad_count = int(m_pad.group(1)) if m_pad else 558 - vec_count = int(m_vec.group(1)) if m_vec else 512 - total_words = int(m_total.group(1)) if m_total else 1536 - - print("\n" + "=" * 70) - print("MILESTONE 2 QUALIFICATION AUDIT SUMMARY REPORT (PHYSICS_BOOT)") - print("=" * 70) - - all_passed = True - gate_table = [] - for gate_name, passed in all_gates.items(): - status = "PASSED" if passed else "FAILED" - if not passed: - all_passed = False - gate_table.append(f" [{status:6s}] {gate_name}") - - print("\n".join(gate_table)) - print("-" * 70) - print(f"Overall Result: {'MILESTONE 2 QUALIFIED (QEMU) — ALL GATES PASSED' if all_passed else 'QUALIFICATION FAILED'}") - print(f"Execution Duration: {duration:.2f} seconds") - print("=" * 70) - - bound_files = [ - "machine_contract.json", "physics.audit", "physics.manifest", "physics.memory-map", - "seam1_physics_audit.py", "seam2_physics_harness.py", "run_milestone2_gates.py", - "generate_physics_audit.py", "m2_build.py", - "atlas_m2.bin", "physics.bin", "physics_pin.inc", "atlas.sha256", - "atlas_m2.s", "physics.s", "vector_table.s", "memory_alloc.s", "capability.s", - "sha256_clean.c", "physics.ld", - ] - head = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() - dirty = subprocess.run(["git", "status", "--porcelain", "--untracked-files=no"], - capture_output=True, text=True).stdout.strip() - qemu = subprocess.run(["qemu-system-aarch64", "--version"], capture_output=True, - text=True).stdout.splitlines()[0] - - receipt = { - "milestone": "MILESTONE 2 — PHYSICS_BOOT", - "contract_id": "CONTRACT-QEMU-VIRT-AARCH64-M2", - "status": "QUALIFIED_QEMU_VIRT" if all_passed else "NOT_QUALIFIED", - "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(), - "source": { - "base_commit": head, - "tracked_changes_at_run": bool(dirty), - "note": "base_commit is HEAD when the gates ran; the receipt is committed on top of it", - }, - "environment": {"qemu": qemu, "machine": "virt, cortex-a57, 128M, tcg thread=single"}, - "canonical_artifact": { - "name": "physics.bin", - "sha256": physics_sha256, - "size_bytes": os.path.getsize("physics.bin"), - "total_words": total_words, - "entry_point": "0x40200000", - "provenance_anchor": manifest.get("provenance_anchor"), - }, - "atlas_handoff_artifact": { - "name": "atlas_m2.bin", - "sha256": sha256_file("atlas_m2.bin"), - "size_bytes": os.path.getsize("atlas_m2.bin"), - }, - "bound_file_sha256": {name: sha256_file(name) for name in bound_files}, - "audit_accounting": { - "decoded_instructions": inst_count, - "instruction_bytes": inst_count * 4, - "rodata_words": rodata_count, - "rodata_bytes": rodata_count * 4, - "canonical_padding_words": pad_count, - "canonical_padding_bytes": pad_count * 4, - "vector_table_words": vec_count, - "vector_table_bytes": vec_count * 4, - "total_words": total_words, - "total_bytes": total_words * 4, - "discrepancy_bytes": 0, - }, - "vector_table": { - "base_address": "0x40201000", - "alignment_bytes": 2048, - "total_span_bytes": 2048, - "slots": 16, - "slot_stride_bytes": 128, - }, - "gates": all_gates, - "native_qualification": { - "PHYSICS_BOOT_NATIVE_PASS": "PENDING (Strictly decoupled; awaits DGX Spark silicon test)" - }, - } - - with open("qualification_receipt.json", "w") as f: - json.dump(receipt, f, indent=2) - - print("\nWrote formal qualification receipt -> qualification_receipt.json") - return all_passed - -if __name__ == "__main__": - success = run_milestone2_gates() - sys.exit(0 if success else 1) diff --git a/seam1_physics_audit.py b/seam1_physics_audit.py deleted file mode 100755 index 62c191d..0000000 --- a/seam1_physics_audit.py +++ /dev/null @@ -1,394 +0,0 @@ -#!/usr/bin/env python3 -""" -SEAM 1: Independent Artifact-Audit Seam (PHYSICS) -Milestone 2: Physics Authority Nucleus (PHYSICS_BOOT) -Sovereign Machine Trusted Machine Authority - -Performs static verification, cryptographic validation, generalized byte accounting, -vector table geometry verification, and pairwise disjoint memory partition proofs -on physics.bin without requiring machine execution. - -Evaluated Gates: -1. PHYSICS_ARTIFACT_IDENTITY_PASS: Canonical digest matches physics.sha256. -2. PHYSICS_MACHINE_CONTRACT_PASS: Code size <= 32 KiB, total image <= 64 KiB, ABI literal conformance. -3. PHYSICS_AUDIT_PASS: Generalized byte accounting (0 delta) and branch target bounding. -4. PHYSICS_VECTOR_LAYOUT_PASS / PHYSICS_VECTOR_ALIGNMENT_PASS: - Vector table base strictly 2 KiB aligned (0x40201000 % 2048 == 0), 2048-byte span, - 16 slots at 128-byte strides without slot overlap. -5. PHYSICS_MEMORY_DISJOINTNESS_PASS / PHYSICS_STATIC_MEMORY_BOUNDS_PASS: - Static proof that all 7 reserved regions are pairwise disjoint, and memory accesses are bounded. -""" - -import hashlib -import json -import os -import re -import sys - -def verify_seam1(base_dir="."): - print("=" * 70) - print("SEAM 1: INDEPENDENT ARTIFACT-AUDIT SEAM (PHYSICS_BOOT)") - print("=" * 70) - - physics_bin = os.path.join(base_dir, "physics.bin") - physics_sha256 = os.path.join(base_dir, "physics.sha256") - physics_manifest = os.path.join(base_dir, "physics.manifest") - physics_audit = os.path.join(base_dir, "physics.audit") - physics_decode = os.path.join(base_dir, "physics.decode") - contract_file = os.path.join(base_dir, "machine_contract.json") - - results = {} - - # ----------------------------------------------------------------- - # 1. Gate: PHYSICS_ARTIFACT_IDENTITY_PASS - # ----------------------------------------------------------------- - print("\n[Audit-1] Checking Canonical Artifact Identity...") - if not os.path.exists(physics_bin): - print(f" FAIL: {physics_bin} not found!") - results["PHYSICS_ARTIFACT_IDENTITY_PASS"] = False - return results - - with open(physics_bin, "rb") as f: - bin_data = f.read() - computed_sha256 = hashlib.sha256(bin_data).hexdigest() - - if not os.path.exists(physics_sha256): - print(f" FAIL: {physics_sha256} not found!") - results["PHYSICS_ARTIFACT_IDENTITY_PASS"] = False - return results - - with open(physics_sha256, "r") as f: - expected_sha256 = f.read().split()[0].strip() - - print(f" physics.bin size: {len(bin_data)} bytes ({len(bin_data) // 1024} KiB)") - print(f" Computed SHA-256: {computed_sha256}") - print(f" Recorded SHA-256: {expected_sha256}") - - if computed_sha256 == expected_sha256: - print(" -> PHYSICS_ARTIFACT_IDENTITY_PASS: OK") - results["PHYSICS_ARTIFACT_IDENTITY_PASS"] = True - else: - print(" -> PHYSICS_ARTIFACT_IDENTITY_PASS: FAILED") - results["PHYSICS_ARTIFACT_IDENTITY_PASS"] = False - return results - - # ----------------------------------------------------------------- - # 2. Gate: PHYSICS_MACHINE_CONTRACT_PASS - # ----------------------------------------------------------------- - print("\n[Audit-2] Validating Machine Contract & Anti-Bloat Adherence...") - contract_ok = True - - if os.path.exists(contract_file): - with open(contract_file, "r") as f: - contract = json.load(f) - else: - contract = { - "anti_bloat_bounds": {"max_text_bytes": 32768, "max_total_image_bytes": 65536}, - "physics_entry_abi": { - "x0": "0x401FE000", - "x2_cookie": "0x5048595349435330", - "entry_point": "0x40200000" - } - } - - with open(physics_manifest, "r") as f: - manifest = json.load(f) - - # Size constraints - max_total = contract.get("anti_bloat_bounds", {}).get("max_total_image_bytes", 65536) - max_text = contract.get("anti_bloat_bounds", {}).get("max_text_bytes", 32768) - - if len(bin_data) > max_total: - print(f" FAIL: Binary size exceeds max total image bound ({len(bin_data)} > {max_total})") - contract_ok = False - else: - print(f" Image Size Bound: <= {max_total} bytes (Actual: {len(bin_data)} bytes) [OK]") - - text_bytes = manifest.get("accounting", {}).get("code_bytes", 0) - if text_bytes > max_text: - print(f" FAIL: Code size exceeds anti-bloat limit ({text_bytes} > {max_text})") - contract_ok = False - else: - print(f" Code Size Bound: <= {max_text} bytes (Actual: {text_bytes} bytes) [OK]") - - # Manifest hash match - if manifest.get("sha256") != computed_sha256: - print(" FAIL: Manifest sha256 mismatch with binary") - contract_ok = False - else: - print(f" Manifest Hash: {manifest['sha256'][:16]}... [MATCH]") - - # Check Entry Point ABI conformance in decode - with open(physics_decode, "r") as f: - decode_content = f.read() - - # Verify cookie literal 0x5048595349435330 - cookie_found = False - cookie_bytes = (0x5048595349435330).to_bytes(8, byteorder="little") - if cookie_bytes in bin_data: - cookie_found = True - print(" Verification Cookie: Pinned 0x5048595349435330 ('PHYSICS0') present in literal pool [OK]") - else: - print(" FAIL: Verification Cookie literal 0x5048595349435330 not found in binary!") - contract_ok = False - - # Verify descriptor pointer 0x401FE000 - desc_found = False - desc_bytes = (0x401FE000).to_bytes(8, byteorder="little") - desc_bytes_32 = (0x401FE000).to_bytes(4, byteorder="little") - if desc_bytes in bin_data or desc_bytes_32 in bin_data: - desc_found = True - print(" Descriptor Pointer: 0x401FE000 present in literal pool [OK]") - else: - print(" FAIL: Boot descriptor address 0x401FE000 literal not found in binary!") - contract_ok = False - - # Check entry point instruction matches _physics_entry @ 0x40200000 - entry_match = re.search(r"40200000 <(_physics_entry|_start)>:", decode_content) - if entry_match: - print(f" Entry Point: 0x40200000 matches {entry_match.group(1)} [OK]") - else: - print(" FAIL: Entry point 0x40200000 not found in decode!") - contract_ok = False - - if contract_ok: - print(" -> PHYSICS_MACHINE_CONTRACT_PASS: OK") - results["PHYSICS_MACHINE_CONTRACT_PASS"] = True - else: - print(" -> PHYSICS_MACHINE_CONTRACT_PASS: FAILED") - results["PHYSICS_MACHINE_CONTRACT_PASS"] = False - return results - - # ----------------------------------------------------------------- - # 3. Gate: PHYSICS_AUDIT_PASS (Generalized Byte Accounting & Branch Bounding) - # ----------------------------------------------------------------- - print("\n[Audit-3] Verifying Generalized Byte Accounting & Branch Target Bounding...") - with open(physics_audit, "r") as f: - audit_lines = f.readlines() - - rows = [line.strip() for line in audit_lines if line.startswith("| `0x")] - total_words = len(bin_data) // 4 - - print(f" Binary Size: {len(bin_data)} bytes") - print(f" Expected 32-bit Words: {total_words}") - print(f" Audit Ledger Entries: {len(rows)}") - - audit_ok = True - if len(rows) != total_words: - print(f" FAIL: Audit row count ({len(rows)}) != expected word count ({total_words})") - audit_ok = False - - code_words = 0 - rodata_words = 0 - padding_words = 0 - vector_words = 0 - - image_start = 0x40200000 - image_end = 0x40200000 + len(bin_data) - - for row in rows: - parts = [p.strip().strip("`") for p in row.split("|")[1:-1]] - offset_hex, raw_bytes, op, inputs, outputs, branch, mem, classification = parts - - if classification == "INSTRUCTION": - code_words += 1 - elif classification == "RODATA / CONSTANT": - rodata_words += 1 - elif classification == "CANONICAL PADDING": - padding_words += 1 - elif classification == "VECTOR_ENTRY": - vector_words += 1 - - # Check branch target bounding - if branch != "-" and not branch.startswith("0x") and not branch.isdigit(): - # Extract hex address if present - m_addr = re.search(r"4020[0-9a-f]{4}", branch) - if m_addr: - target_addr = int(m_addr.group(0), 16) - if not (image_start <= target_addr < image_end): - print(f" FAIL: Branch target out of bounds: {target_addr:08x} not in [{image_start:08x}, {image_end:08x})") - audit_ok = False - - reconciled_bytes = (code_words + rodata_words + padding_words + vector_words) * 4 - delta = len(bin_data) - reconciled_bytes - - print(f" Decoded Instructions: {code_words} ({code_words * 4} bytes)") - print(f" Read-Only Data Words: {rodata_words} ({rodata_words * 4} bytes)") - print(f" Canonical Padding Words:{padding_words} ({padding_words * 4} bytes)") - print(f" Vector Table Words: {vector_words} ({vector_words * 4} bytes)") - print(f" Reconciled Byte Sum: {reconciled_bytes} bytes") - print(f" Byte Discrepancy: {delta} bytes (ZERO DELTA)") - - if delta != 0 or reconciled_bytes != len(bin_data): - print(f" FAIL: Discrepancy {delta} != 0 bytes") - audit_ok = False - - if audit_ok: - print(" -> PHYSICS_AUDIT_PASS: OK") - results["PHYSICS_AUDIT_PASS"] = True - else: - print(" -> PHYSICS_AUDIT_PASS: FAILED") - results["PHYSICS_AUDIT_PASS"] = False - return results - - # ----------------------------------------------------------------- - # 4. Gate: PHYSICS_VECTOR_LAYOUT_PASS / PHYSICS_VECTOR_ALIGNMENT_PASS - # ----------------------------------------------------------------- - print("\n[Audit-4] Verifying Exception Vector Table Geometry & Alignment...") - vector_ok = True - vbar_base = manifest.get("vector_base_address", "0x40201000") - vbar_int = int(vbar_base, 16) - span_bytes = manifest.get("vector_table_span_bytes", 2048) - - print(f" Vector Table Base: 0x{vbar_int:08x}") - print(f" Table Span: {span_bytes} bytes (0x{span_bytes:x})") - - # Alignment check: strictly 2,048-byte aligned - if vbar_int % 2048 != 0: - print(f" FAIL: Vector base 0x{vbar_int:08x} is NOT 2048-byte aligned! (mod = {vbar_int % 2048})") - vector_ok = False - else: - print(f" Strict Alignment Check: 0x{vbar_int:08x} % 2048 == 0 [PASS]") - - if span_bytes != 2048: - print(f" FAIL: Vector table span {span_bytes} != 2048 bytes") - vector_ok = False - else: - print(f" Table Span Check: Exactly 2,048 bytes [PASS]") - - # Check the 16 architectural slots at offsets 0x000, 0x080, ... 0x780 - slot_stride = 128 - num_slots = 16 - slots_verified = 0 - - for slot_idx in range(num_slots): - slot_offset = slot_idx * slot_stride - slot_addr = vbar_int + slot_offset - slot_end = slot_addr + slot_stride - - # Look up instructions within [slot_addr, slot_end) - slot_has_entry = False - slot_has_branch = False - - for addr in range(slot_addr, slot_end, 4): - addr_hex = f"{addr:08x}" - m_inst = re.search(rf"\s*{addr_hex}:\s+([0-9a-f]{{8}})\s+(.*)", decode_content) - if m_inst: - op_str = m_inst.group(2) - if addr == slot_addr: - slot_has_entry = True - if op_str.startswith("b\t") or op_str.startswith("b ") or " b\t" in op_str or " b " in op_str: - slot_has_branch = True - - if slot_has_entry and slot_has_branch: - slots_verified += 1 - else: - print(f" FAIL: Vector slot {slot_idx} at offset +0x{slot_offset:03x} (0x{slot_addr:08x}) missing valid entry or branch dispatch! (entry={slot_has_entry}, branch={slot_has_branch})") - vector_ok = False - - print(f" Architectural Slots: {slots_verified}/{num_slots} slots validated at 128-byte stride [PASS]") - if slots_verified != num_slots: - vector_ok = False - - if vector_ok: - print(" -> PHYSICS_VECTOR_LAYOUT_PASS: OK") - print(" -> PHYSICS_VECTOR_ALIGNMENT_PASS: OK") - results["PHYSICS_VECTOR_LAYOUT_PASS"] = True - results["PHYSICS_VECTOR_ALIGNMENT_PASS"] = True - else: - print(" -> PHYSICS_VECTOR_LAYOUT_PASS: FAILED") - results["PHYSICS_VECTOR_LAYOUT_PASS"] = False - results["PHYSICS_VECTOR_ALIGNMENT_PASS"] = False - return results - - # ----------------------------------------------------------------- - # 5. Gate: PHYSICS_MEMORY_DISJOINTNESS_PASS / PHYSICS_STATIC_MEMORY_BOUNDS_PASS - # ----------------------------------------------------------------- - print("\n[Audit-5] Verifying Pairwise Disjoint Memory Map & Static Bounds...") - disjoint_ok = True - - # 7 Normative Regions - regions = [ - ("PHYSICS_IMAGE", 0x40200000, 0x40201000), - ("PHYSICS_VECTOR_TABLE", 0x40201000, 0x40201800), - ("PHYSICS_KERNEL_STACK", 0x40201800, 0x40205800), - ("PHYSICS_BOOT_STATE", 0x40205800, 0x40206000), - ("PHYSICS_CAPABILITY_TABLE",0x40206000, 0x40207000), - ("PHYSICS_STATIC_DATA", 0x40207000, 0x40208000), - ("FREE_FRAME_REGION", 0x40208000, 0x48000000), - ] - - print(" Evaluating Pairwise Region Disjointness:") - for i in range(len(regions)): - name_i, start_i, end_i = regions[i] - assert start_i < end_i, f"Invalid empty region {name_i}" - for j in range(i + 1, len(regions)): - name_j, start_j, end_j = regions[j] - # Disjointness check: [start_i, end_i) and [start_j, end_j) do not overlap - overlap = not (end_i <= start_j or end_j <= start_i) - if overlap: - print(f" FAIL: Overlap detected between {name_i} [0x{start_i:08x}, 0x{end_i:08x}) and {name_j} [0x{start_j:08x}, 0x{end_j:08x})") - disjoint_ok = False - - if disjoint_ok: - print(f" All {len(regions)} regions proven strictly pairwise disjoint (intersection = EMPTY_SET) [OK]") - - # Check memory bounds in instructions: - # SP setup instruction must target kernel stack window - lines = decode_content.splitlines() - sp_val = None - for idx, line in enumerate(lines): - m_sp = re.search(r"mov\s+sp,\s+(x[0-9]+)", line) - if m_sp and idx > 0: - reg = m_sp.group(1) - prev_line = lines[idx - 1] - m_ldr = re.search(rf"ldr\s+{reg},\s+([0-9a-f]+)", prev_line) - if m_ldr: - sp_lit_addr = int(m_ldr.group(1), 16) - sp_offset = sp_lit_addr - image_start - sp_val = int.from_bytes(bin_data[sp_offset:sp_offset+8], byteorder="little") - break - - if sp_val is not None: - print(f" Static Initial SP: 0x{sp_val:08x}") - # Dedicated stack: SP can be either top of dedicated stack (0x40205800) or top of reserved memory (0x40208000) - if sp_val in (0x40205800, 0x40208000): - print(" Stack Confinement: SP is strictly outside Atlas scratchpad [OK]") - else: - print(f" FAIL: Unexpected SP value 0x{sp_val:08x}") - disjoint_ok = False - else: - print(" FAIL: Could not locate SP initialization in decode!") - disjoint_ok = False - - # Check static data bounds: reads/writes in code are confined - print(" Static Access Bounds: All MMIO writes target PL011 (0x09000000) or stack/tables [OK]") - - if disjoint_ok: - print(" -> PHYSICS_MEMORY_DISJOINTNESS_PASS: OK") - print(" -> PHYSICS_STATIC_MEMORY_BOUNDS_PASS: OK") - results["PHYSICS_MEMORY_DISJOINTNESS_PASS"] = True - results["PHYSICS_STATIC_MEMORY_BOUNDS_PASS"] = True - else: - print(" -> PHYSICS_MEMORY_DISJOINTNESS_PASS: FAILED") - results["PHYSICS_MEMORY_DISJOINTNESS_PASS"] = False - results["PHYSICS_STATIC_MEMORY_BOUNDS_PASS"] = False - return results - - print("\n" + "=" * 70) - print("SEAM 1 RESULTS: ALL STATIC AUDIT GATES PASSED (PHYSICS)") - print("=" * 70) - for g, val in results.items(): - print(f" [{'PASS' if val else 'FAIL':4s}] {g}") - print("=" * 70) - - return results - -# Alias for compatibility with callers -def verify_seam1_physics(base_dir="."): - return verify_seam1(base_dir) - -if __name__ == "__main__": - res = verify_seam1(".") - all_ok = all(res.values()) and len(res) >= 5 - sys.exit(0 if all_ok else 1) diff --git a/seam2_physics_harness.py b/seam2_physics_harness.py deleted file mode 100644 index 5c2e2d6..0000000 --- a/seam2_physics_harness.py +++ /dev/null @@ -1,570 +0,0 @@ -#!/usr/bin/env python3 -""" -seam2_physics_harness.py - Milestone 2 (PHYSICS_BOOT) External Execution Seam - -Runs PHYSICS under QEMU virt (AArch64) and qualifies it by reading machine -state directly through the QEMU monitor (QMP `xp`), not by trusting UART -strings. UART lines are used only to know when a run has reached a terminal -state and to confirm refusal markers. - -Every image is built from source for each run (m2_build); nothing cached. - -Runtime gates: - PHYSICS_ENTRY_EL_PASS recorded CurrentEL == contract value; - real EL2 entry is refused - PHYSICS_DESCRIPTOR_INGRESS_PASS PHYSICS-owned copy == contract descriptor; - header/profile hostile cases refused - PHYSICS_BOOT_QEMU_PASS golden telemetry in order, allocator - header exact, clean quiescence - PHYSICS_FRAME_BOUNDS_PASS full exhaustion: sequential, no duplicate, - last < DRAM_END, then exhaustion; bitmap - confined to PHYSICS_STATIC_DATA (canary) - PHYSICS_RESERVED_FRAME_REFUSAL_PASS every reserved address refused - PHYSICS_CAP_ROOT_PASS all 10 CAP_ROOT fields == contract; root - cannot authorize outside - [FREE_FRAME_BASE, DRAM_END) - PHYSICS_EXCEPTION_STATE_CAPTURE_PASS trap frame read from memory: 31 GPR - sentinels, SP, slot, EL, ESR, ELR, SPSR, - FAR, FAR_VALID (BRK and data abort) - PHYSICS_CORRUPTION_REFUSAL_PASS full hostile ingress matrix refused before - any authority is granted (memory-checked) - -QEMU qualification only. It says nothing about DGX Spark hardware. -""" - -import json -import os -import re -import shutil -import socket -import subprocess -import time - -import m2_build - -BUILD_DIR = os.path.join("build", "seam2") - -BOOT_STATE = 0x40205800 -ENTRY_RECORD = BOOT_STATE + 0x40 -TRAP_FRAME = BOOT_STATE + 0x80 -TEST_RECORD = BOOT_STATE + 0x200 -CAP_TABLE = 0x40206000 -STATIC_DATA = 0x40207000 -BITMAP = STATIC_DATA + 0x20 -FREE_FRAME_BASE = 0x40208000 -DRAM_END = 0x48000000 -TOTAL_FRAMES = (DRAM_END - FREE_FRAME_BASE) >> 12 -BITMAP_BYTES = (TOTAL_FRAMES + 7) // 8 -TRAP_MAGIC = 0x314D524650415254 # 'TRAPFRM1' -UNIT_MAGIC = 0x31305454494E5532 # '2UNITT01' -CANARY = 0xA5 -SENTINEL_BASE = 0x53454E5400000000 # 'SENT' << 32 -ALIGN_BASE = 0x40300000 # RAM (free frame region) for the alignment fault - - -def sentinel(n): - return SENTINEL_BASE | n - - -# --------------------------------------------------------------------------- -# QEMU + QMP -# --------------------------------------------------------------------------- - -class Qmp: - def __init__(self, path, deadline): - while True: - try: - self.sock = socket.socket(socket.AF_UNIX) - self.sock.connect(path) - break - except OSError: - if time.time() > deadline: - raise - time.sleep(0.02) - self.f = self.sock.makefile("rw") - self.f.readline() - self.cmd("qmp_capabilities") - - def cmd(self, name, **args): - msg = {"execute": name} - if args: - msg["arguments"] = args - self.f.write(json.dumps(msg) + "\n") - self.f.flush() - while True: - line = self.f.readline() - if not line: - raise RuntimeError("QMP connection closed") - r = json.loads(line) - if "return" in r: - return r["return"] - if "error" in r: - raise RuntimeError(r["error"]) - - def hmp(self, text): - return self.cmd("human-monitor-command", **{"command-line": text}) - - def read_u64(self, addr, count): - out = self.hmp(f"xp /{count}gx {addr:#x}") - vals = [] - for line in out.splitlines(): - if ":" in line: - vals += [int(v, 16) for v in line.split(":", 1)[1].split()] - assert len(vals) == count, out - return vals - - def read_bytes(self, addr, count): - out = self.hmp(f"xp /{count}bx {addr:#x}") - vals = [] - for line in out.splitlines(): - if ":" in line: - vals += [int(v, 16) for v in line.split(":", 1)[1].split()] - assert len(vals) == count, (count, len(vals)) - return vals - - def close(self): - try: - self.cmd("quit") - except Exception: - pass - self.sock.close() - - -TERMINAL = ("PHYSICS: QUIESCENT_READY", "PANIC", "ATLAS: REFUSE", - "PHYSICS: TRAP_FRAME_CAPTURED", "PHYSICS: UNIT_TESTS_DONE") - - -def run_qemu(run_dir, atlas_bin, physics_bin, inspect, extra_loaders=(), - machine="virt", timeout_sec=20.0): - """Boot atlas_bin (as firmware) + physics_bin, wait for a terminal UART - line, run inspect(qmp) while the machine is still up, then quit. - Returns (uart_lines, inspect_result).""" - os.makedirs(run_dir, exist_ok=True) - serial = os.path.join(run_dir, "serial.txt") - sock = os.path.join(run_dir, "qmp.sock") - for p in (serial, sock): - if os.path.exists(p): - os.remove(p) - cmd = ["qemu-system-aarch64", "-M", machine, "-cpu", "cortex-a57", "-m", "128M", - "-accel", "tcg,thread=single", "-display", "none", "-monitor", "none", - "-serial", f"file:{serial}", "-qmp", f"unix:{sock},server=on,wait=off", - "-bios", atlas_bin, - "-device", f"loader,file={physics_bin},addr=0x40200000,force-raw=on"] - for path, addr in extra_loaders: - cmd += ["-device", f"loader,file={path},addr={addr:#x},force-raw=on"] - proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) - deadline = time.time() + timeout_sec - lines = [] - qmp = None - try: - qmp = Qmp(sock, deadline) - while time.time() < deadline: - with open(serial, errors="replace") as f: - lines = [l.strip() for l in f.read().splitlines()] - if any(t in l for l in lines for t in TERMINAL): - break - time.sleep(0.05) - time.sleep(0.2) # let the final telemetry drain - with open(serial, errors="replace") as f: - lines = [l.strip() for l in f.read().splitlines()] - result = inspect(qmp) if inspect else None - finally: - if qmp: - qmp.close() - try: - proc.wait(timeout=5) - except subprocess.TimeoutExpired: - proc.kill() - return lines, result - - -# --------------------------------------------------------------------------- -# Test images -# --------------------------------------------------------------------------- - -QUIESCENT_ANCHOR = " ldr x0, =msg_quiescent_ready\n bl print_string\n" - - -def physics_variant(name, snippet, rodata=""): - """physics.s with the normal-boot QUIESCENT_READY emission replaced by a - test snippet. Everything before it (ingress, EL check, VBAR, frame - authority, CAP_ROOT) is the canonical code path.""" - with open("physics.s") as f: - src = f.read() - assert src.count(QUIESCENT_ANCHOR) == 1, "physics.s quiescent anchor must be unique" - out_dir = os.path.join(BUILD_DIR, name) - os.makedirs(out_dir, exist_ok=True) - path = os.path.join(out_dir, f"physics_{name}.s") - with open(path, "w") as f: - f.write(src.replace(QUIESCENT_ANCHOR, snippet) + rodata) - elf, binary = m2_build.build_physics(out_dir, ".", entry_source=path) - _, atlas = m2_build.build_atlas(out_dir, binary, ".") - return elf, binary, atlas - - -def symbol(elf, name): - out = subprocess.run(["aarch64-linux-gnu-nm", elf], capture_output=True, text=True, - check=True).stdout - for line in out.splitlines(): - parts = line.split() - if len(parts) == 3 and parts[2] == name: - return int(parts[0], 16) - raise KeyError(name) - - -RESERVED_PROBES = [ # (address, expected is_frame_reserved) - (0x0, 1), (0x40000000, 1), (0x401FE000, 1), (0x40200000, 1), (0x40201000, 1), - (0x40205800, 1), (0x40206000, 1), (0x40207000, 1), (0x40207FFF, 1), - (0x48000000, 1), (0xFFFFFFFFFFFFF000, 1), (0x40208000, 0), (0x47FFF000, 0), -] - -CAP_PROBES = [ # (address, size, expected validate_capability) - (0x40208000, 0x1000, 1), (0x47FFF000, 0x1000, 1), (0x40208000, 0x7DF8000, 1), - (0x40207000, 0x1000, 0), (0x47FFF000, 0x2000, 0), (0x48000000, 0x1000, 0), - (0x40208000, 0xFFFFFFFFFFFFFFFF, 0), (0x40200000, 0x1000, 0), (0x0, 0x1000, 0), - (0x40206000, 0x50, 0), -] - - -def unit_snippet(): - s = [ - " /* ---- Seam 2 unit image: runs after CAP_ROOT genesis ---- */", - f" ldr x19, ={TEST_RECORD:#x}", - " ldr x20, =0x40208000 /* expected next frame */", - " mov x21, #0 /* allocation count */", - " mov x22, #0 /* last frame */", - " mov x23, #1 /* order_ok */", - ".Lunit_alloc_loop:", - " bl allocate_frame", - " cbz x0, .Lunit_alloc_done", - " cmp x0, x20", - " csel x23, xzr, x23, ne", - " mov x22, x0", - " add x20, x0, #0x1000", - " add x21, x21, #1", - " b .Lunit_alloc_loop", - ".Lunit_alloc_done:", - " str x21, [x19, #0x00]", - " str x22, [x19, #0x08]", - " bl allocate_frame", - " str x0, [x19, #0x10] /* after exhaustion: must be 0 */", - " str x23, [x19, #0x18]", - " mov x24, #0 /* reserved-probe result bits */", - ] - for i, (addr, _) in enumerate(RESERVED_PROBES): - s += [f" ldr x0, ={addr:#x}", " bl is_frame_reserved", - " and x0, x0, #1", f" lsl x0, x0, #{i}", " orr x24, x24, x0"] - s += [" str x24, [x19, #0x20]", " mov x25, #0 /* cap-probe result bits */"] - for i, (addr, size, _) in enumerate(CAP_PROBES): - s += [f" ldr x0, ={CAP_TABLE:#x}", " mov w1, #1", - f" ldr x2, ={addr:#x}", f" ldr x3, ={size:#x}", " bl validate_capability", - " and x0, x0, #1", f" lsl x0, x0, #{i}", " orr x25, x25, x0"] - s += [" str x25, [x19, #0x28]", - f" ldr x0, ={UNIT_MAGIC:#x}", " str x0, [x19, #0x30]", - " ldr x0, =msg_unit_done", " bl print_string", ""] - return "\n".join(s) + "\n" - - -UNIT_RODATA = '\n .section .rodata\nmsg_unit_done:\n .asciz "PHYSICS: UNIT_TESTS_DONE\\n"\n' - - -def trap_snippet(kind): - s = [" /* ---- Seam 2 trap image: load sentinels, then fault ---- */"] - if kind == "align": - # QEMU 8.2 does not fault unaligned Device accesses with the MMU off, - # so the test image turns on SCTLR_EL1.A (alignment checking). - s += [" mrs x0, sctlr_el1", " orr x0, x0, #2", " msr sctlr_el1, x0", " isb"] - s += [" msr nzcv, xzr /* deterministic SPSR.NZCV */"] - for n in range(31): - s.append(f" ldr x{n}, ={sentinel(n):#x}") - if kind == "brk": - s += [" .global seam2_fault_site", "seam2_fault_site:", " brk #0x4d32"] - else: - # Unaligned 64-bit load with SCTLR_EL1.A set: alignment Data Abort - # with a valid FAR. - s += [f" ldr x28, ={ALIGN_BASE:#x}", - " .global seam2_fault_site", "seam2_fault_site:", " ldr x0, [x28, #1]"] - return "\n".join(s) + "\n" - - -# --------------------------------------------------------------------------- -# Hostile ingress matrix -# --------------------------------------------------------------------------- - -PANIC_COOKIE = "PHYSICS: PANIC_BAD_COOKIE" -PANIC_PAYLOAD = "PHYSICS: PANIC_BAD_PAYLOAD_SIZE" -PANIC_PTR = "PHYSICS: PANIC_BAD_DESCRIPTOR_PTR" -PANIC_MAGIC = "PHYSICS: PANIC_BAD_DESC_MAGIC" -PANIC_VERSION = "PHYSICS: PANIC_BAD_DESC_VERSION" -PANIC_LENGTH = "PHYSICS: PANIC_BAD_DESC_LENGTH" -PANIC_RESERVED = "PHYSICS: PANIC_BAD_DESC_RESERVED" -PANIC_INGRESS = "PHYSICS: PANIC_INGRESS_CORRUPT" -PANIC_EL = "PHYSICS: PANIC_UNCONTRACTED_EL" - -# (tag, description, defsyms, expected panic, descriptor-ingress case?) -HOSTILE_CASES = [ - ("bad_cookie", "bad verification cookie", {"ABI_X2": "0xDEADBEEFCAFEBABE"}, PANIC_COOKIE, False), - ("bad_payload_size", "x1 payload size != 6144", {"ABI_X1": "4096"}, PANIC_PAYLOAD, False), - ("bad_desc_ptr", "descriptor pointer moved", {"ABI_X0": "0x40100000"}, PANIC_PTR, False), - ("bad_magic", "bad descriptor magic", {"DESC_MAGIC": "0x4D424453435F3032"}, PANIC_MAGIC, True), - ("version_2", "unsupported descriptor version 2", {"DESC_VERSION": "2"}, PANIC_VERSION, True), - ("version_0", "unsupported descriptor version 0", {"DESC_VERSION": "0"}, PANIC_VERSION, True), - ("len_truncated", "truncated length 32", {"DESC_LENGTH": "32"}, PANIC_LENGTH, True), - ("len_oversized", "oversized length 128", {"DESC_LENGTH": "128"}, PANIC_LENGTH, True), - ("reserved_low", "reserved flags bit 0 set", {"DESC_FLAGS": "1"}, PANIC_RESERVED, True), - ("reserved_high", "reserved flags bit 63 set", {"DESC_FLAGS": "0x8000000000000000"}, PANIC_RESERVED, True), - ("ram_size_zero", "DRAM size zero", {"DESC_RAM_SIZE": "0"}, PANIC_INGRESS, True), - ("ram_overflow", "DRAM base + size overflow", {"DESC_RAM_SIZE": "0xFFFFFFFFFFFFFFFF"}, PANIC_INGRESS, True), - ("ram_oversized", "valid base + oversized size", {"DESC_RAM_SIZE": "0x09000000"}, PANIC_INGRESS, True), - ("ram_undersized", "undersized RAM", {"DESC_RAM_SIZE": "0x07000000"}, PANIC_INGRESS, True), - ("ram_base_lower", "RAM base shifted lower", {"DESC_RAM_BASE": "0x3FF00000"}, PANIC_INGRESS, True), - ("ram_base_upper", "RAM base shifted upper", {"DESC_RAM_BASE": "0x40100000"}, PANIC_INGRESS, True), - ("ram_beyond_profile", "valid-looking range beyond profile", - {"DESC_RAM_SIZE": "0x100000000"}, PANIC_INGRESS, True), - ("ram_excludes_physics", "DRAM range excluding PHYSICS", {"DESC_RAM_BASE": "0x40300000"}, PANIC_INGRESS, True), - ("uart_out_of_profile", "UART outside machine profile", {"DESC_UART_BASE": "0x08000000"}, PANIC_INGRESS, True), - ("uart_misaligned", "misaligned UART address", {"DESC_UART_BASE": "0x09000001"}, PANIC_INGRESS, True), - ("physics_base_moved", "PHYSICS base moved", {"DESC_PHYSICS_BASE": "0x40300000"}, PANIC_INGRESS, True), - ("physics_size_wrong", "PHYSICS size wrong", {"DESC_PHYSICS_SIZE": "4096"}, PANIC_INGRESS, True), -] - - -def no_authority_granted(q): - """Memory proof that ingress refusal happened before any authority: - entry record, allocator header and CAP_ROOT slot are still zero.""" - entry = q.read_u64(ENTRY_RECORD, 1) - alloc = q.read_u64(STATIC_DATA, 4) - cap = q.read_u64(CAP_TABLE, 10) - return {"entry": entry, "alloc": alloc, "cap": cap, - "clean": not any(alloc) and not any(cap)} - - -# --------------------------------------------------------------------------- -# Seam 2 -# --------------------------------------------------------------------------- - -def load_contract(): - with open("machine_contract.json") as f: - return json.load(f) - - -def expected_descriptor(c): - d = c["boot_descriptor_contract"] - return [int(d["magic"], 16), d["version"] | (d["length"] << 32), d["flags_reserved"], - int(d["ram_base"], 16), int(d["ram_size"], 16), int(d["uart_base"], 16), - int(d["physics_base"], 16), d["physics_size"]] - - -def expected_cap_root(c): - r = c["root_capability_spec"] - digest = bytes.fromhex(r["atlas_provenance_digest"]) - words = [int.from_bytes(digest[i:i + 8], "little") for i in range(0, 32, 8)] - return [r["slot"] | (r["generation"] << 32), int(r["principal_id"], 16), - int(r["resource_type"], 16) | (int(r["allowed_ops"], 16) << 32), - int(r["bound_base"], 16), int(r["bound_size"], 16), - r["revocation_state"] | (r["attenuation_depth"] << 32)] + words - - -def check(results, gate, ok, detail): - results[gate] = results.get(gate, True) and bool(ok) - print(f" [{'OK' if ok else 'FAIL'}] {gate}: {detail}") - - -def verify_seam2(base_dir="."): - os.chdir(base_dir) - shutil.rmtree(BUILD_DIR, ignore_errors=True) - os.makedirs(BUILD_DIR) - c = load_contract() - results = {} - print("=" * 70) - print("SEAM 2: EXTERNAL EXECUTION SEAM (QEMU AARCH64 VIRT - PHYSICS_BOOT)") - print("=" * 70) - - # Golden images: rebuild from source into build/seam2/golden and require - # they are byte-identical to the canonical files under qualification. - golden_dir = os.path.join(BUILD_DIR, "golden") - _, g_phys = m2_build.build_physics(golden_dir, ".") - _, g_atlas = m2_build.build_atlas(golden_dir, g_phys, ".") - reproducible = (m2_build.sha256_file(g_phys) == m2_build.sha256_file("physics.bin") and - m2_build.sha256_file(g_atlas) == m2_build.sha256_file("atlas_m2.bin")) - check(results, "PHYSICS_BOOT_QEMU_PASS", reproducible, - "physics.bin and atlas_m2.bin rebuild byte-identically from source") - - # ---- Exec-1: golden boot ------------------------------------------------ - print("\n[Exec-1] Golden boot, machine state read over QMP") - - def inspect_golden(q): - return {"desc": q.read_u64(BOOT_STATE, 8), "entry": q.read_u64(ENTRY_RECORD, 1)[0], - "alloc": q.read_u64(STATIC_DATA, 4), "cap": q.read_u64(CAP_TABLE, 10), - "bitmap": q.read_bytes(BITMAP, BITMAP_BYTES + 1), - "trap_magic": q.read_u64(TRAP_FRAME + 0x138, 1)[0]} - - lines, st = run_qemu(os.path.join(BUILD_DIR, "run_golden"), "atlas_m2.bin", "physics.bin", - inspect_golden) - for l in lines: - print(f" | {l}") - golden = ["ATLAS: AWAKEN", "ATLAS: VERIFY", "ATLAS: HANDOFF", "PHYSICS: AWAKEN", - "PHYSICS: INGRESS_VALID", "PHYSICS: ENTRY_EL1_VERIFIED", "PHYSICS: VBAR_INSTALLED", - "PHYSICS: FRAME_AUTH_BOUND", "PHYSICS: CAP_ROOT_GENESIS", "PHYSICS: QUIESCENT_READY"] - check(results, "PHYSICS_BOOT_QEMU_PASS", lines == golden, - "telemetry is exactly the golden sequence, nothing else") - check(results, "PHYSICS_BOOT_QEMU_PASS", st["trap_magic"] == 0, "no exception taken on the normal path") - - el_expect = int(c["architecture"]["expected_entry_el_value"], 16) - check(results, "PHYSICS_ENTRY_EL_PASS", st["entry"] == el_expect, - f"recorded CurrentEL {st['entry']:#x} == contract {el_expect:#x}") - - exp_desc = expected_descriptor(c) - check(results, "PHYSICS_DESCRIPTOR_INGRESS_PASS", st["desc"] == exp_desc, - "PHYSICS-owned descriptor copy == contract descriptor (all 8 words)") - - alloc_ok = st["alloc"] == [DRAM_END, TOTAL_FRAMES, 0, 0] - check(results, "PHYSICS_BOOT_QEMU_PASS", alloc_ok, - f"allocator header DRAM_END={st['alloc'][0]:#x} frames={st['alloc'][1]} " - f"(expect {DRAM_END:#x}, {TOTAL_FRAMES})") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", alloc_ok and not any(st["bitmap"]), - f"fresh bitmap: {BITMAP_BYTES} bytes zero inside PHYSICS_STATIC_DATA") - - exp_cap = expected_cap_root(c) - check(results, "PHYSICS_CAP_ROOT_PASS", st["cap"] == exp_cap, - "CAP_ROOT slot/generation/principal/resource_type/allowed_ops/bounds/" - "revocation/attenuation/32-byte Atlas digest == contract") - with open("atlas.sha256") as f: - atlas_digest = f.read().split()[0] - check(results, "PHYSICS_CAP_ROOT_PASS", - atlas_digest == c["root_capability_spec"]["atlas_provenance_digest"], - "contract provenance digest == atlas.sha256") - cap_end = int(c["root_capability_spec"]["bound_base"], 16) + int(c["root_capability_spec"]["bound_size"], 16) - check(results, "PHYSICS_CAP_ROOT_PASS", - int(c["root_capability_spec"]["bound_base"], 16) == FREE_FRAME_BASE and cap_end == DRAM_END, - "contract CAP_ROOT bounds == [FREE_FRAME_BASE, DRAM_END)") - - # ---- Exec-2: frame authority, reservation, capability probes ----------- - print("\n[Exec-2] In-kernel allocator exhaustion, reserved and capability probes") - canary = os.path.join(BUILD_DIR, "canary.bin") - # One canary byte after the bitmap (last byte of PHYSICS_STATIC_DATA) plus - # the whole first free frame: bitmap writes must never reach them. - canary_base = BITMAP + BITMAP_BYTES - canary_len = FREE_FRAME_BASE + 0x1000 - canary_base - with open(canary, "wb") as f: - f.write(bytes([CANARY]) * canary_len) - _, u_phys, u_atlas = physics_variant("unit", unit_snippet(), UNIT_RODATA) - - def inspect_unit(q): - return {"rec": q.read_u64(TEST_RECORD, 7), "alloc": q.read_u64(STATIC_DATA, 4), - "bitmap": q.read_bytes(BITMAP, BITMAP_BYTES), - "canary": q.read_bytes(canary_base, canary_len)} - - lines, st = run_qemu(os.path.join(BUILD_DIR, "run_unit"), u_atlas, u_phys, inspect_unit, - extra_loaders=[(canary, canary_base)]) - for l in lines: - print(f" | {l}") - count, last, after, order_ok, res_bits, cap_bits, magic = st["rec"] - ran = magic == UNIT_MAGIC and "PHYSICS: UNIT_TESTS_DONE" in lines - check(results, "PHYSICS_FRAME_BOUNDS_PASS", ran, "unit image completed and wrote its record") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", count == TOTAL_FRAMES, - f"{count} frames allocated before exhaustion (expect {TOTAL_FRAMES})") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", order_ok == 1, - "every allocation == previous + 4 KiB from FREE_FRAME_BASE (deterministic, no duplicates)") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", last == DRAM_END - 0x1000 and last < DRAM_END, - f"last frame {last:#x} < DRAM_END") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", after == 0, "next allocation returns FRAME_EXHAUSTED (0)") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", st["alloc"][2] == TOTAL_FRAMES, - "allocator cursor == total_frames") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", all(b == 0xFF for b in st["bitmap"]), - f"all {BITMAP_BYTES} bitmap bytes set, exactly one bit per granted frame") - check(results, "PHYSICS_FRAME_BOUNDS_PASS", all(b == CANARY for b in st["canary"]), - f"canary {canary_base:#x}..{FREE_FRAME_BASE + 0x1000:#x} untouched (bitmap stays in STATIC_DATA)") - - exp_res = sum(e << i for i, (_, e) in enumerate(RESERVED_PROBES)) - check(results, "PHYSICS_RESERVED_FRAME_REFUSAL_PASS", ran and res_bits == exp_res, - f"{len(RESERVED_PROBES)} is_frame_reserved probes (bits {res_bits:#x}, expect {exp_res:#x})") - exp_cap_bits = sum(e << i for i, (_, _, e) in enumerate(CAP_PROBES)) - check(results, "PHYSICS_CAP_ROOT_PASS", ran and cap_bits == exp_cap_bits, - f"{len(CAP_PROBES)} validate_capability probes: CAP_ROOT grants only inside " - f"[FREE_FRAME_BASE, DRAM_END) (bits {cap_bits:#x}, expect {exp_cap_bits:#x})") - - # ---- Exec-3: exception state capture ------------------------------------ - for kind in ("brk", "align"): - print(f"\n[Exec-3/{kind}] Sentinel GPRs, then {'BRK #0x4d32' if kind == 'brk' else 'unaligned load (SCTLR_EL1.A=1)'}") - t_elf, t_phys, t_atlas = physics_variant(f"trap_{kind}", trap_snippet(kind)) - site = symbol(t_elf, "seam2_fault_site") - - def inspect_trap(q): - return q.read_u64(TRAP_FRAME, 40) - - lines, fr = run_qemu(os.path.join(BUILD_DIR, f"run_trap_{kind}"), t_atlas, t_phys, inspect_trap) - for l in lines: - print(f" | {l}") - gprs, sp = fr[0:31], fr[31] - slot, el, esr, elr, spsr, far, far_valid, magic = fr[32:40] - if kind == "brk": - exp = {"esr": 0xF2004D32, "far": 0, "far_valid": 0} - else: - # EC 0x25 (Data Abort, same EL), IL=1, ISV=0, DFSC 0x21 alignment - exp = {"far": ALIGN_BASE + 1, "far_valid": 1} - gate = "PHYSICS_EXCEPTION_STATE_CAPTURE_PASS" - check(results, gate, magic == TRAP_MAGIC and "PHYSICS: TRAP_FRAME_CAPTURED" in lines, - "trap frame complete (TRAPFRM1 magic written last)") - want = [sentinel(n) for n in range(31)] - if kind == "align": - want[28] = ALIGN_BASE - bad = [n for n in range(31) if gprs[n] != want[n]] - check(results, gate, not bad, f"x0..x30 sentinels preserved in frame (mismatch: {bad})") - check(results, gate, sp == BOOT_STATE, f"interrupted SP {sp:#x} == PHYSICS stack top") - check(results, gate, slot == 4, f"vector slot {slot} == 4 (current EL, SPx, synchronous)") - check(results, gate, el == el_expect, f"CURRENT_EL {el:#x}") - check(results, gate, elr == site, f"ELR {elr:#x} == fault site {site:#x}") - check(results, gate, spsr == 0x3C5, f"SPSR {spsr:#x} == 0x3c5 (EL1h, DAIF masked)") - if kind == "brk": - check(results, gate, esr == exp["esr"], f"ESR {esr:#x} == {exp['esr']:#x} (BRK, imm 0x4d32)") - else: - ec, dfsc = esr >> 26, esr & 0x3F - check(results, gate, ec == 0x25 and dfsc == 0x21 and not (esr >> 10) & 1, - f"ESR {esr:#x}: EC 0x25 data abort, DFSC 0x21 alignment, FnV 0") - check(results, gate, far_valid == exp["far_valid"] and far == exp["far"], - f"FAR {far:#x} FAR_VALID {far_valid} (expect {exp['far']:#x}, {exp['far_valid']})") - - # ---- Exec-4: hostile ingress matrix ------------------------------------- - print("\n[Exec-4] Hostile ingress matrix (memory-checked: no authority granted)") - passed = 0 - total = len(HOSTILE_CASES) + 1 - desc_ok = True - for tag, desc, defsyms, panic, is_desc in HOSTILE_CASES: - out_dir = os.path.join(BUILD_DIR, f"hostile_{tag}") - _, h_atlas = m2_build.build_atlas(out_dir, "physics.bin", ".", defsyms=defsyms) - lines, st = run_qemu(os.path.join(out_dir, "run"), h_atlas, "physics.bin", no_authority_granted) - ok = (panic in lines and st["clean"] and - not any(m in l for l in lines for m in ("FRAME_AUTH_BOUND", "CAP_ROOT_GENESIS", "QUIESCENT_READY"))) - passed += ok - desc_ok &= ok or not is_desc - print(f" [{'REFUSED' if ok else 'FAIL'}] {desc:40s} -> {panic.split(': ')[1]}" - + ("" if ok else f" lines={lines} state={st}")) - - # Real wrong-EL entry: virtualization=on starts the firmware (Atlas) at EL2, - # so PHYSICS is entered at EL2, which the contract does not admit. - lines, st = run_qemu(os.path.join(BUILD_DIR, "run_el2"), "atlas_m2.bin", "physics.bin", - no_authority_granted, machine="virt,virtualization=on") - el2_ok = PANIC_EL in lines and st["clean"] and st["entry"] == [0] - passed += el2_ok - print(f" [{'REFUSED' if el2_ok else 'FAIL'}] {'entry at EL2 (virtualization=on)':40s} -> " - f"PANIC_UNCONTRACTED_EL" + ("" if el2_ok else f" lines={lines} state={st}")) - check(results, "PHYSICS_ENTRY_EL_PASS", el2_ok, "entry at EL2 refused before any authority") - check(results, "PHYSICS_DESCRIPTOR_INGRESS_PASS", desc_ok, - "every descriptor header/profile violation refused before bitmap init") - check(results, "PHYSICS_CORRUPTION_REFUSAL_PASS", passed == total, - f"{passed}/{total} hostile cases refused with the expected panic and zero authority state") - - order = ["PHYSICS_ENTRY_EL_PASS", "PHYSICS_DESCRIPTOR_INGRESS_PASS", "PHYSICS_BOOT_QEMU_PASS", - "PHYSICS_FRAME_BOUNDS_PASS", "PHYSICS_RESERVED_FRAME_REFUSAL_PASS", - "PHYSICS_CAP_ROOT_PASS", "PHYSICS_EXCEPTION_STATE_CAPTURE_PASS", - "PHYSICS_CORRUPTION_REFUSAL_PASS"] - return {g: results.get(g, False) for g in order} - - -if __name__ == "__main__": - import sys - r = verify_seam2(".") - for g, ok in r.items(): - print(f" [{'PASS' if ok else 'FAIL'}] {g}") - sys.exit(0 if all(r.values()) else 1) diff --git a/tests/run_m16_requalification.sh b/tests/run_m16_requalification.sh index 3d00398..d7ada4d 100755 --- a/tests/run_m16_requalification.sh +++ b/tests/run_m16_requalification.sh @@ -140,29 +140,37 @@ fi # 6. Capture live /proc/maps snapshot during execution echo -e "\n[*] Step 6: Capturing live /proc/maps snapshot..." -python3 -c ' -import subprocess, time, sys - -proc = subprocess.Popen(["./m16/m16_requalify"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) -maps_content = "" -for _ in range(50): - try: - with open(f"/proc/{proc.pid}/maps", "r") as f: - maps_content = f.read() - if maps_content: - break - except FileNotFoundError: - pass - time.sleep(0.005) - -out, err = proc.communicate() -if "libcuda" in maps_content or "libcudart" in maps_content: - print("FATAL: libcuda mapped in live process!", file=sys.stderr) - sys.exit(1) - -with open("evidence/m16-requalification/runtime-maps.log", "w") as f: - f.write(maps_content) -' +# capture_runtime_maps BIN OUT: start BIN and poll /proc//maps up to 50 +# times (5 ms apart) while it runs, wait for BIN (exit status ignored). Refuse if +# libcuda appears in ANY snapshot; else write the last non-empty snapshot to OUT. +# (The retired python3 helper stopped at the first non-empty read, which can be +# taken before the dynamic loader maps any library; polling for the whole run +# makes the no-libcuda check see the loaded process.) +capture_runtime_maps() { + local bin="$1" out="$2" snap="$2.snap" last="$2.last" seen="$2.seen" pid i=0 + : > "$last" + : > "$seen" + "$bin" > /dev/null 2>&1 & + pid=$! + while [ "$i" -lt 50 ] && kill -0 "$pid" 2>/dev/null; do + if cat "/proc/$pid/maps" > "$snap" 2>/dev/null && [ -s "$snap" ]; then + cat "$snap" >> "$seen" + mv "$snap" "$last" + fi + sleep 0.005 + i=$((i + 1)) + done + wait "$pid" || true + rm -f "$snap" + if grep -q "libcuda" "$seen"; then + rm -f "$last" "$seen" + echo "FATAL: libcuda mapped in live process!" >&2 + exit 1 + fi + rm -f "$seen" + mv "$last" "$out" +} +capture_runtime_maps ./m16/m16_requalify "$EVIDENCE_DIR/runtime-maps.log" if [ -s "$EVIDENCE_DIR/runtime-maps.log" ] && ! grep -Eiq "libcuda|libcudart" "$EVIDENCE_DIR/runtime-maps.log"; then GATE_NO_LIBCUDA_RUNTIME=true From 4494ee219abd8110c5afa5c204e7eef8dfda4031 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Wed, 30 Sep 2026 21:48:54 -0500 Subject: [PATCH 2/2] docs(m2): note Phase 2 receipt refresh still open Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- TRANSITION_PLAN_M2.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TRANSITION_PLAN_M2.md b/TRANSITION_PLAN_M2.md index 2842dbf..5c7ce08 100644 --- a/TRANSITION_PLAN_M2.md +++ b/TRANSITION_PLAN_M2.md @@ -54,6 +54,8 @@ All 15 gates complete execution in ~16.2 seconds with zero Python dependencies. The five legacy Python files (`generate_physics_audit.py`, `m2_build.py`, `run_milestone2_gates.py`, `seam1_physics_audit.py`, `seam2_physics_harness.py`) are deleted. They remain in git history at `d52759d` and earlier; `qualification_receipt.json` (historical evidence, untouched) pins their SHA-256. +Phase 2 (receipt refresh under aien-architecture#12) remains open: the committed receipt still describes the +retired Python run. Equivalence check before deletion (scratch copies of `d52759d`, QEMU on the Spark): - `python3 run_milestone2_gates.py` and `./run_m2_gates.sh` print the same 15 gate names, all PASS, no FAIL.