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
omega-mv / seed / omc / qualify-x86.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Read-only FR-9 qualification oracle, not a compiler/backend/build dependency. |
| 3 | |
| 4 | Run on Linux AArch64, from any directory: |
| 5 | python3 seed/omc/qualify-x86.py --compiler /absolute/path/to/omc |
| 6 | Requires Python 3.10+, qemu-x86_64 and GNU x86-64 objdump or llvm-objdump. |
| 7 | Use --inventory for corpus categorization without compiling/running anything. |
| 8 | |
| 9 | All outputs go to stdout and a new TemporaryDirectory, removed on exit. Existing |
| 10 | receipts, compiler binaries, sources and gate manifests are never rewritten. |
| 11 | A fresh cwd and resource limits are NOT a security sandbox. Only trusted fixture |
| 12 | sources belong here. Reviewed, content-pinned host tests normalize their own |
| 13 | clock/random/process results and run in separate architecture-local directories. |
| 14 | Unreviewed host effects remain NOT_RUN and make the verdict nonzero. |
| 15 | |
| 16 | The fixture inventory includes every .om/.omegese under tests/, every seed/*/tests, |
| 17 | seed/omc/{om2,contracts}, seed/qualification, unit .om files and wasm/SPIRV case tables. |
| 18 | Frozen .cases and C2 rows retain their pinned historical assertions and exact |
| 19 | inputs. Current C2 compatibility assertions remain mandatory and separate from |
| 20 | their frozen provenance replay. Mutant specifications link to actual compiler |
| 21 | mutation executions with build/control verdicts; healthy compiler output is not |
| 22 | treated as a mutant. Current cross-target comparisons remain additional coverage. |
| 23 | """ |
| 24 | from __future__ import annotations |
| 25 | |
| 26 | import argparse |
| 27 | from collections import Counter, OrderedDict |
| 28 | from dataclasses import dataclass, field, replace |
| 29 | import hashlib |
| 30 | from functools import lru_cache |
| 31 | import json |
| 32 | import os |
| 33 | from pathlib import Path |
| 34 | import platform |
| 35 | import re |
| 36 | import resource |
| 37 | import shutil |
| 38 | import signal |
| 39 | import stat |
| 40 | import struct |
| 41 | import subprocess |
| 42 | import tempfile |
| 43 | |
| 44 | from x86_corpus_drivers import EFFECT_CPU_SECONDS, bare_calls, bridge_plan, bridge_positive_plan, directive_plan, plan_case, prepare_case, select_a64_entry, wrap_bare |
| 45 | |
| 46 | ROOT = Path(__file__).resolve().parents[2] |
| 47 | MAIN = re.compile(rb"(?m)^[ \t]*(?:export[ \t]+)?fn[ \t]+main(?:[ \t]|$)") |
| 48 | MODE = re.compile(rb"^(?:ir(?:[ \t\r\n]|$)|check(?:[ \t\r\n]|$)|next(?:[ \t\r\n]|$)|om2 fmt(?:[ \t\r\n]|$)|target(?:[ \t\r\n]|$))") |
| 49 | TEXT = re.compile(rb'(?m)^[ \t]*text[ \t]+\w+[ \t]+"((?:[^"\\]|\\.)*)"[^\n]*$') |
| 50 | UNSAFE = set(""" |
| 51 | devctl devcall uvmctl mapnew mapdrop mapget mapset mapread mapwrite mapaddr maphold mapbind |
| 52 | efi socket socknew bind sockbind connect listen accept send recv sockname peername sockopt shutdown |
| 53 | fork exec execprog waitpid kill killpid clock realns monons sleep sleepns random cwd |
| 54 | chdir fchdir envcnt envlen envread open openat fopen fclose fseek fsync fdsync fchmod |
| 55 | chmod chown umask unlink rename renames link symlnk mkdir makedir rmdir stat lstat |
| 56 | fstat getdnts faccess readlnk memfd ftrunc truncate pread pwrite ioctl flock syncfs |
| 57 | setpgid setsid |
| 58 | """.split()) |
| 59 | INSTRUCTION = re.compile(r"^\s*([0-9a-fA-F]+):\s+((?:[0-9a-fA-F]{2}[ \t]+)+)(.*?)\s*$") |
| 60 | DIAG = re.compile(rb"line ([0-9]+): error ([0-9]+)") |
| 61 | TARGET_PREFIX = b"target x86linux\n" |
| 62 | QEMU_IOCTL_URL = "https://github.com/qemu/qemu/blob/v10.0.14/linux-user/syscall.c#L5713-L5717" |
| 63 | QEMU_SYSCALL_SHA256 = "0d6212a547d456f47612a4c297e093dd60fe59ad021f44e3f21e5c6bb9be0cf7" |
| 64 | QEMU_ORACLE_SHA256 = "fd7ae7768c1d698d387893688d28abde90512f1f445d171a1389110eb7c237ee" |
| 65 | QEMU_SOURCE_ARCHIVE_SHA256 = "c7230968906fdb5540d803e2af1f515e77590a414f2a4dbd3ec9ada3c47083d0" |
| 66 | QEMU_IOCTL_EXCERPT = b""" if (ie->target_cmd == 0) { |
| 67 | qemu_log_mask( |
| 68 | LOG_UNIMP, "Unsupported ioctl: cmd=0x%04lx\\n", (long)cmd); |
| 69 | return -TARGET_ENOTTY; |
| 70 | } |
| 71 | """ |
| 72 | |
| 73 | # Inspected host fixtures at the source revision below. These are not authority |
| 74 | # to run a changed fixture: hashes pin exact reviewed effects. Drivers use local |
| 75 | # scratch paths, anonymous mappings, private children, invalid-fd ioctls and |
| 76 | # /dev/zero reads, never GPU nodes. Pinned sockets use relative Unix paths or |
| 77 | # OS-assigned loopback ports, not fixed ports/outbound endpoints/live services. |
| 78 | # Original gate.sh supplies the arguments/environment/expected statuses below. |
| 79 | HOST_PINS = """ |
| 80 | args 0e6bdbfb63ef9e52028682ddbecb1e9b4d81a3326b2e63848be570a775c31e6e |
| 81 | chdir 33f64d79ae5655a020d795f8f31b7e4cff9f8c176534e4474216a2709b04f759 |
| 82 | chmod 21ee5f82d67f2b286cbcd3c5e1242199f0b7b66f020caa98f5a53212d4245532 |
| 83 | chown 9e5d8e7f2fd5678c63ed95bbde66f9d6f753b42791701d45311bfe20dd7f4d17 |
| 84 | devcall ca76010ea6cf2ab7acd8b8fab36234dcaad8f2cede057e01a52e840842a2e8ed |
| 85 | directories c25fcaeb5e6fc0331b31d7f4af5aa5d00c87c5df6d99c8d2fa42456268e0124c |
| 86 | environment d798e64c66d39fa9cf6df29ed67026e747a8cff2e4c4f95f84ccc2ea8d01bff6 |
| 87 | environment_trap 93043b312007ee2dedce62d8a7a5d4601c34c80a4f142ce471270b585ce7dc66 |
| 88 | errors a6fcf6e1ede30da15f4ad75ea11173cd4d5001613ae424cd0b30eff62f96898a |
| 89 | faccess e4aec179deea0ab97c88ab0a274bba8fab2f1f0ca6d54b9829d8b724967e4087 |
| 90 | fchdir d647e8917878fc9e9b42b2d65102d302710e0592055bb84fa9fc67ce4b1d1c26 |
| 91 | fdsync 4a7bc7d82979b05511a5ea2cd8a7c51ebce6e36a52a3fc929b0e9db1f99e3733 |
| 92 | files 7599eaaa3936a7342b4825965f6fd0a0a2517075f12168b5bc54d4d06ddc5a4b |
| 93 | flock cb1c63d6738e4923018d3014be4358ef1d80b60f7c406db677b36b8684066fd1 |
| 94 | genlimit ea4f544b49878f5532f75b0ac7e8fa42e6926d5b57ea002e748679922859ad48 |
| 95 | links 9fa1710075bf9ce64bf57d3f0c6ffe8deac39a294bb8242c64ba185e8cb7cd3a |
| 96 | links_short 5cf587ad20927ccf7c2873f58d332623f1a2e60adac8efa2e3877d74647cdc98 |
| 97 | location 691bc9c2903c9c269ded9a55596ce1cb08adc693fe3e08ffcbf274b3e523a944 |
| 98 | lstat 544cf17cf26ab54eb71e42030027a6a171faccc084294e235c76c8df419a8a6f |
| 99 | mapio f657ff3daa44b070608178834b46f1f83ade03e65b73c00e05a1c2e2a9356267 |
| 100 | mapping b42c477a43862018dc0cb1f1c4f06374d1413130eeb112b6fd6b81132360c607 |
| 101 | pgroup 97cee434be0cc7dc8c27b2786747e2ecdd9dc31a33c558e5c54c20f787a19ece |
| 102 | pio d36aec6170344d4c3126212a092bc021e671c24ab3bc31871562847429767c80 |
| 103 | random cf1eff4a9e12ff42141d76dd0a2eb136ca345e9cbf9f4e3ee73d70abdd7e16fb |
| 104 | reserve 8498b995e3ee7a2d9ac86085af1674af7c14b57da5778051fc5e7a15406768dc |
| 105 | stat 6ff1b76d4fd35599e67684e706a5d66eec84584f51326c74a1fc35bec023ab60 |
| 106 | stat_short 628c9696acb656943ad68a4137a81fbfafdc1a1aafb59e0fe4a09332957b2600 |
| 107 | structfile 8a861930643b73590772a575f62985389eb6c1daf77820d37e88a8c648171505 |
| 108 | trunc 6a48633d31aa718ca9bd543a3c0ec134318d74005b31e6424bd4b0f920963764 |
| 109 | truncate 53dab870239429150e88616fe5173a0ad8637719cc15eac7bbf955f0e5662b3d |
| 110 | uvmctl 1e7b46b9d0fb44f5c97768f92daa7599e9b36e6d5cbc6553ac755a7c02047b5f |
| 111 | network a8b16320610b79bd0a3e96e303d631c1a9a00b6464d963f3d79c5b4e1ff2d514 |
| 112 | sockopt 0ee354c31e3e33c63da7cd8ade18cdf3f98d6d742adeedbffa506d746b5ff0c1 |
| 113 | netdata 6762de311b8b1cb4f1f9220bc3837b29733fcf382ac3c2cd19e8096c02789f88 |
| 114 | netpeer ed93e15648c6fe304cc28590065fab6d36887db448c253813b8a762ca9c61193 |
| 115 | peername 3052bbfc59647745e2576bb5ffb528ec10f23dc467b2c1b1d55d0a8980f8a728 |
| 116 | process 0c1292a905cb1263a733e26f2e026a2915089d6d6959d16b617c05f446452964 |
| 117 | memcheck 652a4bc9455251bb51d01a75fc5be0ad008ae5e022e4835e43959f073c82413d |
| 118 | device 375898c6ac071af5ab50bb41fce6aa93ee5796302916cac65df70831c52d3d67 |
| 119 | psync 8355680fe35976dc5fd3621c3dc9b2ff8f6cc8b210ec90915d2044a4de133473 |
| 120 | """ |
| 121 | HOST_DRIVERS = {sha: name for name, sha in (row.split() for row in HOST_PINS.splitlines() if row)} |
| 122 | |
| 123 | # Explicit reviewed verdicts, not a name-prefix heuristic. The first comments |
| 124 | # of these manifests fix ctl PASS / mutant FAIL in advance; the lexical list's |
| 125 | # RESULTS.txt:38-43 describes exactly the listed refusals/format/diag failures. |
| 126 | CONDUCTOR_FAILURES = { |
| 127 | "seed/omc/contracts/mutant.cases": "mutant-requires mutant-proof", |
| 128 | "seed/omc/om2/s1/s1-mutants.cases": "m-rotl m-rchk m-hexd m-hexU m-optin m-paren m-unk m-tyunk m-kwlong", |
| 129 | "seed/omc/om2/s2/s2-mutants.cases": "m-div0 m-sovf m-ucount m-brk m-idx m-depth m-cyc", |
| 130 | "seed/omc/om2/s3/s3-mutants.cases": "m-l-ovl m-l-rev m-l-lix m-l-past m-fuel m-e16-d3 m-e16-inl m-fzu m-fzl m-fzc m-fzr m-fzn m-aer m-aex m-act m-aop m-araw", |
| 131 | "seed/omc/om2/s4/s4-mutants.cases": "m-uce m-slot m-pwrap m-pfirst m-p19 m-tramp m-preadwr m-textlen", |
| 132 | "seed/qualification/om2/candidates/s1/s1-lexmutants.cases": |
| 133 | "hex-upper-s1-d-hexupper hex-upper-s1-d-hexupper-plain hex-upper-s2-r6-upper hex-upper-s2-r6-mixed hex-upper-s2-r6-upper-ulong " |
| 134 | "hex-17-s2-r6-17small hex-17-s2-r6-17big diag-col0-s1-d-left diag-col0-s1-d-eof-left diag-col0-s1-d-hexrange diag-col0-s1-d-unknown-fn " |
| 135 | "fmt-note-s2-fmt-x1 fmt-note-s2-fmt-x3 fmt-text-s2-fmt-x1 fmt-text-s2-fmt-x5", |
| 136 | "seed/qualification/om2/candidates/s1/s1-mutants.cases": "", |
| 137 | "seed/qualification/om2/candidates/s2/s2-mutants.cases": "", |
| 138 | "seed/qualification/om2/candidates/s3/s3-mutants.cases": "", |
| 139 | "seed/qualification/om2/candidates/s4/s4-mutants.cases": "", |
| 140 | "seed/qualification/om2/candidates/s4/s4-part-mutants.cases": "", |
| 141 | "seed/qualification/om2/baseline/guard.cases": "", |
| 142 | "seed/qualification/om2/baseline/transform.cases": "", |
| 143 | # Headers fix ctl PASS / kill FAIL in advance (s5: "ctl-* PASS, m-* FAIL"; |
| 144 | # bnd: "pass=2 fail=8"; hex: "pass=3 fail=5"); seed/host/check.sh runs each. |
| 145 | "seed/omc/om2/s5/s5-mutants.cases": "m-msr m-stp m-live m-tst m-zpool m-zvec m-movz16 m-twinall m-twinnone", |
| 146 | "seed/omc/om2/bnd/mutants.cases": |
| 147 | "bnd-extra-om1-left-typed bnd-extra-om2-left-typed bnd-extra-om1-left-assign bnd-extra-om2-left-assign " |
| 148 | "bnd-missing-om1-short-next bnd-missing-om2-short-next bnd-missing-om1-short-bare bnd-missing-om2-short-bare", |
| 149 | "seed/omc/om2/hex/mutants.cases": |
| 150 | "hex-tbig-pairs-run hex-tbig-places-run hex-nolimit-r6-17trunc hex-digit-pairs-run hex-digit-floatlike-run", |
| 151 | # Header: "These cases must produce OM2GATE FAIL, not a qualification PASS." Each row |
| 152 | # substitutes wrong bytes into a pinned emit source, so its oracle digest must differ. |
| 153 | "seed/qualification/security673/relational/binding-negative.cases": "wrong-source-bytes wrong-checker-bytes", |
| 154 | # Header: "The expectation stays the correct one (trap 3, exit 103), so every row must FAIL: the |
| 155 | # mutant executes /bin/true (exit 0)." seed/host/check.sh requires exactly these FAIL verdicts. |
| 156 | "seed/qualification/security673/packets-mutant.cases": "mutant-size mutant-count mutant-exact", |
| 157 | } |
| 158 | NEGATIVE_CONDUCTOR_MANIFESTS = { |
| 159 | "seed/qualification/security673/relational/binding-negative.cases": "stdout sha256 differs", |
| 160 | } |
| 161 | HISTORICAL_COMPILERS = { |
| 162 | "build/om2-qual/cand-s1/omc.om": ("a5927895c02a5abe6b5c3a455f5d54303962ebe8", "3d7bcf9afdaa36fc42b862e0af39c524a14e85204bd5f40ee74107db40ce6a1d"), |
| 163 | "build/om2-qual/cand-s2/omc.om": ("7fb62f3a87104f48bb1317ab05333c5805ce5340", "1f41c7dc4f27324c2595c60f601e74548cd1bb4aeca8d4d367056ee803e7de72"), |
| 164 | "build/om2-qual/cand-s3/omc.om": ("ad220c054b2e018a985384a33bf09b9f0d612787", "656d4e25f503d38ae7523c758b37734b191ecc064d370ac7928011f25c02a3d6"), |
| 165 | "build/om2-qual/cand-s4/omc.om": ("f6a6492fd1a3b608f0413a75685ddbb712075a73", "c792b401193d8477d38965d6ddb0fd0cb8fd5ac24fcb92fae9af52037a765f1c"), |
| 166 | } |
| 167 | ORIGINAL_SOURCE = { |
| 168 | "path": "seed/omc/omc.om", |
| 169 | "git_revision": "acb3f15cdc691b1b046b48b0dad0f9255a12ba4b", |
| 170 | "git_path": "seed/omc/omc.om", |
| 171 | "sha256": "2e35db7d6c2066fb4a20d19b8a9579c44caca9c9937b0594a89422010b673637", |
| 172 | } |
| 173 | PINNED_COMPILER_SHA256 = "734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61" |
| 174 | MUTANT_SPECIFICATIONS = { |
| 175 | "seed/qualification/om2/sec/s3s4/mutant-kills.cases", |
| 176 | "seed/qualification/om2/sec/s5s7/mutant-side.cases", |
| 177 | } |
| 178 | |
| 179 | |
| 180 | def frozen_manifest(rel): |
| 181 | return rel.startswith("seed/qualification/om2/sec/") and rel.endswith("/pinned.cases") |
| 182 | |
| 183 | |
| 184 | def conductor_identity(rel): |
| 185 | if rel.startswith("seed/qualification/om2/candidates/"): |
| 186 | stage = rel.split("/")[4] |
| 187 | return "build/om2-qual/cand-" + stage + "/omc.om" |
| 188 | if frozen_manifest(rel) or rel.startswith("seed/qualification/om2/baseline/") or rel.endswith("/manifest-c2.txt"): |
| 189 | return "pinned" |
| 190 | return "current" |
| 191 | SELFTEST_MANIFESTS = { |
| 192 | "seed/qualification/om2/selftest/" + name + ".cases" |
| 193 | for name in ("controls", "emit", "fail", "pass") |
| 194 | } |
| 195 | DELIBERATELY_ABSENT = { |
| 196 | "seed/qualification/om2/selftest/does-not-exist", |
| 197 | "seed/qualification/om2/selftest/does-not-exist.om", |
| 198 | } |
| 199 | |
| 200 | |
| 201 | @dataclass |
| 202 | class Case: |
| 203 | name: str |
| 204 | source: bytes |
| 205 | stdin: bytes = b"" |
| 206 | args: tuple[str, ...] = () |
| 207 | expected_exit: int | None = None |
| 208 | expected_compile: str | None = None |
| 209 | operation: str = "differential" |
| 210 | stdout_oracle: str | None = None |
| 211 | stderr_oracle: str | None = None |
| 212 | same_source: bytes | None = None |
| 213 | driver: str | None = None |
| 214 | blocker: str | None = None |
| 215 | evidence: dict = field(default_factory=dict) |
| 216 | deadline: int | None = None |
| 217 | bridge: dict | None = None |
| 218 | |
| 219 | |
| 220 | class Failure(Exception): |
| 221 | pass |
| 222 | |
| 223 | |
| 224 | def digest(data): |
| 225 | return hashlib.sha256(data).hexdigest() |
| 226 | |
| 227 | |
| 228 | def fixture_files(): |
| 229 | roots = [ROOT / "tests", ROOT / "seed/qualification", ROOT / "seed/omc/om2", |
| 230 | ROOT / "seed/omc/contracts", ROOT / "tools/exp445/arms/examples"] |
| 231 | roots += sorted((ROOT / "seed").glob("*/tests")) |
| 232 | files = {p for root in roots if root.is_dir() for p in root.rglob("*") |
| 233 | if p.is_file() and (p.suffix in (".om", ".omegese", ".cases") or |
| 234 | (p.name.startswith("manifest-c2") and p.suffix == ".txt"))} |
| 235 | files.update((ROOT / "seed").glob("*/*.unit.om")) |
| 236 | files.add(ROOT / "seed/wasm/cases.tsv") |
| 237 | files.update((ROOT / "seed/spirv/demo.tsv", ROOT / "seed/spirv/regression.tsv")) |
| 238 | return sorted(files) |
| 239 | |
| 240 | |
| 241 | def contained(path): |
| 242 | p = (ROOT / path).resolve() |
| 243 | if not p.is_relative_to(ROOT): |
| 244 | raise Failure("fixture path escapes repository: " + path) |
| 245 | return p |
| 246 | |
| 247 | |
| 248 | def source_bytes(spec): |
| 249 | parts = [] |
| 250 | for part in spec.split("+"): |
| 251 | if part.startswith("pack:"): |
| 252 | path, off, length = part[5:].rsplit(":", 2) |
| 253 | off, length = int(off), int(length) |
| 254 | data = contained(path).read_bytes() |
| 255 | if off < 0 or length < 0 or off + length > len(data): |
| 256 | raise Failure("invalid pack range: " + part) |
| 257 | parts.append(data[off:off + length]) |
| 258 | elif part.startswith("cyc:"): |
| 259 | path, length = part[4:].rsplit(":", 1) |
| 260 | length = int(length) |
| 261 | data = contained(path).read_bytes() |
| 262 | if not data or length < 0: |
| 263 | raise Failure("invalid cyclic input: " + part) |
| 264 | parts.append((data * (length // len(data) + 1))[:length]) |
| 265 | elif part == "om/sha256/sha256.om" and not contained(part).exists(): |
| 266 | # Removed by the OM-2 cutover. The old caller uses omsha, not the |
| 267 | # current API: recover its EXACT frozen source, never alias APIs. |
| 268 | frozen = source_bytes("pack:seed/qualification/om2/c2/corpus.pack:12540:35333") |
| 269 | expected = "7f034814303a8a40b4bc56383ddd55ab2ae8460291f80793340bc3b0ac024e21" |
| 270 | if digest(frozen) != expected: |
| 271 | raise Failure("historical SHA source differs from independent c2/index.tsv pin") |
| 272 | parts.append(frozen) |
| 273 | else: |
| 274 | parts.append(contained(part).read_bytes()) |
| 275 | return b"".join(parts) |
| 276 | |
| 277 | |
| 278 | def stdin_bytes(spec): |
| 279 | if spec == "-": |
| 280 | return b"" |
| 281 | if spec.startswith("file:"): |
| 282 | return contained(spec[5:]).read_bytes() |
| 283 | if spec.startswith("rep:"): |
| 284 | _, byte, length = spec.split(":") |
| 285 | return bytes([int(byte)]) * int(length) |
| 286 | if spec.startswith("seq:"): |
| 287 | return bytes(i % 251 for i in range(int(spec[4:]))) |
| 288 | if spec.startswith("rnd:"): |
| 289 | _, seed, length = spec.split(":") |
| 290 | state, length, out = int(seed), int(length), bytearray() |
| 291 | mask = (1 << 64) - 1 |
| 292 | while len(out) < length: |
| 293 | state = (state + 0x9e3779b97f4a7c15) & mask |
| 294 | z = ((state ^ (state >> 30)) * 0xbf58476d1ce4e5b9) & mask |
| 295 | z = ((z ^ (z >> 27)) * 0x94d049bb133111eb) & mask |
| 296 | out.extend((z ^ (z >> 31)).to_bytes(8, "little")) |
| 297 | return bytes(out[:length]) |
| 298 | raise Failure("unknown stdin grammar: " + spec) |
| 299 | |
| 300 | |
| 301 | def host_words(source): |
| 302 | source = re.sub(rb'"(?:[^"\\]|\\.)*"', b'""', source) |
| 303 | source = re.sub(rb"(?m)^[ \t]*note[^\n]*", b"", source) |
| 304 | return sorted(set(re.findall(r"\b\w+\b", source.decode("utf-8", "replace"))) & UNSAFE) |
| 305 | |
| 306 | |
| 307 | def target_source(case, driver): |
| 308 | if driver not in ("directories", "fchdir"): |
| 309 | return case.source, None |
| 310 | # These exact pinned fixtures use the Linux AArch64 O_DIRECTORY literal. |
| 311 | # This is target-adapted ABI coverage, explicitly NOT identical-source parity. |
| 312 | old = b"len dir 16384 0" if driver == "directories" else b"len subd 16384 0" |
| 313 | if case.source.count(old) != 1: |
| 314 | raise Failure("reviewed O_DIRECTORY adaptation anchor changed") |
| 315 | return case.source.replace(old, old.replace(b"16384", b"65536")), "O_DIRECTORY: AArch64 16384 -> x86-64 65536" |
| 316 | |
| 317 | |
| 318 | def unit_cases(path): |
| 319 | # Same full-bit dumper as seed/wasm/gate-irwasm.sh, not a status-byte proxy. |
| 320 | dumper = b"""global dumpbuf uchar 8 |
| 321 | fn ir_dump x ulong to void |
| 322 | for j ulong 8 |
| 323 | put dumpbuf j uchar and shr x mul j 8 255 |
| 324 | end |
| 325 | p = ulong 0 |
| 326 | while lt p 8 bound 8 |
| 327 | k = write 1 dumpbuf p sub ulong 8 p |
| 328 | if le k 0 |
| 329 | exit 90 |
| 330 | end |
| 331 | p = add p ulong k |
| 332 | end |
| 333 | end |
| 334 | fn main to int |
| 335 | """ |
| 336 | for number, row in enumerate(path.read_text().splitlines(), 1): |
| 337 | if not row.strip() or row.startswith("#"): |
| 338 | continue |
| 339 | unit, function, result, typed, status = row.split() |
| 340 | if not re.fullmatch(r"\w+", unit) or not re.fullmatch(r"\w+", function): |
| 341 | raise Failure("invalid unit/function name in cases.tsv") |
| 342 | source_path = ROOT / ("seed/wasm/" + unit + ".unit.om") |
| 343 | if not source_path.is_file(): |
| 344 | source_path = ROOT / ("seed/spirv/" + unit + ".unit.om") |
| 345 | if not source_path.is_file(): |
| 346 | source_path = contained("tests/one_layer/omegese/dev/" + unit + ".omegese") |
| 347 | actual = [] |
| 348 | for item in (() if typed == "-" else typed.split(",")): |
| 349 | kind, value = item.split(":") |
| 350 | if kind == "bool" and value in ("true", "false"): |
| 351 | actual.append(value) |
| 352 | elif kind in ("byte", "uchar", "short", "ushort", "int", "uint", "long", "ulong") and re.fullmatch(r"-?\d+", value): |
| 353 | actual.append(kind + " " + value) |
| 354 | else: |
| 355 | raise Failure("unknown typed unit argument: " + item) |
| 356 | call = function + " " + " ".join(actual) |
| 357 | if result == "bool": |
| 358 | body = "if " + call + "\nir_dump ulong 1\nelse\nir_dump ulong 0\nend\n" |
| 359 | elif result == "void": |
| 360 | body = call + "\nir_dump ulong 0\n" |
| 361 | elif result in ("byte", "short", "int", "long"): |
| 362 | body = "ir_dump bitcast ulong long " + call + "\n" |
| 363 | elif result in ("uchar", "ushort", "uint", "ulong"): |
| 364 | body = "ir_dump ulong " + call + "\n" |
| 365 | else: |
| 366 | raise Failure("unknown unit result type: " + result) |
| 367 | source = source_path.read_bytes() + b"\n" + dumper + body.encode() + b"ret 0\nend\n" |
| 368 | yield Case(f"{path.relative_to(ROOT).as_posix()}:{number}:{unit}.{function}", source, |
| 369 | expected_exit=int(status), expected_compile="accept") |
| 370 | |
| 371 | |
| 372 | def positional_view_cases(): |
| 373 | # Mutability controls for the pread/pwrite writable-destination distinction. |
| 374 | # Invalid fd -1 makes accepted cases deterministic without filesystem effects. |
| 375 | for word, qualifier, accepted in (("pread", "view", False), |
| 376 | ("pread", "edit", True), |
| 377 | ("pwrite", "view", True), |
| 378 | ("pwrite", "edit", False)): |
| 379 | source = ( |
| 380 | "text ro \"abcd\"\n" |
| 381 | f"fn probe b {qualifier} uchar 4 to long\n" |
| 382 | f"ret {word} neg int 1 b 0 4 0\nend\nfn main to int\nrw = new uchar 4 0\n" |
| 383 | f"if ne probe {'rw' if word == 'pread' else 'ro'} neg long 9\n" |
| 384 | "ret 1\nend\nret 0\nend\n").encode() |
| 385 | yield Case(f"oracle-positional-{word}-{qualifier}", source, |
| 386 | expected_exit=0 if accepted else None, |
| 387 | expected_compile="accept" if accepted else "20") |
| 388 | |
| 389 | |
| 390 | def expanded_cases(files, record): |
| 391 | for case in cases(files, record): |
| 392 | plan = {} if case.operation in ("conductor", "bridge") else plan_case(ROOT, case.name.split(":", 1)[0], case.source) |
| 393 | if plan: |
| 394 | for key in ("source", "stdin", "args", "expected_exit", "driver", "blocker", "deadline"): |
| 395 | if key in plan and (case.operation == "differential" or key in ("driver", "blocker")): |
| 396 | setattr(case, key, plan[key]) |
| 397 | case.evidence.update(plan.get("evidence", {})) |
| 398 | if "effects" in plan: |
| 399 | case.evidence["reviewed_effects"] = plan["effects"] |
| 400 | case.evidence.update(stdin_bytes=len(case.stdin), stdin_sha256=digest(case.stdin), |
| 401 | args=list(case.args), original_case=case.name) |
| 402 | yield case |
| 403 | if plan and case.operation == "differential": |
| 404 | for variant in plan.get("variants", ()): |
| 405 | yield Case(case.name + ":" + variant["name"], case.source, variant["stdin"], tuple(variant["args"]), |
| 406 | driver=case.driver, expected_exit=variant["expected_exit"], deadline=case.deadline, |
| 407 | evidence={**case.evidence, "stdin_bytes": len(variant["stdin"]), |
| 408 | "stdin_sha256": digest(variant["stdin"]), "args": list(variant["args"]), |
| 409 | "variant_of": case.name}) |
| 410 | driver = case.driver or HOST_DRIVERS.get(digest(case.source)) |
| 411 | if driver == "network" and not case.args: |
| 412 | yield Case(case.name + ":gate-host-tcp-loopback", case.source, args=("tcp",), expected_exit=0) |
| 413 | elif driver in ("netdata", "peername") and not case.args: |
| 414 | for argument in ("1", "2", "3"): |
| 415 | yield Case(case.name + ":gate-host-bounds-" + argument, case.source, |
| 416 | args=(argument,), expected_exit=103) |
| 417 | elif driver == "memcheck": |
| 418 | # Read the conductor's literal-name and want assignments together. |
| 419 | # Literal ordering is not the case index (letters i/l/o/r are absent). |
| 420 | texts = {m[1]: literal_bytes(m[0])[0] for m in re.finditer( |
| 421 | rb'(?m)^[ \t]*text[ \t]+(\w+)[ \t]+"(?:[^"\\]|\\.)*"[^\n]*$', case.source)} |
| 422 | default = re.search(rb"(?m)^want = int (\d+)$", case.source) |
| 423 | arms = list(re.finditer( |
| 424 | rb"(?m)^if eq num (\d+)\nr = write fd (\w+) 0 len \2\n(?:want = (\d+)\n)?end$", case.source)) |
| 425 | if default is None or len(arms) != 36: |
| 426 | record("INVALID", case.name + ":embedded-refusals", |
| 427 | "memcheck conductor grammar changed; cannot infer expectations", |
| 428 | source_sha256=digest(case.source)) |
| 429 | continue |
| 430 | for arm in arms: |
| 431 | number, literal, code = arm.groups() |
| 432 | yield Case(case.name + ":embedded-refusal-" + number.decode(), texts[literal], |
| 433 | expected_compile=(code or default[1]).decode()) |
| 434 | yield from positional_view_cases() |
| 435 | current_sha = contained("om/sha256/sha256-om2.om").read_bytes() |
| 436 | yield Case("oracle-current-sha256-private-api", current_sha, driver="bare-private-abi", |
| 437 | expected_compile="accept", evidence={ |
| 438 | "source_spec": "om/sha256/sha256-om2.om", "source_sha256": digest(current_sha), |
| 439 | "scope": "current API, separate from frozen historical omsha composition and leak scanner"}) |
| 440 | |
| 441 | |
| 442 | @lru_cache(maxsize=None) |
| 443 | def conductor_resources(path): |
| 444 | """Exact transitive file allowlist for an original-conductor replay.""" |
| 445 | resources = {} |
| 446 | |
| 447 | def add(name): |
| 448 | if name in resources: |
| 449 | return |
| 450 | contained(name) |
| 451 | if path.relative_to(ROOT).as_posix() in SELFTEST_MANIFESTS and name in DELIBERATELY_ABSENT: |
| 452 | if contained(name).exists(): |
| 453 | raise Failure("original absent-input control unexpectedly exists: " + name) |
| 454 | return |
| 455 | if name in HISTORICAL_COMPILERS: |
| 456 | revision, sha = HISTORICAL_COMPILERS[name] |
| 457 | resources[name] = {"path": name, "sha256": sha, |
| 458 | "git_revision": revision, "git_path": "seed/omc/omc.om"} |
| 459 | elif (name == "seed/omc/omc.om" and path.relative_to(ROOT).as_posix().startswith("seed/qualification/om2/baseline/") |
| 460 | and path.relative_to(ROOT).as_posix() != "seed/qualification/om2/baseline/guard.cases"): |
| 461 | # guard.cases mutates the CURRENT compiler (its header); f56a372ae (#971) moved |
| 462 | # guard-wrapped.from to the current vs_chk text, which acb3f15's omc.om lacks. |
| 463 | resources[name] = dict(ORIGINAL_SOURCE) |
| 464 | elif name == "om/sha256/sha256.om": |
| 465 | resources[name] = {"path": name, "sha256": "7f034814303a8a40b4bc56383ddd55ab2ae8460291f80793340bc3b0ac024e21", |
| 466 | "pack_path": "seed/qualification/om2/c2/corpus.pack", "offset": 12540, "length": 35333} |
| 467 | else: |
| 468 | resources[name] = {"path": name, "sha256": digest(contained(name).read_bytes())} |
| 469 | |
| 470 | def source(spec, review=False): |
| 471 | for segment in spec.split("+"): |
| 472 | if segment.startswith(("pack:", "cyc:")): |
| 473 | add(segment.split(":")[1]) |
| 474 | else: |
| 475 | add(segment) |
| 476 | if review: |
| 477 | if spec in DELIBERATELY_ABSENT and path.relative_to(ROOT).as_posix() in SELFTEST_MANIFESTS: |
| 478 | return |
| 479 | data = source_bytes(spec) |
| 480 | words = host_words(data) |
| 481 | if words and digest(data) not in HOST_DRIVERS: |
| 482 | plan = plan_case(ROOT, spec, data) |
| 483 | if not plan or "blocker" in plan: |
| 484 | raise Failure(f"original conductor source {spec} has unreviewed effects: {words}" |
| 485 | + (f"; {plan['blocker']}" if plan else "")) |
| 486 | |
| 487 | add(path.relative_to(ROOT).as_posix()) |
| 488 | for constant in ("sha256-k", "sha256-iv"): |
| 489 | add("seed/qualification/om2/fixtures/" + constant + ".dec") |
| 490 | for line in path.read_text().splitlines(): |
| 491 | row = line.split() |
| 492 | if not row or row[0].startswith("#"): |
| 493 | continue |
| 494 | if path.relative_to(ROOT).as_posix() in SELFTEST_MANIFESTS and row[0] == "malformed": |
| 495 | continue # This exact reviewed control has no syntactically valid source field. |
| 496 | if row[0] == "subst": |
| 497 | for name in row[1:]: |
| 498 | add(name) |
| 499 | elif row[0] == "cc": |
| 500 | if row[1:] != ["pinned"]: |
| 501 | source("+".join(row[1:])) |
| 502 | elif len(row) > 2 and row[1] != "notrun": |
| 503 | source(row[2], review=row[1] in ("run", "kill")) |
| 504 | if row[1] == "same": |
| 505 | source(row[3]) |
| 506 | for spec in row[3:]: |
| 507 | if spec.startswith(("file:", "has:", "tok:")): |
| 508 | add(spec.split(":", 1)[1]) |
| 509 | return list(resources.values()) |
| 510 | |
| 511 | |
| 512 | @lru_cache(maxsize=None) |
| 513 | def selftest_expectations(path): |
| 514 | """Parse the original selftest's explicit comment groups, not case indices.""" |
| 515 | verdicts, group, overall = {}, None, None |
| 516 | for line in path.read_text().splitlines(): |
| 517 | if line.startswith("#"): |
| 518 | match = re.search(r"(?:expected|Expected)(?::\s+([\w-]+))?\s+(PASS|FAIL|INVALID|NOT_RUN)\b", line) |
| 519 | if match: |
| 520 | if match[1]: |
| 521 | verdicts[match[1]] = match[2] |
| 522 | else: |
| 523 | group = match[2] |
| 524 | elif "every case must PASS" in line: |
| 525 | group = "PASS" |
| 526 | exit_match = re.search(r"\bexit ([0-3])\b", line) |
| 527 | if exit_match: |
| 528 | overall = int(exit_match[1]) |
| 529 | continue |
| 530 | fields = line.split() |
| 531 | if not fields or fields[0] in ("subst", "cc", "deadline"): |
| 532 | continue |
| 533 | if fields[0] not in verdicts: |
| 534 | if group is None: |
| 535 | raise Failure("selftest case has no explicit comment verdict: " + line) |
| 536 | verdicts[fields[0]] = group |
| 537 | return verdicts, overall |
| 538 | |
| 539 | |
| 540 | def conductor_case(path, name, line, alternate, compiler_subst): |
| 541 | rel = path.relative_to(ROOT).as_posix() |
| 542 | selftest = rel in SELFTEST_MANIFESTS |
| 543 | old_om2_refusal = (rel == "seed/qualification/om2/leak/leak.cases" |
| 544 | and line.split()[0] == "s1-rot-refused") |
| 545 | historical = frozen_manifest(rel) or rel.endswith("/manifest-c2.txt") or old_om2_refusal |
| 546 | adequacy = rel == "seed/qualification/om2/baseline/adequacy.cases" |
| 547 | if not selftest and not historical and not adequacy and rel not in CONDUCTOR_FAILURES: |
| 548 | raise Failure(f"alternate compiler manifest has no reviewed original-verdict authority: {rel}") |
| 549 | resources = conductor_resources(path) |
| 550 | original_name = line.split()[0] |
| 551 | expected = (selftest_expectations(path)[0][original_name] if selftest else |
| 552 | ("FAIL" if adequacy or original_name in CONDUCTOR_FAILURES.get(rel, "").split() else "PASS")) |
| 553 | historical_failure = None |
| 554 | if rel == "seed/qualification/om2/candidates/s2/s2-mutants.cases": |
| 555 | failures = {"unroll-kplus1-kill-unroll-nest": "compile exit=21 expected=0"} |
| 556 | for arm, code in (("B", 101), ("C", 105), ("D", 107), ("E", 101), |
| 557 | ("F", 101), ("H", 105), ("I", 102)): |
| 558 | failures["fold-div0-kill-fold-trap-" + arm] = ( |
| 559 | f"run exit={code} expected=0 mutant survived: stdout equals the oracle " |
| 560 | "stderr=match; not a meaningful kill") |
| 561 | if original_name in failures: |
| 562 | # f56a372ae (#971) moved only the four ctl-*-sha control sources from the deleted |
| 563 | # om/sha256/sha256.om to seed/qualification/om2/baseline/sha256-om1.om, whose sha256 |
| 564 | # 7f034814...4e21 equals the acb3f15 source pinned below; kill and failure rows unchanged. |
| 565 | # Previous manifest sha256 0ac554e4497232cc1ba99caca4e07cb12c62b5e3dd1c4af027864a31b29fbc64. |
| 566 | if digest(path.read_bytes()) != "69eb3687c3f0a108c4aab3a7989ded6de0e46b118b4e2856ebfbacbaec3cc90c": |
| 567 | raise Failure("historical S2 failure contract manifest changed") |
| 568 | historical_failure = { |
| 569 | "original_expected": expected, "original_observed": "FAIL", |
| 570 | "exact_verdict": f"VERDICT {original_name} FAIL {failures[original_name]}", |
| 571 | "scope": "historical failed experiment; reproduction is not a successful mutant kill"} |
| 572 | authority = "\n".join(row for row in path.read_text().splitlines() if row.startswith("#")) |
| 573 | authority_path = rel |
| 574 | if rel.endswith("s1-lexmutants.cases"): |
| 575 | authority_path = "seed/qualification/om2/candidates/s1/RESULTS.txt" |
| 576 | authority = "\n".join(contained(authority_path).read_text().splitlines()[37:43]) |
| 577 | return Case(name, contained("seed/qualification/om2/gate.om").read_bytes(), |
| 578 | driver="corpus-gate", operation="conductor", |
| 579 | expected_compile="accept", evidence={ |
| 580 | "manifest": rel, "resources": resources, "conductor_row": line, |
| 581 | "alternate_compiler": alternate, "compiler_substitution": compiler_subst, |
| 582 | "child_compiler_identity": "pinned" if old_om2_refusal else conductor_identity(rel), |
| 583 | "expected_failure_reason": "mutant survived" if adequacy else NEGATIVE_CONDUCTOR_MANIFESTS.get(rel), |
| 584 | "control_kind": "supervisor_verdict_control" if selftest else ("compiler_mutant" if expected == "FAIL" else "compiler_control"), |
| 585 | "expected_overall_exit": selftest_expectations(path)[1] if selftest else None, |
| 586 | "expected_original_conductor": expected, "original_case_name": original_name, |
| 587 | "historical_failure": historical_failure, |
| 588 | "authority": {"path": authority_path, "sha256": digest(contained(authority_path).read_bytes()), |
| 589 | "quote": authority}}) |
| 590 | |
| 591 | |
| 592 | def current_c2_contract(fields): |
| 593 | """Use the already accepted deltas, retaining the frozen replay separately.""" |
| 594 | for relative in ("seed/qualification/om2/manifest-c2-capacity.txt", |
| 595 | "seed/qualification/om2/manifest-c2-batch2.txt", |
| 596 | "seed/qualification/om2/manifest-c2-fpvreg.txt", |
| 597 | "seed/qualification/om2/manifest-c2-closerange.txt", |
| 598 | "seed/qualification/om2/manifest-c2-longnames.txt"): |
| 599 | path = ROOT / relative |
| 600 | for line in path.read_text().splitlines(): |
| 601 | replacement = line.split() |
| 602 | if not replacement or replacement[0].startswith("#") or replacement[0] != fields[0]: |
| 603 | continue |
| 604 | if replacement[1:3] != fields[1:3]: |
| 605 | raise Failure("current C2 delta changed the frozen operation or input") |
| 606 | return replacement, {"path": relative, "sha256": digest(path.read_bytes()), |
| 607 | "frozen_row": " ".join(fields), "current_row": line} |
| 608 | return fields, None |
| 609 | |
| 610 | |
| 611 | def cases(files, record): |
| 612 | for path in files: |
| 613 | rel = path.relative_to(ROOT).as_posix() |
| 614 | if path.suffix == ".tsv": |
| 615 | try: |
| 616 | yield from unit_cases(path) |
| 617 | except (OSError, ValueError, Failure) as error: |
| 618 | record("MISSING_INPUT", rel, str(error)) |
| 619 | continue |
| 620 | if path.suffix in (".om", ".omegese"): |
| 621 | source = path.read_bytes() |
| 622 | # Conductors are real compiler inputs too. Their effects are gated |
| 623 | # by reviewed drivers, not dropped just because they test a checker. |
| 624 | yield Case(rel, source) |
| 625 | if rel in ("seed/rung4/tests/echo.om", "seed/rung4/tests/bytecopy.om"): |
| 626 | yield Case(rel + ":gate4-nonempty", source, stdin_bytes("seq:50000")) |
| 627 | continue |
| 628 | alternate, compiler_subst, subst = None, None, None |
| 629 | deadline = 30 # Original gate.om's documented default, seconds. |
| 630 | for number, line in enumerate(path.read_text().splitlines(), 1): |
| 631 | fields = line.split() |
| 632 | if not fields or fields[0].startswith("#"): |
| 633 | continue |
| 634 | name = f"{rel}:{number}:{fields[0]}" |
| 635 | if fields[0] == "cc": |
| 636 | alternate = None if fields[1:] == ["pinned"] else "+".join(fields[1:]) |
| 637 | compiler_subst, subst = subst, None |
| 638 | record("EXCLUDED", name, |
| 639 | f"compiler-selection directive {' '.join(fields[1:])}; subsequent rows retain this compiler identity", |
| 640 | conductor_row=line, compiler_substitution=compiler_subst) |
| 641 | continue |
| 642 | if fields[0] == "deadline": |
| 643 | if len(fields) != 2 or not fields[1].isdigit() or not 1 <= int(fields[1]) <= 900: |
| 644 | record("INVALID", name, "deadline requires original conductor's integer seconds 1..900", conductor_row=line) |
| 645 | continue |
| 646 | deadline = int(fields[1]) |
| 647 | record("EXCLUDED", name, |
| 648 | f"conductor-only metadata: exact {deadline}-second deadline attached to subsequent child arms", |
| 649 | conductor_row=line, manifest_sha256=digest(path.read_bytes())) |
| 650 | continue |
| 651 | if fields[0] == "subst": |
| 652 | subst = fields[1:] |
| 653 | record("EXCLUDED", name, |
| 654 | f"stateful substitution {' '.join(fields[1:])}; not a standalone source; interpreted by the next arm or complete original selftest conductor", |
| 655 | conductor_row=line, manifest_sha256=digest(path.read_bytes()), substitution_paths=fields[1:]) |
| 656 | continue |
| 657 | if len(fields) < 2: |
| 658 | record("INVALID", name, "malformed conductor row", conductor_row=line) |
| 659 | continue |
| 660 | mode = fields[1] |
| 661 | if rel == "seed/qualification/om2/leak/leak.cases" and fields[0] == "s1-rot-refused": |
| 662 | yield conductor_case(path, name + ":frozen-provenance", line, None, None) |
| 663 | current_path = ROOT / "seed/qualification/om2/leak/candidate.cases" |
| 664 | current = next(row for row in current_path.read_text().splitlines() |
| 665 | if row.startswith("s1-rot-build ")) |
| 666 | replacement = current.split() |
| 667 | if replacement[1:] != ["emit", fields[2], "any", "-", "0"]: |
| 668 | raise Failure("current OM-2 acceptance contract changed") |
| 669 | yield Case(name + ":current", source_bytes(fields[2]), expected_compile="accept", |
| 670 | operation="emit", stdout_oracle="any", stderr_oracle="-", |
| 671 | evidence={"historical_obligation": name, "accepted_current_contract": { |
| 672 | "path": current_path.relative_to(ROOT).as_posix(), |
| 673 | "sha256": digest(current_path.read_bytes()), "row": current}}) |
| 674 | continue |
| 675 | if frozen_manifest(rel): |
| 676 | yield conductor_case(path, name, line, None, None) |
| 677 | # The old compiler's oracle remains a separate, mandatory replay. |
| 678 | # Current code generation is additionally compared, not substituted. |
| 679 | source = source_bytes(fields[2]) |
| 680 | yield Case(name + ":current-differential", source, |
| 681 | stdin=stdin_bytes(fields[3]) if fields[1] == "run" else b"", |
| 682 | args=tuple(fields[7:]) if fields[1] == "run" else (), |
| 683 | evidence={"historical_obligation": name, "conductor_row": line}) |
| 684 | continue |
| 685 | if rel == "seed/qualification/om2/baseline/adequacy.cases": |
| 686 | yield conductor_case(path, name, line, None, None) |
| 687 | subst = None |
| 688 | continue |
| 689 | if rel in MUTANT_SPECIFICATIONS and mode != "notrun": |
| 690 | matches = [] |
| 691 | for candidate in sorted((ROOT / "seed/qualification/om2/candidates").rglob("*mutants.cases")): |
| 692 | for candidate_line in candidate.read_text().splitlines(): |
| 693 | candidate_fields = candidate_line.split() |
| 694 | if candidate_fields and candidate_fields[1:] == fields[1:]: |
| 695 | matches.append(conductor_case(candidate, name, candidate_line, None, None)) |
| 696 | if not matches: |
| 697 | record("FAIL", name, "mutant specification has no executable compiler mutation", conductor_row=line) |
| 698 | else: |
| 699 | obligation = matches[0] |
| 700 | replays = [dict(item.evidence) for item in matches] |
| 701 | obligation.evidence["mutant_specification"] = {"path": rel, "line": number, "row": line} |
| 702 | obligation.evidence["required_mutant_replays"] = replays |
| 703 | yield obligation |
| 704 | continue |
| 705 | if rel in SELFTEST_MANIFESTS: |
| 706 | try: |
| 707 | yield conductor_case(path, name, line, alternate, compiler_subst) |
| 708 | except (OSError, ValueError, Failure) as error: |
| 709 | record("FAIL", name, str(error), conductor_row=line) |
| 710 | subst = None |
| 711 | continue |
| 712 | if mode == "notrun": |
| 713 | try: |
| 714 | binding = bridge_plan(ROOT, name) |
| 715 | except (OSError, ValueError, Failure) as error: |
| 716 | record("FAIL", name, "reviewed bridge plan: " + str(error), conductor_row=line) |
| 717 | continue |
| 718 | if binding: |
| 719 | if binding["operation"] == "units-check": |
| 720 | source = contained(binding["script"]).read_bytes() |
| 721 | elif "driver_source" in binding: |
| 722 | source = binding["driver_source"] |
| 723 | else: |
| 724 | source = contained(binding["driver"]).read_bytes() |
| 725 | yield Case(name, source, driver="external-c-boundary", operation="bridge", bridge=binding, |
| 726 | args=tuple(binding["args"]), expected_exit=binding["expected_exit"], |
| 727 | evidence={"conductor_row": line, "unit_sources": binding["units"], |
| 728 | "driver_sha256": binding["driver_sha256"], **binding["evidence"]}) |
| 729 | continue |
| 730 | plan = directive_plan(ROOT, name) |
| 731 | evidence = {"conductor_row": line, **(plan.get("evidence", {}) if plan else {})} |
| 732 | if plan and "source" in plan: |
| 733 | yield Case(name, plan["source"], stdin=plan.get("stdin", b""), |
| 734 | args=tuple(plan.get("args", ())), driver=plan.get("driver"), |
| 735 | expected_exit=plan.get("expected_exit"), |
| 736 | expected_compile=plan.get("expected_compile", "accept"), |
| 737 | operation=plan.get("operation", "differential"), evidence=evidence, deadline=deadline, |
| 738 | stdout_oracle=plan.get("stdout_oracle"), stderr_oracle=plan.get("stderr_oracle")) |
| 739 | else: |
| 740 | reason = plan.get("blocker", " ".join(fields[2:])) if plan else " ".join(fields[2:]) |
| 741 | record("BLOCKED" if reason.startswith("BLOCKED_ON ") else "NOT_RUN", |
| 742 | name, reason, evidence=evidence, conductor_row=line) |
| 743 | continue |
| 744 | if rel in NEGATIVE_CONDUCTOR_MANIFESTS: |
| 745 | yield conductor_case(path, name, line, None, None) |
| 746 | subst = None |
| 747 | continue |
| 748 | if alternate: |
| 749 | try: |
| 750 | yield conductor_case(path, name, line, alternate, compiler_subst) |
| 751 | except (OSError, ValueError, Failure) as error: |
| 752 | record("BLOCKED", name, str(error), conductor_row=line, |
| 753 | alternate_compiler=alternate, compiler_substitution=compiler_subst) |
| 754 | subst = None |
| 755 | continue |
| 756 | try: |
| 757 | source = source_bytes(fields[2]) |
| 758 | if rel.endswith("/manifest-c2.txt"): |
| 759 | frozen = conductor_case(path, name + ":frozen-provenance", line, None, None) |
| 760 | yield frozen |
| 761 | evidence = {"conductor_row": line, "source_spec": fields[2], "conductor_deadline_seconds": deadline} |
| 762 | if rel.endswith("/manifest-c2.txt"): |
| 763 | fields, replacement = current_c2_contract(fields) |
| 764 | if replacement: |
| 765 | evidence["accepted_current_contract"] = replacement |
| 766 | if ("om/sha256/sha256.om" in fields[2] or |
| 767 | "seed/qualification/om2/baseline/sha256-om1.om" in fields[2]): |
| 768 | evidence["historical_source"] = { |
| 769 | "path": "om/sha256/sha256.om", "revision": "acb3f15", |
| 770 | "packed_spec": "pack:seed/qualification/om2/c2/corpus.pack:12540:35333", |
| 771 | "sha256": "7f034814303a8a40b4bc56383ddd55ab2ae8460291f80793340bc3b0ac024e21", |
| 772 | "provenance": "seed/qualification/om2/c2/index.tsv:c2-00003"} |
| 773 | if subst is not None: |
| 774 | if mode == "same": |
| 775 | raise Failure("original conductor forbids substitution before same") |
| 776 | if len(subst) != 2: |
| 777 | raise Failure("malformed subst directive") |
| 778 | old, new = (source_bytes(part) for part in subst) |
| 779 | if not old or source.count(old) != 1: |
| 780 | raise Failure("subst source must contain FROMFILE exactly once") |
| 781 | source = source.replace(old, new) |
| 782 | evidence["source_substitution"] = subst |
| 783 | subst = None |
| 784 | if mode in ("run", "kill") and len(fields) >= 7: |
| 785 | yield Case(name, source, stdin_bytes(fields[3]), tuple(fields[7:]), |
| 786 | expected_exit=int(fields[6]), expected_compile="accept", |
| 787 | operation=mode, stdout_oracle=fields[4], stderr_oracle=fields[5], evidence=evidence, deadline=deadline) |
| 788 | elif mode == "emit" and len(fields) == 6: |
| 789 | code = int(fields[5]) |
| 790 | yield Case(name, source, expected_exit=code, |
| 791 | expected_compile="accept" if code == 0 else str(code), |
| 792 | operation=mode, stdout_oracle=fields[3], stderr_oracle=fields[4], evidence=evidence, deadline=deadline) |
| 793 | elif mode == "refuse" and len(fields) == 4: |
| 794 | yield Case(name, source, expected_compile=fields[3], operation=mode, evidence=evidence, deadline=deadline) |
| 795 | elif mode == "same" and len(fields) == 4: |
| 796 | yield Case(name, source, expected_compile="accept", operation=mode, |
| 797 | same_source=source_bytes(fields[3]), evidence=evidence, deadline=deadline) |
| 798 | else: |
| 799 | record("INVALID", name, "unknown/malformed conductor operation " + mode, conductor_row=line) |
| 800 | except (OSError, ValueError, Failure) as error: |
| 801 | record("MISSING_INPUT", name, str(error), conductor_row=line) |
| 802 | |
| 803 | |
| 804 | def limits(cpu_seconds=None, nofile=256): |
| 805 | resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) |
| 806 | resource.setrlimit(resource.RLIMIT_FSIZE, (64 * 1024 * 1024, 64 * 1024 * 1024)) |
| 807 | resource.setrlimit(resource.RLIMIT_NOFILE, (nofile, nofile)) |
| 808 | if cpu_seconds is not None: |
| 809 | # Soft limit delivers SIGXCPU; the higher hard limit keeps SIGKILL out of the way. |
| 810 | resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 2)) |
| 811 | |
| 812 | |
| 813 | def run(command, data, cwd, timeout, *, extra_env=None, cpu_seconds=None, nofile=256): |
| 814 | # Regular-file stdin matches seekable-input fixtures; no shell interpolation. |
| 815 | with tempfile.TemporaryFile() as inp, tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err: |
| 816 | inp.write(data) |
| 817 | inp.seek(0) |
| 818 | process = subprocess.Popen(command, stdin=inp, stdout=out, stderr=err, cwd=cwd, |
| 819 | env={"LC_ALL": "C", "PATH": os.defpath, "HOME": ".", "OMTEST": "hello", **(extra_env or {})}, |
| 820 | start_new_session=True, preexec_fn=lambda: limits(cpu_seconds, nofile)) |
| 821 | try: |
| 822 | process.wait(timeout=timeout) |
| 823 | except subprocess.TimeoutExpired: |
| 824 | os.killpg(process.pid, signal.SIGKILL) |
| 825 | process.wait() |
| 826 | out.seek(0, os.SEEK_END) |
| 827 | out.seek(max(0, out.tell() - 4096)) |
| 828 | err.seek(0, os.SEEK_END) |
| 829 | err.seek(max(0, err.tell() - 4096)) |
| 830 | raise Failure(f"child timeout after {timeout}s: {command!r}; stdout_tail={out.read()!r}; stderr_tail={err.read()!r}") |
| 831 | finally: |
| 832 | # Also remove descendants of a child which exited before its children. |
| 833 | try: |
| 834 | os.killpg(process.pid, signal.SIGKILL) |
| 835 | except ProcessLookupError: |
| 836 | pass |
| 837 | out.seek(0) |
| 838 | err.seek(0) |
| 839 | return process.returncode, out.read(), err.read() |
| 840 | |
| 841 | |
| 842 | def elf_range(image): |
| 843 | if len(image) < 64 or image[:6] != b"\x7fELF\x02\x01": |
| 844 | raise Failure("not ELF64 little endian") |
| 845 | if struct.unpack_from("<H", image, 18)[0] != 62: |
| 846 | raise Failure("ELF e_machine is not x86-64") |
| 847 | phoff = struct.unpack_from("<Q", image, 32)[0] |
| 848 | size, count = struct.unpack_from("<HH", image, 54) |
| 849 | executable = [] |
| 850 | for i in range(count): |
| 851 | p = phoff + i * size |
| 852 | if p + 56 > len(image): |
| 853 | raise Failure("truncated ELF program headers") |
| 854 | kind, flags, offset, address, _, length, _, _ = struct.unpack_from("<IIQQQQQQ", image, p) |
| 855 | if kind == 1 and flags & 1: |
| 856 | executable.append((offset, address, length)) |
| 857 | if len(executable) != 1: |
| 858 | raise Failure("expected one executable PT_LOAD") |
| 859 | offset, address, length = executable[0] |
| 860 | # FR-9 sectionless emitter reserves bytes [0,512) for ELF headers, then emits |
| 861 | # code/literals in source order. This is a checked format contract, not guessed |
| 862 | # by looking for byte sequences that resemble function prologues. |
| 863 | if offset != 0 or length != len(image) or length <= 512: |
| 864 | raise Failure("unsupported executable layout: expected whole-file PT_LOAD and 512-byte prelude") |
| 865 | return 512, length, address |
| 866 | |
| 867 | |
| 868 | def literal_bytes(source): |
| 869 | result = [] |
| 870 | for match in TEXT.finditer(source): |
| 871 | literal = re.sub(rb'\\([nt\\"])', lambda m: {b'n': b'\n', b't': b'\t', b'\\': b'\\', b'"': b'"'}[m[1]], match[1]) |
| 872 | result.append(literal) |
| 873 | return result |
| 874 | |
| 875 | |
| 876 | def code_spans(image, source): |
| 877 | if not MAIN.search(source) and image[:4] != b"\x7fELF": |
| 878 | # Bare x86 units omit the reserved 512 bytes. Their six-byte entry |
| 879 | # branches and function bodies use the private frame ABI, not SysV. |
| 880 | if not image: |
| 881 | raise Failure("empty bare unit") |
| 882 | start, end, address = 0, len(image), 0 |
| 883 | else: |
| 884 | start, end, address = elf_range(image) |
| 885 | cursor, spans, carveouts = start, [], [] |
| 886 | # Every literal must be unambiguously protected by a near JMP, exactly match |
| 887 | # the source-decoded bytes, and have only zero alignment padding. Ambiguous |
| 888 | # matches fail closed rather than silently carving possible instructions out. |
| 889 | # Empty text emits no bytes, jump or padding in the integrated compiler. |
| 890 | # It creates no carveout: every executable byte still goes to the decoder. |
| 891 | literals = [literal for literal in literal_bytes(source) if literal] |
| 892 | locations = {} |
| 893 | for literal in set(literals): |
| 894 | candidates = [] |
| 895 | for p in range(start, end - 4): |
| 896 | if image[p] != 0xe9: |
| 897 | continue |
| 898 | after = p + 5 + struct.unpack_from("<i", image, p + 1)[0] |
| 899 | # xbranch reserves six bytes: E9 rel32 followed by a NOP. |
| 900 | # The NOP is an instruction, not a literal/data carveout. |
| 901 | if p + 5 >= end or image[p + 5] != 0x90: |
| 902 | continue |
| 903 | data_start = p + 6 |
| 904 | data_end = data_start + len(literal) |
| 905 | if (data_end <= after <= data_end + 3 and after <= end and |
| 906 | image[data_start:data_end] == literal and |
| 907 | image[data_end:after] == b"\0" * (after - data_end)): |
| 908 | candidates.append((p, data_start, after)) |
| 909 | locations[literal] = candidates |
| 910 | earliest, latest = [], [] |
| 911 | lower = start |
| 912 | for literal in literals: |
| 913 | candidate = next((c for c in locations[literal] if c[0] >= lower), None) |
| 914 | if candidate is None: |
| 915 | raise Failure("ORACLE_COVERAGE_MISSING no ordered branch-around location for source literal") |
| 916 | earliest.append(candidate) |
| 917 | lower = candidate[2] |
| 918 | upper = end |
| 919 | for literal in reversed(literals): |
| 920 | candidate = next((c for c in reversed(locations[literal]) if c[2] <= upper), None) |
| 921 | if candidate is None: |
| 922 | raise Failure("ORACLE_COVERAGE_MISSING no reverse ordered literal mapping") |
| 923 | latest.append(candidate) |
| 924 | upper = candidate[0] |
| 925 | if earliest != list(reversed(latest)): |
| 926 | raise Failure("ORACLE_COVERAGE_MISSING ambiguous ordered literal mapping") |
| 927 | for p, data_start, after in earliest: |
| 928 | spans.append((cursor, data_start)) |
| 929 | carveouts.append((data_start, after)) |
| 930 | cursor = after |
| 931 | spans.append((cursor, end)) |
| 932 | return [(a, b, address) for a, b in spans if b > a], carveouts |
| 933 | |
| 934 | |
| 935 | def oracle_elf(code, address): |
| 936 | # An oracle-only ELF wrapper exposes a code span to either disassembler. It |
| 937 | # does not transform or implement the candidate instructions. |
| 938 | names = b"\0.text\0.shstrtab\0" |
| 939 | names_at = 64 + len(code) |
| 940 | sections_at = (names_at + len(names) + 7) & ~7 |
| 941 | header = struct.pack("<16sHHIQQQIHHHHHH", b"\x7fELF\x02\x01\x01" + bytes(9), |
| 942 | 1, 62, 1, 0, 0, sections_at, 0, 64, 0, 0, 64, 3, 2) |
| 943 | text = struct.pack("<IIQQQQIIQQ", 1, 1, 6, address, 64, len(code), 0, 0, 1, 0) |
| 944 | strings = struct.pack("<IIQQQQIIQQ", 7, 3, 0, 0, names_at, len(names), 0, 0, 1, 0) |
| 945 | body = header + code + names |
| 946 | return body + bytes(sections_at - len(body)) + bytes(64) + text + strings |
| 947 | |
| 948 | |
| 949 | def disassemble(image, source, objdump, llvm, cwd, timeout): |
| 950 | spans, carveouts = code_spans(image, source) |
| 951 | mnemonics = Counter() |
| 952 | instructions = [] |
| 953 | for n, (start, end, base) in enumerate(spans): |
| 954 | cursor = base + start |
| 955 | while cursor < base + end: |
| 956 | offset = cursor - base |
| 957 | chunk_end = min(offset + 65536, end) |
| 958 | # Decode from an established instruction boundary, with enough |
| 959 | # lookahead to finish a boundary-crossing x86 instruction. Consume |
| 960 | # only through that instruction, then start the next bounded chunk |
| 961 | # there. The child output cap never truncates a large whole image. |
| 962 | decode_end = min(chunk_end + 15, end) |
| 963 | wrapper = cwd / f"oracle-{n}.elf" |
| 964 | wrapper.write_bytes(oracle_elf(image[offset:decode_end], cursor)) |
| 965 | options = ["-d", "-z", "--x86-asm-syntax=intel"] if llvm else ["-d", "-z", "-M", "intel", "--insn-width=16"] |
| 966 | rc, output, error = run([objdump, *options, str(wrapper)], b"", cwd, timeout) |
| 967 | if rc: |
| 968 | raise Failure(f"disassembler refusal: exit={rc} stdout_bytes={len(output)} stderr={error!r}") |
| 969 | for line in output.decode("utf-8", "replace").splitlines(): |
| 970 | match = INSTRUCTION.match(line) |
| 971 | if not match: |
| 972 | continue |
| 973 | address = int(match[1], 16) |
| 974 | raw = bytes.fromhex(match[2]) |
| 975 | asm = match[3].strip() |
| 976 | if address != cursor or not raw or not asm: |
| 977 | raise Failure("disassembly byte gap/overlap or undecoded instruction: " + line) |
| 978 | offset = address - base |
| 979 | if image[offset:offset + len(raw)] != raw: |
| 980 | raise Failure("disassembler bytes differ from emitted image") |
| 981 | if re.search(r"\(bad\)|<unknown>|\.byte|\.word|\.short|\.long|\.quad", asm): |
| 982 | raise Failure("invalid instruction: " + line) |
| 983 | mnemonic = asm.split()[0] |
| 984 | if mnemonic in ("rex", "rex.W", "data16", "addr32", "rep", "repz", "repnz", "lock") and len(asm.split()) == 1: |
| 985 | raise Failure("orphan instruction prefix: " + line) |
| 986 | mnemonics[mnemonic] += 1 |
| 987 | instructions.append((offset, raw, asm)) |
| 988 | cursor += len(raw) |
| 989 | if cursor >= base + chunk_end: |
| 990 | break |
| 991 | if cursor < base + chunk_end or cursor > base + end: |
| 992 | raise Failure(f"disassembler did not cover every code byte: stopped {cursor:x}, expected chunk {base + chunk_end:x}") |
| 993 | boundaries = {base + offset for offset, _, _ in instructions} |
| 994 | for offset, raw, asm in instructions: |
| 995 | branch = re.match(r"(?:j\w+|callq?)\s+(?:0x)?([0-9a-fA-F]+)(?:\s|$)", asm) |
| 996 | if branch and int(branch[1], 16) not in boundaries: |
| 997 | raise Failure("direct control-flow target is not a decoded instruction boundary: " + asm) |
| 998 | return mnemonics, instructions, carveouts |
| 999 | |
| 1000 | |
| 1001 | def normalized_diagnostics(error, shift): |
| 1002 | """Undo ONLY the known selector's source-coordinate translation. |
| 1003 | |
| 1004 | xlead replaces the 14 selector characters by spaces but keeps its LF. |
| 1005 | Human and structured line fields move by one, absolute spans by 15 bytes. |
| 1006 | Columns, codes, token bytes, obligations and all other text stay exact. |
| 1007 | """ |
| 1008 | if not shift: |
| 1009 | return error |
| 1010 | translated = [] |
| 1011 | for line in error.splitlines(keepends=True): |
| 1012 | if line.startswith(b"omc: line "): |
| 1013 | line = re.sub(rb"(?<=line )\d+(?=: error )", |
| 1014 | lambda m: str(int(m[0]) - shift if int(m[0]) else 0).encode(), line) |
| 1015 | elif re.match(rb"omc-(?:diag|site|check) 1 ", line): |
| 1016 | line = re.sub(rb"(?<=line=)\d+", |
| 1017 | lambda m: str(int(m[0]) - shift if int(m[0]) else 0).encode(), line) |
| 1018 | line = re.sub(rb"(?<=span=)(\d+)-(\d+)", |
| 1019 | lambda m: f"{int(m[1]) - shift * len(TARGET_PREFIX)}-{int(m[2]) - shift * len(TARGET_PREFIX)}".encode(), |
| 1020 | line) |
| 1021 | translated.append(line) |
| 1022 | return b"".join(translated) |
| 1023 | |
| 1024 | |
| 1025 | def source_site_diagnostics(native, target, source_lines): |
| 1026 | """Compare reviewed source sites, retaining architecture-specific stub tables.""" |
| 1027 | allowed = set(source_lines) |
| 1028 | |
| 1029 | def parse(data): |
| 1030 | other, all_sites, source_sites, seen = [], [], [], set() |
| 1031 | for line in data.splitlines(keepends=True): |
| 1032 | if not line.startswith(b"omc-site "): |
| 1033 | other.append(line) |
| 1034 | continue |
| 1035 | match = re.fullmatch(rb"omc-site 1 line=(\d+) iter=(-|\d+(?:\.\d+)*)\n", line) |
| 1036 | if not match: |
| 1037 | raise Failure("malformed compiler site record: " + repr(line)) |
| 1038 | site = int(match[1]), match[2].decode() |
| 1039 | all_sites.append(site) |
| 1040 | if site[0] in allowed and site not in seen: |
| 1041 | source_sites.append(site) |
| 1042 | seen.add(site) |
| 1043 | return b"".join(other), all_sites, source_sites |
| 1044 | |
| 1045 | left, right = parse(native), parse(target) |
| 1046 | observation = {"native_sites": left[1], "x86_normalized_sites": right[1], |
| 1047 | "native_source_sites": left[2], "x86_source_sites": right[2], |
| 1048 | "reviewed_source_lines": source_lines, |
| 1049 | "comparison": "ordered first-occurrence (source line, unrolled iteration); all non-site diagnostic bytes exact"} |
| 1050 | if not left[2] or left[0] != right[0] or left[2] != right[2]: |
| 1051 | raise Failure("source-level site/non-site compiler diagnostic differential: " + str(observation)) |
| 1052 | return observation |
| 1053 | |
| 1054 | |
| 1055 | @lru_cache(maxsize=1) |
| 1056 | def diagnostic_contracts(): |
| 1057 | path = ROOT / "seed/omc/x86-diagnostic-contracts.json" |
| 1058 | document = json.loads(path.read_text()) |
| 1059 | if document["schema"] != 1: |
| 1060 | raise Failure("unsupported target diagnostic contract schema") |
| 1061 | contracts = {} |
| 1062 | for entry in document["contracts"]: |
| 1063 | key = entry["source_sha256"] |
| 1064 | if key in contracts or digest(source_bytes(entry["source_spec"])) != key: |
| 1065 | raise Failure("duplicate or stale target diagnostic contract: " + entry["source_spec"]) |
| 1066 | contracts[key] = entry |
| 1067 | return contracts |
| 1068 | |
| 1069 | |
| 1070 | def target_diagnostic_contract(source, native, target): |
| 1071 | """Assert exact records, never discard target-specific safety checks.""" |
| 1072 | contract = diagnostic_contracts().get(digest(source)) |
| 1073 | if contract is None: |
| 1074 | return None |
| 1075 | for architecture, actual in (("aarch64", native), ("x86_64", target)): |
| 1076 | expected = contract[architecture] |
| 1077 | if actual[0] != expected["exit"] or actual[2] != expected["stderr"].encode(): |
| 1078 | raise Failure("exact target diagnostic contract differs: " + architecture) |
| 1079 | if expected["exit"]: |
| 1080 | refusal(actual, 0) # Refusals must still be clean, with no artifact. |
| 1081 | return {"path": "seed/omc/x86-diagnostic-contracts.json", |
| 1082 | "sha256": digest((ROOT / "seed/omc/x86-diagnostic-contracts.json").read_bytes()), |
| 1083 | "source_spec": contract["source_spec"], "reason": contract["reason"], |
| 1084 | "x86_execution": contract.get("x86_execution")} |
| 1085 | |
| 1086 | |
| 1087 | def refusal(result, shift): |
| 1088 | rc, output, error = result |
| 1089 | match = DIAG.search(error) |
| 1090 | if rc <= 0 or output or not match or int(match[2]) != rc: |
| 1091 | raise Failure("not a clean compiler refusal") |
| 1092 | return rc, output, normalized_diagnostics(error, shift) |
| 1093 | |
| 1094 | |
| 1095 | def matches_oracle(actual, spec): |
| 1096 | if spec is None or spec == "any": |
| 1097 | return True |
| 1098 | if spec == "-": |
| 1099 | return actual == b"" |
| 1100 | if spec.startswith("sha:"): |
| 1101 | return digest(actual) == spec[4:] |
| 1102 | if spec.startswith("file:"): |
| 1103 | return actual == contained(spec[5:]).read_bytes() |
| 1104 | if spec.startswith("line:"): |
| 1105 | return actual == spec[5:].encode() + b"\n" |
| 1106 | if spec.startswith("err:"): |
| 1107 | _, line, code = spec.split(":") |
| 1108 | return actual == f"omc: line {line}: error {code}\n".encode() |
| 1109 | if spec.startswith(("has:", "tok:")): |
| 1110 | kind, path = spec.split(":", 1) |
| 1111 | expected = contained(path).read_bytes().splitlines() |
| 1112 | observed = actual.splitlines() |
| 1113 | if kind == "has": |
| 1114 | return all(line in observed for line in expected) |
| 1115 | return all(any(all(word in line.split() for word in wanted.split()) |
| 1116 | for line in observed) for wanted in expected) |
| 1117 | raise Failure("unknown output oracle grammar: " + spec) |
| 1118 | |
| 1119 | |
| 1120 | def assert_oracle(actual, spec, label, different=False): |
| 1121 | matched = matches_oracle(actual, spec) |
| 1122 | if matched == different: |
| 1123 | raise Failure(f"{label} {'mutant survived (equals)' if different else 'differs from'} " |
| 1124 | f"oracle {spec}: bytes={len(actual)} sha256={digest(actual)} " |
| 1125 | f"prefix={actual[:160]!r}") |
| 1126 | |
| 1127 | |
| 1128 | def result_details(result): |
| 1129 | return {"exit": result[0], "stdout_bytes": len(result[1]), |
| 1130 | "stdout_sha256": digest(result[1]), "stdout_prefix": repr(result[1][:160]), |
| 1131 | "stderr_bytes": len(result[2]), "stderr_sha256": digest(result[2]), |
| 1132 | "stderr": result[2][:8192].decode("utf-8", "backslashreplace")} |
| 1133 | |
| 1134 | |
| 1135 | def ioctl_emulator_artifact(case, driver, arun, xrun, qemu, argv0, args, cwd, timeout): |
| 1136 | # Not a PASS or an errno waiver: challenge the exact failed syscall under |
| 1137 | # QEMU's own tracer, after the pinned native fixture has passed its EBADF |
| 1138 | # assertions. Unknown ioctls are rejected before host ioctl(fd,cmd,arg). |
| 1139 | request = {"devcall": 3223340587, "uvmctl": 805306369}.get(driver) |
| 1140 | if digest(Path(qemu).read_bytes()) != QEMU_ORACLE_SHA256: |
| 1141 | return None # No source attribution for an unreviewed QEMU executable. |
| 1142 | if request is None or arun[0] != 0 or xrun != (80, b"", b""): |
| 1143 | return None |
| 1144 | trace = run([qemu, "-strace", "-0", argv0, argv0, *args], case.stdin, cwd, timeout) |
| 1145 | if trace[:2] != xrun[:2]: |
| 1146 | return None |
| 1147 | for line in trace[2].splitlines(): |
| 1148 | match = re.search(rb"ioctl\(-1,([^,]+),.*\)\s*=\s*-1 errno=25\b", line) |
| 1149 | if match: |
| 1150 | try: |
| 1151 | observed = int(match[1], 0) & 0xffffffff |
| 1152 | except ValueError: |
| 1153 | continue |
| 1154 | if observed == request: |
| 1155 | return {"classification": "EMULATOR_ARTIFACT", "syscall": "ioctl", "fd": -1, |
| 1156 | "request": request, "native_required_errno": "EBADF", |
| 1157 | "qemu_observed_errno": "ENOTTY", "qemu_trace_line": line.decode(), |
| 1158 | "qemu_trace_sha256": digest(trace[2]), |
| 1159 | "upstream_source": QEMU_IOCTL_URL, |
| 1160 | "upstream_source_sha256": QEMU_SYSCALL_SHA256, |
| 1161 | "upstream_checked_source_path": "/home/drakestapleton/work/bridge-x86/build/qemu-oracle/qemu-10.0.14/linux-user/syscall.c", |
| 1162 | "upstream_source_archive": "https://download.qemu.org/qemu-10.0.14.tar.xz", |
| 1163 | "upstream_source_archive_sha256": QEMU_SOURCE_ARCHIVE_SHA256, |
| 1164 | "qemu_binary_sha256": QEMU_ORACLE_SHA256, |
| 1165 | "upstream_excerpt": QEMU_IOCTL_EXCERPT.decode(), |
| 1166 | "upstream_excerpt_sha256": digest(QEMU_IOCTL_EXCERPT)} |
| 1167 | return None |
| 1168 | |
| 1169 | |
| 1170 | def filesystem_snapshot(directory, excluded): |
| 1171 | """Compare persistent effects, not inode/timestamp/owner allocation noise.""" |
| 1172 | snapshot = {} |
| 1173 | for path in sorted(directory.rglob("*")): |
| 1174 | rel = path.relative_to(directory).as_posix() |
| 1175 | if rel in excluded: |
| 1176 | continue |
| 1177 | info = path.lstat() |
| 1178 | entry = {"mode": stat.S_IMODE(info.st_mode)} |
| 1179 | if stat.S_ISLNK(info.st_mode): |
| 1180 | entry.update(type="symlink", target=os.readlink(path)) |
| 1181 | elif stat.S_ISREG(info.st_mode): |
| 1182 | entry.update(type="file", bytes=info.st_size, sha256=digest(path.read_bytes())) |
| 1183 | elif stat.S_ISDIR(info.st_mode): |
| 1184 | entry.update(type="directory") |
| 1185 | else: |
| 1186 | entry.update(type=stat.S_IFMT(info.st_mode)) |
| 1187 | snapshot[rel] = entry |
| 1188 | return snapshot |
| 1189 | |
| 1190 | |
| 1191 | def exercise_bare(case, default, x86, qemu, cwd, timeout): |
| 1192 | specs = bare_calls(ROOT, case.name.split(":", 1)[0], case.source) |
| 1193 | outcomes = [] |
| 1194 | for number, spec in enumerate(specs): |
| 1195 | runs, wrappers = [], [] |
| 1196 | for arch, image in (("aarch64", default), ("x86_64", x86)): |
| 1197 | work = cwd / f"caller-{number}-{arch}" |
| 1198 | work.mkdir() |
| 1199 | wrapped = wrap_bare(image, case.source, arch, spec) |
| 1200 | binary = work / "caller" |
| 1201 | binary.write_bytes(wrapped) |
| 1202 | binary.chmod(0o700) |
| 1203 | wrappers.append(digest(wrapped)) |
| 1204 | command = ["./caller"] if arch == "aarch64" else [qemu, "-0", "./caller", "./caller"] |
| 1205 | runs.append(run(command, case.stdin, work, timeout)) |
| 1206 | if runs[0][0] < 0 or runs[1][0] < 0 or runs[0] != runs[1]: |
| 1207 | raise Failure(f"bare caller {spec['name']} differs: default={result_details(runs[0])}; x86={result_details(runs[1])}") |
| 1208 | expected_exit = spec.get("expected_exit", 0) |
| 1209 | if expected_exit is not None and runs[0][0] != expected_exit: |
| 1210 | raise Failure(f"bare caller {spec['name']} exit {runs[0][0]}, expected {expected_exit}") |
| 1211 | if "expected_stdout" in spec and runs[0][1] != spec["expected_stdout"]: |
| 1212 | raise Failure(f"bare caller {spec['name']} full-width return/array oracle differs: " |
| 1213 | f"expected={spec['expected_stdout']!r}; actual={runs[0][1]!r}") |
| 1214 | outcomes.append({"name": spec["name"], "evidence": spec.get("evidence", {}), |
| 1215 | "caller_inputs": {"slots": spec.get("slots", []), |
| 1216 | "calls": spec.get("calls", []), |
| 1217 | "arrays": [{key: value for key, value in array.items() if key != "data"} | |
| 1218 | {"initial_bytes": len(array.get("data", b"")), |
| 1219 | "initial_sha256": digest(array.get("data", b""))} |
| 1220 | for array in spec["arrays"]]}, |
| 1221 | "expected_exit": expected_exit, "observed": result_details(runs[0]), |
| 1222 | "oracle": "independent full-width/array oracle" if "expected_stdout" in spec else "native differential", |
| 1223 | "wrapper_sha256": dict(zip(("aarch64", "x86_64"), wrappers))}) |
| 1224 | return outcomes |
| 1225 | |
| 1226 | |
| 1227 | def exercise_bare_target(case, x86, qemu, cwd, timeout): |
| 1228 | """x86-only private-ABI calls for an entryless unit that only x86 accepts (a reviewed per-target |
| 1229 | limit). There is no native arm to compare, so every call must meet a recorded independent result.""" |
| 1230 | specs = bare_calls(ROOT, case.name.split(":", 1)[0], case.source) |
| 1231 | if not specs or any("expected_stdout" not in spec or spec.get("expected_exit") is None for spec in specs): |
| 1232 | raise Failure("target-limit bare caller requires recorded independent results for every call") |
| 1233 | outcomes = [] |
| 1234 | for number, spec in enumerate(specs): |
| 1235 | work = cwd / f"target-limit-caller-{number}" |
| 1236 | work.mkdir() |
| 1237 | wrapped = wrap_bare(x86, case.source, "x86_64", spec) |
| 1238 | binary = work / "caller" |
| 1239 | binary.write_bytes(wrapped) |
| 1240 | binary.chmod(0o700) |
| 1241 | observed = run([qemu, "-0", "./caller", "./caller"], case.stdin, work, timeout) |
| 1242 | if observed[0] != spec["expected_exit"] or observed[1] != spec["expected_stdout"]: |
| 1243 | raise Failure(f"target-limit bare caller {spec['name']} differs from recorded result: " |
| 1244 | f"expected exit {spec['expected_exit']} stdout {spec['expected_stdout']!r}; " |
| 1245 | f"x86={result_details(observed)}") |
| 1246 | outcomes.append({"name": spec["name"], "evidence": spec.get("evidence", {}), |
| 1247 | "slots": spec.get("slots", []), "expected_exit": spec["expected_exit"], |
| 1248 | "observed": result_details(observed), "wrapper_sha256": digest(wrapped)}) |
| 1249 | return outcomes |
| 1250 | |
| 1251 | |
| 1252 | def exercise_conductor(case, default, x86, compiler, qemu, cwd, timeout): |
| 1253 | runs, effects = [], [] |
| 1254 | # The original conductor itself enforces each directive's child deadline. |
| 1255 | # Its enclosing process must have time for all declared compile/run arms. |
| 1256 | lines = contained(case.evidence["manifest"]).read_text().splitlines() |
| 1257 | outer_timeout = max(timeout, 60) * max(1, len(lines)) |
| 1258 | for arch, image in (("aarch64", default), ("x86_64", x86)): |
| 1259 | work = cwd / ("conductor-" + arch) |
| 1260 | work.mkdir() |
| 1261 | binary = work / "conductor" |
| 1262 | binary.write_bytes(image) |
| 1263 | binary.chmod(0o700) |
| 1264 | args = prepare_case(ROOT, work, "corpus-gate", compiler, case=case.evidence) |
| 1265 | command = ["./conductor", *args] if arch == "aarch64" else [qemu, "-0", "./conductor", "./conductor", *args] |
| 1266 | runs.append(run(command, b"", work, outer_timeout)) |
| 1267 | effects.append(filesystem_snapshot(work, {"conductor"})) |
| 1268 | if runs[0] != runs[1] or effects[0] != effects[1]: |
| 1269 | raise Failure(f"original conductor architecture differential: native={result_details(runs[0])}; x86={result_details(runs[1])}; filesystem_equal={effects[0] == effects[1]}; native_log={runs[0][1]!r}; x86_log={runs[1][1]!r}") |
| 1270 | if runs[0][0] not in (0, 1, 2, 3) or b"OM2GATE " not in runs[0][1]: |
| 1271 | raise Failure(f"original conductor invalid/setup failure: {result_details(runs[0])}; original_log={runs[0][1]!r}") |
| 1272 | verdicts, directives = {}, [] |
| 1273 | for match in re.finditer(rb"(?m)^VERDICT ([^ \n]+) (PASS|FAIL|INVALID|NOT_RUN)([^\n]*)$", runs[0][1]): |
| 1274 | name = match[1].decode() |
| 1275 | verdict = {"status": match[2].decode(), "line": match[0].decode()} |
| 1276 | if name in ("cc", "subst", "deadline"): |
| 1277 | directives.append(verdict) |
| 1278 | continue |
| 1279 | if name in verdicts: |
| 1280 | raise Failure("original conductor emitted duplicate case name: " + name) |
| 1281 | verdicts[name] = verdict |
| 1282 | return {"exit": runs[0][0], "stdout": runs[0][1].decode(), "stdout_sha256": digest(runs[0][1]), "stderr": runs[0][2].decode(), |
| 1283 | "verdicts": verdicts, "directive_verdicts": directives, |
| 1284 | "filesystem_sha256": digest(json.dumps(effects[0], sort_keys=True).encode())} |
| 1285 | |
| 1286 | def exercise_bridge(plan, compiler, qemu, options, scratch, state): |
| 1287 | key = plan["cache_key"] |
| 1288 | if key in state["errors"]: |
| 1289 | raise Failure(state["errors"][key]) |
| 1290 | try: |
| 1291 | return _exercise_bridge(plan, compiler, qemu, options, scratch, state) |
| 1292 | except (OSError, ValueError, Failure) as error: |
| 1293 | state["errors"][key] = str(error) |
| 1294 | raise Failure(str(error)) from error |
| 1295 | |
| 1296 | |
| 1297 | def _exercise_bridge(plan, compiler, qemu, options, scratch, state): |
| 1298 | """Use original reviewed callers and generated native bindings, never raw-ABI substitutes.""" |
| 1299 | if plan["cache_key"] in state["results"]: |
| 1300 | return state["results"][plan["cache_key"]] |
| 1301 | if not options.bridge or not options.bridge.is_file(): |
| 1302 | raise Failure("BLOCKED_ON BridgeX86: --bridge must name its reviewed tools/native executable") |
| 1303 | bridge = options.bridge.resolve() |
| 1304 | bridge_root = bridge.parents[1] |
| 1305 | work = scratch / ("bridge-" + plan["cache_key"]) |
| 1306 | work.mkdir() |
| 1307 | |
| 1308 | def copy_resources(items, directory): |
| 1309 | for item in items: |
| 1310 | data = (git_resource(ROOT, item) if "git_revision" in item |
| 1311 | else contained(item["path"]).read_bytes()) |
| 1312 | if digest(data) != item["sha256"]: |
| 1313 | raise Failure("reviewed bridge input changed: " + item["path"]) |
| 1314 | dest = directory / item["path"] |
| 1315 | dest.parent.mkdir(parents=True, exist_ok=True) |
| 1316 | dest.write_bytes(data) |
| 1317 | |
| 1318 | def git_resource(repository, item): |
| 1319 | result = run(["git", "-C", str(repository), "show", |
| 1320 | item["git_revision"] + ":" + item["git_path"]], b"", work, options.timeout) |
| 1321 | if result[0] or digest(result[1]) != item["sha256"]: |
| 1322 | raise Failure(f"pinned bridge resource unavailable/mismatched: {repository} {item}: {result_details(result)}") |
| 1323 | return result[1] |
| 1324 | |
| 1325 | def mutate(path, mutation): |
| 1326 | data = path.read_bytes() |
| 1327 | if "append" in mutation: |
| 1328 | data += mutation["append"] |
| 1329 | else: |
| 1330 | count = data.count(mutation["old"]) |
| 1331 | if count != mutation["count"]: |
| 1332 | raise Failure(f"reviewed mutation {path} expected {mutation['count']} matches, found {count}; " |
| 1333 | f"source_sha256={digest(data)} old_hex={mutation['old'].hex()} new_hex={mutation['new'].hex()}") |
| 1334 | data = data.replace(mutation["old"], mutation["new"]) |
| 1335 | path.write_bytes(data) |
| 1336 | return {"path": path.relative_to(work).as_posix(), "sha256": digest(data), |
| 1337 | "old_hex": mutation.get("old", b"").hex(), "new_hex": mutation.get("new", mutation.get("append", b"")).hex()} |
| 1338 | |
| 1339 | if plan["operation"] == "units-check": |
| 1340 | tree = work / "tree" |
| 1341 | tree.mkdir() |
| 1342 | copy_resources(plan["resources"], tree) |
| 1343 | old_compiler = work / "pinned-omc" |
| 1344 | old_compiler.write_bytes(git_resource(ROOT, plan["strict_compiler"])) |
| 1345 | old_compiler.chmod(0o700) |
| 1346 | old_bridge = work / "pinned-bridge" |
| 1347 | (old_bridge / "src").mkdir(parents=True) |
| 1348 | (old_bridge / "src/native.om").write_bytes(git_resource(bridge_root, plan["strict_generator"])) |
| 1349 | temp = work / "tmp" |
| 1350 | temp.mkdir() |
| 1351 | environment = {"OMEGA_OMC": str(old_compiler), "OMEGA_BRIDGE": str(old_bridge), "TMPDIR": str(temp)} |
| 1352 | command = ["sh", str(tree / plan["script"]), *plan["args"]] |
| 1353 | before = filesystem_snapshot(tree, set()) |
| 1354 | positive = run(command, b"", tree, options.timeout, extra_env=environment) |
| 1355 | if positive[0] != plan["positive_control_expected_exit"] or filesystem_snapshot(tree, set()) != before: |
| 1356 | raise Failure(f"original strict gate positive control failed or wrote source: {result_details(positive)}") |
| 1357 | mutation = mutate(tree / plan["mutation"]["path"], plan["mutation"]) |
| 1358 | before = filesystem_snapshot(tree, set()) |
| 1359 | negative = run(command, b"", tree, options.timeout, extra_env=environment) |
| 1360 | if negative[0] != plan["expected_exit"] or filesystem_snapshot(tree, set()) != before: |
| 1361 | raise Failure(f"original strict gate did not reject exact stale metadata without writes: {result_details(negative)}") |
| 1362 | result = {"exit": negative[0], "stdout": negative[1].decode(), "stderr": negative[2].decode(), |
| 1363 | "positive_control": result_details(positive), "negative_control": result_details(negative), |
| 1364 | "mutation": mutation, "scope": "original host regeneration gate, not x86 device/runtime evidence", |
| 1365 | "compiler": plan["strict_compiler"], "generator": plan["strict_generator"]} |
| 1366 | state["results"][plan["cache_key"]] = result |
| 1367 | return result |
| 1368 | |
| 1369 | if "positive_control" in plan: |
| 1370 | positive = exercise_bridge(bridge_positive_plan(ROOT, plan), compiler, qemu, options, scratch, state) |
| 1371 | if positive["exit"] != 0: |
| 1372 | raise Failure("original C-boundary positive control did not pass before negative control") |
| 1373 | baseline = options.bridge_baseline_compiler.resolve() |
| 1374 | selected = (options.bridge_compiler or Path(compiler)).resolve() |
| 1375 | if not baseline.is_file() or not selected.is_file(): |
| 1376 | raise Failure("BLOCKED_ON BridgeX86: pinned baseline/candidate compiler artifact missing") |
| 1377 | selected_sha = digest(selected.read_bytes()) |
| 1378 | if digest(baseline.read_bytes()) != "734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61": |
| 1379 | raise Failure("BLOCKED_ON BridgeX86: baseline compiler hash does not match its exact seeded generator pin") |
| 1380 | if selected_sha != digest(Path(compiler).read_bytes()): |
| 1381 | raise Failure("BLOCKED_ON BridgeX86: bridge compiler does not match selected qualification candidate") |
| 1382 | native_cc, x86_cc = shutil.which("cc"), shutil.which("x86_64-linux-gnu-gcc") |
| 1383 | nm = shutil.which("nm") |
| 1384 | if not native_cc or not x86_cc or not nm: |
| 1385 | raise Failure("BLOCKED_ON BridgeX86: native cc, x86_64-linux-gnu-gcc and nm are required") |
| 1386 | observations, runs, effects = [], [], [] |
| 1387 | driver_timeout = options.timeout |
| 1388 | if plan["cache_key"] == "sha-original-driver-big" and plan["args"] == ("big",): |
| 1389 | driver_timeout = max(driver_timeout, options.bridge_big_timeout) |
| 1390 | for arch, cc in (("aarch64", native_cc), ("x86_64", x86_cc)): |
| 1391 | library_key = arch, tuple((unit["path"], unit["sha256"]) for unit in plan["units"]), selected_sha |
| 1392 | if library_key not in state["libraries"]: |
| 1393 | libwork = Path(tempfile.mkdtemp(prefix="bridge-library-", dir=scratch)) |
| 1394 | copy_resources(plan["units"], libwork) |
| 1395 | output = libwork / "generated" |
| 1396 | command = [str(bridge)] |
| 1397 | if arch == "x86_64": |
| 1398 | command += ["--target", "x86linux"] |
| 1399 | command += [str(output), *(str(libwork / unit["path"]) for unit in plan["units"])] |
| 1400 | environment = {"OMEGA_NATIVE_OMC": str(baseline), "OMEGA_NATIVE_OMC2": str(selected), |
| 1401 | "OMEGA_NATIVE_X86_OMC": str(selected), "CC": cc} |
| 1402 | built = run(command, b"", libwork, options.timeout, extra_env=environment) |
| 1403 | if built[0]: |
| 1404 | raise Failure(f"actual {arch} bridge generation failed: {result_details(built)}") |
| 1405 | state["libraries"][library_key] = output |
| 1406 | library = state["libraries"][library_key] |
| 1407 | local = work / arch |
| 1408 | local.mkdir() |
| 1409 | copy_resources(plan["resources"], local) |
| 1410 | generated = local / "generated" |
| 1411 | shutil.copytree(library, generated) |
| 1412 | mutation = None |
| 1413 | if plan["operation"] == "bridge-mutant": |
| 1414 | mutation = mutate(generated / "omega_native.c", plan["mutation"]) |
| 1415 | symbols_result = run([nm, "-D", "--defined-only", str(generated / "libomega_native.so")], |
| 1416 | b"", local, options.timeout) |
| 1417 | if symbols_result[0]: |
| 1418 | raise Failure("cannot inspect generated bridge symbols: " + str(result_details(symbols_result))) |
| 1419 | symbols = sorted({line.split()[-1].decode() for line in symbols_result[1].splitlines() if line.split()}) |
| 1420 | for symbol in plan.get("required_symbols", ()): |
| 1421 | if symbol not in symbols: |
| 1422 | raise Failure("required native binding symbol absent: " + symbol) |
| 1423 | for symbol in plan.get("forbidden_symbols", ()): |
| 1424 | if symbol in symbols: |
| 1425 | raise Failure("forbidden binding symbol exported: " + symbol) |
| 1426 | linked, binary_sha = None, None |
| 1427 | args = () |
| 1428 | if plan["operation"] == "symbols": |
| 1429 | observed = symbols_result |
| 1430 | else: |
| 1431 | if plan.get("driver") is None: |
| 1432 | driver = local / "original-driver.c" |
| 1433 | driver.write_bytes(plan["driver_source"]) |
| 1434 | else: |
| 1435 | driver = local / plan["driver"] |
| 1436 | if digest(driver.read_bytes()) != plan["driver_sha256"]: |
| 1437 | raise Failure("original C driver pin mismatch") |
| 1438 | executable = local / "original-driver" |
| 1439 | command = [cc, *plan["cflags"], "-static", "-I", str(generated), |
| 1440 | str(driver), str(generated / "omega_native.c"), "-o", str(executable)] |
| 1441 | linked = run(command, b"", local, options.timeout) |
| 1442 | if plan["operation"] == "negative-link": |
| 1443 | symbol = plan["undefined_symbol"].encode() |
| 1444 | if linked[0] != plan["expected_exit"] or b"undefined reference" not in linked[2] or symbol not in linked[2]: |
| 1445 | raise Failure(f"negative-link failed for wrong reason or survived: {result_details(linked)}") |
| 1446 | observed = linked |
| 1447 | else: |
| 1448 | if linked[0]: |
| 1449 | raise Failure("original C driver build failed: " + str(result_details(linked))) |
| 1450 | binary_sha = digest(executable.read_bytes()) |
| 1451 | args = tuple(selected_sha if arg == "$COMPILER_SHA256" else arg for arg in plan["args"]) |
| 1452 | before = filesystem_snapshot(local, set()) |
| 1453 | command = ["./original-driver", *args] if arch == "aarch64" else [ |
| 1454 | qemu, "-0", "./original-driver", "./original-driver", *args] |
| 1455 | observed = run(command, b"", local, driver_timeout) |
| 1456 | after = filesystem_snapshot(local, set()) |
| 1457 | changes = {name: after.get(name) for name in before.keys() | after.keys() |
| 1458 | if before.get(name) != after.get(name)} |
| 1459 | effects.append(changes) |
| 1460 | if changes: |
| 1461 | raise Failure("read-only C-boundary caller changed its scratch filesystem: " + str(changes)) |
| 1462 | if observed[0] != plan["expected_exit"]: |
| 1463 | raise Failure(f"original {arch} C-boundary caller expected {plan['expected_exit']}: {result_details(observed)}; stdout={observed[1]!r}; stderr={observed[2]!r}") |
| 1464 | observations.append({"architecture": arch, "compiler_sha256": selected_sha, |
| 1465 | "args": list(args), "stdin_hex": "", "deadline_seconds": driver_timeout, |
| 1466 | "caller_resources": plan["resources"], "unit_sources": plan["units"], |
| 1467 | "baseline_compiler_sha256": digest(baseline.read_bytes()), |
| 1468 | "bridge_tool_sha256": digest(bridge.read_bytes()), |
| 1469 | "bridge_generator_sha256": digest((bridge_root / "src/native.om").read_bytes()), |
| 1470 | "cc": cc, "cc_version": run([cc, "--version"], b"", local, options.timeout)[1].decode(), |
| 1471 | "generated_c_sha256": digest((generated / "omega_native.c").read_bytes()), |
| 1472 | "generated_library_sha256": digest((generated / "libomega_native.so").read_bytes()), |
| 1473 | "driver_sha256": plan.get("driver_sha256"), "driver_binary_sha256": binary_sha, |
| 1474 | "mutation": mutation, "link": result_details(linked) if linked else None, |
| 1475 | "symbol_names": symbols, "symbol_observation": result_details(symbols_result), |
| 1476 | "observed": result_details(observed)}) |
| 1477 | runs.append(observed) |
| 1478 | if plan["operation"] not in ("symbols", "negative-link") and runs[0] != runs[1]: |
| 1479 | raise Failure(f"original C-boundary architecture differential: native={result_details(runs[0])}; x86={result_details(runs[1])}") |
| 1480 | result = {"exit": runs[0][0], "stdout": runs[0][1].decode(), "stderr": runs[0][2].decode(), |
| 1481 | "operation": plan["operation"], "observations": observations, "runtime_filesystem_changes": effects, |
| 1482 | "comparison": ("independent original required/forbidden symbol obligations, not runtime" |
| 1483 | if plan["operation"] == "symbols" else |
| 1484 | "independent original absent-symbol link obligation; complete linker diagnostics retained, not runtime" |
| 1485 | if plan["operation"] == "negative-link" else |
| 1486 | "actual C/SysV native-AArch64 versus EMULATED x86_64")} |
| 1487 | state["results"][plan["cache_key"]] = result |
| 1488 | return result |
| 1489 | |
| 1490 | |
| 1491 | def main(): |
| 1492 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 1493 | parser.add_argument("--compiler", type=Path) |
| 1494 | parser.add_argument("--x86-compiler", type=Path, help="optional x86-hosted paired compiler; otherwise built once from exact current seeded source") |
| 1495 | parser.add_argument("--qemu", default="qemu-x86_64") |
| 1496 | parser.add_argument("--bridge", type=Path, help="reviewed x86-capable omega-bridge executable for external ABI drivers") |
| 1497 | parser.add_argument("--bridge-baseline-compiler", type=Path, default=Path("/tmp/bridge-x86-baseline-omc"), |
| 1498 | help="exact 734f0a39 seeded compiler required by the bridge generator") |
| 1499 | parser.add_argument("--bridge-compiler", type=Path, |
| 1500 | help="bridge candidate artifact, required to hash-match --compiler (default: --compiler)") |
| 1501 | parser.add_argument("--bridge-big-timeout", type=float, default=3600, |
| 1502 | help="per-architecture deadline for unchanged original SHA big mode (all original 2^32+3-byte cases)") |
| 1503 | parser.add_argument("--objdump", help="GNU x86-64 objdump or llvm-objdump executable") |
| 1504 | parser.add_argument("--timeout", type=float, default=30) |
| 1505 | parser.add_argument("--inventory", action="store_true") |
| 1506 | options = parser.parse_args() |
| 1507 | totals, reasons, templates = Counter(), Counter(), Counter() |
| 1508 | |
| 1509 | if options.timeout <= 0: |
| 1510 | parser.error("--timeout must be positive") |
| 1511 | def record(status, name, reason, **details): |
| 1512 | totals[status] += 1 |
| 1513 | if status != "PASS": |
| 1514 | reasons[(status, reason)] += 1 |
| 1515 | if details.get("evidence", {}).get("evidence_kind") == "differential_only": |
| 1516 | details.update(scope="differential_only", conformance_status="UNASSERTED", |
| 1517 | original_not_run_reason=details["evidence"].get("original_not_run_reason", details["evidence"].get("reason"))) |
| 1518 | print(json.dumps(dict(status=status, case=name, reason=reason, **details)), flush=True) |
| 1519 | |
| 1520 | files = fixture_files() |
| 1521 | revision = run(["git", "rev-parse", "HEAD"], b"", ROOT, options.timeout) |
| 1522 | if revision[0] or not re.fullmatch(rb"[0-9a-f]{40}\n", revision[1]): |
| 1523 | parser.error("cannot record actual repository HEAD: " + str(result_details(revision))) |
| 1524 | compiler_source = contained("seed/omc/omc.om").read_bytes() |
| 1525 | print(json.dumps({"inventory_files": len(files), |
| 1526 | "roots": "tests; seed/*/tests; seed/omc/{om2,contracts}; seed/qualification; tools/exp445/arms/examples", |
| 1527 | "source_revision_contract": revision[1].decode().strip(), |
| 1528 | "baseline_revision": "becf5c817bcb7e0846d12ebfc2be91042d8ad89a", |
| 1529 | "compiler_source_sha256": digest(compiler_source), |
| 1530 | "checker_sha256": digest(Path(__file__).read_bytes()), |
| 1531 | "driver_sha256": digest(Path(__file__).with_name("x86_corpus_drivers.py").read_bytes()), |
| 1532 | "bridge": str(options.bridge) if options.bridge else None})) |
| 1533 | if not options.inventory: |
| 1534 | if not options.compiler or not options.compiler.is_file(): |
| 1535 | parser.error("--compiler must name an existing compiler") |
| 1536 | if platform.system() != "Linux" or platform.machine() not in ("aarch64", "arm64"): |
| 1537 | parser.error("native default baseline requires Linux AArch64") |
| 1538 | compiler = str(options.compiler.resolve()) |
| 1539 | qemu = shutil.which(options.qemu) |
| 1540 | objdump = shutil.which(options.objdump) if options.objdump else next( |
| 1541 | (p for name in ("x86_64-linux-gnu-objdump", "llvm-objdump", "objdump") if (p := shutil.which(name))), None) |
| 1542 | if not qemu or not objdump: |
| 1543 | parser.error("qemu-x86_64 and an x86-64-capable GNU/LLVM objdump are required") |
| 1544 | llvm = "llvm" in Path(objdump).name |
| 1545 | print(json.dumps({"compiler": compiler, "compiler_sha256": digest(Path(compiler).read_bytes()), |
| 1546 | "qemu": qemu, "qemu_sha256": digest(Path(qemu).read_bytes()), |
| 1547 | "qemu_version": run([qemu, "--version"], b"", ROOT, options.timeout)[1].decode().strip(), |
| 1548 | "objdump": objdump, "platform": platform.platform(), "timeout_seconds": options.timeout, |
| 1549 | "bridge_big_timeout_seconds": options.bridge_big_timeout})) |
| 1550 | cache = OrderedDict() |
| 1551 | conductor_cache = {} |
| 1552 | conductor_decode_cache = OrderedDict() |
| 1553 | bridge_state = {"results": {}, "errors": {}, "libraries": {}} |
| 1554 | controls = None |
| 1555 | helper_image = None |
| 1556 | frontend_compiler = None |
| 1557 | frontend_evidence = {} |
| 1558 | generation_variant = None |
| 1559 | with tempfile.TemporaryDirectory(prefix="omega-fr9-oracle-") as scratch: |
| 1560 | scratch = Path(scratch) |
| 1561 | original_compilers = {} |
| 1562 | |
| 1563 | def original_compiler(identity): |
| 1564 | if identity == "current": |
| 1565 | return compiler |
| 1566 | baseline = options.bridge_baseline_compiler.resolve() |
| 1567 | if not baseline.is_file() or digest(baseline.read_bytes()) != PINNED_COMPILER_SHA256: |
| 1568 | raise Failure("original conductor requires exact independently pinned OM1 compiler " + PINNED_COMPILER_SHA256) |
| 1569 | if identity == "pinned": |
| 1570 | return str(baseline) |
| 1571 | if identity not in original_compilers: |
| 1572 | revision, sha = HISTORICAL_COMPILERS[identity] |
| 1573 | fetched = run(["git", "show", revision + ":seed/omc/omc.om"], b"", ROOT, options.timeout) |
| 1574 | if fetched[0] or digest(fetched[1]) != sha: |
| 1575 | raise Failure("historical compiler source identity mismatch: " + identity) |
| 1576 | built = run([str(baseline)], fetched[1], scratch, options.timeout) |
| 1577 | if built[0] or built[2] or not built[1]: |
| 1578 | raise Failure("historical compiler bootstrap failed: " + identity + ": " + str(result_details(built))) |
| 1579 | binary = scratch / ("original-" + sha) |
| 1580 | binary.write_bytes(built[1]) |
| 1581 | binary.chmod(0o700) |
| 1582 | original_compilers[identity] = str(binary) |
| 1583 | return original_compilers[identity] |
| 1584 | |
| 1585 | def generation_compiler(): |
| 1586 | nonlocal generation_variant |
| 1587 | if generation_variant is None: |
| 1588 | source = compiler_source |
| 1589 | substitutions = [] |
| 1590 | for old, new in ( |
| 1591 | (b"matconst 15 36028797018963967\n", b"matconst 15 3\n"), |
| 1592 | (b"xhcmp 10 36028797018963967\n", b"xhcmp 10 3\n"), |
| 1593 | ): |
| 1594 | if source.count(old) != 1: |
| 1595 | raise Failure("generation-ceiling whitebox setup no longer matches exact current emitter: " + repr(old)) |
| 1596 | source = source.replace(old, new) |
| 1597 | substitutions.append({"old_hex": old.hex(), "new_hex": new.hex(), "count": 1}) |
| 1598 | built = run([compiler], source, scratch, options.timeout) |
| 1599 | if built[0] or built[2] or not built[1]: |
| 1600 | raise Failure("generation-ceiling compiler build failed: " + str(result_details(built))) |
| 1601 | binary = scratch / "generation-limit-compiler" |
| 1602 | binary.write_bytes(built[1]) |
| 1603 | binary.chmod(0o700) |
| 1604 | generation_variant = str(binary), { |
| 1605 | "authority_path": "seed/host/tests/genlimit.om", |
| 1606 | "authority_sha256": "ea4f544b49878f5532f75b0ac7e8fa42e6926d5b57ea002e748679922859ad48", |
| 1607 | "authority_quote": "White-box boundary fixture: compiler's generation ceiling replaced with 3 for this test only.", |
| 1608 | "original_compiler_source_sha256": digest(compiler_source), |
| 1609 | "variant_source_sha256": digest(source), "variant_compiler_sha256": digest(built[1]), |
| 1610 | "substitutions": substitutions, "scope": "fixture-only, both target generation ceilings; production source unchanged"} |
| 1611 | return generation_variant |
| 1612 | |
| 1613 | def paired_frontend_compiler(): |
| 1614 | nonlocal frontend_compiler, frontend_evidence |
| 1615 | if frontend_compiler is None: |
| 1616 | binary = scratch / "x86-hosted-compiler" |
| 1617 | if options.x86_compiler: |
| 1618 | image = options.x86_compiler.read_bytes() |
| 1619 | frontend_evidence = {"provenance": "explicit external --x86-compiler", |
| 1620 | "path": str(options.x86_compiler.resolve())} |
| 1621 | else: |
| 1622 | source = compiler_source |
| 1623 | built = run([compiler], TARGET_PREFIX + source, scratch, options.timeout) |
| 1624 | if built[0] or built[2] or not built[1]: |
| 1625 | raise Failure(f"x86-hosted compiler bootstrap failed: {result_details(built)}") |
| 1626 | disassemble(built[1], source, objdump, llvm, scratch, options.timeout) |
| 1627 | image = built[1] |
| 1628 | frontend_evidence = {"provenance": "exact current seeded source compiled by selected native compiler", |
| 1629 | "source": "seed/omc/omc.om", "source_sha256": digest(source)} |
| 1630 | binary.write_bytes(image) |
| 1631 | binary.chmod(0o700) |
| 1632 | frontend_compiler = str(binary) |
| 1633 | frontend_evidence.update(x86_compiler_sha256=digest(image), |
| 1634 | native_compiler_sha256=digest(Path(compiler).read_bytes())) |
| 1635 | return frontend_compiler |
| 1636 | |
| 1637 | for index, case in enumerate(expanded_cases(files, record)): |
| 1638 | frontend_mode = bool(MODE.match(case.source)) |
| 1639 | key = digest(case.source) |
| 1640 | driver = case.driver or HOST_DRIVERS.get(key) |
| 1641 | if case.name.startswith("oracle-positional-"): |
| 1642 | driver = "positional-view" |
| 1643 | target, adaptation = (case.source, None) if case.bridge else target_source(case, driver) |
| 1644 | if options.inventory: |
| 1645 | words = host_words(case.source) |
| 1646 | kind = "INVENTORY_HOST" if case.bridge else ("INVENTORY_UNIT" if not MAIN.search(case.source) else ( |
| 1647 | "INVENTORY_HOST" if words else "INVENTORY_PROGRAM")) |
| 1648 | record(kind, case.name, "reviewed host driver" if driver else ( |
| 1649 | "unreviewed host driver missing" if words else "compile/runtime differential input"), |
| 1650 | host_words=words, host_driver=driver, source_sha256=key, |
| 1651 | target_adaptation=adaptation, expected_compile=case.expected_compile, |
| 1652 | operation=case.operation, evidence=case.evidence, blocker=case.blocker) |
| 1653 | continue |
| 1654 | cwd = scratch / str(index) |
| 1655 | cwd.mkdir() |
| 1656 | diagnostics = {} |
| 1657 | child_timeout = case.deadline if case.deadline is not None else options.timeout |
| 1658 | try: |
| 1659 | if case.bridge: |
| 1660 | replay = exercise_bridge(case.bridge, compiler, qemu, options, scratch, bridge_state) |
| 1661 | prefix = case.bridge.get("required_line_prefix") |
| 1662 | if prefix and not any(line.startswith(prefix) for line in replay["stdout"].splitlines()): |
| 1663 | raise Failure("original C driver did not report required exact case: " + prefix) |
| 1664 | record("PASS", case.name, "original C-boundary/gate obligation, actual reviewed driver", |
| 1665 | source_sha256=key, evidence=case.evidence, bridge_result=replay, |
| 1666 | control_kind=case.bridge["operation"], |
| 1667 | evidence_kind=case.evidence.get("evidence_kind", "original explicit oracle"), |
| 1668 | contract_status=case.evidence.get("contract_status", "original fixed obligation")) |
| 1669 | continue |
| 1670 | case_compiler = compiler |
| 1671 | if driver == "genlimit" and case.operation != "emit": |
| 1672 | case_compiler, case.evidence["generation_ceiling_whitebox"] = generation_compiler() |
| 1673 | case.stdout_oracle = "sha:" + digest(literal_bytes(case.source)[0]) |
| 1674 | compilekey = key, digest(target), frontend_mode, child_timeout, case_compiler |
| 1675 | if compilekey not in cache: |
| 1676 | default = run([case_compiler], case.source, cwd, child_timeout) |
| 1677 | if frontend_mode: |
| 1678 | x86 = run([qemu, "-0", "./omc", paired_frontend_compiler()], |
| 1679 | case.source, cwd, child_timeout) |
| 1680 | else: |
| 1681 | x86 = run([case_compiler], TARGET_PREFIX + target, cwd, child_timeout) |
| 1682 | cache[compilekey] = default, x86 |
| 1683 | if len(cache) > 32: |
| 1684 | cache.popitem(last=False) |
| 1685 | default, x86 = cache[compilekey] |
| 1686 | diagnostics = {"default_compile": result_details(default), "x86_compile": result_details(x86)} |
| 1687 | diagnostic_contract = None |
| 1688 | if not frontend_mode and target == case.source: |
| 1689 | diagnostic_contract = target_diagnostic_contract(case.source, default, x86) |
| 1690 | if diagnostic_contract: |
| 1691 | case.evidence["target_diagnostic_contract"] = diagnostic_contract |
| 1692 | if frontend_mode: |
| 1693 | case.evidence.update(frontend_compiler=frontend_evidence, |
| 1694 | comparison="crossHOST native-AArch64 versus EMULATED x86 compiler, exact original mode bytes") |
| 1695 | if case.operation == "emit": |
| 1696 | assert_oracle(default[1], case.stdout_oracle, "compiler stdout") |
| 1697 | assert_oracle(default[2], case.stderr_oracle, "compiler stderr") |
| 1698 | if default[0]: |
| 1699 | if case.expected_compile == "accept": |
| 1700 | raise Failure(f"fixture required acceptance but default compiler refused with {default[0]}") |
| 1701 | if case.expected_compile and default[0] != int(case.expected_compile): |
| 1702 | raise Failure(f"fixture default refusal code {default[0]} differs from explicit oracle {case.expected_compile}") |
| 1703 | if diagnostic_contract and diagnostic_contract["x86_execution"]: |
| 1704 | expected = diagnostic_contract["x86_execution"] |
| 1705 | mnemonics, instructions, carveouts = disassemble( |
| 1706 | x86[1], target, objdump, llvm, cwd, child_timeout) |
| 1707 | if expected == "recorded-bare-caller": |
| 1708 | observed = exercise_bare_target(case, x86[1], qemu, cwd, child_timeout) |
| 1709 | else: |
| 1710 | binary = cwd / "target-limit-control" |
| 1711 | binary.write_bytes(x86[1]) |
| 1712 | binary.chmod(0o700) |
| 1713 | observed = run([qemu, str(binary)], b"", cwd, child_timeout) |
| 1714 | if observed != (expected["exit"], expected["stdout"].encode(), expected["stderr"].encode()): |
| 1715 | raise Failure("target-specific limit execution oracle differs: " + str(result_details(observed))) |
| 1716 | observed = result_details(observed) |
| 1717 | templates.update(mnemonics) |
| 1718 | record("PASS", case.name, "exact per-target limit contract and independent x86 execution oracle", |
| 1719 | source_sha256=key, evidence=case.evidence, |
| 1720 | default_compile=result_details(default), x86_compile=result_details(x86), |
| 1721 | x86_execution=observed, instructions=len(instructions)) |
| 1722 | continue |
| 1723 | if not diagnostic_contract and refusal(default, 0) != refusal(x86, 0 if frontend_mode else 1): |
| 1724 | raise Failure("compile refusal differs after exact source-coordinate translation") |
| 1725 | record("PASS", case.name, "compile-refusal differential + explicit conductor oracle", |
| 1726 | compile_exit=default[0], source_sha256=key, |
| 1727 | target_adaptation=adaptation, evidence=case.evidence, |
| 1728 | comparison="crossHOST exact frontend mode" if frontend_mode else "crossTARGET") |
| 1729 | continue |
| 1730 | if case.expected_compile not in (None, "accept"): |
| 1731 | raise Failure("refusal control was incorrectly accepted by default compiler") |
| 1732 | if x86[0]: |
| 1733 | record("MISSING_IMPLEMENTATION", case.name, "default accepts; x86 compiler refuses", |
| 1734 | compile_exit=x86[0], diagnostic=x86[2].decode("utf-8", "replace"), |
| 1735 | source_sha256=key, evidence=case.evidence) |
| 1736 | continue |
| 1737 | translated_stderr = normalized_diagnostics(x86[2], 0 if frontend_mode else 1) |
| 1738 | if case.evidence.get("compiler_stderr_comparison") == "source-site-records": |
| 1739 | case.evidence["raw_compiler_stderr"] = {"native_hex": default[2].hex(), "x86_hex": x86[2].hex()} |
| 1740 | case.evidence["site_comparison"] = source_site_diagnostics( |
| 1741 | default[2], translated_stderr, case.evidence["site_source_lines"]) |
| 1742 | elif not diagnostic_contract and default[2] != translated_stderr: |
| 1743 | raise Failure("successful compiler diagnostics differ after exact source-coordinate translation") |
| 1744 | if frontend_mode: |
| 1745 | if default[1] != x86[1]: |
| 1746 | raise Failure("exact-mode output differs between native and x86-hosted compiler") |
| 1747 | if case.operation == "same": |
| 1748 | left = run([compiler], case.same_source, cwd, options.timeout) |
| 1749 | right = run([qemu, "-0", "./omc", paired_frontend_compiler()], |
| 1750 | case.same_source, cwd, options.timeout) |
| 1751 | if left[0] or right[0] or default[1] != left[1] or x86[1] != right[1]: |
| 1752 | raise Failure("exact frontend same-artifact oracle differs") |
| 1753 | record("PASS", case.name, "exact-mode frontend crossHOST differential, original conductor oracles preserved", |
| 1754 | source_sha256=key, evidence=case.evidence, compile_exit=default[0], |
| 1755 | stdout_sha256=digest(default[1]), comparison="crossHOST EMULATED, not backend crossTARGET") |
| 1756 | continue |
| 1757 | if MAIN.search(case.source) and ( |
| 1758 | default[1][:6] != b"\x7fELF\x02\x01" or |
| 1759 | struct.unpack_from("<H", default[1], 18)[0] != 183): |
| 1760 | raise Failure("default no longer emits AArch64 ELF program") |
| 1761 | decode_key = digest(x86[1]), digest(target) |
| 1762 | decoded = conductor_decode_cache.get(decode_key) if case.operation == "conductor" else None |
| 1763 | if decoded is None: |
| 1764 | decoded = disassemble(x86[1], target, objdump, llvm, cwd, child_timeout) |
| 1765 | if case.operation == "conductor": |
| 1766 | # Frozen manifests repeatedly execute the same conductor. |
| 1767 | # Cache only an exact image AND source, never a verdict. |
| 1768 | conductor_decode_cache[decode_key] = decoded |
| 1769 | if len(conductor_decode_cache) > 4: |
| 1770 | conductor_decode_cache.popitem(last=False) |
| 1771 | mnemonics, instructions, carveouts = decoded |
| 1772 | templates.update(mnemonics) |
| 1773 | if case.operation == "conductor": |
| 1774 | observations = [] |
| 1775 | required = case.evidence.get("required_mutant_replays", [case.evidence]) |
| 1776 | for replay_number, requirement in enumerate(required): |
| 1777 | manifest = requirement["manifest"] |
| 1778 | identity = requirement["child_compiler_identity"] |
| 1779 | cachekey = manifest, identity, digest(json.dumps(requirement["resources"], sort_keys=True).encode()) |
| 1780 | if cachekey not in conductor_cache: |
| 1781 | try: |
| 1782 | replaydir = cwd / ("replay-" + str(replay_number)) |
| 1783 | replaydir.mkdir() |
| 1784 | replay_case = replace(case, evidence=requirement) |
| 1785 | child_compiler = original_compiler(identity) |
| 1786 | conductor_cache[cachekey] = exercise_conductor( |
| 1787 | replay_case, default[1], x86[1], child_compiler, qemu, replaydir, options.timeout) |
| 1788 | # File the actual build/control/kill transcript |
| 1789 | # once, independently of per-row verdicts. A |
| 1790 | # successful mutation assertion is not merely |
| 1791 | # an expected output attached to healthy code. |
| 1792 | print(json.dumps({"kind": "original-conductor-evidence", |
| 1793 | "manifest": manifest, "child_compiler_identity": identity, |
| 1794 | "child_compiler_sha256": digest(Path(child_compiler).read_bytes()), |
| 1795 | "resources": requirement["resources"], |
| 1796 | "replay": conductor_cache[cachekey]}, sort_keys=True)) |
| 1797 | except (OSError, ValueError, Failure) as error: |
| 1798 | conductor_cache[cachekey] = {"error": str(error)} |
| 1799 | replay = conductor_cache[cachekey] |
| 1800 | if "error" in replay: |
| 1801 | raise Failure(replay["error"]) |
| 1802 | overall = requirement.get("expected_overall_exit") |
| 1803 | if overall is not None and replay["exit"] != overall: |
| 1804 | raise Failure(f"original conductor expected whole-manifest exit {overall}, observed {replay['exit']}; original_log={replay['stdout']}") |
| 1805 | observed = replay["verdicts"].get(requirement["original_case_name"]) |
| 1806 | expected = requirement["expected_original_conductor"] |
| 1807 | historical_failure = requirement.get("historical_failure") |
| 1808 | if historical_failure: |
| 1809 | if observed is None or observed["status"] != "FAIL" or observed["line"] != historical_failure["exact_verdict"]: |
| 1810 | raise Failure("historical failure replay changed: " + str(observed)) |
| 1811 | elif observed is None or observed["status"] != expected: |
| 1812 | raise Failure(f"original conductor oracle: expected {expected}, observed {observed}; log_sha256={replay['stdout_sha256']}; original_log={replay['stdout']}") |
| 1813 | reason = requirement.get("expected_failure_reason") |
| 1814 | if reason and reason not in observed["line"]: |
| 1815 | raise Failure("original negative control failed for the wrong reason: " + observed["line"]) |
| 1816 | if requirement.get("required_mutant_replays") is not None: |
| 1817 | raise Failure("recursive mutant replay plan") |
| 1818 | if "mutant_specification" in case.evidence: |
| 1819 | bad_controls = {name: verdict for name, verdict in replay["verdicts"].items() |
| 1820 | if ("ctl" in name) and verdict["status"] != "PASS"} |
| 1821 | if bad_controls or replay["directive_verdicts"]: |
| 1822 | raise Failure(f"mutant replay build/control failed: {bad_controls}; {replay['directive_verdicts']}") |
| 1823 | observations.append({"manifest": manifest, "child_compiler_identity": identity, |
| 1824 | "expected": expected, "observed": observed, |
| 1825 | "historical_failure": historical_failure, |
| 1826 | "conductor_exit": replay["exit"], |
| 1827 | "conductor_stdout_sha256": replay["stdout_sha256"], |
| 1828 | "filesystem_sha256": replay["filesystem_sha256"], |
| 1829 | "directive_verdicts": replay["directive_verdicts"]}) |
| 1830 | historical_failures = [item for item in observations if item["historical_failure"]] |
| 1831 | record("PASS", case.name, ("historical FAIL reproduced exactly; not current acceptance or a successful mutant kill" |
| 1832 | if historical_failures else "original conductor oracle proved on native/x86 hosts with explicit child compiler identity"), |
| 1833 | source_sha256=key, evidence=case.evidence, replays=observations, |
| 1834 | control_kind=case.evidence["control_kind"], oracle_instructions=len(instructions), |
| 1835 | child_compiler_architecture="native AArch64 in both conductor runs") |
| 1836 | continue |
| 1837 | if case.operation == "structural": |
| 1838 | minimum = case.evidence["structural"]["minimum_calls"] |
| 1839 | calls = sum(count for mnemonic, count in mnemonics.items() if mnemonic in ("call", "callq")) |
| 1840 | if calls < minimum: |
| 1841 | raise Failure(f"explicit structural call obligation: decoded {calls}, requires at least {minimum}") |
| 1842 | if case.operation == "same": |
| 1843 | left = run([compiler], case.same_source, cwd, options.timeout) |
| 1844 | right = run([compiler], TARGET_PREFIX + case.same_source, cwd, options.timeout) |
| 1845 | if left[0] or right[0] or default[1] != left[1] or x86[1] != right[1]: |
| 1846 | diagnostics.update(default_same=result_details(left), x86_same=result_details(right)) |
| 1847 | raise Failure("same oracle failed: each architecture must compile both sources to byte-identical artifacts") |
| 1848 | record("PASS", case.name, "same-artifact oracle independently satisfied on both architectures + decoded x86", |
| 1849 | source_sha256=key, evidence=case.evidence, oracle_instructions=len(instructions)) |
| 1850 | continue |
| 1851 | if case.operation == "emit": |
| 1852 | record("PASS", case.name, "explicit compiler exit/stdout/stderr oracle + x86 differential/decode", |
| 1853 | source_sha256=key, evidence=case.evidence, oracle_instructions=len(instructions)) |
| 1854 | continue |
| 1855 | if case.blocker: |
| 1856 | record("BLOCKED" if case.blocker.startswith("BLOCKED_ON ") else "NOT_RUN", |
| 1857 | case.name, case.blocker, source_sha256=key, |
| 1858 | evidence=case.evidence, oracle_instructions=len(instructions), |
| 1859 | bridge=str(options.bridge) if options.bridge else None) |
| 1860 | continue |
| 1861 | if not MAIN.search(case.source): |
| 1862 | callers = exercise_bare(case, default[1], x86[1], qemu, cwd, options.timeout) |
| 1863 | if callers: |
| 1864 | record("PASS", case.name, "original bare artifact decoded + reviewed full-width private-ABI callers exercised", |
| 1865 | source_sha256=key, evidence=case.evidence, callers=callers, |
| 1866 | oracle_instructions=len(instructions), data_carveouts=carveouts) |
| 1867 | continue |
| 1868 | record("NOT_RUN", case.name, f"entryless source {key} has no reviewed private-ABI caller for its exported/last entry", |
| 1869 | source_sha256=key, evidence=case.evidence, |
| 1870 | oracle_instructions=len(instructions), data_carveouts=carveouts) |
| 1871 | continue |
| 1872 | words = host_words(case.source) |
| 1873 | if words and not driver: |
| 1874 | record("NOT_RUN", case.name, f"source {key} requires unreviewed effects: {', '.join(words)}", |
| 1875 | source_sha256=key, evidence=case.evidence, host_words=words, |
| 1876 | oracle_instructions=len(instructions), data_carveouts=carveouts) |
| 1877 | continue |
| 1878 | native, emulated = cwd / "native", cwd / "emulated" |
| 1879 | native.mkdir(); emulated.mkdir() |
| 1880 | basename = driver if driver and driver != "positional-view" else "program" |
| 1881 | for directory, image in ((native, default[1]), (emulated, x86[1])): |
| 1882 | binary = directory / basename |
| 1883 | binary.write_bytes(image); binary.chmod(0o700) |
| 1884 | args = case.args |
| 1885 | if driver == "args" and not args: |
| 1886 | args = ("", "two words", "π") |
| 1887 | elif driver == "memcheck": |
| 1888 | args = (compiler,) |
| 1889 | elif driver == "process": |
| 1890 | if helper_image is None: |
| 1891 | helper = run([compiler], (ROOT / "seed/host/tests/args.om").read_bytes(), cwd, options.timeout) |
| 1892 | if helper[0]: |
| 1893 | raise Failure("native exec-child helper compilation refused") |
| 1894 | helper_image = helper[1] |
| 1895 | # execve intentionally enters a native host ELF in both runs. |
| 1896 | # qemu-user is not assumed registered as a system binfmt. |
| 1897 | for directory in (native, emulated): |
| 1898 | child = directory / "exec-child" |
| 1899 | child.write_bytes(helper_image); child.chmod(0o700) |
| 1900 | elif driver == "effect-scratch" and "native_child" in case.evidence: |
| 1901 | spec = case.evidence["native_child"] |
| 1902 | child_source = contained(spec["source"]).read_bytes() |
| 1903 | if digest(child_source) != spec["source_sha256"]: |
| 1904 | raise Failure("reviewed native child source changed: " + spec["source"]) |
| 1905 | built = run([compiler], child_source, cwd, options.timeout) |
| 1906 | if built[0] or built[2]: |
| 1907 | raise Failure(f"native child compilation failed: {result_details(built)}") |
| 1908 | case.evidence["native_child_sha256"] = digest(built[1]) |
| 1909 | # Both arms exec the same native AArch64 child; only the parent changes architecture. |
| 1910 | for directory in (native, emulated): |
| 1911 | child = directory / "exec-child" |
| 1912 | child.write_bytes(built[1]); child.chmod(0o700) |
| 1913 | prepared = [prepare_case(ROOT, directory, driver, compiler, case=case.evidence) |
| 1914 | for directory in (native, emulated)] |
| 1915 | if prepared[0] != prepared[1]: |
| 1916 | raise Failure("reviewed prepare_case produced architecture-dependent argv") |
| 1917 | if prepared[0]: |
| 1918 | args = tuple(prepared[0]) |
| 1919 | if "stdin_compiled_source" in case.evidence: |
| 1920 | source_path = case.evidence["stdin_compiled_source"] |
| 1921 | stdin_source = contained(source_path).read_bytes() |
| 1922 | if digest(stdin_source) != case.evidence["stdin_source_sha256"]: |
| 1923 | raise Failure("reviewed scanner input source changed: " + source_path) |
| 1924 | compiled_input = run([compiler], stdin_source, cwd, options.timeout) |
| 1925 | if compiled_input[0] or compiled_input[2]: |
| 1926 | raise Failure(f"scanner input compilation failed: {result_details(compiled_input)}") |
| 1927 | case.evidence["stdin_original_artifact_sha256"] = digest(compiled_input[1]) |
| 1928 | case.stdin = select_a64_entry(compiled_input[1], case.evidence["stdin_export_index"]) |
| 1929 | case.evidence["stdin_selected_entry_artifact_sha256"] = digest(case.stdin) |
| 1930 | case.evidence["runtime_args"] = list(args) |
| 1931 | case.evidence["runtime_stdin_sha256"] = digest(case.stdin) |
| 1932 | expected = case.expected_exit |
| 1933 | if expected is None and driver: |
| 1934 | expected = 103 if driver in ("environment_trap", "stat_short", "links_short") else 0 |
| 1935 | # Both argv[0] strings and initial environments are byte-identical; |
| 1936 | # filesystem mutations cannot leak between architectures. |
| 1937 | argv0 = "./" + basename |
| 1938 | cpu_seconds = 1 if driver == "cpu-limit" else EFFECT_CPU_SECONDS if driver == "effect-scratch" else None |
| 1939 | nofile = case.evidence.get("nofile", 256) if driver == "effect-scratch" else 256 |
| 1940 | arun = run([argv0, *args], case.stdin, native, child_timeout, cpu_seconds=cpu_seconds, nofile=nofile) |
| 1941 | xrun = run([qemu, "-0", argv0, argv0, *args], case.stdin, emulated, child_timeout, cpu_seconds=cpu_seconds, nofile=nofile) |
| 1942 | volatile = case.evidence.get("volatile_stdout_line") if driver == "effect-scratch" else None |
| 1943 | if volatile: |
| 1944 | # Only whole lines PREFIX<digits> (wall-clock observations) are masked; the line count must match. |
| 1945 | pattern = re.compile(rb"(?m)^" + re.escape(volatile.encode()) + rb"[0-9]+$") |
| 1946 | counts = len(pattern.findall(arun[1])), len(pattern.findall(xrun[1])) |
| 1947 | case.evidence["volatile_stdout_lines_masked"] = list(counts) |
| 1948 | if counts[0] != counts[1]: |
| 1949 | raise Failure(f"runtime differential: {volatile} line count default={counts[0]} x86={counts[1]}") |
| 1950 | arun = (arun[0], pattern.sub(volatile.encode() + b"#", arun[1]), arun[2]) |
| 1951 | xrun = (xrun[0], pattern.sub(volatile.encode() + b"#", xrun[1]), xrun[2]) |
| 1952 | diagnostics.update(default_run=result_details(arun), x86_run=result_details(xrun)) |
| 1953 | if "required_verdict" in case.evidence: |
| 1954 | required = ("VERDICT " + case.evidence["required_verdict"]).encode() |
| 1955 | if required not in arun[1].splitlines() or required not in xrun[1].splitlines(): |
| 1956 | raise Failure(f"original scanner did not prove required verdict {required!r}") |
| 1957 | native_files = filesystem_snapshot(native, {basename, "exec-child"}) |
| 1958 | x86_files = filesystem_snapshot(emulated, {basename, "exec-child"}) |
| 1959 | diagnostics.update(default_filesystem=native_files, x86_filesystem=x86_files) |
| 1960 | if native_files != x86_files: |
| 1961 | raise Failure("persistent scratch filesystem effects differ (type/mode/contents/symlink target)") |
| 1962 | if arun[0] < 0 or xrun[0] < 0: |
| 1963 | if not ((driver == "supervisor-self-signal" and case.operation == "differential" and |
| 1964 | case.evidence.get("required_conductor_verdict") == "INVALID signal" and |
| 1965 | arun[0] == xrun[0] == case.expected_exit == -9) or |
| 1966 | (driver == "cpu-limit" and arun[0] == xrun[0] == case.expected_exit == -signal.SIGXCPU)): |
| 1967 | raise Failure(f"runtime signal: default={arun[0]} x86={xrun[0]}") |
| 1968 | if arun != xrun: |
| 1969 | artifact = ioctl_emulator_artifact(case, driver, arun, xrun, qemu, argv0, |
| 1970 | args, emulated, options.timeout) |
| 1971 | if artifact: |
| 1972 | record("NOT_RUN", case.name, "EMULATOR_ARTIFACT: exact invalid-fd ioctl returned QEMU ENOTTY instead of native EBADF", |
| 1973 | source_sha256=key, evidence=case.evidence, emulator_artifact=artifact, |
| 1974 | diagnostics=diagnostics, oracle_instructions=len(instructions)) |
| 1975 | continue |
| 1976 | raise Failure(f"runtime differential: default={arun[0]} x86={xrun[0]}, stdout={arun[1] == xrun[1]}, stderr={arun[2] == xrun[2]}") |
| 1977 | if expected is not None and arun[0] != expected: |
| 1978 | raise Failure(f"fixture oracle exit {expected}, observed {arun[0]}") |
| 1979 | assert_oracle(arun[1], case.stdout_oracle, "runtime stdout", different=case.operation == "kill") |
| 1980 | assert_oracle(arun[2], case.stderr_oracle, "runtime stderr") |
| 1981 | reason = "target-adapted ABI differential" if adaptation else "identical-source native-AArch64/qemu-x86 differential" |
| 1982 | if driver == "supervisor-self-signal": |
| 1983 | reason = "supervisor negative-input control: both children observed SIGKILL, never an ordinary mutant kill" |
| 1984 | record("PASS", case.name, reason + " + every code byte decoded", run_exit=arun[0], |
| 1985 | stdout_sha256=digest(arun[1]), source_sha256=key, x86_source_sha256=digest(target), |
| 1986 | x86_sha256=digest(x86[1]), oracle_instructions=len(instructions), |
| 1987 | data_carveouts=carveouts, host_driver=driver, target_adaptation=adaptation, |
| 1988 | exec_child_architecture="native AArch64" if driver == "process" else None, |
| 1989 | generation_ceiling_whitebox=driver == "genlimit", evidence=case.evidence, |
| 1990 | conductor_operation=case.operation, |
| 1991 | control_kind=("generation_ceiling_whitebox" if driver == "genlimit" else |
| 1992 | "supervisor_negative_input" if driver in ("supervisor-self-signal", "supervisor-self-sleep") else None), |
| 1993 | filesystem_sha256=digest(json.dumps(native_files, sort_keys=True).encode()), |
| 1994 | filesystem_entries=len(native_files)) |
| 1995 | if case.name == "seed/rung4/tests/t_exit.om": |
| 1996 | expected = int((ROOT / "seed/rung4/tests/t_exit.want").read_text()) |
| 1997 | if arun != (expected, b"", b""): |
| 1998 | raise Failure("exit control disagrees with existing .want oracle") |
| 1999 | controls = (case.source, x86[1], arun) |
| 2000 | except (OSError, ValueError, struct.error, Failure) as error: |
| 2001 | record("BLOCKED" if str(error).startswith("BLOCKED_ON ") else "FAIL", case.name, str(error), source_sha256=key, |
| 2002 | evidence=case.evidence, diagnostics=diagnostics) |
| 2003 | if not options.inventory: |
| 2004 | if controls is None: |
| 2005 | record("FAIL", "negative-controls", "required t_exit.om did not qualify") |
| 2006 | else: |
| 2007 | source, image, baseline = controls |
| 2008 | cwd = scratch / "negative-controls" |
| 2009 | cwd.mkdir() |
| 2010 | try: |
| 2011 | _, instructions, _ = disassemble(image, source, objdump, llvm, cwd, options.timeout) |
| 2012 | bad = bytearray(image) |
| 2013 | first = instructions[0][0] |
| 2014 | bad[first:first + 2] = b"\x0f\x04" # unassigned x86 opcode, not UD2 (which is valid). |
| 2015 | try: |
| 2016 | disassemble(bytes(bad), source, objdump, llvm, cwd, options.timeout) |
| 2017 | except Failure: |
| 2018 | record("PASS", "negative-invalid-encoding", "independent disassembler rejected deliberately invalid emitted opcode") |
| 2019 | else: |
| 2020 | raise Failure("invalid-opcode mutant survived disassembler") |
| 2021 | candidates = [(offset, raw) for offset, raw, _ in instructions |
| 2022 | if len(raw) == 10 and raw[:2] == b"\x48\xb8" and raw[2:] == (42).to_bytes(8, "little")] |
| 2023 | if len(candidates) != 1: |
| 2024 | raise Failure("expected unique MOVABS RAX,42 in exit fixture for wrong-immediate control") |
| 2025 | offset, raw = candidates[0] |
| 2026 | wrong = bytearray(image) |
| 2027 | wrong[offset + 2] = 43 |
| 2028 | disassemble(bytes(wrong), source, objdump, llvm, cwd, options.timeout) |
| 2029 | mutant = cwd / "wrong-immediate" |
| 2030 | mutant.write_bytes(wrong); mutant.chmod(0o700) |
| 2031 | observed = run([qemu, str(mutant)], b"", cwd, options.timeout) |
| 2032 | if observed[0] < 0 or observed == baseline: |
| 2033 | raise Failure("valid-but-wrong encoding mutant not caught by behavior differential") |
| 2034 | record("PASS", "negative-valid-wrong-encoding", "disassembler accepts valid changed immediate; behavior oracle rejects it", expected_exit=baseline[0], observed_exit=observed[0]) |
| 2035 | except (OSError, Failure) as error: |
| 2036 | record("FAIL", "negative-controls", str(error)) |
| 2037 | missing = sum(count for status, count in totals.items() if status not in ("PASS", "EXCLUDED", "INVENTORY_PROGRAM", "INVENTORY_HOST", "INVENTORY_UNIT")) |
| 2038 | print(json.dumps({ |
| 2039 | "summary": dict(totals), |
| 2040 | "reasons": [{"status": status, "reason": reason, "count": count} |
| 2041 | for (status, reason), count in sorted(reasons.items())], |
| 2042 | "oracle_mnemonic_counts": dict(sorted(templates.items())), |
| 2043 | "coverage_limits": [ |
| 2044 | "Every emitted code byte is linearly decoded, including unreachable functions; direct branches must target decoded instruction boundaries", |
| 2045 | "Only source-matched JMP-protected literal/padding spans are carved out; ambiguous/missing data maps fail closed", |
| 2046 | "Mnemonic counts are not exhaustive encoding-template, register, width, displacement or trap coverage", |
| 2047 | "The default baseline may share frontend defects; invalid and valid-but-wrong encoding controls challenge separate oracles", |
| 2048 | "Frozen C2 retains exact historical inputs; original frontend modes compare unchanged bytes through native/x86-hosted compilers, separately from cross-target code generation", |
| 2049 | "Reviewed content-pinned host drivers run in separate architecture-local directories and compare persistent filesystem effects; other host effects remain NOT_RUN", |
| 2050 | "Bare callers execute original unit bytes through architecture-specific ABI wrappers and observe full-width returns/arrays; missing callers remain individually NOT_RUN", |
| 2051 | "process exec enters a native AArch64 helper in both runs, not an x86 child; generation retirement uses the original fixture's exact ceiling3 compiler variant on both targets", |
| 2052 | "psync invokes syncfs on its scratch-file descriptor and therefore flushes the scratch filesystem; no service process is controlled", |
| 2053 | "No hardware qualification"], |
| 2054 | "verdict": "INVENTORY_ONLY" if options.inventory else ("FAIL" if missing else "PASS")})) |
| 2055 | return 0 if options.inventory else int(bool(missing)) |
| 2056 | |
| 2057 | |
| 2058 | if __name__ == "__main__": |
| 2059 | raise SystemExit(main()) |