Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-bridge/blob/main/tests/native/x86/suite.py # omega-bridge Omega-first language interoperability: checked conversion backends and native language bindings Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-bridge / tests / native / x86 / suite.py` 873 lines ยท 56392 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """ABI v2 cross-qualification, reusing tests/native/v2's unmodified oracles. 3 4 Required: OMEGA_NATIVE_OMC (baseline generator compiler), OMEGA_NATIVE_X86_OMC 5 (pinned x86 compiler), CC=x86_64-linux-gnu-gcc, CXX=x86_64-linux-gnu-g++, 6 rustc with x86_64-unknown-linux-gnu std, Zig 0.13, Go with cgo, qemu-x86_64, 7 and OMEGA_NATIVE_X86_PYTHON (an x86 Linux interpreter, NOT host python). 8 OMEGA_NATIVE_X86_SYSROOT defaults to /usr/x86_64-linux-gnu; an extracted Python 9 runtime may supply OMEGA_NATIVE_X86_LIBPATH. Missing tools refuse aggregate PASS. 10 The emulator's sha256 and version are recorded, and qemu_probe.c must show that it 11 provides the guest services the callers use; otherwise QEMU-ORACLE-UNUSABLE refuses 12 aggregate PASS before any caller runs. 13 No CPU timing or native hardware qualification is inferred from emulation. 14 15 OMEGA_NATIVE_X86_EXEC=native runs every target executable directly on the host CPU 16 instead of under QEMU. It requires an x86-64 host, does not use or probe QEMU, and 17 still needs the AArch64 compilers to execute there (binfmt_misc qemu-aarch64). The 18 CPU model, kernel and virtualization detected are printed; check names and the 19 aggregate line say NATIVE instead of EMULATED. docs/NATIVE-X86-PHYSICAL.md is the 20 runbook and receipt format for a physical run. 21 """ 22 import hashlib 23 import importlib.util 24 import os 25 from pathlib import Path 26 import platform 27 import re 28 import shlex 29 import shutil 30 import struct 31 import subprocess 32 import sys 33 34 ROOT = Path(__file__).resolve().parents[3] 35 HERE = Path(__file__).resolve().parent 36 T = ROOT / "tests/native/v2" 37 N = ROOT / "tests/native" 38 SPAN_SPEC = importlib.util.spec_from_file_location("native_span_compare", T / "span_compare.py") 39 SPAN_COMPARE = importlib.util.module_from_spec(SPAN_SPEC) 40 SPAN_SPEC.loader.exec_module(SPAN_COMPARE) 41 OUTPUTS = {"c": "c", "h": "h", "python": "py", "rust": "rs", "zig": "zig", "go": "go", 42 "api": "api.h", "apih": "api_decl.h", "apic": "api_defs.c"} 43 REQUIRED = {"c", "cpp", "python", "rust", "zig", "go"} 44 # The AArch64 parity baseline is the generator of the last intentional AArch64 output change: 45 # `f637021` (#26, f32 and ushort array kinds). Moving it requires a reviewed AArch64 output change. 46 BASELINE = "`f637021`" 47 # #27 respelled the object-format directives (OMBR_* macros in the texts pre, fp, fr, fv and xjmp) 48 # and the Python loader's library name (tb); the AArch64 bytes they assemble to are unchanged. #24 49 # reworded pre's comment on the registers a unit may write; that is C comment text only. Before the 50 # comparison, a "~"-separated piece of those baseline texts that equals the same piece of PREOBJ's 51 # takes that piece of OBJFMT (blob of src/native.om after #24 and #27), and tb's two loader literals 52 # take #27's spelling. Both sides are pinned objects, never this tree's src/native.om, so any other 53 # change to those texts still fails parity (tests/native/v2/run.sh basegen does the same for fr, fv 54 # and tb). PREOBJ's texts equal BASELINE's for all six names. 55 PREOBJ = "`7af4d11`" 56 OBJFMT = "`3eece7baf184ac38b102e7edd7b120f41f225e78`" 57 SPELLED = (b"pre", b"fp", b"fr", b"fv", b"xjmp") 58 LOADER = ((rb"import ctypes, os\n", rb"import ctypes, os, sys\n"), 59 (rb'os.path.abspath(__file__)), \"libomega_native.so\"))', 60 rb'os.path.abspath(__file__)),\n \"libomega_native.dylib\" if sys.platform == \"darwin\" else \"libomega_native.so\"))')) 61 62 63 def digest(data): 64 return hashlib.sha256(data).hexdigest() 65 66 67 def texts(source): 68 return {line.split(b" ", 2)[1]: line for line in source.split(b"\n") if line.startswith(b"text ")} 69 70 71 def respell(source, old, new): 72 old, new = texts(old), texts(new) 73 lines = [] 74 for line in source.split(b"\n"): 75 name = line.split(b" ", 2)[1] if line.startswith(b"text ") else b"" 76 if name in SPELLED and name in old and name in new: 77 # The closing quote belongs to the text, not to its last piece: piece counts differ (fr). 78 h, o, c = (t.removesuffix(b'"').split(b"~") for t in (line, old[name], new[name])) 79 line = b"~".join(c[k] if k < len(o) and k < len(c) and h[k] == o[k] else h[k] 80 for k in range(len(h))) + b'"' 81 elif name == b"tb": 82 for spelled, respelled in LOADER: 83 line = line.replace(spelled, respelled, 1) 84 lines.append(line) 85 return b"\n".join(lines) 86 87 88 89 def command(key, default): 90 return shlex.split(os.environ.get(key, default)) 91 92 93 class Suite: 94 def __init__(self, out): 95 self.out = out.resolve() 96 self.out.mkdir(parents=True, exist_ok=True) 97 self.cc = command("CC", "x86_64-linux-gnu-gcc") 98 self.cxx = command("CXX", "x86_64-linux-gnu-g++") 99 self.zig = command("ZIG", "zig") 100 self.go = command("GO", "go") 101 self.rust = command("RUSTC", "rustc") 102 self.mode = os.environ.get("OMEGA_NATIVE_X86_EXEC", "qemu") 103 self.native = self.mode == "native" 104 self.how = "NATIVE" if self.native else "EMULATED" 105 self.virt = "unknown" 106 self.qemu = command("QEMU_X86_64", "qemu-x86_64") 107 self.sysroot = os.environ.get("OMEGA_NATIVE_X86_SYSROOT", "/usr/x86_64-linux-gnu") 108 self.python = os.environ.get("OMEGA_NATIVE_X86_PYTHON", "") 109 self.nm = command("NM", "x86_64-linux-gnu-nm") 110 self.objdump = command("OBJDUMP", "x86_64-linux-gnu-objdump") 111 self.env = dict(os.environ, CC=shlex.join(self.cc), CGO_ENABLED="1", GOOS="linux", GOARCH="amd64") 112 self.failed = [] 113 self.missing = [] 114 self.ran = set() 115 self.omc = os.environ.get("OMEGA_NATIVE_OMC", "") 116 self.xomc = os.environ.get("OMEGA_NATIVE_X86_OMC", "") 117 self.lib = self.out / "library" 118 self.gen = self.lib / "work/native-gen" 119 self.counter = 0 120 121 def check(self, name, ok): 122 print(("PASS " if ok else "FAIL ") + name, flush=True) 123 if not ok: 124 self.failed.append(name) 125 return ok 126 127 def call(self, args, *, data=None, cwd=None, env=None): 128 args = list(map(str, args)) 129 self.counter += 1 130 result = subprocess.run(args, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 131 cwd=cwd, env=self.env if env is None else env) 132 log = self.out / f"{self.counter:04d}.log" 133 log.write_bytes(("$ " + shlex.join(args) + "\n").encode() + result.stdout + result.stderr 134 + f"\nexit={result.returncode}\n".encode()) 135 if result.returncode: 136 print(f"INFO exit={result.returncode} log={log}", flush=True) 137 return result 138 139 def must(self, args, **kwargs): 140 result = self.call(args, **kwargs) 141 if result.returncode: 142 raise RuntimeError(f"command failed: {shlex.join(list(map(str, args)))}") 143 return result.stdout 144 145 def guest(self, exe, *args): 146 # Every target execution goes through QEMU unless native execution was requested. 147 libpath = os.environ.get("OMEGA_NATIVE_X86_LIBPATH") 148 if self.native: 149 cmd = ["env", "LD_LIBRARY_PATH=" + libpath] if libpath else [] 150 return cmd + [str(exe), *map(str, args)] 151 cmd = self.qemu + ["-L", self.sysroot] 152 if libpath: 153 cmd += ["-E", "LD_LIBRARY_PATH=" + libpath] 154 return cmd + [str(exe), *map(str, args)] 155 156 def native_host(self): 157 # Identify the CPU that runs the callers; the label PHYSICAL needs virtualization=none. 158 if not self.check("native execution host is x86-64 (uname -m " + platform.machine() + ")", 159 platform.machine() == "x86_64"): 160 return False 161 cpuinfo = Path("/proc/cpuinfo").read_text(errors="replace") 162 model = re.search(r"^model name\s*:\s*(.*)$", cpuinfo, re.M) 163 flags = re.search(r"^flags\s*:\s*(.*)$", cpuinfo, re.M) 164 print("INFO cpu model=" + (model.group(1).strip() if model else "(none)"), flush=True) 165 print("INFO cpu hypervisor flag=" + ("yes" if flags and "hypervisor" in flags.group(1).split() else "no"), flush=True) 166 print("INFO kernel=" + platform.release(), flush=True) 167 if shutil.which("systemd-detect-virt"): 168 result = subprocess.run(["systemd-detect-virt"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) 169 self.virt = result.stdout.decode(errors="replace").strip() or "unknown" 170 print("INFO virtualization=" + self.virt, flush=True) 171 binfmt = Path("/proc/sys/fs/binfmt_misc/qemu-aarch64") 172 if binfmt.is_file(): 173 interpreter = re.search(r"^interpreter (.*)$", binfmt.read_text(errors="replace"), re.M) 174 print("INFO binfmt qemu-aarch64 interpreter=" + (interpreter.group(1) if interpreter else "(none)"), flush=True) 175 # The pinned compilers are AArch64 executables; they must still run on this host. 176 for name, path in (("generator", self.omc), ("x86", self.xomc)): 177 try: 178 ran = subprocess.run([path], input=b"", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60) 179 runs = ran.returncode >= 0 180 except (OSError, subprocess.TimeoutExpired): 181 runs = False 182 self.check(name + " compiler (AArch64) executes on this host", runs) 183 return not self.failed 184 185 186 def qemu_oracle(self): 187 # Identify the emulator, then probe the guest services the callers depend on. 188 # A probe, not a version string: a patched or rebuilt QEMU is judged by behavior. 189 exe = Path(shutil.which(self.qemu[0])).resolve() 190 print("INFO qemu executable=" + str(exe), flush=True) 191 print("INFO qemu sha256=" + digest(exe.read_bytes()), flush=True) 192 version = self.must(self.qemu + ["--version"]).decode(errors="replace").splitlines() 193 print("INFO qemu version=" + (version[0] if version else "(none)"), flush=True) 194 folder = self.out / "qemu-probe" 195 folder.mkdir() 196 probe = folder / "qemu_probe" 197 self.must(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", 198 str(HERE / "qemu_probe.c"), "-o", str(probe)]) 199 usable = True 200 for mode in ("maps", "sigframe"): 201 result = self.call(self.guest(probe, mode)) 202 if result.returncode == 0 and result.stdout == f"QEMU-PROBE {mode} ok\n".encode(): 203 print(f"INFO qemu oracle {mode} ok", flush=True) 204 continue 205 usable = False 206 seen = (result.stdout + result.stderr).decode(errors="replace").strip().splitlines() 207 print(f"NOT_RUN QEMU-ORACLE-UNUSABLE {mode}: exit={result.returncode} " 208 + (seen[-1] if seen else "(no output)"), flush=True) 209 if not usable: 210 self.missing.append("qemu-oracle") 211 return usable 212 213 def preflight(self): 214 if self.mode not in ("qemu", "native"): 215 self.check("OMEGA_NATIVE_X86_EXEC is qemu or native, not " + repr(self.mode), False) 216 return False 217 tools = {"c": self.cc, "cpp": self.cxx, "rust": self.rust, "zig": self.zig, "go": self.go, 218 "nm": self.nm, "objdump": self.objdump} 219 if not self.native: 220 tools["qemu"] = self.qemu 221 for language, cmd in tools.items(): 222 if not cmd or not shutil.which(cmd[0]): 223 self.missing.append(language) 224 print(f"NOT_RUN {language} caller/tool: {shlex.join(cmd)} unavailable", flush=True) 225 if not self.python or not Path(self.python).is_file(): 226 self.missing.append("python") 227 print("NOT_RUN python caller: set OMEGA_NATIVE_X86_PYTHON to an x86 interpreter", flush=True) 228 else: 229 elf = Path(self.python).resolve().read_bytes()[:20] 230 self.check("Python is ELF64 x86-64, not the host interpreter", 231 elf[:6] == b"\x7fELF\x02\x01" and elf[18:20] == b"\x3e\x00") 232 for name, path, key in (("generator", self.omc, "PIN"), ("x86", self.xomc, "X86_PIN")): 233 match = re.search(r"^" + key + r"=([0-9a-f]{64})$", (ROOT / "tools/native").read_text(), re.M) 234 self.check(name + " compiler pin", bool(match and path and Path(path).is_file() 235 and digest(Path(path).read_bytes()) == match.group(1))) 236 if self.missing or self.failed: 237 return False 238 if self.native and not self.native_host(): 239 return False 240 if not self.native and not self.qemu_oracle(): 241 return False 242 rustlib = self.must(self.rust + ["--print", "target-libdir", "--target", "x86_64-unknown-linux-gnu"]).decode().strip() 243 if not list(Path(rustlib).glob("libstd-*.rlib")): 244 self.missing.append("rust-std-x86_64") 245 print("NOT_RUN rust caller: x86_64-unknown-linux-gnu standard library absent", flush=True) 246 print("INFO x86 compiler sha256=" + digest(Path(self.xomc).read_bytes()), flush=True) 247 print("INFO generator compiler sha256=" + digest(Path(self.omc).read_bytes()), flush=True) 248 # Prove the extracted runtime can load ctypes before importing generated bindings. 249 p = self.call(self.guest(self.python, "-I", "-c", "import ctypes, platform; assert platform.machine() == 'x86_64'; print('X86-PYTHON READY')")) 250 self.check("x86 Python interpreter and ctypes runtime", p.returncode == 0 and b"X86-PYTHON READY" in p.stdout) 251 return not self.failed and not self.missing 252 253 def generate(self, word, frame, gen=None, target=True): 254 return self.call([gen or self.gen, word] + (["x86linux"] if target else []), data=frame) 255 256 def frame(self, source, code, name=None): 257 result = source + b"\0" + f"{len(code):08d}".encode() + code 258 if name is not None: 259 result += f"omega-unit {name} {digest(Path(self.xomc).read_bytes())}\n".encode() 260 return result 261 262 def compile_unit(self, source): 263 return self.must([self.xomc], data=b"target x86linux\n" + source) 264 265 def build_c(self, folder, source=None, output="caller_c", shared=False, extra=()): 266 source = source or T / "caller.c" 267 flags = ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror"] 268 if shared: 269 flags += ["-fPIC", "-shared", "-Wl,-soname,libomega_native.so", "-include", str(folder / "omega_native.h")] 270 else: 271 flags += ["-pthread", "-I", str(folder)] 272 cmd = self.cc + flags + [str(source)] 273 if not shared: 274 cmd += ["-L" + str(folder), "-lomega_native", "-Wl,-rpath," + str(folder), "-ldl"] 275 return self.call(cmd + list(extra) + ["-o", str(folder / output)]) 276 277 def initial_library(self): 278 units = [N / "madd.om"] + [T / (name + ".om") for name in ("vec", "lay", "one")] 279 self.must([ROOT / "tools/native", "--target", "x86linux", self.lib, *units]) 280 self.frame_set = (self.lib / "work/units.in").read_bytes() 281 for caller in T.glob("caller.*"): 282 shutil.copy2(caller, self.lib / caller.name) 283 self.check("tools/native built mixed OM-1/OM-2 x86 library and all bindings", True) 284 285 def identity_and_code(self): 286 ctext = (self.lib / "omega_native.c").read_text() 287 self.check("x86 floor uses actual usable stack base, independent of out carve", 288 "mov %r9,%r15" in ctext and 289 bool(re.search(r"ombr_xenter.*ombr_stk\s*-\s*OMBR_STACK", ctext))) 290 htext = (self.lib / "omega_native.h").read_text() 291 identities = (self.lib / "work/ident.txt").read_text() 292 elf = (self.lib / "libomega_native.so").read_bytes() 293 self.check("library ELF machine is x86-64", elf[:6] == b"\x7fELF\x02\x01" and elf[18:20] == b"\x3e\x00") 294 for name in ("madd", "vec", "lay", "one"): 295 path = (N if name == "madd" else T) / (name + ".om") 296 source = path.read_bytes() 297 abi = 1 if name == "madd" else 2 298 identity = f"omega-ident 1 unit={name} abi={abi} profile=OM-{abi} src={digest(source)} omc={digest(Path(self.xomc).read_bytes())}" 299 self.check("original source/compiler identity " + name, identity + " path=" + str(path) in identities 300 and (abi == 1 or ('"' + identity + '"' in ctext and '"' + identity + '"' in htext))) 301 self.check("source snapshot excludes target directive " + name, 302 (self.lib / f"work/{name}.om").read_bytes() == source) 303 code = (self.lib / f"work/{name}.bin").read_bytes() 304 self.check("compiler bytes reproduce " + name, code == self.compile_unit(source)) 305 entries = len(re.findall(rb"^export fn ", source, re.M)) 306 if entries: 307 valid = len(code) >= entries * 6 308 for index in range(entries): 309 start = index * 6 310 slot = code[start:start + 6] 311 valid = valid and len(slot) == 6 and slot[0] == 0xe9 and slot[5] == 0x90 312 if len(slot) == 6: 313 destination = start + 5 + struct.unpack("= entries and b"(bad)" not in listing) 320 symbol = ("ombr_code_" if abi == 1 else "ombr2_code_") + name 321 symbols = self.must(self.objdump + ["-t", str(self.lib / "libomega_native.so")]).decode() 322 address = next(int(line.split()[0], 16) for line in symbols.splitlines() if line.split() and line.split()[-1] == symbol) 323 sections = self.must(self.objdump + ["-h", str(self.lib / "libomega_native.so")]).decode() 324 offsets = [line.split() for line in sections.splitlines() if re.match(r"\s*\d+\s+\.", line)] 325 offset = next(address - int(s[3], 16) + int(s[5], 16) for s in offsets 326 if int(s[3], 16) <= address < int(s[3], 16) + int(s[2], 16)) 327 self.check("embedded bytes unchanged " + name, elf[offset:offset + len(code)] == code) 328 exports = set(line.split()[-1] for line in self.must(self.nm + ["-D", "--defined-only", str(self.lib / "libomega_native.so")]).decode().splitlines()) 329 expected = {"omega2_" + name for name in "absorb bsum digest fillv halt ident_lay ident_one ident_vec lsum swap8 two vcopy vlen vpart wsum".split()} | {"omega_madd"} 330 self.check("exact public ABI symbol set", exports == expected) 331 private = [line.split() for line in self.must(self.nm + ["--defined-only", str(self.lib / "libomega_native.so")]).decode().splitlines() 332 if line.split()[-1].startswith("ombr")] 333 self.check("all runtime/code/entry symbols private", bool(private) and all(s[-2].islower() for s in private)) 334 self.check("no caller hand-declares Omega ABI", not any(re.search(r'uint32_t omega|fn omega|argtypes|CDLL|import "C"', p.read_text()) for p in T.glob("caller.*"))) 335 # Declarations do not depend on instruction bytes. Pad only the payload 336 # to satisfy the default generator's four-byte AArch64 word boundary. 337 declaration_frame = b"" 338 for name in ("madd", "vec", "lay", "one"): 339 source = (self.lib / f"work/{name}.om").read_bytes() 340 code = (self.lib / f"work/{name}.bin").read_bytes() 341 code += b"\x90" * (-len(code) % 4) 342 declaration_frame += self.frame(source, code, None if name == "madd" else name) 343 for word in ("h", "python", "rust", "zig", "go", "api", "apih", "apic"): 344 a = self.generate(word, declaration_frame) 345 b = self.generate(word, declaration_frame, target=False) 346 self.check("target-independent declarations " + word, a.returncode == b.returncode == 0 and a.stdout == b.stdout) 347 348 def build_language(self, language, folder, stem="caller", edition="2021"): 349 source = folder / stem 350 if language == "c": 351 return self.build_c(folder, source.with_suffix(".c"), stem + "_c") 352 if language == "cpp": 353 return self.call(self.cxx + ["-std=c++17", "-O2", "-Wall", "-Wextra", "-Werror", "-I", str(folder), str(source.with_suffix(".cpp")), "-L" + str(folder), "-lomega_native", "-Wl,-rpath," + str(folder), "-o", str(folder / (stem + "_cpp"))]) 354 if language == "rust": 355 return self.call(self.rust + ["--target", "x86_64-unknown-linux-gnu", "-C", "linker=" + self.cc[0], "-O", "--edition", edition, "-D", "warnings", str(source.with_suffix(".rs")), "-L", str(folder), "-C", "link-arg=-Wl,-rpath," + str(folder), "-o", str(folder / (stem + "_rust"))]) 356 if language == "zig": 357 return self.call(self.zig + ["build-exe", str(source.with_suffix(".zig")), "-target", "x86_64-linux-gnu", "-L" + str(folder), "-lomega_native", "-lc", "-rpath", str(folder), "-femit-bin=" + str(folder / (stem + "_zig"))], cwd=folder) 358 if language == "go": 359 pkg = folder / (stem + "-go") 360 (pkg / "omeganative").mkdir(parents=True) 361 for name in ("omega_native.go", "omega_native.h", "libomega_native.so"): 362 shutil.copy2(folder / name, pkg / "omeganative" / name) 363 shutil.copy2(source.with_suffix(".go"), pkg / "main.go") 364 (pkg / "go.mod").write_text("module omegacaller\n\ngo 1.20\n") 365 env = dict(self.env, CGO_LDFLAGS="-Wl,-rpath," + str(pkg / "omeganative")) 366 return self.call(self.go + ["build", "-o", str(folder / (stem + "_go")), "."], cwd=pkg, env=env) 367 raise ValueError(language) 368 369 def callers(self): 370 for language in sorted(REQUIRED): 371 if language == "python": 372 result = self.call(self.guest(self.python, "-I", self.lib / "caller.py", self.lib)) 373 else: 374 build = self.build_language(language, self.lib) 375 if not self.check(language + " caller built", build.returncode == 0): 376 continue 377 result = self.call(self.guest(self.lib / ("caller_" + language))) 378 transcript = result.stdout + result.stderr 379 if self.check(language + " caller " + self.how, result.returncode == 0 and b"PASS" in transcript and b"FAIL" not in transcript): 380 self.ran.add(language) 381 if language == "rust": 382 build = self.build_language(language, self.lib, edition="2024") 383 self.check("rust-2024 caller " + self.how, build.returncode == 0 and self.call(self.guest(self.lib / "caller_rust")).returncode == 0) 384 built = self.build_c(self.lib, Path(__file__).with_name("sysv.c"), "sysv", 385 extra=[str(Path(__file__).with_name("sysv.S"))]) 386 self.check("SysV AMD64 saved-register oracle " + self.how, 387 built.returncode == 0 and self.call(self.guest(self.lib / "sysv")).returncode == 0) 388 389 def stale_and_v1(self): 390 stale = self.out / "stale" 391 stale.mkdir() 392 shutil.copy2(self.lib / "libomega_native.so", stale) 393 original = (T / "vec.om").read_bytes() 394 changed = original.replace(b"an OM-2 unit", b"An OM-2 unit", 1) 395 self.check("stale source mutation changes bytes", changed != original) 396 frame = self.frame(changed, (self.lib / "work/vec.bin").read_bytes(), "vec") 397 for word, ext in (("h", "h"), ("python", "py")): 398 result = self.generate(word, frame) 399 self.check("stale " + word + " generated", result.returncode == 0) 400 (stale / ("omega_native." + ext)).write_bytes(result.stdout) 401 self.must(self.cc + ["-std=gnu11", "-I", str(stale), str(T / "stale.c"), "-L" + str(stale), "-lomega_native", "-Wl,-rpath," + str(stale), "-o", str(stale / "stale_c")]) 402 result = self.call(self.guest(stale / "stale_c")) 403 self.check("stale C identity refused", result.returncode == 3 and ("src=" + digest(changed)).encode() in result.stdout) 404 self.must(self.cc + ["-std=gnu11", "-I", str(self.lib), str(T / "stale.c"), "-L" + str(self.lib), "-lomega_native", "-Wl,-rpath," + str(self.lib), "-o", str(stale / "fresh_c")]) 405 self.check("fresh C identity control", self.call(self.guest(stale / "fresh_c")).returncode == 0) 406 result = self.call(self.guest(self.python, "-I", "-c", f"import sys; sys.path.insert(0, {str(stale)!r}); import omega_native")) 407 self.check("stale Python import refused for identity", result.returncode != 0 and b"ImportError: libomega_native.so is not the library" in result.stderr) 408 old = self.out / "v1use" 409 old.mkdir() 410 shutil.copy2(self.lib / "libomega_native.so", old) 411 source = (T / "v1use/bsum.om").read_bytes() 412 frame = self.frame(source, self.compile_unit(source)) 413 for word in ("h", "python", "rust", "zig", "go"): 414 result = self.generate(word, frame) 415 self.check("v1 refusal binding generated " + word, result.returncode == 0) 416 (old / ("omega_native." + OUTPUTS[word])).write_bytes(result.stdout) 417 for source in (T / "v1use").glob("use.*"): 418 shutil.copy2(source, old / source.name) 419 for language in sorted(REQUIRED): 420 result = self.call(self.guest(self.python, "-I", old / "use.py", old)) if language == "python" else self.build_language(language, old, "use") 421 self.check(language + " refuses old v1 symbol", result.returncode != 0 and b"omega_bsum" in result.stdout + result.stderr 422 and bool(re.search(rb"undefined reference|undefined symbol", result.stdout + result.stderr))) 423 424 def refusals(self): 425 code = (self.lib / "work/vec.bin").read_bytes() 426 b = b"om2\nexport fn e1 d view uchar * to ulong\nret 0\nend\n" 427 trailer = b"omega-unit u " + b"0" * 64 + b"\n" 428 def frame(source=b, binary=code, tail=trailer): 429 return source + b"\0" + f"{len(binary):08d}".encode() + binary + tail 430 result = self.generate("c", frame()) 431 self.check("generator accepts refusal control", result.returncode == 0 and b"omega2_e1(uint64_t *result, const uint8_t *o_d, uint64_t o_d_len)" in result.stdout) 432 cases = [("missing identity", frame(tail=b"")), ("short digest", frame(tail=b"omega-unit u 0123\n")), 433 ("nonhex digest", frame(tail=b"omega-unit u " + b"0" * 63 + b"G\n")), 434 ("invalid unit name", frame(tail=trailer.replace(b" u ", b" a-b "))), 435 ("repeated unit", frame() + frame(source=b.replace(b"e1", b"e2"))), 436 ("repeated export", frame() + frame(tail=trailer.replace(b" u ", b" v "))), 437 ("diag", frame(source=b.replace(b"om2\n", b"om2 diag\n"))), 438 ("eight slots", frame(source=b"om2\nexport fn e1 a view uchar * b view uchar * c view uchar * d view uchar * to ulong\nret 0\nend\n")), 439 ("unknown layout", frame(source=b"om2\nexport fn e1 c edit nolay to void\nend\n")), 440 ("oversized out", frame(source=b"om2\nexport fn e1 o out ulong 8193 to void\nend\n")), 441 ("uint scalar", frame(source=b"om2\nexport fn e1 x uint to ulong\nret 0\nend\n")), 442 ("uint result", frame(source=b.replace(b"to ulong", b"to uint"))), 443 ("reserved len name", frame(source=b.replace(b"e1 d ", b"e1 d_len "))), 444 ("short six-byte entry table", frame(source=b"om2\nexport fn e1 to void\nend\nexport fn e2 to void\nend\n", binary=b"x" * 11)), 445 ("unknown c-type layout", frame(source=b"note bridge c-type nolay x\nom2\nexport fn e1 to void\nend\n"))] 446 for name, data in cases: 447 result = self.generate("c", data) 448 self.check("generator refuses " + name, result.returncode == 110 and not result.stdout) 449 for args in ([], ["java", "x86linux"], ["c", "unknown"], ["c", "x86linux", "extra"]): 450 result = self.call([self.gen, *args], data=self.frame_set) 451 self.check("generator refuses argument vector " + repr(args), result.returncode == 110 and not result.stdout) 452 wrong_pin = dict(self.env, OMEGA_NATIVE_X86_OMC=self.omc) 453 absent = self.out / "wrong-compiler-pin" 454 result = self.call([ROOT / "tools/native", "--target", "x86linux", absent, N / "madd.om"], env=wrong_pin) 455 self.check("mismatched x86 compiler refuses before creating outputs", 456 result.returncode == 1 and not result.stdout and b"x86 omc sha256" in result.stderr 457 and b", pinned " in result.stderr and not absent.exists()) 458 keep = self.out / "keep" 459 self.must([ROOT / "tools/native", "--target", "x86linux", keep, N / "madd.om"]) 460 before = {str(p.relative_to(keep)): p.read_bytes() for p in keep.rglob("*") if p.is_file()} 461 result = self.call([ROOT / "tools/native", "--target", "x86linux", keep, N / "madd.om"], env=wrong_pin) 462 after = {str(p.relative_to(keep)): p.read_bytes() for p in keep.rglob("*") if p.is_file()} 463 self.check("mismatched x86 compiler preserves previous outputs", 464 result.returncode == 1 and not result.stdout and b"x86 omc sha256" in result.stderr 465 and before == after) 466 bad = self.out / "bad.om" 467 bad.write_bytes(b"fn m a ulong to uchar\nret uchar a\nend\n") 468 result = self.call([ROOT / "tools/native", "--target", "x86linux", keep, N / "madd.om", bad]) 469 after = {str(p.relative_to(keep)): p.read_bytes() for p in keep.rglob("*") if p.is_file()} 470 self.check("tools/native refusal preserves previous outputs and removes scratch", result.returncode == 110 and str(bad).encode() in result.stderr and before == after) 471 472 def mutant_generator(self, name, old, new, count=1, within=None): 473 # within: mutate only the one src/native.om line starting with these bytes. 474 folder = self.out / ("mut-" + name) 475 folder.mkdir() 476 source = (ROOT / "src/native.om").read_bytes() 477 if within is None: 478 assert source.count(old) == count, (name, source.count(old), count) 479 changed = source.replace(old, new) 480 else: 481 lines = source.split(b"\n") 482 hit = [i for i, line in enumerate(lines) if line.startswith(within)] 483 assert len(hit) == 1, (name, within, len(hit)) 484 assert lines[hit[0]].count(old) == count, (name, lines[hit[0]].count(old), count) 485 lines[hit[0]] = lines[hit[0]].replace(old, new) 486 changed = b"\n".join(lines) 487 binary = self.must([self.omc], data=changed) 488 gen = folder / "gen" 489 gen.write_bytes(binary) 490 gen.chmod(0o755) 491 return folder, gen 492 493 def runtime_mutants(self): 494 for name, old, new, expected in ( 495 ("wrap", b" || n * es > UINTPTR_MAX - lo)", b")", b"#748 golden: vpart len 2^64-1"), 496 ("overlap", b"if ((sp[i].w == 1 || sp[j].w == 1 ||", b"if ((", b"vcopy edit == view"), 497 ("outcopy", b"memmove(o[i].dst, buf[i], o[i].n);", b"(void)buf[i];", b"digest: tag")): 498 # The hosted ABI v2 runtime (text fv) only: the freestanding OM-2 runtime (text fq) 499 # carries some of the same guards, and these callers link output c. 500 folder, gen = self.mutant_generator(name, old, new, within=b"text fv ") 501 for word, ext in (("c", "c"), ("h", "h")): 502 result = self.generate(word, self.frame_set, gen) 503 self.check(name + " mutant generated " + word, result.returncode == 0) 504 (folder / ("omega_native." + ext)).write_bytes(result.stdout) 505 self.check(name + " mutant differs", (folder / "omega_native.c").read_bytes() != (self.lib / "omega_native.c").read_bytes()) 506 shutil.copy2(self.lib / "omega_api.h", folder) 507 self.must_build(self.build_c(folder, folder / "omega_native.c", "libomega_native.so", shared=True)) 508 self.must_build(self.build_c(folder)) 509 result = self.call(self.guest(folder / "caller_c")) 510 self.check(name + " mutant caught by existing boundary oracle", result.returncode != 0 and b"FAIL " + expected in result.stdout) 511 512 @staticmethod 513 def must_build(result): 514 if result.returncode: 515 raise RuntimeError("control could not build; not a mutant detection") 516 517 def private_symbols(self): 518 source = (ROOT / "src/native.om").read_bytes() 519 for mutated in (False, True): 520 folder = self.out / ("private-mutant" if mutated else "private") 521 folder.mkdir() 522 gen = self.gen 523 if mutated: 524 changed = source.replace(b".local ombr_enter", b".globl ombr_enter") 525 assert changed != source 526 gen = folder / "gen" 527 gen.write_bytes(self.must([self.omc], data=changed)) 528 gen.chmod(0o755) 529 objects = [] 530 for name in ("madd", "smadd"): 531 text = (N / (name + ".om")).read_bytes() 532 result = self.generate("c", self.frame(text, self.compile_unit(text)), gen) 533 self.check("private fixture generated " + name, result.returncode == 0) 534 cfile = folder / (name + ".c") 535 cfile.write_bytes(result.stdout) 536 obj = folder / (name + ".o") 537 self.must(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-c", str(cfile), "-o", str(obj)]) 538 objects.append(obj) 539 if not mutated: 540 symbols = [line.split() for line in self.must(self.nm + ["--defined-only", str(obj)]).decode().splitlines()] 541 public = {line[-1] for line in symbols if line[-2].isupper()} 542 private = {line[-1]: line[-2] for line in symbols if line[-1].startswith("ombr_")} 543 helpers = ("ombr_enter", "ombr_trap", "ombr_no_entry", "ombr_code_" + name, "ombr_entry_" + name, 544 "ombr_active", "ombr_stk", "ombr_rt_table") 545 self.check("separate object private locals " + name, public == {"omega_" + name} and all(h in private and private[h].islower() for h in helpers)) 546 result = self.call(self.cc + ["-pthread", str(N / "private_symbols.c"), *map(str, objects), "-o", str(folder / "caller")]) 547 if mutated: 548 self.check("global helper mutant rejected at link", result.returncode != 0 and b"multiple definition" in result.stderr and b"ombr_enter" in result.stderr) 549 else: 550 self.must_build(result) 551 self.check("separate bindings and TLS isolation " + self.how, self.call(self.guest(folder / "caller")).returncode == 0) 552 553 def freestanding_api(self): 554 folder = self.out / "api" 555 folder.mkdir() 556 flags = ["-std=gnu11", "-ffreestanding", "-fno-builtin", "-O2", "-Wall", "-Wextra", "-Werror"] 557 def imports(obj): 558 return {line.split()[-1] for line in self.must(self.nm + ["-u", str(obj)]).decode().splitlines()} 559 self.must(self.cc + flags + ["-I", str(self.lib), "-c", str(T / "fsuse.c"), "-o", str(folder / "use.o")]) 560 self.check("prototype-only API has no libc imports", imports(folder / "use.o") == {"absorb", "bsum", "digest", "swap8"}) 561 self.must(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-Wmissing-prototypes", "-I", str(self.lib), "-c", str(self.lib / "omega_api_defs.c"), "-o", str(folder / "defs.o")]) 562 symbols = self.must(self.nm + [str(folder / "defs.o")]) 563 self.check("out-of-line API owns abort and definitions", "abort" in imports(folder / "defs.o") and b" T swap8" in symbols) 564 inline = folder / "inline.c" 565 inline.write_bytes((T / "fsuse.c").read_bytes().replace(b'"omega_api_decl.h"', b'"omega_api.h"')) 566 self.must(self.cc + flags + ["-I", str(self.lib), "-c", str(inline), "-o", str(folder / "inline.o")]) 567 self.check("inline API import negative control", "abort" in imports(folder / "inline.o")) 568 exe = folder / "fsmain" 569 self.must(self.cc + ["-std=gnu11", "-O2", "-I", str(self.lib), str(T / "fsmain.c"), str(folder / "use.o"), str(folder / "defs.o"), "-L" + str(self.lib), "-lomega_native", "-Wl,-rpath," + str(self.lib), "-o", str(exe)]) 570 result = self.call(self.guest(exe)) 571 self.check("out-of-line API " + self.how, result.returncode == 0 and b"PASS fs_check 0" in result.stdout) 572 result = self.call(self.guest(exe, "refuse")) 573 self.check("out-of-line API trap aborts", result.returncode in (-6, 134)) 574 for name, old, new in (("apih", b"if eq get st 5 8\n", b"if eq get st 5 98\n"), 575 ("api", b"if eq get st 5 7\n", b"if eq get st 5 97\n")): 576 mutant, gen = self.mutant_generator(name, old, new) 577 result = self.generate(name, self.frame_set, gen) 578 self.check(name + " API mutant generated", result.returncode == 0) 579 if name == "apih": 580 shutil.copy2(self.lib / "omega_native.h", mutant) 581 (mutant / "omega_api_decl.h").write_bytes(result.stdout) 582 # Supply abort's declaration so this control detects the import 583 # leak, not an unrelated implicit-declaration compilation error. 584 build = self.call(self.cc + flags + ["-include", "stdlib.h", "-I", str(mutant), "-c", str(T / "fsuse.c"), "-o", str(mutant / "use.o")]) 585 self.check("prototype-only API mutant caught", (build.returncode == 0 and "abort" in imports(mutant / "use.o"))) 586 else: 587 self.check("inline API mutant caught", result.stdout != (self.lib / "omega_api.h").read_bytes() and b"static inline" not in result.stdout) 588 589 def aarch64_parity(self): 590 SPAN_COMPARE.self_test() 591 self.check("AArch64 span normalization refuses five controls, including another wrapper byte", True) 592 baseline = self.out / "baseline-native-gen" 593 source = respell(self.must(["git", "-C", str(ROOT), "show", BASELINE + ":src/native.om"]), 594 self.must(["git", "-C", str(ROOT), "show", PREOBJ + ":src/native.om"]), 595 self.must(["git", "-C", str(ROOT), "cat-file", "blob", OBJFMT])) 596 baseline.write_bytes(self.must([self.omc], data=source)) 597 baseline.chmod(0o755) 598 frames = {} 599 span_counts = {} 600 om2_frames = {"v2-set"} 601 for path in sorted(N.rglob("*.om")): 602 # Hosted file/device units require the separate hosted compiler and --host; 603 # their explicit AArch64/x86 device conductors cover that admission contract. 604 # tests/native/macos holds #27's host-word unit, whose C output gains the intended 605 # macOS #error; no baseline generator emits it, and tests/native/macos/run.sh covers it. 606 if (Path(__file__).parent in path.parents 607 or any(N / "v2" / name in path.parents for name in ("host", "dev")) 608 or N / "macos" in path.parents): 609 continue 610 text = path.read_bytes() 611 # A note line is one whose first word is note (a bare `note` too), as src/native.om reads it. 612 significant = [line for line in text.splitlines() if line.split()[:1] not in ([], [b"note"])] 613 om2 = bool(significant and significant[0] == b"om2") 614 compiler = self.xomc if om2 else self.omc 615 result = self.call([compiler], data=text) 616 if result.returncode: 617 self.check("AArch64 parity fixture compiles " + str(path.relative_to(N)), False) 618 continue 619 # The unit name as tools/native writes it (tr -c 'A-Za-z0-9_' '_'). 620 trailer = ("omega-unit " + re.sub(r"[^A-Za-z0-9_]", "_", path.stem) + " " + digest(Path(compiler).read_bytes()) + "\n").encode() if om2 else b"" 621 frame = text + b"\0" + f"{len(result.stdout):08d}".encode() + result.stdout + trailer 622 frames[path] = frame 623 # Expected declarations come from input exports, never from either C output. 624 exports = sum(line.split()[:2] == [b"export", b"fn"] for line in text.splitlines()) 625 span_counts[str(path.relative_to(N))] = (exports or 1) if om2 else 1 626 if om2: 627 om2_frames.add(str(path.relative_to(N))) 628 sets = {"v1-set": b"".join(frame for path, frame in frames.items() if path.parent == N), 629 "v2-set": frames.get(N / "madd.om", b"") + b"".join(frames.get(T / (name + ".om"), b"") for name in ("vec", "lay", "one"))} 630 span_counts["v1-set"] = sum(span_counts[str(path.relative_to(N))] for path in frames if path.parent == N) 631 span_counts["v2-set"] = span_counts["madd.om"] + sum(span_counts["v2/" + name + ".om"] for name in ("vec", "lay", "one")) 632 self.check("AArch64 combined OM1 span count is exactly9", span_counts["v1-set"] == 9) 633 self.check("AArch64 combined OM2 span count is exactly13", span_counts["v2-set"] == 13) 634 comparisons = [(str(path.relative_to(N)), frame) for path, frame in frames.items()] + list(sets.items()) 635 for name, frame in comparisons: 636 for word in (*OUTPUTS, "freest"): 637 old = self.generate(word, frame, baseline, target=False) 638 new = self.generate(word, frame, target=False) 639 if word == "freest" and name in om2_frames: 640 # Deliberate change: the baseline refuses OM-2 units in output freest (exit 110); 641 # they are now bound on the caller's stack (docs/NATIVE-ABI.md, ABI v2, freestanding). 642 self.check("AArch64 freest " + name + ": " + BASELINE + " refused OM-2, now accepted", 643 old.returncode == 110 and not old.stdout and new.returncode == 0 and new.stdout) 644 continue 645 same_output = old.stdout == new.stdout 646 if word == "c" and old.returncode == new.returncode == 0: 647 try: 648 SPAN_COMPARE.compare(old.stdout, new.stdout, span_counts[name]) 649 same_output = True 650 except ValueError: 651 same_output = False 652 self.check("AArch64 byte parity " + BASELINE + " " + name + " " + word, 653 old.returncode == new.returncode and same_output and old.stderr == new.stderr) 654 655 def trap_controls(self): 656 here = Path(__file__).parent 657 source = (here / "trapcall.om").read_bytes() 658 code = self.compile_unit(source) 659 follow_source = (here / "follow.om").read_bytes() 660 follow_frame = self.frame(follow_source, self.compile_unit(follow_source)) 661 out_source = (here / "outtrap.om").read_bytes() 662 out_frame = self.frame(out_source, self.compile_unit(out_source), "outtrap") 663 pattern = b"\xbe\x05\x00\x00\x00\x41\xff\x66\x10" 664 self.check("nested explicit trap uses ESI and runtime table slot 2", code.count(pattern) == 1) 665 if code.count(pattern) != 1: 666 return 667 basicwrite = self.call([self.xomc], data=b"target x86linux\nfn hostbad d edit uchar 1 to ulong\nr = write 1 d 0 1\nret ulong r\nend\n") 668 self.check("legacy basic write remains permitted in bare code", basicwrite.returncode == 0 and bool(basicwrite.stdout)) 669 hostword = self.call([self.xomc], data=b"target x86linux\nfn hostbad to long\nr = fclose -1\nret r\nend\n") 670 self.check("advanced bare host helper remains compiler refusal 9", hostword.returncode == 9 and b"error 9" in hostword.stderr) 671 for name, changed, expected in ( 672 ("trap", code, 5), 673 ("zero-code", code.replace(pattern, b"\xbe\x00\x00\x00\x00\x41\xff\x66\x10"), 34), 674 ("wrong-slot", code.replace(pattern, b"\xbe\x05\x00\x00\x00\x41\xff\x66\x00"), 34), 675 ("xsave-stack", code, 6)): 676 folder = self.out / name 677 folder.mkdir() 678 frame = self.frame(source, changed) + follow_frame + out_frame 679 for word, ext in (("c", "c"), ("h", "h")): 680 result = self.generate(word, frame) 681 self.check(name + " control generated " + word, result.returncode == 0) 682 output = result.stdout 683 if name == "xsave-stack" and word == "c": 684 before = b"mov %r9,%r15" 685 self.check("xsave control bounds only owned runtime stack", output.count(before) == 1) 686 output = output.replace(before, b"lea -1024(%r8),%r15") 687 (folder / ("omega_native." + ext)).write_bytes(output) 688 self.must_build(self.build_c(folder, folder / "omega_native.c", "libomega_native.so", shared=True)) 689 build = self.build_c(folder, here / "trapcheck.c", "trapcheck", 690 extra=["-DEXPECT_TRAP=" + str(expected), str(here / "sysv.S")]) 691 self.must_build(build) 692 result = self.call(self.guest(folder / "trapcheck")) 693 self.check(name + ": status " + str(expected) + ", sentinel, saved regs and subsequent call " + self.how, 694 result.returncode == 0 and b"PASS trap status" in result.stdout) 695 696 def freestanding_x86(self): 697 # tests/native/test_freestanding.py's caller (four threads, nested trap, signed trap) 698 # against `tools/native --target x86linux --freestanding`, i.e. the xfasm adapter. 699 sys.path.insert(0, str(N)) 700 import test_freestanding 701 good = (ROOT / "src/native.om").read_bytes() 702 old, new = b"mov %rax,(%rcx)", b"mov %rbx,(%rcx)" 703 xfasm = [line for line in good.split(b"\n") if line.startswith(b"text xfasm ")] 704 # The mutant must hit the freestanding adapter's result store exactly once. 705 if not self.check("freestanding result-store mutant applies once to xfasm", 706 len(xfasm) == 1 and xfasm[0].count(old) == 1): 707 return 708 bad = good.replace(xfasm[0], xfasm[0].replace(old, new)) 709 for name, source in (("freestanding-x86", good), ("freestanding-x86-mutant", bad)): 710 tree = self.out / name 711 (tree / "tools").mkdir(parents=True) 712 (tree / "src").mkdir() 713 shutil.copy2(ROOT / "tools/native", tree / "tools/native") 714 (tree / "src/native.om").write_bytes(source) 715 epoch = tree / "epoch.om" 716 epoch.write_text(test_freestanding.EPOCH) 717 lib = tree / "lib" 718 self.must([tree / "tools/native", "--target", "x86linux", "--freestanding", lib, epoch, N / "smadd.om"]) 719 obj = lib / "omega_native.o" 720 elf = obj.read_bytes() 721 imports = {line.split()[-1] for line in self.must(self.nm + ["-u", str(obj)]).decode().splitlines() if line.split()} 722 self.check(name + " object is x86-64 with no runtime imports (GOT marker only)", 723 elf[:6] == b"\x7fELF\x02\x01" and elf[18:20] == b"\x3e\x00" 724 and not imports - test_freestanding.ALLOWED) 725 caller = tree / "caller.c" 726 caller.write_text(test_freestanding.CALLER) 727 self.must_build(self.call(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-pthread", 728 "-I", str(lib), str(caller), str(obj), "-o", str(tree / "caller")])) 729 result = self.call(self.guest(tree / "caller")) 730 if source is good: 731 self.check("freestanding x86 epoch/MAX trap, nested and signed trap, four threads " + self.how, 732 result.returncode == 0) 733 else: 734 self.check("freestanding x86 result-store mutant caught by caller " + self.how, 735 result.returncode == 1) 736 737 def freestanding_om2_x86(self): 738 # tests/native/test_freestanding_om2.py's caller (FIPS 180-4 digests, out-buffer rules, four 739 # threads) against `tools/native --target x86linux --freestanding` with OM-2 units, i.e. 740 # outputs freest + fapic through the SysV adapter, and the copy-back-dropped mutant. 741 sys.path.insert(0, str(N)) 742 import test_freestanding_om2 as om2 743 good = (ROOT / "src/native.om").read_text() 744 units = list(om2.UNITS) 745 for name, source in (("freestanding-om2-x86", good), ("freestanding-om2-x86-mutant", om2.drop_copyback(good))): 746 tree = self.out / name 747 (tree / "tools").mkdir(parents=True) 748 (tree / "src").mkdir() 749 shutil.copy2(ROOT / "tools/native", tree / "tools/native") 750 (tree / "src/native.om").write_text(source) 751 lib = tree / "lib" 752 self.must([tree / "tools/native", "--target", "x86linux", "--freestanding", lib, *units]) 753 objs = [lib / "omega_native.o", lib / "omega_api_defs.o"] 754 defined, imports = set(), set() 755 for obj in objs: 756 elf = obj.read_bytes() 757 self.check(name + " " + obj.name + " is x86-64 ELF", elf[:6] == b"\x7fELF\x02\x01" and elf[18:20] == b"\x3e\x00") 758 imports |= {l.split()[-1] for l in self.must(self.nm + ["-u", str(obj)]).decode().splitlines() if l.split()} 759 defined |= {l.split()[-1] for l in self.must(self.nm + ["--defined-only", "-g", str(obj)]).decode().splitlines() if l.split()} 760 self.check(name + " objects have no runtime imports (GOT marker only)", not imports - om2.ALLOWED - defined) 761 self.must_build(self.call(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-pthread", 762 "-I", str(lib), str(N / "v2/fsom2.c"), *map(str, objs), 763 "-o", str(tree / "fsom2")])) 764 result = self.call(self.guest(tree / "fsom2")) 765 lines = result.stdout.decode().splitlines() 766 got = dict(l.split() for l in lines if l.split() and l.split()[0] in om2.WANT) 767 if source is good: 768 self.check("freestanding x86 OM-2 FIPS 180-4 digests, bad-arg and trap leave out untouched, four threads " + self.how, 769 result.returncode == 0 and got == om2.WANT and "badarg 32 1" in lines 770 and "outok 0 2 7 1" in lines and "outtrap 5 1" in lines 771 and "threads 1" in lines and "floatbits 1" in lines) 772 # The fapic wrapper's __builtin_trap() is ud2 on x86-64: SIGILL, and the call never returns. 773 result = self.call(self.guest(tree / "fsom2", "trap")) 774 self.check("freestanding x86 OM-2 fapic wrapper traps (SIGILL) on a nonzero status " + self.how, 775 result.returncode == -4 and not result.stdout) 776 else: 777 # Every digest must be the caller's untouched 0xa5 pre-call fill, so a crash or a 778 # partial run cannot pass as the mutant being caught. 779 self.check("freestanding x86 OM-2 copy-back-dropped mutant leaves the pre-call fill in every digest " + self.how, 780 result.returncode == 0 and got == om2.MUTANT) 781 782 def freestanding_f32_x86(self): 783 # Reuse the gate's exact guest command, including its sysroot and optional 784 # LD_LIBRARY_PATH, for both the bare caller and the hosted reference. 785 marker = "omega-f32-executable" 786 guest = self.guest(marker) 787 assert guest[-1] == marker 788 env = dict(self.env, NM=shlex.join(self.nm), 789 FREEST_RUNNER=shlex.join(guest[:-1])) 790 result = self.call([sys.executable, N / "test_freestanding_f32.py", 791 "--target", "x86linux", "--out", self.out / "freestanding-f32-x86"], 792 env=env) 793 self.check("freestanding x86 private FP32 integer ABI, bare no-libc, raw hosted differential and five mutants " + self.how, 794 result.returncode == 0 and b"three source and two generator mutants caught" in result.stdout) 795 796 def floor_controls(self): 797 # This is a byte-level foreign ABI oracle, not compiler behavior: 798 # mov %r15,%rax; ret; nop; nop occupies one six-byte export slot. 799 source = b"om2\nexport fn floor o out uchar 64 to ulong\nput o 0 1\nret 0\nend\n" 800 frame = self.frame(source, b"\x4c\x89\xf8\xc3\x90\x90", "floor") 801 generated = {} 802 for word in ("c", "h"): 803 result = self.generate(word, frame) 804 self.check("direct floor oracle generated " + word, result.returncode == 0) 805 generated[word] = result.stdout 806 correct = b"ombr_stk - OMBR_STACK" 807 self.check("direct floor oracle finds one true-floor argument", generated["c"].count(correct) == 1) 808 for name, mutated in (("floor", False), ("floor-mutant", True)): 809 folder = self.out / name 810 folder.mkdir() 811 for ext, payload in generated.items(): 812 if mutated and ext == "c": 813 payload = payload.replace(correct, b"(unsigned char *)(top) - OMBR_STACK") 814 (folder / ("omega_native." + ext)).write_bytes(payload) 815 self.must(self.cc + ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", 816 "-I", str(folder), str(Path(__file__).with_name("floorcheck.c")), 817 "-pthread", "-o", str(folder / "floorcheck")]) 818 result = self.call(self.guest(folder / "floorcheck")) 819 if mutated: 820 self.check("carved-top floor mutant rejected without crash " + self.how, 821 result.returncode == 1 and b"FAIL stack floor" in result.stdout) 822 else: 823 self.check("actual R15 mapping floor with ABI-v2 out buffer " + self.how, 824 result.returncode == 0 and b"PASS R15 equals actual" in result.stdout) 825 826 def finish(self): 827 if not self.native: 828 print("NATIVE-X86 NATIVE NOT_RUN (physical x86 execution not requested)", flush=True) 829 if self.failed: 830 print("NATIVE-X86 FAIL " + "; ".join(self.failed), flush=True) 831 return 1 832 missing = set(self.missing) | (REQUIRED - self.ran) 833 if missing: 834 print("NATIVE-X86 NOT_RUN (not run: " + " ".join(sorted(missing)) + ")", flush=True) 835 return 1 836 if self.native: 837 print("NATIVE-X86 NATIVE PASS (six languages built and run on the host x86-64 CPU; " 838 "virtualization=" + self.virt + ")", flush=True) 839 return 0 840 print("NATIVE-X86 EMULATED PASS (six languages built and run; native x86 NOT_RUN)", flush=True) 841 return 0 842 843 844 def main(): 845 if len(sys.argv) > 2: 846 print("usage: suite.py [EMPTY_OUTPUT]", flush=True) 847 return 2 848 out = Path(sys.argv[1]) if len(sys.argv) == 2 else ROOT / "build/native-x86" 849 # Refuse overwriting any previous evidence. Give each integration run a fresh directory. 850 if out.exists() and any(out.iterdir()): 851 print("FAIL output directory must be empty: " + str(out), flush=True) 852 return 1 853 suite = Suite(out) 854 try: 855 if suite.preflight(): 856 for step in (suite.initial_library, suite.identity_and_code, suite.aarch64_parity, 857 suite.callers, suite.stale_and_v1, suite.refusals, suite.runtime_mutants, 858 suite.private_symbols, suite.freestanding_api, suite.trap_controls, 859 suite.freestanding_x86, suite.freestanding_om2_x86, 860 suite.freestanding_f32_x86, suite.floor_controls): 861 try: 862 step() 863 except (RuntimeError, AssertionError, OSError, StopIteration) as error: 864 suite.check(step.__name__ + ": " + str(error), False) 865 if step == suite.initial_library: 866 break 867 except (RuntimeError, OSError) as error: 868 suite.check("preflight: " + str(error), False) 869 return suite.finish() 870 871 872 if __name__ == "__main__": 873 sys.exit(main())