The observer emits an optional extent inside each proven definition span from the body's last statement finish (the C++ frontend does not set function_end_locus). The occurrence decoder binds it to the same snapshot through the negotiated encoding and rejects malformed extents; call hierarchy attributes nested calls to the enclosing extent. A real stdio session reported both inner calls as outgoing from outer, and the observer and occurrence corpora still pass.
416 lines
19 KiB
Python
Executable File
416 lines
19 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Verify the stock GCC occurrence observer against closed, byte-checked fixtures."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import secrets
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
MAX_REPORT = 1024 * 1024
|
|
HEX = re.compile(r"[0-9a-f]{32}")
|
|
|
|
|
|
def check(condition, detail):
|
|
if not condition:
|
|
raise ValueError(detail)
|
|
|
|
|
|
def unique_keys(pairs):
|
|
result = {}
|
|
for key, value in pairs:
|
|
check(key not in result, f"duplicate JSON key {key!r}")
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def reject_constant(value):
|
|
raise ValueError(f"non-finite JSON number {value}")
|
|
|
|
|
|
def strict_json(data):
|
|
return json.loads(data.decode("utf-8", errors="strict"), object_pairs_hook=unique_keys,
|
|
parse_constant=reject_constant)
|
|
|
|
|
|
def compiler():
|
|
selected = shutil.which("g++")
|
|
check(selected, "g++ not found")
|
|
return Path(selected).resolve(strict=True)
|
|
|
|
|
|
def manifest(work, nonce, paths):
|
|
lines = ["VLS-OCCURRENCES-1", nonce, *(str(path) for path in paths)]
|
|
(work / "inputs").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
return work / "inputs"
|
|
|
|
|
|
def compile(compiler, observer, work, main, flags=()):
|
|
env = {**os.environ, "LC_ALL": "C", "TZ": "UTC0",
|
|
"VLS_OBSERVER_INPUTS": str(work / "inputs"),
|
|
"VLS_OBSERVER_OUTPUT": str(work / "report")}
|
|
argv = [compiler, "-std=c++26", "-freflection", "-fsyntax-only", *flags,
|
|
f"-fplugin={observer}", str(main)]
|
|
return subprocess.run(argv, cwd=work, env=env, stdin=subprocess.DEVNULL,
|
|
capture_output=True, timeout=120)
|
|
|
|
|
|
def read_span(span, name, label):
|
|
check(isinstance(span, dict)
|
|
and set(span) in ({"path", "line", "startByte", "endByte"},
|
|
{"path", "line", "startByte", "endByte", "extent"}),
|
|
f"invalid {label} span {span!r}")
|
|
check(all(type(span[key]) is int for key in ("line", "startByte", "endByte")),
|
|
f"non-integer {label} span {span!r}")
|
|
path = Path(span["path"])
|
|
check(path.is_absolute() and path.is_file(), f"{label} path is not an admitted file: {path}")
|
|
lines = path.read_bytes().split(b"\n")
|
|
check(1 <= span["line"] <= len(lines), f"{label} line outside {path}: {span}")
|
|
raw = lines[span["line"] - 1]
|
|
start, end = span["startByte"], span["endByte"]
|
|
check(1 <= start < end <= len(raw) + 1, f"{label} bytes outside line: {span}")
|
|
check(raw[start - 1:end - 1] == name.encode("ascii"),
|
|
f"{label} {name!r} does not occupy {span}: {raw!r}")
|
|
raw[:start - 1].decode("utf-8")
|
|
raw[:end - 1].decode("utf-8")
|
|
if "extent" in span:
|
|
extent = span["extent"]
|
|
check(isinstance(extent, dict)
|
|
and set(extent) == {"startLine", "startByte", "endLine", "endByte"}
|
|
and all(type(value) is int for value in extent.values()),
|
|
f"invalid {label} extent {extent!r}")
|
|
check(extent["startLine"] == span["line"] and extent["startByte"] == start
|
|
and (extent["endLine"], extent["endByte"]) >= (extent["startLine"], start),
|
|
f"{label} extent does not start at its span: {extent} vs {span}")
|
|
check(1 <= extent["endLine"] <= len(lines),
|
|
f"{label} extent line outside {path}: {extent}")
|
|
last = lines[extent["endLine"] - 1]
|
|
check(1 <= extent["endByte"] <= len(last) + 1,
|
|
f"{label} extent bytes outside line: {extent}")
|
|
return (path, span["line"], start, end)
|
|
|
|
|
|
def analyze(work, nonce, admitted, complete=True, partial=None):
|
|
report_path = work / "report"
|
|
check(report_path.is_file(), "observer wrote no report")
|
|
data = report_path.read_bytes()
|
|
check(0 < len(data) <= MAX_REPORT, "report size out of bounds")
|
|
report = strict_json(data)
|
|
check(set(report) == {"schema", "nonce", "complete", "partial", "reason", "occurrences"},
|
|
f"unexpected report keys {sorted(report)}")
|
|
check(type(report["schema"]) is int and report["schema"] == 1, "wrong schema")
|
|
check(report["nonce"] == nonce and HEX.fullmatch(report["nonce"]) is not None, "wrong nonce")
|
|
check(type(report["complete"]) is bool and type(report["partial"]) is bool,
|
|
"non-boolean status")
|
|
check(isinstance(report["reason"], str), "reason is not a string")
|
|
check(report["complete"] is complete, f"complete={report['complete']}, expected {complete}")
|
|
if partial is not None:
|
|
check(report["partial"] is partial, f"partial={report['partial']}, expected {partial}")
|
|
check((report["reason"] == "") is complete, f"reason {report['reason']!r} disagrees with status")
|
|
occurrences = report["occurrences"]
|
|
check(isinstance(occurrences, list), "occurrences is not a list")
|
|
seen = set()
|
|
for occurrence in occurrences:
|
|
check(isinstance(occurrence, dict), "occurrence is not an object")
|
|
check({"name", "type", "canonicalType", "use", "definition"} <= set(occurrence)
|
|
and set(occurrence) <= {"name", "type", "canonicalType", "signature",
|
|
"use", "definition"},
|
|
f"unexpected occurrence keys {sorted(occurrence)}")
|
|
name = occurrence["name"]
|
|
check(re.fullmatch(r"[A-Za-z_]\w{0,63}", name, re.ASCII), f"bad name {name!r}")
|
|
check(isinstance(occurrence["type"], str) and occurrence["type"], "bad type")
|
|
check(isinstance(occurrence["canonicalType"], str) and occurrence["canonicalType"],
|
|
"bad canonical type")
|
|
if "signature" in occurrence:
|
|
signature = occurrence["signature"]
|
|
check(isinstance(signature, str) and 0 < len(signature) <= 300, "bad signature")
|
|
use = read_span(occurrence["use"], name, "use")
|
|
check(use[0] in admitted, f"use is outside the captured set: {use[0]}")
|
|
key = (use[0], use[1], use[2])
|
|
check(key not in seen, f"duplicate use {key}")
|
|
seen.add(key)
|
|
if occurrence["definition"] is not None:
|
|
definition = read_span(occurrence["definition"], name, "definition")
|
|
check(definition[0] in admitted,
|
|
f"definition is outside the captured set: {definition[0]}")
|
|
return report
|
|
|
|
|
|
def case(compiler, observer, name, files, main, *, flags=(), status=0, nonce=None,
|
|
verify=None, complete=True, partial=None):
|
|
with tempfile.TemporaryDirectory(prefix="vls-observer-") as temp:
|
|
work = Path(temp)
|
|
for relative, content in files.items():
|
|
path = work / relative
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(content if isinstance(content, bytes) else content.encode("utf-8"))
|
|
nonce = nonce or secrets.token_hex(16)
|
|
admitted = {(work / relative).resolve() for relative in files}
|
|
manifest(work, nonce, sorted(admitted))
|
|
result = compile(compiler, observer, work, (work / main).resolve(), flags)
|
|
check(result.returncode == status,
|
|
f"{name}: compiler exit {result.returncode}, expected {status}: "
|
|
f"{result.stderr[-800:]!r}")
|
|
if not (work / "report").exists():
|
|
check(status != 0, f"{name}: no report")
|
|
return None
|
|
report = analyze(work, nonce, admitted, complete=complete, partial=partial)
|
|
if verify:
|
|
verify(report, work)
|
|
print(f"{name}: ok")
|
|
return report
|
|
|
|
|
|
def by_name(report, name):
|
|
return [occurrence for occurrence in report["occurrences"] if occurrence["name"] == name]
|
|
|
|
|
|
def overload_case(compiler, observer):
|
|
source = """namespace shapes {
|
|
constexpr int coordinate(int value) { return value; }
|
|
constexpr double coordinate(double value) { return value; }
|
|
}
|
|
double query(int whole, double fraction) {
|
|
return shapes::coordinate(whole) + shapes::coordinate(fraction);
|
|
}
|
|
"""
|
|
def verify(report, work):
|
|
found = by_name(report, "coordinate")
|
|
check(len(found) == 2, f"expected two same-line overloads: {found}")
|
|
check({occurrence["type"] for occurrence in found} == {"int", "double"}, found)
|
|
definitions = {occurrence["definition"]["line"] for occurrence in found}
|
|
check(definitions == {2, 3}, f"overload definitions collapsed: {definitions}")
|
|
check(found[0]["use"]["line"] == found[1]["use"]["line"] == 6, found)
|
|
|
|
case(compiler, observer, "same-line overloads", {"unit.cpp": source}, "unit.cpp",
|
|
verify=verify)
|
|
edited = source.replace("double fraction", "int fraction")
|
|
def verify_edited(report, work):
|
|
found = by_name(report, "coordinate")
|
|
check(len(found) == 2, f"expected two calls after the edit: {found}")
|
|
check({occurrence["type"] for occurrence in found} == {"int"}, found)
|
|
check({occurrence["definition"]["line"] for occurrence in found} == {2}, found)
|
|
|
|
case(compiler, observer, "overload edit", {"unit.cpp": edited}, "unit.cpp",
|
|
verify=verify_edited)
|
|
|
|
|
|
def header_case(compiler, observer):
|
|
header = "int shifted(int value) {\n return value;\n}\n"
|
|
main = '#include "header.hpp"\nint q() { return shifted(3); }\n'
|
|
def verify(report, work):
|
|
found = by_name(report, "shifted")
|
|
check(len(found) == 1 and found[0]["definition"]["line"] == 1, found)
|
|
case(compiler, observer, "header definition", {"main.cpp": main, "header.hpp": header},
|
|
"main.cpp", verify=verify)
|
|
shifted = "// a new first line\n" + header
|
|
def verify_shifted(report, work):
|
|
found = by_name(report, "shifted")
|
|
check(len(found) == 1 and found[0]["definition"]["line"] == 2, found)
|
|
check(found[0]["use"]["line"] == 2, found)
|
|
case(compiler, observer, "header shift", {"main.cpp": main, "header.hpp": shifted},
|
|
"main.cpp", verify=verify_shifted)
|
|
|
|
|
|
def macro_case(compiler, observer):
|
|
source = "int call(int value) { return value; }\n#define SITE call\nint q() { return SITE(1); }\n"
|
|
def verify(report, work):
|
|
check(not by_name(report, "call"), "macro use escaped the provenance gate")
|
|
case(compiler, observer, "macro use", {"unit.cpp": source}, "unit.cpp",
|
|
verify=verify, partial=True)
|
|
|
|
|
|
def line_directive_case(compiler, observer):
|
|
source = "int call(int value) { return value; }\n#line 11\nint q() { return call(1); }\n"
|
|
def verify(report, work):
|
|
check(report["occurrences"] == [], "line remap published facts")
|
|
check(report["reason"] == "lineDirective", report["reason"])
|
|
case(compiler, observer, "line directive", {"unit.cpp": source}, "unit.cpp",
|
|
complete=False, verify=verify)
|
|
|
|
|
|
def qualifier_case(compiler, observer):
|
|
source = "namespace x { int x(int value) { return value; } }\nint q() { return x::x(1); }\n"
|
|
def verify(report, work):
|
|
found = by_name(report, "x")
|
|
check(len(found) == 1, f"expected the terminal x only: {found}")
|
|
line = source.splitlines()[1]
|
|
terminal = line.rindex("x") + 1
|
|
check(found[0]["use"]["line"] == 2 and found[0]["use"]["startByte"] == terminal,
|
|
f"wrong terminal token: {found[0]['use']} vs column {terminal}")
|
|
check(found[0]["definition"]["line"] == 1, found)
|
|
case(compiler, observer, "same-name qualifier", {"unit.cpp": source}, "unit.cpp",
|
|
verify=verify)
|
|
|
|
|
|
def declared_only_case(compiler, observer):
|
|
source = "int only(int);\nint use() { return only(1); }\n"
|
|
def verify(report, work):
|
|
found = by_name(report, "only")
|
|
check(len(found) == 1 and found[0]["definition"] is None, found)
|
|
case(compiler, observer, "declared only", {"unit.cpp": source}, "unit.cpp",
|
|
verify=verify)
|
|
|
|
|
|
def template_case(compiler, observer):
|
|
source = "template <class T> T twice(T value) { return value + value; }\nint q() { return twice(1); }\n"
|
|
def verify(report, work):
|
|
check(not by_name(report, "twice"), "template instantiation escaped the filter")
|
|
case(compiler, observer, "template instantiation", {"unit.cpp": source}, "unit.cpp",
|
|
verify=verify, partial=True)
|
|
|
|
|
|
def bom_case(compiler, observer):
|
|
source = "\ufeffint f() { return 1; } int q() { return f(); }\n"
|
|
def verify(report, work):
|
|
found = by_name(report, "f")
|
|
check(len(found) == 1, found)
|
|
expected = source.encode("utf-8").rindex(b"f()") + 1
|
|
check(found[0]["use"]["startByte"] == expected,
|
|
f"BOM-shifted use {found[0]['use']} vs byte column {expected}")
|
|
case(compiler, observer, "UTF-8 BOM", {"unit.cpp": source}, "unit.cpp", verify=verify)
|
|
|
|
|
|
def space_case(compiler, observer):
|
|
source = "int spaced(int value) { return value; }\nint q() { return spaced(1); }\n"
|
|
with tempfile.TemporaryDirectory(prefix="vls-observer-") as temp:
|
|
work = Path(temp) / "left right"
|
|
work.mkdir()
|
|
path = work / "unit file.cpp"
|
|
path.write_text(source, encoding="utf-8")
|
|
nonce = secrets.token_hex(16)
|
|
manifest(work, nonce, [path.resolve()])
|
|
result = compile(compiler, observer, work, path.resolve())
|
|
check(result.returncode == 0, result.stderr[-800:])
|
|
report = analyze(work, nonce, {path.resolve()})
|
|
found = by_name(report, "spaced")
|
|
check(len(found) == 1 and found[0]["use"]["path"] == str(path.resolve()), found)
|
|
print("path with spaces: ok")
|
|
|
|
|
|
def capacity_case(compiler, observer):
|
|
calls = "\n".join(f" total += f({index});" for index in range(300))
|
|
source = f"int f(int value) {{ return value; }}\nint q() {{\n int total = 0;\n{calls}\n return total;\n}}\n"
|
|
def verify(report, work):
|
|
check(report["reason"] == "capacity", report["reason"])
|
|
check(report["occurrences"] == [], "partial facts published after capacity")
|
|
case(compiler, observer, "capacity", {"unit.cpp": source}, "unit.cpp",
|
|
complete=False, verify=verify)
|
|
|
|
|
|
def error_case(compiler, observer):
|
|
source = "int q() { return missing(1); }\n"
|
|
def verify(report, work):
|
|
check(report["reason"] == "compileErrors", report["reason"])
|
|
check(report["occurrences"] == [], "facts published for a failed compile")
|
|
case(compiler, observer, "compile error", {"unit.cpp": source}, "unit.cpp",
|
|
status=1, complete=False, verify=verify)
|
|
recovered = "int missing(int value) { return value; }\nint q() { return missing(1); }\n"
|
|
def verify_recovered(report, work):
|
|
found = by_name(report, "missing")
|
|
check(len(found) == 1 and found[0]["definition"]["line"] == 1, found)
|
|
case(compiler, observer, "recovery", {"unit.cpp": recovered}, "unit.cpp",
|
|
verify=verify_recovered)
|
|
|
|
|
|
def malformed_case(compiler, observer):
|
|
source = "int f(int value) { return value; }\nint q() { return f(1); }\n"
|
|
for label, nonce, paths in (
|
|
("uppercase nonce", "A" * 32, None),
|
|
("short nonce", "a" * 31, None),
|
|
("relative path", "a" * 32, "unit.cpp"),
|
|
("missing file", "a" * 32, "/nonexistent/vls-observer.cpp")):
|
|
with tempfile.TemporaryDirectory(prefix="vls-observer-") as temp:
|
|
work = Path(temp)
|
|
(work / "unit.cpp").write_text(source, encoding="utf-8")
|
|
selected = paths if paths is not None else str((work / "unit.cpp").resolve())
|
|
(work / "inputs").write_text(
|
|
f"VLS-OCCURRENCES-1\n{nonce}\n{selected}\n", encoding="utf-8")
|
|
result = compile(compiler, observer, work, (work / "unit.cpp").resolve())
|
|
check(result.returncode != 0, f"{label}: malformed manifest was accepted")
|
|
check(not (work / "report").exists(), f"{label}: report after a malformed manifest")
|
|
print("malformed manifests: ok")
|
|
|
|
|
|
def fixed_paths(compiler, observer):
|
|
"""Consume a report from the fixed runtime paths inside a sealed view."""
|
|
bwrap, store = shutil.which("bwrap"), shutil.which("nix-store")
|
|
if not bwrap or not store:
|
|
print("fixed runtime paths: skipped (bubblewrap or nix-store unavailable)")
|
|
return
|
|
frontend = Path(subprocess.check_output([compiler, "-print-prog-name=cc1plus"],
|
|
text=True).strip()).resolve(strict=True)
|
|
check(frontend.is_relative_to("/nix/store"), "expected a Nix GCC package")
|
|
roots = sorted({Path(*frontend.parts[:4]), Path(*compiler.parts[:4])})
|
|
closure = sorted({Path(p) for root in roots
|
|
for p in subprocess.check_output([store, "-qR", str(root)],
|
|
text=True).splitlines()})
|
|
check(0 < len(closure) <= 256, "unexpected compiler runtime closure")
|
|
with tempfile.TemporaryDirectory(prefix="vls-observer-fixed-") as temp:
|
|
work = Path(temp)
|
|
source = (work / "unit.cpp").resolve()
|
|
source.write_text("int f(int value) { return value; }\nint q() { return f(1); }\n",
|
|
encoding="utf-8")
|
|
nonce = secrets.token_hex(16)
|
|
inputs = (work / "inputs").resolve()
|
|
inputs.write_text(f"VLS-OCCURRENCES-1\n{nonce}\n{source}\n", encoding="utf-8")
|
|
output = work / "out"
|
|
output.mkdir()
|
|
sandbox = [bwrap, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv",
|
|
"--setenv", "LC_ALL", "C", "--dev", "/dev", "--tmpfs", "/tmp"]
|
|
for path in closure:
|
|
sandbox += ["--ro-bind", str(path), str(path)]
|
|
sandbox += ["--dir", "/vls-observer",
|
|
"--bind", str(output.resolve()), "/vls-observer",
|
|
"--ro-bind", str(observer.resolve()), "/vls-observer/occurrences.so",
|
|
"--ro-bind", str(inputs), "/vls-observer/inputs",
|
|
"--ro-bind", str(source), str(source),
|
|
"--chdir", str(work), "--"]
|
|
result = subprocess.run([*sandbox, str(compiler), "-std=c++26", "-fsyntax-only",
|
|
"-fplugin=/vls-observer/occurrences.so", str(source)],
|
|
capture_output=True, text=True, timeout=120)
|
|
check(result.returncode == 0, f"sealed compile failed: {result.stderr[-800:]}")
|
|
report = strict_json((output / "report").read_bytes())
|
|
check(report["nonce"] == nonce and report["complete"] and len(report["occurrences"]) == 1,
|
|
f"wrong sealed report: {report}")
|
|
occurrence = report["occurrences"][0]
|
|
read_span(occurrence["use"], "f", "sealed use")
|
|
read_span(occurrence["definition"], "f", "sealed definition")
|
|
print(f"fixed runtime paths: sealed report with {len(closure)} compiler runtime paths")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--observer", required=True, type=Path)
|
|
parser.add_argument("--cxx", default="g++")
|
|
options = parser.parse_args()
|
|
observer = options.observer.resolve(strict=True)
|
|
check(observer.is_file(), "observer artifact is not a file")
|
|
selected = compiler()
|
|
overload_case(selected, observer)
|
|
header_case(selected, observer)
|
|
macro_case(selected, observer)
|
|
line_directive_case(selected, observer)
|
|
qualifier_case(selected, observer)
|
|
declared_only_case(selected, observer)
|
|
template_case(selected, observer)
|
|
bom_case(selected, observer)
|
|
space_case(selected, observer)
|
|
capacity_case(selected, observer)
|
|
error_case(selected, observer)
|
|
malformed_case(selected, observer)
|
|
fixed_paths(selected, observer)
|
|
print(f"stock observer: all cases passed with {selected}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (OSError, ValueError, subprocess.SubprocessError) as exc:
|
|
raise SystemExit(f"verify-stock-observer: {exc}")
|