#!/usr/bin/env python3 """Verify private GCC 16.2 IDE observations against sealed primary-file snapshots.""" import argparse from contextlib import ExitStack from dataclasses import dataclass import fcntl import hashlib import json import os from pathlib import Path import re import runpy import secrets import selectors import signal import subprocess import sys import tempfile import time HERE = Path(__file__).resolve().parent WIRE = runpy.run_path(str(HERE / "verify-gcc-events.py")) check = WIRE["check"] KINDS = {"hello", "occurrence", "ideCoverage", "frontendEnd", "terminal"} IDE = ("-fvls-observe", "-fvls-ide") TRACE_LIMIT = 1024 * 1024 SIDE_LIMIT = 256 * 1024 def strict_json(data): return json.loads(data.decode("utf-8", errors="strict"), object_pairs_hook=WIRE["unique_keys"], parse_constant=WIRE["reject_number"]) def sealed_file(owned, data): check(len(data) <= 256 * 1024, "oversized primary snapshot") # Keep the immutable source open across the fd 3/4 launcher shuffle. initial = os.memfd_create("vls-query.cpp", os.MFD_CLOEXEC | os.MFD_ALLOW_SEALING) try: fd = fcntl.fcntl(initial, fcntl.F_DUPFD_CLOEXEC, 5) finally: os.close(initial) owned.callback(os.close, fd) with os.fdopen(os.dup(fd), "wb") as output: output.write(data) seals = fcntl.F_SEAL_WRITE | fcntl.F_SEAL_GROW | fcntl.F_SEAL_SHRINK | fcntl.F_SEAL_SEAL fcntl.fcntl(fd, fcntl.F_ADD_SEALS, seals) check(fcntl.fcntl(fd, fcntl.F_GET_SEALS) & seals == seals, "source seal failed") return fd @dataclass class Result: source: bytes snapshot: str nonce: str pid: int events: list stderr: bytes def run(binary, source, flags=IDE, expected=0, valid_digest=True): data = source.encode("utf-8") digest = hashlib.sha256(data).hexdigest() nonce = secrets.token_hex(16) env = {"LC_ALL": "C", "VLS_GCC_NONCE": nonce, "VLS_GCC_SNAPSHOT": digest if valid_digest else digest[:-1]} deadline = time.monotonic() + 10 def remaining(): left = deadline - time.monotonic() check(left > 0, "cc1plus deadline expired") return left with tempfile.TemporaryDirectory(prefix="vls-gcc-ide-") as work, ExitStack() as owned: snapshot_fd = sealed_file(owned, data) (Path(work) / "query.cpp").symlink_to(f"/proc/self/fd/{snapshot_fd}") with ExitStack() as child: control_read, control_write = os.pipe() child.callback(os.close, control_read) owned.callback(os.close, control_write) event_read, event_write = os.pipe() owned.callback(os.close, event_read) child.callback(os.close, event_write) args = [sys.executable, "-I", "-c", WIRE["LAUNCH"], str(control_read), str(event_write), str(binary), "-quiet", "-std=c++26", "-freflection", "-fsyntax-only", "-nostdinc", "-fdiagnostics-format=sarif-stderr", *flags, "query.cpp", "-o", os.devnull] proc = subprocess.Popen(args, cwd=work, env=env, start_new_session=True, pass_fds=(control_read, event_write, snapshot_fd), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) owned.callback(proc.stdout.close) owned.callback(proc.stderr.close) mux = owned.enter_context(selectors.DefaultSelector()) for stream, channel in ((event_read, "trace"), (proc.stdout, "stdout"), (proc.stderr, "stderr")): mux.register(stream, selectors.EVENT_READ, channel) buffers = {key: bytearray() for key in ("trace", "stdout", "stderr")} try: while mux.get_map(): for key, _ in mux.select(remaining()): chunk = os.read(key.fd, 16384) if not chunk: mux.unregister(key.fileobj) continue buf = buffers[key.data] limit = TRACE_LIMIT if key.data == "trace" else SIDE_LIMIT check(len(buf) + len(chunk) <= limit, f"{key.data} exceeded {limit} bytes") buf.extend(chunk) code = proc.wait(timeout=remaining()) except BaseException: try: os.killpg(proc.pid, signal.SIGKILL) except ProcessLookupError: pass proc.wait(timeout=2) raise stderr = bytes(buffers["stderr"]) check(code == expected, f"cc1plus exit {code}, expected {expected}: {stderr[:800]!r}") check(not buffers["stdout"], f"unexpected compiler stdout: {buffers['stdout'][:200]!r}") trace = bytes(buffers["trace"]) check(not trace or trace.endswith(b"\n"), "incomplete final frame") lines = trace.split(b"\n")[:-1] check(len(lines) <= 4096, "event-count limit") events = [] for index, line in enumerate(lines): check(len(line) + 1 <= 4096, "oversized event") event = strict_json(line) check(isinstance(event, dict) and type(event.get("v")) is int and event["v"] == 1 and type(event.get("seq")) is int and event["seq"] == index and event.get("nonce") == nonce, f"invalid v1 envelope at {index}") events.append(event) return Result(data, digest, nonce, proc.pid, events, stderr) def point(source, line, spelling, ordinal=0): raw = source.splitlines()[line - 1] pattern = rb"(?= 3 and events[0]["kind"] == "hello" and events[-2]["kind"] == "ideCoverage" and events[-1]["kind"] == "frontendEnd", f"missing IDE handshake, final coverage or frontend end: {events[:2]}") hello, coverage = events[0], events[-2] check(hello["backend"] == "gcc-16.2.0/vls-ide-1" and hello["pid"] == result.pid and hello["snapshot"] == result.snapshot and set(hello["kinds"]) == KINDS and hello["capabilities"] == ["primaryFileOccurrences"], f"wrong IDE handshake {hello}") check(coverage["source"] == "query.cpp" and coverage["reason"] == reason and coverage["state"] == ("unavailable" if reason else "partial") and all(type(coverage[k]) is bool for k in ("tentative", "unmapped", "unsupported", "conflict")), f"wrong coverage {coverage}") facts = {} for event in events[1:-2]: check(event["kind"] == "occurrence" and event["sourceKind"] == "primaryFileToken" and event["role"] in ("field", "call") and type(event["declUid"]) is int and event["declUid"] > 0 and event["resultType"] in ("int", "double") and re.fullmatch(r"[a-zA-Z_]\w{0,63}", event["name"], re.ASCII), f"bad fact {event}") use = read_span(event["use"], result, event["name"]) check(use not in facts, f"duplicate fact at {use}") target = None if event["targetKind"] == "unavailable": check(event["target"] is None, "unavailable target with a location") else: check(event["targetKind"] in ("definition", "declaration"), f"bad target {event}") target = read_span(event["target"], result, event["name"]) facts[use] = (event["role"], event["resultType"], event["targetKind"], target, event["declUid"]) check(reason is None or not facts, f"positive occurrence after {reason}") return facts, coverage def witness(result, role, name, use_line, target_line, result_type, *, use_ordinal=0, target_ordinal=0, target_kind="definition"): facts, _ = inspect(result) use = point(result.source, use_line, name, use_ordinal) target = point(result.source, target_line, name, target_ordinal) check(use in facts and facts[use][:4] == (role, result_type, target_kind, target), f"missing {role} from {use} to {target}: {facts}") return facts[use][4] def missing_region(result): payload = strict_json(result.stderr) diagnostics = payload["runs"][0]["results"] match = next(entry for entry in diagnostics if entry["level"] == "error" and "missing" in entry["message"]["text"]) location = match["locations"][0]["physicalLocation"] check(location["artifactLocation"]["uri"] == "query.cpp", "wrong diagnostic source") return location["region"] def verify(binary): saved = (HERE / "gcc-queries.cpp").read_text() edited = saved.replace("Point point)", "Point point, double weight)").replace("coordinate(point)", "coordinate(weight)") original, changed = run(binary, saved), run(binary, edited) witness(original, "field", "x", 6, 3, "int") witness(original, "call", "coordinate", 11, 6, "int") witness(changed, "call", "coordinate", 11, 7, "double") broken = run(binary, edited.replace("coordinate(weight)", "missing(weight)"), expected=1) inspect(broken, "compileErrors") region = missing_region(broken) check((region["startLine"], region["startColumn"], region["endColumn"]) == (11, 20, 27), f"incorrect ASCII diagnostic {region}") witness(run(binary, saved), "call", "coordinate", 11, 6, "int") print("Observed field and overload definitions, changed overload, invalid edit and recovery") for reverse in (False, True): args = ("1.0", "point") if reverse else ("point", "1.0") pair = run(binary, saved.replace("shapes::coordinate(point)", f"shapes::coordinate({args[0]}) + shapes::coordinate({args[1]})")) a = witness(pair, "call", "coordinate", 11, 7 if reverse else 6, "double" if reverse else "int") b = witness(pair, "call", "coordinate", 11, 6 if reverse else 7, "int" if reverse else "double", use_ordinal=1) check(a != b, "two overloads have the same declaration identity in one invocation") fields = run(binary, "struct A{int x;};\nstruct B{double x;};\ndouble q(A a,B b){return a.x+b.x;}\n") first = witness(fields, "field", "x", 3, 1, "int") second = witness(fields, "field", "x", 3, 2, "double", use_ordinal=1) check(first != second, "distinct field owners collapsed") qualified = run(binary, "struct Base { int x; }; using x=Base; int q(Base b){return b.x::x;}\n") witness(qualified, "field", "x", 1, 1, "int", use_ordinal=3) check(point(qualified.source, 1, "x", 2) not in inspect(qualified)[0], "published a qualifier as field use") print("Distinguished same-line overloads, same-spelling fields and a same-spelling qualifier") bom = run(binary, "\ufeffnamespace x { int x(int); } int q(){return x::x(1);}\n" "namespace x { int x(int n){return n;} }\n") witness(bom, "call", "x", 1, 2, "int", use_ordinal=3, target_ordinal=1) check(point(bom.source, 1, "x", 2) not in inspect(bom)[0], "first-line BOM shifted a call to its same-spelling qualifier") first_line_target = run(binary, "\ufeffint f(){return 1;}\nint q(){return f();}\n") witness(first_line_target, "call", "f", 2, 1, "int") print("Verified physical byte positions for a BOM-prefixed call and definition") prototype = "int only(int); int use(){return only(1);}" witness(run(binary, prototype), "call", "only", 1, 1, "int", use_ordinal=1, target_kind="declaration") witness(run(binary, prototype + " int only(int a){return a;}"), "call", "only", 1, 1, "int", use_ordinal=1, target_ordinal=2) line_remap = "int call(int x){return x;}\n#line 11\nint a(){return call(1);}\n#line 11\nint b(){return call(2);}\n" inspect(run(binary, line_remap), "lineDirective") macro = run(binary, "int call(int p){return p;}\n#define SITE call\nint q(){return SITE(1);}\n") facts, coverage = inspect(macro) check(not facts and coverage["unmapped"], "macro use escaped the provenance gate") tentative = run(binary, "struct Box{int x;}; int q(Box a){return sizeof(decltype(a.x));}\n") facts, coverage = inspect(tentative) check(not facts and coverage["tentative"], "speculative member access was published") print("Verified forward declaration, later definition, ambiguous line map, macro use and tentative parse") utf = "int q(){\t/*🙂e\u0301*/ return missing(1);}\n" failure = run(binary, utf, expected=1) inspect(failure, "compileErrors") display = missing_region(failure)["startColumn"] prefix = utf.partition("missing")[0] byte = len(prefix.encode()) + 1 utf16 = len(prefix.encode("utf-16-le")) // 2 + 1 check((display, byte, utf16) == (32, 29, 26), "Unicode diagnostic coordinate witness failed") utf_success = run(binary, "int only(int a){return a;}\n" + utf.replace("missing(1)", "only(1)")) witness(utf_success, "call", "only", 2, 1, "int") print("Verified UTF-8 token bytes and three distinct SARIF display, byte and UTF-16 columns") for flags, valid in ((IDE, False), (("-fvls-ide",), True), ((*IDE, "-fvls-step"), True)): denied = run(binary, saved, flags=flags, expected=1, valid_digest=valid) check(not denied.events and denied.stderr, "invalid IDE setup produced events") check(not run(binary, saved, flags=()).events, "disabled hooks emitted an event") print("Verified mode isolation, snapshot identity and disabled hooks") if __name__ == "__main__": ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--cc1plus", type=Path, required=True) verify(ap.parse_args().cc1plus.resolve(strict=True))