Implement the VLS roadmap on the native VBS build

Native VBS and CMake builds of the server and every registered suite:
protocol and document sync, VBS/compdb providers, stock GCC diagnostics
(including in-process default profile preparation), the stock occurrence
observer and hover/definition, the bounded Scheduler, C++ module graph,
scan and artifact cache with real CMI production, the context-aware
symbol index with schema-2 snapshot migration, navigation and guarded
rename, reflection provenance with splice-origin extraction, index-backed
completion and signature help, live GCC worker control with a registered
DAP suite, and the Neovim and VS Code clients.

VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced
from the versioned patches and verified stepping reflection/template code
with projected values 17/34 and 41/82.
This commit is contained in:
faumaray committed 2026-12-05 14:06:50 +03:00
1 parent ca04975d54
commit da8003f6d4
310 files changed
+47552 -480

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# C++26 frontend reference
Run the corpus from the repository with GCC 16.2 and the full VoidLibrary
source include directory. The test needs both the public Meta header and its
Detail implementation.
```sh
dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc.py \
--void-include build/bootstrap/_deps/voidlibrary-src/include
```
Each invocation creates its own module cache in a temporary directory. The
runner checks both enum helper entry points, the GCC reflection feature macro,
constexpr range expansion, a named module and a reflection splice in its
importer. It verifies the output of the compiled programs and the locations
of two deliberately malformed edits before analyzing the valid importer again.
Retain the fixture line and column positions when reformatting.
On GCC 16.2, VoidLibrary main `7d7d23e` and libstdc++ dated 20260807,
all 19 checks matched their expected results. Six cases require compiler
diagnostics. Editor queries and the candidate compiler have separate acceptance
criteria in [roadmap 08](../../../docs/roadmap/08-frontend-feasibility.md).
Probe a locally built candidate using the target triple and standard-library
include directories obtained from the reference GCC driver. The candidate uses
its own compiler resource headers.
```sh
dev cpp-gcc -c python3 tests/corpus/frontend/probe-clang.py \
--clang build/frontend-gate/llvm/bin/clang \
--void-include build/bootstrap/_deps/voidlibrary-src/include
```
The JSON report includes driver arguments and each case's exit status and
diagnostics. The process returns nonzero when a tested input fails. On candidate
`562409c7`, six of ten cases passed. The public and internal Void enum helper
checks, the reference meta library and its module importer failed.
Run the GCC tooling experiment with `dev cpp-gcc -c python3
tests/corpus/frontend/probe-gcc-tooling.py`. It checks overload and member
bindings in compiler trees, diagnostics after invalid edits, recovery, two
private module generations and nested consteval instantiation. Returned timings
measure individual compiler invocations. The projected edits use temporary
source files and preserve the saved fixture.
## Live returns on stock GCC
On x86-64 Linux, run the standalone observation with GCC 16.2.0, its matching
plugin development headers, GMP headers and a Python-enabled GDB. If GMP is in
a separate development prefix, append `--include-dir /path/to/gmp/include`.
```sh
dev cpp-gcc -c python3 tests/corpus/frontend/verify-stock-gcc-gdb.py
```
The probe compiles a small type-description object for GDB. It launches the
installed `cc1plus` on the existing `gcc-live.cpp` fixture with ordinary
compilation flags. The first run observes inner/outer returns of 17/34 and
22/44. Changing the enumerator to 41 produces 41/82 and 46/92 with the same
two assertions. Both members of each pair are read at live return stops in
the same process. This probe depends on the named evaluator remaining
observable in the selected GCC binary. Constraint decisions, splices as
individual events and full editor debugging have separate verification gates.
+25
View File
@@ -0,0 +1,25 @@
#ifdef PUBLIC_ENTRY
#include <Void/Core/Meta.hpp>
namespace api = Void::Meta;
#else
#include <Void/Detail/Enum.hpp>
namespace api = Void::Detail;
#endif
#include <cstdio>
enum class Source { Idle = 3, Ready = 17 };
enum class Target { None = 0, Ready = 41 };
int main() {
auto name = api::enum_name(Source::Ready);
auto unknown = api::enum_name(static_cast<Source>(99));
auto parsed = api::enum_parse<Source>("Ready");
auto missed = api::enum_parse<Source>("ready");
auto matched = api::enum_cast<Target>(Source::Ready);
auto fallback = api::enum_cast<Target>(Source::Idle);
std::printf("%.*s %.*s %d %d %d %d\n", int(name.size()), name.data(),
int(unknown.size()), unknown.data(), int(parsed.value_or(Source::Idle)),
int(missed.has_value()), int(matched), int(fallback));
return !(name == "Ready" && unknown == "?" && parsed == Source::Ready &&
!missed && matched == Target::Ready && fallback == Target::None);
}
@@ -0,0 +1,17 @@
struct Range {
constexpr const int* begin() const { return values; }
constexpr const int* end() const { return values + 2; }
private:
int values[2]{3, 17};
};
consteval int sum() {
static constexpr Range items{};
int total = 0;
#ifdef INIT_LIST
template for (constexpr int item : {3, 17}) { total += item; }
#else
template for (constexpr int item : items) { total += item; }
#endif
return total;
}
static_assert(sum() == 20);
+9
View File
@@ -0,0 +1,9 @@
module;
#include <meta>
export module gate;
export namespace gate {
enum class State { Idle = 3, Ready = 17 };
consteval auto ready_info() { return ^^State::Ready; }
template<auto R> consteval auto materialize() { return [:R:]; }
}
+16
View File
@@ -0,0 +1,16 @@
#include <meta>
enum class State { Idle = 3, Ready = 17 };
template <class T> concept HasReady = requires { T::Ready; };
template <HasReady T> consteval int reflected_value() {
constexpr auto ready = ^^T::Ready;
return static_cast<int>([:ready:]);
}
template <class T> consteval int twice() { return 2 * reflected_value<T>(); }
static_assert(twice<State>() == 34);
#ifdef CHECK_CONSTRAINT_DIAGNOSTIC
constexpr int bad = twice<int>();
#endif
+20
View File
@@ -0,0 +1,20 @@
enum class State { Ready = 17 };
template<class T> concept HasReady = requires { T::Ready; };
template<HasReady T> consteval int reflected_value(int bias) {
constexpr auto entity = ^^T::Ready;
return static_cast<int>([:entity:]) + bias;
}
template<class T> consteval int twice(int bias) {
return 2 * reflected_value<T>(bias);
}
// The predicates stay true for both 17 and the edited value 41. They expose
// neither the intermediate result nor its type to the trace verifier.
static_assert(twice<State>(0) > 0);
static_assert(twice<State>(5) > 0);
#ifdef VLS_CHECK_REJECTED_CONSTRAINT
constexpr auto rejected = twice<int>(0);
#endif
+12
View File
@@ -0,0 +1,12 @@
namespace shapes {
struct Point {
int x;
int y;
};
constexpr int coordinate(Point p) { return p.x; }
constexpr double coordinate(double value) { return value; }
} // namespace shapes
int read_x(shapes::Point point) {
return shapes::coordinate(point);
}
+8
View File
@@ -0,0 +1,8 @@
#include <meta>
import gate;
static_assert(gate::materialize<^^gate::State::Ready>() == gate::State::Ready);
static_assert([:gate::ready_info():] == gate::State::Ready);
static_assert(std::meta::identifier_of(gate::ready_info()) == "Ready");
int main() { return int([:gate::ready_info():]) == 17 ? 0 : 1; }
+8
View File
@@ -0,0 +1,8 @@
#include <meta>
import gate;
static_assert(gate::materialize<^^gate::State::Readi>() == gate::State::Ready);
static_assert([:gate::ready_info():] == gate::State::Ready);
static_assert(std::meta::identifier_of(gate::ready_info()) == "Ready");
int main() { return int([:gate::ready_info():]) == 17 ? 0 : 1; }
+8
View File
@@ -0,0 +1,8 @@
#include <meta>
import gate;
static_assert(gate::materialize<^^gate::State::Ready>() == gate::State::Ready);
static_assert([:gate::ready_info()] == gate::State::Ready);
static_assert(std::meta::identifier_of(gate::ready_info()) == "Ready");
int main() { return int([:gate::ready_info():]) == 17 ? 0 : 1; }
+11
View File
@@ -0,0 +1,11 @@
#include <meta>
#ifndef __GLIBCXX__
#error expected libstdc++
#elif !defined(__cpp_lib_reflection) || __cpp_lib_reflection < 202603L
#error GCC 16.2 reflection declarations are inactive
#else
enum class State { Idle = 3, Ready = 17 };
using Items = decltype(std::define_static_array(std::meta::enumerators_of(^^State)));
static_assert(std::is_same_v<Items, std::span<const std::meta::info>>);
static_assert(std::meta::identifier_of(std::meta::enumerators_of(^^State)[1]) == "Ready");
#endif
+78
View File
@@ -0,0 +1,78 @@
"""Probe a candidate Clang with the reference GCC's C++ and platform headers."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import tempfile
FIXTURES = Path(__file__).resolve().parent
def run(argv, *, source="", cwd=None, checked=True):
return subprocess.run(
argv, input=source, text=True, capture_output=True, check=checked,
timeout=60, cwd=cwd, env={**os.environ, "LC_ALL": "C"},
)
def reference_flags(clang, gcc):
triple = run([gcc, "-dumpmachine"]).stdout.strip()
search = run([gcc, "-E", "-x", "c++", "-v", "-"]).stderr
start = "#include <...> search starts here:"
paths = search.split(start, 1)[1].split("End of search list.", 1)[0].splitlines()
gcc_builtin = Path(run([gcc, "-print-file-name=include"]).stdout.strip()).resolve()
resource = Path(run([clang, "-print-resource-dir"]).stdout.strip()) / "include"
flags = [f"--target={triple}", "-nostdinc"]
for raw in paths:
if raw.strip():
path = Path(raw.strip()).resolve(strict=True)
flags.extend(["-isystem", str(resource if path == gcc_builtin else path)])
return flags
def probe(clang, gcc, void_include, work):
report = {
"clang": run([clang, "--version"]).stdout.splitlines()[0],
"gcc": run([gcc, "--version"]).stdout.splitlines()[0],
"cases": {},
}
base = [str(clang), "--driver-mode=g++", "-std=c++26", "-freflection",
"-fexpansion-statements", "-ferror-limit=4", *reference_flags(clang, gcc)]
report["driver"] = base
def check(name, args, source=""):
result = run([*base, *args], source=source, cwd=work, checked=False)
report["cases"][name] = {"exit": result.returncode, "stderr": result.stderr[:6000]}
return result.returncode == 0
check("reference cstddef", ["-fsyntax-only", "-x", "c++", "-"],
"#include <cstddef>\n#ifndef __GLIBCXX__\n#error expected libstdc++\n#endif\n")
check("language reflection and splice", ["-fsyntax-only", "-x", "c++", "-"],
"enum class E { x }; static_assert([:^^E::x:] == E::x);\n")
check("constexpr range expansion", ["-fsyntax-only", FIXTURES / "expansion-static.cpp"])
if check("plain module interface", ["--precompile", "-x", "c++-module", "-", "-o", "control.pcm"],
"export module control; export constexpr int answer = 42;\n"):
check("plain module importer", ["-fmodule-file=control=control.pcm", "-fsyntax-only", "-x", "c++", "-"],
"import control; static_assert(answer == 42);\n")
check("reference meta library", ["-fsyntax-only", FIXTURES / "library.cpp"])
for name, flags in (("Void detail enum", []), ("Void public enum", ["-DPUBLIC_ENTRY"])):
check(name, [*flags, "-I", void_include, "-fsyntax-only", FIXTURES / "enum.cpp"])
if check("Void reflection module", ["--precompile", FIXTURES / "gate.cppm", "-o", "gate.pcm"]):
check("Void module importer", ["-fmodule-file=gate=gate.pcm", "-fsyntax-only", FIXTURES / "importer.cpp"])
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--clang", type=Path, required=True)
parser.add_argument("--gcc", default="g++")
parser.add_argument("--void-include", type=Path, required=True)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="vls-clang-corpus-") as scratch:
result = probe(args.clang.resolve(strict=True), args.gcc,
args.void_include.resolve(strict=True), Path(scratch))
print(json.dumps(result, indent=2))
raise SystemExit(int(any(record["exit"] for record in result["cases"].values())))
+156
View File
@@ -0,0 +1,156 @@
"""Exercise GCC 16's observable query, recovery, module and metaprogram data."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import time
FIXTURES = Path(__file__).resolve().parent
def run(argv, work, expected=0):
start = time.monotonic()
result = subprocess.run(argv, cwd=work, env={**os.environ, "LC_ALL": "C"},
capture_output=True, text=True, timeout=60)
if result.returncode != expected:
raise RuntimeError(f"{argv}: expected {expected}, got {result.returncode}\n{result.stderr}")
return result, round((time.monotonic() - start) * 1000, 2)
def require(value, reason):
if not value:
raise ValueError(reason)
def fixture_tree(path):
# This fixture has a single invocation and a single field access. Its node
# numbers and declaration ordering may change independently of its bindings.
nodes = {}
for match in re.finditer(r"^@(\d+)\s+(\w+)\s+(.*?)(?=^@\d+|\Z)",
path.read_text(), re.MULTILINE | re.DOTALL):
nodes[match[1]] = (match[2], match[3])
return nodes
def edge(nodes, node, key, expected_kind=None):
target = re.search(r"(?<!\w)" + re.escape(key) + r"\s*:\s*@(\d+)", node[1])
require(target, f"missing {key} on {node[0]}")
result = nodes[target[1]]
require(expected_kind is None or result[0] == expected_kind, f"{key} leads to {result[0]}")
return result
def unique_node(nodes, kind):
found = [node for node in nodes.values() if node[0] == kind]
require(len(found) == 1, f"fixture has {len(found)} {kind} nodes")
return found[0]
def spelling(nodes, declaration):
identifier = edge(nodes, declaration, "name", "identifier_node")
return re.search(r"strg:\s*(\S+)", identifier[1])[1]
def declaration_line(node):
return int(re.search(r"srcp:\s*query\.cpp:(\d+)", node[1])[1])
def check_query(flags, work, source, name, target_line, result_type):
(work / "query.cpp").write_text(source)
dump = work / "query.raw"
_, elapsed = run([*flags, f"-fdump-lang-raw={dump}", "-fsyntax-only", "query.cpp"], work)
nodes = fixture_tree(dump)
call = unique_node(nodes, "call_expr")
declaration = edge(nodes, edge(nodes, call, "fn", "addr_expr"), "op 0", "function_decl")
actual_type = spelling(nodes, edge(nodes, edge(nodes, call, "type"), "name", "type_decl"))
require((spelling(nodes, declaration), declaration_line(declaration), actual_type) ==
("coordinate", target_line, result_type), "overload binding or type mismatch")
field = edge(nodes, unique_node(nodes, "component_ref"), "op 1", "field_decl")
require((spelling(nodes, field), declaration_line(field)) == ("x", 3), "field resolution")
return {"case": name, "definition_line": target_line, "type": actual_type,
"field_definition_line": 3, "compile_ms": elapsed}
def diagnostic(stderr, source_name, line, needle):
report = json.loads(stderr)
require(report["version"] == "2.1.0", "unexpected SARIF version")
for entry in report["runs"][0]["results"]:
if entry["level"] != "error" or needle not in entry["message"]["text"]:
continue
for location in entry["locations"]:
physical = location["physicalLocation"]
region = physical["region"]
if Path(physical["artifactLocation"]["uri"]).name == source_name and region["startLine"] == line:
require(region["startColumn"] >= 1, "missing source column")
return {"message": entry["message"]["text"], "region": region,
"related_locations": len(entry.get("relatedLocations", []))}
raise ValueError(f"missing {source_name}:{line} diagnostic containing {needle}")
def check_modules(flags, work, value):
# A content generation gets an isolated GCC module cache. Compile an
# importer against the new interface and a control expecting the old value.
work.mkdir()
provider = (FIXTURES / "gate.cppm").read_text()
require(provider.count("Ready = 17") == 1, "expected one serialized enum value")
(work / "gate.cppm").write_text(provider.replace("Ready = 17", f"Ready = {value}"))
importer = (FIXTURES / "importer.cpp").read_text()
importer += f"\nstatic_assert(int([:gate::ready_info():]) == {value});\n"
(work / "importer.cpp").write_text(importer)
_, compile_ms = run([*flags, "-fmodules", "-x", "c++", "-c", "gate.cppm", "-o", "gate.o"], work)
_, import_ms = run([*flags, "-fmodules", "-fsyntax-only", "importer.cpp"], work)
other = 41 if value == 17 else 17
(work / "control.cpp").write_text(importer + f"static_assert(int([:gate::ready_info():]) == {other});\n")
failed, _ = run([*flags, "-fmodules", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr",
"control.cpp"], work, expected=1)
diagnostic(failed.stderr, "control.cpp", len((work / "control.cpp").read_text().splitlines()),
"static assertion failed")
return {"case": f"private module generation {value}", "imported_value": value,
"interface_ms": compile_ms, "import_ms": import_ms}
def probe(compiler, work):
version, _ = run([compiler, "-dumpfullversion"], work)
require(version.stdout.startswith("16."), f"expected GCC 16, got {version.stdout}")
flags = [compiler, "-std=c++26", "-freflection"]
saved = (FIXTURES / "gcc-queries.cpp").read_text()
projected = saved.replace("shapes::Point point)", "shapes::Point point, double weight)").replace(
"coordinate(point)", "coordinate(weight)")
cases = [check_query(flags, work, saved, "saved overload", 6, "int"),
check_query(flags, work, projected, "projected edit", 7, "double")]
(work / "query.cpp").write_text(projected.replace("coordinate(weight)", "missing(weight)"))
failed, _ = run([*flags, "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", "query.cpp"],
work, expected=1)
cases.append({"case": "malformed edit", **diagnostic(failed.stderr, "query.cpp", 11, "missing")})
cases.append(check_query(flags, work, saved, "recovered overload", 6, "int"))
for value in (17, 41):
cases.append(check_modules(flags, work / f"module-{value}", value))
source = FIXTURES / "gcc-evaluation.cpp"
trace = work / "template.txt"
run([*flags, f"-fdump-lang-tinst={trace}", "-fsyntax-only", source], work)
lines = trace.read_text().splitlines()
outer = next(i for i, line in enumerate(lines) if re.match(r"I consteval int twice\(\).*State", line))
require(any(re.match(r" I consteval int reflected_value\(\).*State", line)
for line in lines[outer + 1:]), "missing nested consteval instantiation")
cases.append({"case": "template instantiation dump", "outer": "twice<State>",
"inner": "reflected_value<State>"})
failed, _ = run([*flags, "-DCHECK_CONSTRAINT_DIAGNOSTIC", "-fconcepts-diagnostics-depth=3",
"-fsyntax-only", "-fdiagnostics-format=sarif-stderr", source], work, expected=1)
constraint = diagnostic(failed.stderr, source.name, 11, "reflected_value<int>")
require(constraint["related_locations"] > 0, "constraint failure has no related source locations")
cases.append({"case": "constraint rejection", **constraint})
require((FIXTURES / "gcc-queries.cpp").read_text() == saved, "saved input changed")
return {"gcc": version.stdout.strip(), "cases": cases}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="vls-gcc-tooling-") as temp:
print(json.dumps(probe(args.cxx, Path(temp)), indent=2))
+10
View File
@@ -0,0 +1,10 @@
#include <meta>
enum class State { Idle = 3, Ready = 17 };
consteval int sum() {
static constexpr auto items = std::define_static_array(std::meta::enumerators_of(^^State));
int total = 0;
template for (constexpr auto item : items) { total += int([:item:]); }
return total;
}
static_assert(sum() == 20);
+10
View File
@@ -0,0 +1,10 @@
#include <meta>
enum class State { Idle = 3, Ready = 17 };
consteval int sum() {
constexpr auto items = std::define_static_array(std::meta::enumerators_of(^^State));
int total = 0;
template for (constexpr auto item : items) { total += int([:item:]); }
return total;
}
static_assert(sum() == 20);
+550
View File
@@ -0,0 +1,550 @@
#!/usr/bin/env python3
"""Exercise the private GCC evaluator on the real gcc-live.cpp translation unit."""
import argparse
from contextlib import ExitStack
import json
import os
from pathlib import Path
import re
import secrets
import select
import selectors
import signal
import subprocess
import sys
import tempfile
import time
BACKEND = "gcc-16.2.0/vls-eval-1"
KINDS = {"hello", "enter", "body", "cached", "value", "stopped", "resumed",
"leave", "terminal", "frontendEnd"}
TRACE_LIMIT = 1024 * 1024
FRAME_LIMIT = 64 * 1024
DEADLINE = 10
# Relocate both inherited endpoints before touching 3 or 4. exec preserves the
# PID; raw stdin/stdout and diagnostics are independent of the two probe pipes.
LAUNCH = """
import fcntl, os, sys
original = [int(fd) for fd in sys.argv[1:3]]
high = [fcntl.fcntl(fd, fcntl.F_DUPFD_CLOEXEC, 5) for fd in original]
for fd, target in zip(high, (3, 4)):
os.dup2(fd, target, inheritable=True)
for fd in original:
if fd > 4:
os.close(fd)
os.execv(sys.argv[3], sys.argv[3:])
"""
def check(condition, message):
if not condition:
raise AssertionError(message)
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_number(value):
raise ValueError(f"non-JSON number {value}")
def integer(value):
check(set(value) == {"kind", "precision", "signed", "bitsHex"},
f"malformed integer {value}")
width, signed, bits = value["precision"], value["signed"], value["bitsHex"]
check(type(width) is int and 1 <= width <= 64 and type(signed) is bool,
f"invalid integer type {value}")
check(isinstance(bits, str) and len(bits) == (width + 3) // 4
and re.fullmatch("[0-9a-f]+", bits), f"invalid integer encoding {value}")
raw = int(bits, 16)
check(raw < 1 << width, f"excess bits {value}")
return raw - (1 << width) if signed and raw & (1 << (width - 1)) else raw
class Invocation:
"""Own and reap one private cc1plus process, with bounded multiplexed reads."""
def __init__(self, binary, source, flags, nonce=None, invalid_pipe=False):
self.nonce = nonce if nonce is not None else secrets.token_hex(16)
self.events = []
self.pending = bytearray()
self.trace_bytes = 0
self.outputs = {"stdout": bytearray(), "stderr": bytearray()}
self.mux = selectors.DefaultSelector()
self.deadline = time.monotonic() + DEADLINE
self.control = None
self.process = None
self.owned = ExitStack()
self.owned.callback(self.mux.close)
try:
with ExitStack() as child:
control_read, self.control = os.pipe()
child.callback(os.close, control_read)
self.owned.callback(self.close_control)
event_read, event_write = os.pipe()
self.owned.callback(os.close, event_read)
child.callback(os.close, event_write)
if invalid_pipe:
event_write = os.open(os.devnull, os.O_WRONLY)
child.callback(os.close, event_write)
args = [sys.executable, "-I", "-c", LAUNCH, str(control_read),
str(event_write), str(binary), "-quiet", "-std=c++26",
"-freflection", "-fsyntax-only", "-nostdinc", *flags,
source.name, "-o", os.devnull]
self.process = subprocess.Popen(
args, cwd=source.parent,
env={"LC_ALL": "C", "VLS_GCC_NONCE": self.nonce},
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
pass_fds=(control_read, event_write), start_new_session=True)
self.owned.callback(self.process.stdout.close)
self.owned.callback(self.process.stderr.close)
os.set_blocking(self.control, False)
for stream, channel in ((event_read, "trace"), (self.process.stdout, "stdout"),
(self.process.stderr, "stderr")):
self.mux.register(stream, selectors.EVENT_READ, channel)
except BaseException:
self.close()
raise
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def close_control(self):
if self.control is not None:
os.close(self.control)
self.control = None
def close(self):
try:
if self.process is not None and self.process.poll() is None:
try:
os.killpg(self.process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
self.process.wait(timeout=2)
finally:
self.owned.close()
def remaining(self):
seconds = self.deadline - time.monotonic()
check(seconds > 0, f"cc1plus timeout after {len(self.events)} events")
return seconds
def trace(self, data):
self.trace_bytes += len(data)
check(self.trace_bytes <= TRACE_LIMIT, "trace too large")
self.pending.extend(data)
while (end := self.pending.find(b"\n")) >= 0:
check(end + 1 <= FRAME_LIMIT, "frame too large")
event = json.loads(bytes(self.pending[:end]).decode("utf-8", errors="strict"),
object_pairs_hook=unique_keys, parse_constant=reject_number)
del self.pending[:end + 1]
index = len(self.events)
check(isinstance(event, dict) and type(event.get("v")) is int and event["v"] == 1
and event.get("nonce") == self.nonce and type(event.get("seq")) is int
and event["seq"] == index and index < 4096 and event.get("kind") in KINDS,
f"invalid envelope at {index}: {event}")
if index == 0:
check(event["kind"] == "hello" and event.get("backend") == BACKEND
and event.get("pid") == self.process.pid and set(event["kinds"]) == KINDS
and {"integralReturn", "cooperativeStep"} <= set(event["capabilities"]),
f"unexpected handshake {event}")
self.events.append(event)
check(len(self.pending) < FRAME_LIMIT, "oversized unfinished frame")
def pump(self, timeout):
for key, _ in self.mux.select(timeout=min(timeout, self.remaining())):
data = os.read(key.fd, 16384)
if not data:
self.mux.unregister(key.fileobj)
continue
if key.data == "trace":
self.trace(data)
else:
output = self.outputs[key.data]
output.extend(data)
check(len(output) <= 256 * 1024, f"{key.data} exceeded its byte limit")
def next_stop(self, after=-1):
while True:
for event in self.events[after + 1:]:
if event["kind"] == "stopped":
return event
check(self.mux.get_map(), f"missing stopped event: {self.outputs['stderr'][:500]!r}")
self.pump(self.remaining())
def held(self, stop):
end = time.monotonic() + 0.1
while time.monotonic() < end:
self.pump(max(0, end - time.monotonic()))
check(self.process.poll() is None and os.getpgid(self.process.pid) == self.process.pid,
"compiler left the held stop")
check(self.events[-1] == stop and not self.pending, "compiler emitted data past the stop")
def send(self, data):
while data:
_, writable, _ = select.select([], [self.control], [], self.remaining())
check(writable, "timeout sending control")
try:
size = os.write(self.control, data)
except BlockingIOError:
continue
check(size > 0, "short control write")
data = data[size:]
def command(self, stop, action):
return f"{self.nonce} {stop['seq']} {action}\n".encode("ascii")
def wait(self, code):
while self.mux.get_map():
self.pump(self.remaining())
result = self.process.wait(timeout=self.remaining())
check(not self.pending, "truncated last record")
check(not self.outputs["stdout"], f"unexpected stdout {self.outputs['stdout'][:200]!r}")
check(result == code, f"exit {result}, expected {code}: {self.outputs['stderr'][:500]!r}")
return bytes(self.outputs["stderr"])
def frames(events, terminal="frontendEnd"):
"""Check the full call/stop grammar and index each observed frame's evidence."""
check(events and events[0]["kind"] == "hello" and events[-1]["kind"] == terminal,
f"missing handshake or expected {terminal}")
calls, stack = {}, []
stopped = None
for i, event in enumerate(events[1:], 1):
kind = event["kind"]
if stopped is not None:
check(kind in ("resumed", "terminal") and event.get("stop") == stopped["seq"],
"unacknowledged stop")
if kind in ("terminal", "frontendEnd"):
check(i == len(events) - 1, "records after termination")
if kind == "frontendEnd":
check(not stack and stopped is None, "unfinished calls at frontendEnd")
continue
frame = event.get("frame")
parent = event.get("parent")
check(type(frame) is int and frame > 0 and "parent" in event
and (parent is None or type(parent) is int), f"invalid call identity {event}")
if kind == "enter":
check(frame not in calls and parent == (stack[-1] if stack else None),
"wrong call parent or reused frame")
stack.append(frame)
calls[frame] = {"enter": event}
continue
check(stack and frame == stack[-1] and calls[frame]["enter"]["parent"] == parent,
"event for inactive frame")
call = calls[frame]
check(kind not in call, f"duplicate {kind} in frame {frame}")
call[kind] = event
if kind == "body":
check("cached" not in call, "body for cache hit")
elif kind == "cached":
check("body" not in call and "value" not in call, "cache hit with observed body")
elif kind == "value":
check("body" in call, "value outside body")
value = event["value"]
if value["kind"] == "integer":
integer(value)
else:
check(value == {"kind": "unavailable", "reason": "unsupportedScalar"},
f"invalid unavailable value {value}")
elif kind == "stopped":
prev = events[i - 1]
check(prev["kind"] == "value" and prev["frame"] == frame
and prev["value"]["kind"] == "integer", "stop without an actual integer")
stopped = event
elif kind == "resumed":
check(stopped is not None and event["action"] in ("step", "continue"),
"unmatched resume")
stopped = None
elif kind == "leave":
check(event["outcome"] in {"returned", "failed", "overflow", "throw", "jump",
"void", "constructor"}, f"unexpected outcome {event}")
stack.pop()
else:
raise AssertionError(f"unexpected {kind}")
return calls
def witness(calls, ready):
pairs = []
for frame, outer in calls.items():
if outer["enter"]["name"] != "twice" or "value" not in outer:
continue
children = [c for c in calls.values() if c["enter"]["parent"] == frame
and c["enter"]["name"] == "reflected_value" and "value" in c]
check(len(children) == 1, f"expected inner reflected_value for frame {frame}")
inner = children[0]
check(outer["body"]["seq"] < inner["enter"]["seq"] < inner["body"]["seq"]
< inner["value"]["seq"] < inner["leave"]["seq"] < outer["value"]["seq"]
< outer["leave"]["seq"], "observed values outside their dynamic bodies")
for call in (inner, outer):
check(call["leave"]["outcome"] == "returned", "return failed after capture")
check(call["value"]["value"]["signed"] and call["value"]["value"]["precision"] == 32,
"fixture did not return int")
pairs.append((integer(inner["value"]["value"]), integer(outer["value"]["value"])))
expected = [(ready, 2 * ready), (ready + 5, 2 * (ready + 5))]
check(pairs == expected, f"observed {pairs}, expected {expected}")
return pairs
OBSERVE = ["-fvls-observe"]
STEP = [*OBSERVE, "-fvls-step"]
def completed(binary, source, flags, code=0, **kwargs):
with Invocation(binary, source, flags, **kwargs) as run:
diagnostics = run.wait(code)
return run.events, diagnostics
def values_and_parity(binary, source, original):
for ready in (17, 41):
edited = original.replace("Ready = 17", f"Ready = {ready}")
check(edited.count(">(0) > 0") == 1 and edited.count(">(5) > 0") == 1,
"fixture predicates changed")
source.write_text(edited, encoding="utf-8")
disabled, reference = completed(binary, source, [])
observed, diagnostics = completed(binary, source, OBSERVE)
check(not disabled and reference == diagnostics == b"", "disabled/on parity failed")
calls = frames(observed)
pairs = witness(calls, ready)
for call in calls.values():
enter = call["enter"]
if enter["name"] in ("reflected_value", "twice"):
check(enter.get("sourceKind") == "logicalDeclaration"
and enter["source"] == source.name and enter["byteColumn"] > 0
and enter["line"] in (5, 10), f"unexpected declaration location {enter}")
print(f"Ready={ready} real integral returns at bias 0 and 5: {pairs}")
def control_cases(binary, source):
with Invocation(binary, source, STEP) as run:
inner = run.next_stop()
frames_seen = {e["frame"]: e for e in run.events if e["kind"] == "enter"}
value = run.events[inner["seq"] - 1]
check(frames_seen[inner["frame"]]["name"] == "reflected_value"
and frames_seen[inner["parent"]]["name"] == "twice"
and value["frame"] == inner["frame"] and integer(value["value"]) == 17,
"first stop outside the real inner return")
run.held(inner)
# Same shape but guaranteed different nonce; old and future sequences,
# an unrecognized action, and a NUL suffix must also leave the child held.
other = ("0" if run.nonce[0] != "0" else "1") + run.nonce[1:]
run.send(f"{other} {inner['seq']} step\n".encode())
run.send(run.command({"seq": inner["seq"] - 1}, "continue"))
run.send(run.command({"seq": inner["seq"] + 1}, "cancel"))
run.send(run.command(inner, "step\0garbage"))
run.held(inner)
command = run.command(inner, "step")
run.send(command[:-1])
run.held(inner)
run.send(command[-1:])
outer = run.next_stop(after=inner["seq"])
check(outer["frame"] == inner["parent"]
and integer(run.events[outer["seq"] - 1]["value"]) == 34,
"step did not reach the outer return")
run.send(run.command(inner, "continue"))
run.held(outer)
run.send(run.command(outer, "continue"))
check(not run.wait(0), "unexpected step diagnostics")
witness(frames(run.events), 17)
acks = [(e["stop"], e["action"]) for e in run.events if e["kind"] == "resumed"]
check(acks == [(inner["seq"], "step"), (outer["seq"], "continue")],
f"wrong control acknowledgements {acks}")
print(f"PID {run.process.pid} held at inner 17, stepped to outer 34, continued and reaped")
for action, reason, code in (("cancel", "cancelled", 125), ("EOF", "controlEOF", 126),
("oversize", "controlLimit", 126)):
with Invocation(binary, source, STEP) as run:
stop = run.next_stop()
check(integer(run.events[stop["seq"] - 1]["value"]) == 17, "wrong initial stop")
run.held(stop)
if action == "EOF":
run.close_control()
elif action == "oversize":
run.send(b"x" * 4097)
else:
run.send(run.command(stop, action))
run.wait(code)
calls = frames(run.events, "terminal")
check(run.events[-1]["reason"] == reason and "value" not in calls[stop["parent"]],
"control loss or cancellation allowed outer evaluation")
print(f"{action} at inner stop: {reason}, exit {code}, reaped PID {run.process.pid}")
SCALARS = """
consteval signed char narrow(int n) { return static_cast<signed char>(-n); }
consteval unsigned long long high(unsigned n) { return (1ULL << 63) + n; }
consteval long long negative(long long n) { return -n; }
consteval bool flag(int n) { return n != 0; }
consteval __int128 wide(int n) { return static_cast<__int128>(n) << 64; }
consteval double floating(int n) { return static_cast<double>(n); }
consteval int reuse(int n) { return n + 1; }
consteval int repeat(int n) { return reuse(n) + reuse(n); }
static_assert(narrow(3) < 0 && high(5) > 0 && flag(7));
static_assert(negative(23) < 0 && wide(7) > 0 && floating(3) > 0);
static_assert(repeat(11) > 0);
"""
FAILURES = """
consteval int may_throw(int n) {
if (n) throw n;
return n;
}
consteval int recover(int n) {
try { return may_throw(n); } catch (int caught) { return caught * 2; }
}
static_assert(recover(7) > 0);
struct Piece { int x; constexpr Piece(int n): x(n) {} };
constexpr void bump(Piece& p) { ++p.x; }
consteval int worked(int n) { Piece p(n); bump(p); return p.x; }
static_assert(worked(18) > 0);
"""
BAD_CLEANUP = """
struct Gone { int x; };
consteval int provisional(Gone g, Gone*& p) { p = &g; g.~Gone(); return 9; }
consteval int caller(int n) { Gone* p; return provisional(Gone{n}, p); }
static_assert(caller(5) > 0);
"""
OVERFLOW = """
consteval int over(int n) { return n + 1; }
static_assert(over(__INT_MAX__) > 0);
"""
LIMIT = """
consteval int one(int n) { return n + 1; }
consteval int many(int count) {
int sum = 0;
for (int i = 0; i < count; ++i) sum += one(i);
return sum;
}
static_assert(many(1600) > 0);
"""
def scalar_cases(binary, source, original):
source.write_text(original + SCALARS + FAILURES, encoding="utf-8")
events, diagnostics = completed(binary, source, OBSERVE)
check(not diagnostics, f"unexpected scalar diagnostics {diagnostics[:400]!r}")
calls = frames(events)
by_name = {}
for call in calls.values():
by_name.setdefault(call["enter"]["name"], []).append(call)
def snapshot(name):
values = [c["value"]["value"] for c in by_name[name] if "value" in c
and c["leave"]["outcome"] == "returned"]
check(len(values) == 1, f"expected one scalar result for {name}, got {values}")
return values[0]
for name, width, signed, bits in (
("narrow", 8, True, "fd"), ("high", 64, False, "8000000000000005"),
("negative", 64, True, "ffffffffffffffe9"), ("flag", 1, False, "1")):
value = snapshot(name)
check((value["precision"], value["signed"], value["bitsHex"]) == (width, signed, bits),
f"{name}: wrong bits or type {value}")
for name in ("wide", "floating"):
check(snapshot(name)["kind"] == "unavailable", f"{name}: unsupported scalar reported")
hits = [c for c in by_name["reuse"] if "cached" in c]
check(hits and all("body" not in c and "value" not in c for c in hits),
"reused evaluator result had no distinct cache-hit witness")
check(all(not any(x["enter"]["parent"] == hit["enter"]["frame"] for x in calls.values())
for hit in hits), "cache hit fabricated children")
thrown = [c for c in by_name["may_throw"] if c["leave"]["outcome"] == "throw"]
check(thrown and all("value" not in c for c in thrown), "throw reported a normal return")
check(integer(snapshot("recover")) == 14, "caught exception lost its caller's return")
constructors = [c for c in calls.values() if c["leave"]["outcome"] == "constructor"]
check(constructors and all("value" not in c for c in constructors)
and all(c["leave"]["outcome"] == "void" and "value" not in c for c in by_name["bump"])
and integer(snapshot("worked")) == 19, "misclassified void or constructor")
print("Verified integer widths and bits, unsupported scalars, cache, throw, void and constructor")
def failure_parity(binary, source, original):
source.write_text(original, encoding="utf-8")
reject = ["-DVLS_CHECK_REJECTED_CONSTRAINT"]
disabled, reference = completed(binary, source, reject, 1)
events, diagnostics = completed(binary, source, [*OBSERVE, *reject], 1)
check(not disabled and reference == diagnostics and b"constraints not satisfied" in diagnostics,
"constraint diagnostic changed in the observed compiler")
frames(events)
for tail, name, outcome in ((BAD_CLEANUP, "provisional", "failed"),
(OVERFLOW, "over", "overflow")):
source.write_text(original + tail, encoding="utf-8")
disabled, reference = completed(binary, source, [], 1)
events, diagnostics = completed(binary, source, OBSERVE, 1)
check(not disabled and reference and reference == diagnostics, f"{name} diagnostic changed")
attempts = [c for c in frames(events).values() if c["enter"]["name"] == name]
check(attempts and all(c["leave"]["outcome"] == outcome for c in attempts),
f"{name} lost its final outcome")
if name == "provisional":
check(all(integer(c["value"]["value"]) == 9 for c in attempts)
and b"outside its lifetime" in reference, "missing provisional pre-cleanup value")
else:
check(all("value" not in c for c in attempts), "fabricated integer on overflow")
source.write_text(original, encoding="utf-8")
for flags, nonce, invalid_pipe in ((OBSERVE, "a" * 31, False),
(OBSERVE, "A" * 32, False),
(OBSERVE, None, True),
(["-fvls-step"], None, False)):
events, diagnostics = completed(binary, source, flags, 1,
nonce=nonce, invalid_pipe=invalid_pipe)
check(not events and b"invalid private evaluator observer setup" in diagnostics,
"invalid setup did not fail before emitting events")
print("Matched constraint, cleanup and overflow diagnostics; provisional 9 left as failed")
print("Four invalid observer setups rejected before handshake")
def wire_limits(binary, directory, original):
for name, expected in (('quote"slash\\.cpp', 'quote"slash\\.cpp'), ("ctrl\x1f.cpp", None),
(os.fsdecode(b"byte\xff.cpp"), None)):
source = directory / name
source.write_text(original, encoding="utf-8")
events, diagnostics = completed(binary, source, OBSERVE)
check(not diagnostics, "unexpected diagnostics for source name")
calls = frames(events)
witness(calls, 17)
check(all("source" in c["enter"] and c["enter"]["source"] == expected
for c in calls.values()), "unescaped or incorrectly reconstructed source name")
source = directory / "many.cpp"
source.write_text(original + LIMIT, encoding="utf-8")
events, _ = completed(binary, source, OBSERVE, 126)
frames(events, "terminal")
check(len(events) == 4096 and events[-1]["reason"] == "truncated", "invalid quota result")
print(f"Strict JSON survived special source names; event quota closed at {len(events)} records")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc1plus", type=Path, required=True, help="absolute private cc1plus path")
binary = parser.parse_args().cc1plus
check(binary.is_absolute() and binary.is_file() and os.access(binary, os.X_OK),
"supply the absolute path to the patched private cc1plus")
original = Path(__file__).with_name("gcc-live.cpp").read_text(encoding="utf-8")
check(original.count("Ready = 17") == 1, "fixture no longer has its controlled edit")
with tempfile.TemporaryDirectory(prefix="vls-gcc-events-") as work:
directory = Path(work)
source = directory / "live.cpp"
values_and_parity(binary, source, original)
source.write_text(original, encoding="utf-8")
control_cases(binary, source)
scalar_cases(binary, source, original)
failure_parity(binary, source, original)
wire_limits(binary, directory, original)
print(f"{BACKEND} direct evaluator checks passed")
if __name__ == "__main__":
main()
+292
View File
@@ -0,0 +1,292 @@
#!/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"(?<![a-zA-Z_0-9])" + re.escape(spelling.encode("ascii")) + rb"(?![a-zA-Z_0-9])"
matches = list(re.finditer(pattern, raw))
check(0 <= ordinal < len(matches), f"fixture lacks {spelling} at line {line}")
match = matches[ordinal]
return (line, match.start() + 1, match.end() + 1)
def read_span(value, result, name):
check(isinstance(value, dict) and set(value) == {"line", "startByte", "endByte"}
and all(type(x) is int for x in value.values()), f"invalid byte span {value!r}")
line, start, end = (value[k] for k in ("line", "startByte", "endByte"))
lines = result.source.splitlines()
check(1 <= line <= len(lines), f"line outside primary file: {value}")
raw = lines[line - 1]
check(1 <= start < end <= len(raw) + 1 and raw[start - 1:end - 1] == name.encode("ascii"),
f"{name} does not occupy emitted span {value}: {raw!r}")
# Both byte endpoints must also be UTF-8 scalar boundaries.
raw[:start - 1].decode("utf-8")
raw[:end - 1].decode("utf-8")
return (line, start, end)
def inspect(result, reason=None):
events = result.events
check(len(events) >= 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))
+72
View File
@@ -0,0 +1,72 @@
"""Run the Void C++26 reference cases with GCC in a private module cache."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
FIXTURES = Path(__file__).resolve().parent
def check_case(name, argv, work, *, diagnostic=None, stdout=None):
result = subprocess.run(
argv, cwd=work, env={**os.environ, "LC_ALL": "C"}, timeout=45,
capture_output=True, text=True, errors="replace",
)
if diagnostic is None:
matched = result.returncode == 0
else:
matched = result.returncode == 1 and diagnostic in result.stderr
if not matched or (stdout is not None and result.stdout.strip() != stdout):
raise SystemExit(
f"{name}: exit {result.returncode}\n{result.stdout}\n{result.stderr}"
)
print(f"{name}: exit {result.returncode}")
def verify(compiler, include, work):
flags = [compiler, "-std=c++26", "-freflection", "-fdiagnostics-color=never"]
syntax = ["-fsyntax-only"]
for public in (False, True):
name = "public" if public else "detail"
defines = ["-DPUBLIC_ENTRY"] if public else []
program = work / f"enum-{name}"
check_case(f"compile {name} enum helper",
[*flags, *defines, "-I", include, FIXTURES / "enum.cpp", "-o", program], work)
check_case(f"run {name} enum helper", [program], work, stdout="Ready ? 17 0 41 0")
check_case("GCC reflection library", [*flags, *syntax, FIXTURES / "library.cpp"], work)
check_case("library without reflection",
[compiler, "-std=c++26", "-fno-reflection", *syntax, FIXTURES / "library.cpp"],
work, diagnostic="GCC 16.2 reflection declarations are inactive")
check_case("constexpr span with static storage", [*flags, *syntax, FIXTURES / "range-static.cpp"], work)
check_case("constexpr span with automatic storage", [*flags, *syntax, FIXTURES / "range.cpp"],
work, diagnostic="constant expression")
for defines in ([], ["-DINIT_LIST"]):
check_case("constexpr range expansion", [*flags, *defines, *syntax, FIXTURES / "expansion-static.cpp"], work)
provider = ["-x", "c++", "-c", FIXTURES / "gate.cppm", "-o", "gate.o"]
importer = ["-c", FIXTURES / "importer.cpp", "-o", "importer.o"]
modules = [*flags, "-fmodules"]
check_case("import before module is built", [*modules, *importer], work, diagnostic="gate")
check_case("provider without module flag", [*flags, *provider], work, diagnostic="-fmodules")
check_case("module interface", [*modules, *provider], work)
check_case("module importer", [*modules, *importer], work)
check_case("link module program", [compiler, "gate.o", "importer.o", "-o", "module"], work)
check_case("run imported reflection", [work / "module"], work)
for source, location in (("invalid-name.cpp", ":4:48:"), ("invalid-splice.cpp", ":5:35:")):
check_case(f"diagnose {source}", [*modules, *syntax, FIXTURES / source], work,
diagnostic=source + location)
check_case("valid importer after invalid edit", [*modules, *syntax, FIXTURES / "importer.cpp"], work)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++", help="GCC 16+ C++ compiler")
parser.add_argument("--void-include", type=Path, required=True, help="tested VoidLibrary include directory")
args = parser.parse_args()
include = args.void_include.resolve(strict=True)
with tempfile.TemporaryDirectory(prefix="vls-gcc-corpus-") as scratch:
verify(args.cxx, include, Path(scratch))
@@ -0,0 +1,300 @@
"""Exercise the VLS diagnostic adapter with an unmodified GCC and a real native Void TU."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[3]
TU = ROOT / "src/Documents/DocumentSnapshot.cpp"
LIB_INCLUDE = ROOT / "build/voidlibrary/current/include"
MAX_REPORT = 4 * 1024 * 1024
def check(condition, detail):
if not condition:
raise ValueError(detail)
def checked_command(fixture, compiler, database=None):
command = [fixture, "--command", ROOT, TU, compiler]
if database:
command.append(database)
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
check(result.returncode == 0 and not result.stderr,
f"could not acquire a checked editor compiler context: {result.stderr}")
row = json.loads(result.stdout)
with open(compiler, "rb") as binary:
digest = hashlib.file_digest(binary, "sha256").hexdigest()
check(row["provider"] == ("compdb" if database else "vbs") and Path(row["directory"]).is_absolute()
and row["file"] == str(TU) and row["driverSha256"] == digest, "wrong compiler lease")
return row
def native_flags(fixture, compiler, expected):
selected = checked_command(fixture, compiler)
path = Path(selected["database"])
check(expected is None or path == expected, "the selected native VBS generation changed")
check(path.stat().st_size <= 16 * 1024 * 1024, "oversized compilation database")
rows = json.loads(path.read_bytes())
matches = [r for r in rows if r.get("file") == str(TU)]
check(len(matches) == 1, "the native fixture requires one command for DocumentSnapshot.cpp")
row = matches[0]
args = row["arguments"]
check(Path(args[0]).samefile(compiler) and row["directory"] == selected["directory"] == str(ROOT),
"the native fixture and selected stock compiler must agree")
check(args[-4:] == ["-c", str(TU), "-o", row["output"]], "unexpected native output operands")
check(selected["arguments"] == args[:-2], "C++ lease and native semantic argument order disagree")
flags = selected["arguments"][1:-2]
roots = {str(ROOT / "include"), str(LIB_INCLUDE.resolve(strict=True))}
accepted = {"-std=c++26", "-freflection", "-DVOID_CRYPTO_HAS_OPENSSL=0", "-g", "-O0", "-O2",
"-O3", "-DNDEBUG"}
i = 0
while i < len(flags):
if flags[i] == "-I":
check(i + 1 < len(flags) and flags[i + 1] in roots, "unexpected fixture include root")
i += 2
else:
check(flags[i] in accepted, f"unexpected native fixture argument {flags[i]!r}")
i += 1
check(roots.issubset(flags) and {"-std=c++26", "-freflection"}.issubset(flags),
"incomplete native C++26 fixture command")
return flags
def capture_report(argv, cwd, status):
with tempfile.TemporaryFile() as report, tempfile.TemporaryFile() as output:
proc = subprocess.run(argv, cwd=cwd, env={**os.environ, "LC_ALL": "C"},
stdin=subprocess.DEVNULL, stdout=output, stderr=report, timeout=45)
size = report.tell()
check(0 < size <= MAX_REPORT and output.tell() == 0, "incomplete GCC diagnostic output")
report.seek(0)
wire = report.read()
check(proc.returncode == status, f"GCC exit {proc.returncode}, expected {status}: {wire[:400]!r}")
return wire
def compile_report(compiler, flags, source, status):
return capture_report([compiler, *flags, "-fsyntax-only", "-fdiagnostics-format=sarif-stderr",
source.name], source.parent, status)
def observe(fixture, compiler, flags, source, text, status, witness=()):
source.write_text(text, encoding="utf-8")
report = compile_report(compiler, flags, source, status)
result = subprocess.run([fixture, source.name, str(status), *map(str, witness)], cwd=source.parent,
input=report, capture_output=True, check=True, timeout=10)
check(not result.stderr, result.stderr)
return json.loads(result.stdout), json.loads(report)["runs"][0]
def clean(result):
check(result == {"complete": True, "diagnostics": []}, f"expected a clean owner: {result!r}")
def isolated_inputs(fixture, compiler, flags, work):
"""Nix/Linux fixture. Mount only the known compiler and fixture inputs at their original paths."""
def captured_input(path, edited=None):
mode = "--capture-disk" if edited is None else "--capture-overlay"
proc = subprocess.run([fixture, mode, ROOT, TU, compiler, path], input=edited or b"",
capture_output=True, timeout=30)
check(proc.returncode == 0 and not proc.stderr, f"source capture failed: {proc.stderr!r}")
entry = json.loads(proc.stdout)
check(entry["uri"] == path.as_uri() and entry["overlay"] == (edited is not None),
f"source capture returned the wrong binding for {path}")
data = entry["text"].encode("utf-8")
if edited is not None:
check(data == edited, "captured bytes lost an editor change")
return data
bwrap, store = shutil.which("bwrap"), shutil.which("nix-store")
check(bwrap and store, "isolated fixture requires bubblewrap and nix-store")
frontend = Path(subprocess.check_output([compiler, "-print-prog-name=cc1plus"],
timeout=10, text=True).strip()).resolve(strict=True)
check(frontend.is_relative_to("/nix/store") and len(frontend.parts) > 4, "expected a Nix GCC package")
package = Path(*frontend.parts[:4])
closure = {Path(p) for p in subprocess.check_output([store, "-qR", package], timeout=20,
text=True).splitlines()}
check(0 < len(closure) <= 128 and all(p.parent == Path("/nix/store") for p in closure),
"unexpected compiler runtime closure")
probe = subprocess.run([compiler, "-###", *flags, "-frandom-seed=vls-test-view", "-fsyntax-only",
"-fdiagnostics-format=sarif-stderr", TU], cwd=ROOT, capture_output=True,
text=True, check=True, timeout=15, env={**os.environ, "LC_ALL": "C"})
cmds = [shlex.split(line) for line in probe.stderr.splitlines()
if line.lstrip().startswith((str(frontend) + " ", '"' + str(frontend) + '" '))]
check(len(cmds) == 1 and cmds[0][0] == str(frontend) and cmds[0].count(str(TU)) == 1,
"could not identify one GCC frontend for the original translation unit")
args = cmds[0]
system_dirs = {Path(args[i + 1]) for i, arg in enumerate(args[:-1])
if arg in {"-isystem", "-idirafter"}}
check(all(p.is_relative_to("/nix/store") and p.is_dir() for p in system_dirs),
"expected immutable toolchain include directories")
sandbox = [bwrap, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv",
"--setenv", "LC_ALL", "C", "--dev", "/dev", "--tmpfs", "/tmp"]
for p in sorted(closure | {p for p in system_dirs if not any(p.is_relative_to(k) for k in closure)}):
sandbox.extend(["--ro-bind", p, p])
include = work / "vls-headers"
for name in ("DocumentSnapshot.hpp", "Position.hpp", "Uri.hpp"):
relative = Path("Void/LanguageServer/Documents", name)
dest = include / relative
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(captured_input(ROOT / "include" / relative))
deps = LIB_INCLUDE.resolve(strict=True)
original = captured_input(TU)
text = original.decode("utf-8")
saved = work / "saved-input.cpp"
saved.write_bytes(original)
broken = work / "broken-input.cpp"
broken.write_bytes(captured_input(TU, text.replace("Void::Hash::fnv1a64(text)",
"Void::Hash::missing(text)").encode()))
line, = [i for i, s in enumerate(broken.read_text().splitlines(), 1) if "Void::Hash::missing(text)" in s]
first = broken.read_text().splitlines()[line - 1].index("missing") + 1
end = first + len("missing")
def compile_view(source, code, witness=(), additional=()):
mounts = [(include, ROOT / "include"), (deps, deps), (source, TU), *additional]
command = [*sandbox]
for src, dst in mounts:
command.extend(["--ro-bind", src, dst])
wire = capture_report([*command, "--chdir", ROOT, "--", *args], work, code)
out = subprocess.run([fixture, "--logical-file", TU, source.name, str(code), *map(str, witness)],
cwd=work, input=wire, capture_output=True, check=True, timeout=10)
check(not out.stderr, out.stderr)
return json.loads(out.stdout)
clean(compile_view(saved, 0))
batch = compile_view(broken, 1, (line, first, end))
check(batch["complete"] and any(d["range"] == [[line-1, first-1], [line-1, end-1]] and
"missing" in d["message"] for d in batch["diagnostics"]), batch)
clean(compile_view(saved, 0))
header = Path("Void/Core/Hash.hpp")
overlay = work / "Hash.hpp"
overlay.write_bytes(captured_input(deps / header, b'#error "VLS private header snapshot"\n'
+ captured_input(deps / header)))
header_error = compile_view(saved, 1, additional=[(overlay, deps / header)])
check(any("VLS private header snapshot" in d["message"] for d in header_error["diagnostics"]),
"the compiler ignored the staged header at its original name")
clean(compile_view(saved, 0))
# A benign host-only file distinguishes a private lookup domain from accidental fallback.
marker = work / "host-only.hpp"
marker.write_text("// fixture\n", encoding="ascii")
lookup = work / "lookup.cpp"
lookup.write_bytes(captured_input(TU, (f'#if __has_include("{marker}")\n'
'#error host-only file visible\n#endif\n' + text).encode()))
outside = json.loads(compile_report(compiler, flags, lookup, 1))["runs"][0]
check(any("host-only file visible" in d["message"]["text"] for d in outside["results"]),
"missing ambient positive control")
clean(compile_view(lookup, 0))
check(TU.read_bytes() == original, "the original TU was modified")
print(f"private source view: {len(closure)} compiler runtime paths, saved/edit/recover, "
"header overlay and __has_include controls passed")
def run(fixture, compiler, database, work):
flags = native_flags(fixture, compiler, database)
path = work / TU.name
text = TU.read_text(encoding="utf-8")
call = "Void::Hash::fnv1a64(text)"
check(text.count(call) == 1, "the real Void overload witness changed")
modified = text.replace(call, "Void::Hash::fnv1a64(std::as_bytes(std::span{text}))")
broken = text.replace(call, "Void::Hash::missing(text)")
line, = [i for i,s in enumerate(broken.splitlines(), 1) if "Void::Hash::missing(text)" in s]
first = broken.splitlines()[line-1].index("missing") + 1
end = first + len("missing")
clean(observe(fixture, compiler, flags, path, text, 0)[0])
clean(observe(fixture, compiler, flags, path, modified, 0)[0])
batch, _ = observe(fixture, compiler, flags, path, broken, 1, (line, first, end))
matches = [d for d in batch["diagnostics"] if "missing" in d["message"]]
check(batch["complete"] and len(matches) == 1 and
matches[0]["range"] == [[line-1, first-1], [line-1, end-1]], batch)
clean(observe(fixture, compiler, flags, path, text, 0)[0])
print(f"stock GCC: saved, overload edit, source error at {line}:[{first},{end}), restored")
# Change just the copied overload attributes. The two messages independently identify
# the overload selected by the compiler when the caller's argument type changes.
relative = Path("Void/Core/Hash.hpp")
original = (LIB_INCLUDE / relative).read_bytes()
header = original.decode("utf-8")
for signature, tag in (("fnv1a64(std::string_view s)", "string_view"),
("fnv1a64(std::span<const std::byte> data)", "byte_span")):
check(header.count(signature) == 1, signature)
start = header.rindex("[[nodiscard]]", 0, header.index(signature))
header = header[:start] + header[start:].replace(
"[[nodiscard]]", f'[[nodiscard, deprecated("vls-diagnostic-{tag}")]]', 1)
overlay_root = work / "header"
overlay = overlay_root / relative
overlay.parent.mkdir(parents=True)
overlay.write_text(header, encoding="utf-8")
insert = flags.index(str(LIB_INCLUDE.resolve())) - 1
header_flags = [*flags[:insert], "-I", str(overlay_root), *flags[insert:]]
for caller, tag in ((text, "string_view"), (modified, "byte_span")):
batch, raw = observe(fixture, compiler, header_flags, path, caller, 0)
matched = [r for r in raw["results"] if f"vls-diagnostic-{tag}" in r["message"]["text"] and
any(loc["physicalLocation"]["artifactLocation"].get("uri") == path.name and
loc["physicalLocation"]["region"]["startLine"] == line for loc in r["locations"])]
check(len(matched) == 1 and any(d["message"] == matched[0]["message"]["text"] for d in
batch["diagnostics"]), f"missing overload evidence for {tag}")
check(all(d["range"] is None for d in batch["diagnostics"]), "range without a physical witness")
overlay.write_bytes(original)
clean(observe(fixture, compiler, header_flags, path, text, 0)[0])
check((LIB_INCLUDE / relative).read_bytes() == original, "prepared dependency changed")
print("stock GCC: staged header reports string_view, then byte_span, then clears on restoration")
path = work / "main.cpp"
inactive = "int q(){return missing;}"
(work / "alias.hpp").write_text('#line 2 "main.cpp"\n' + inactive + "\n", encoding="utf-8")
batch, raw = observe(fixture, compiler, ["-std=c++26", "-freflection"], path,
"#if 0\n" + inactive + '\n#endif\n#include "alias.hpp"\n', 1)
locations = raw["results"][0]["locations"]
check(any(loc["physicalLocation"]["artifactLocation"]["uri"] == "main.cpp" and
loc["physicalLocation"]["region"]["startLine"] == 2 for loc in locations),
"expected GCC to remap the header to the inactive main line")
check(not batch["complete"] and any("missing" in d["message"] and d["range"] is None
for d in batch["diagnostics"]), batch)
print("stock GCC: header remapped to an inactive source line retained an unlocated message")
return flags
if __name__ == "__main__":
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument("--fixture", required=True, type=Path)
cli.add_argument("--database", type=Path, help="assert this is the selected native VBS compilation database")
cli.add_argument("--comparison", type=Path, help="also acquire the real TU from this compile_commands.json")
cli.add_argument("--cxx", default="g++")
cli.add_argument("--isolated-inputs", action="store_true",
help="also verify a private Linux/Nix input view with bubblewrap")
options = cli.parse_args()
compiler = shutil.which(options.cxx)
if not compiler:
cli.error(f"compiler not found: {options.cxx}")
with tempfile.TemporaryDirectory(prefix="vls-stock-diagnostic-") as temp:
fixture = options.fixture.resolve(strict=True)
for directory in ("left right", "left%20right"):
work = Path(temp) / directory
work.mkdir()
result, run_data = observe(fixture, compiler, ["-std=c++26"], work / "unit.cpp",
"int x;\n", 0)
clean(result)
check(run_data["originalUriBaseIds"]["PWD"]["uri"] == f"file://{work}/",
"GCC working-directory spelling changed")
database = options.database.resolve(strict=True) if options.database else None
flags = run(fixture, compiler, database, Path(temp))
if options.comparison:
comparison = options.comparison.resolve(strict=True)
compat = checked_command(fixture, compiler, comparison)
expected_rows = [r for r in json.loads(comparison.read_bytes()) if r["file"] == str(TU)]
check(len(expected_rows) == 1 and compat["directory"] == expected_rows[0]["directory"]
and compat["database"] == str(comparison) and "-freflection" in compat["arguments"],
"incomplete compatibility compiler context")
print("compile_commands: acquired and revalidated the selected real Void translation unit")
if options.isolated_inputs:
isolated_inputs(fixture, compiler, flags, Path(temp))
@@ -0,0 +1,140 @@
"""Observe nested consteval returns on stock x86-64 Linux GCC 16.2 using GDB."""
import argparse
import json
from pathlib import Path
import subprocess
import sys
import tempfile
def observe(gdb):
# The type object is loaded only in GDB. The installed cc1plus runs the
# original source with its ordinary flags and receives no plugin.
tree = gdb.lookup_type("tree_node").pointer()
codes = {name: int(gdb.parse_and_eval(name)) for name in
("CALL_EXPR", "ADDR_EXPR", "FUNCTION_DECL", "IDENTIFIER_NODE", "INTEGER_CST")}
def code(node):
return int(node["base"]["code"])
def operand(node, index):
return (node["exp"]["operands"][0].address + index).dereference()
def callee(call):
if code(call) != codes["CALL_EXPR"]:
return None
function = operand(call, 1)
if function and code(function) == codes["ADDR_EXPR"]:
function = operand(function, 0)
if not function or code(function) != codes["FUNCTION_DECL"]:
return None
identifier = function["decl_minimal"]["name"]
if not identifier or code(identifier) != codes["IDENTIFIER_NODE"]:
return None
entry = identifier["identifier"]["id"]
length = int(entry["len"])
if 0 < length <= 64:
return entry["str"].string(length=length)
return None
hits = []
active = []
observations = []
class Entry(gdb.Breakpoint):
def stop(self):
hits.append((None, None))
return True
class Return(gdb.FinishBreakpoint):
def __init__(self, name):
super().__init__(gdb.newest_frame(), internal=True)
self.function_name = name
def stop(self):
result = gdb.newest_frame().read_register("rax").cast(tree)
value = int(result["int_cst"]["val"][0]) if result and code(result) == codes["INTEGER_CST"] else None
hits.append((self.function_name, value))
return True
# The unmodified package retains this out-of-line function symbol.
# rsi and rax are the second argument and return registers of this ABI.
signature = "cxx_eval_call_expression(constexpr_ctx const*, tree_node*, value_cat, bool*, bool*, tree_node**)"
Entry(f"*'{signature}'", internal=True)
command = "run"
for _ in range(1024):
hits.clear()
stopped = gdb.execute(command, to_string=True)
if not gdb.selected_inferior().pid:
break
if len(hits) != 1:
raise RuntimeError(f"Unexpected stop {hits}: {stopped}")
frame = gdb.newest_frame()
name, value = hits[0]
if name is None:
name = callee(frame.read_register("rsi").cast(tree))
if name in ("twice", "reflected_value"):
active.append(name)
Return(name)
else:
if not active or active.pop() != name:
raise RuntimeError("Unexpected evaluator return order")
observations.append([name, active.copy(), value, gdb.selected_inferior().pid])
command = "continue"
else:
raise RuntimeError("Exceeded the fixture stop limit")
if active or int(gdb.parse_and_eval("$_exitcode")) != 0:
raise RuntimeError("Incomplete stock compiler run")
print("VLS_STOCK_RETURNS " + json.dumps(observations))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
parser.add_argument("--gdb", default="gdb")
parser.add_argument("--include-dir", action="append", default=[], type=Path,
help="additional header directory for building the GDB type object")
args = parser.parse_args()
def compiler_value(option):
return subprocess.check_output([args.cxx, option], text=True, timeout=10).strip()
target = compiler_value("-dumpmachine")
if compiler_value("-dumpfullversion") != "16.2.0" or not target.startswith("x86_64-") or "linux" not in target:
parser.error("this fixture adapter covers x86-64 Linux GCC 16.2.0")
frontend = compiler_value("-print-prog-name=cc1plus")
headers = Path(compiler_value("-print-file-name=plugin")) / "include"
script = Path(__file__).resolve()
fixture = script.with_name("gcc-live.cpp").read_text()
if fixture.count("Ready = 17") != 1:
raise RuntimeError("Missing the unique fixture edit")
with tempfile.TemporaryDirectory(prefix="vls-stock-gcc-") as temporary:
directory = Path(temporary)
(directory / "types.cc").write_text(
'#include "gcc-plugin.h"\n#include "tree.h"\n'
'tree_node *vls_debug_tree;\ntree_code vls_debug_code;\n')
includes = [f"-I{path.resolve()}" for path in [headers, *args.include_dir]]
subprocess.run([args.cxx, "-g", "-O0", "-c", *includes, "types.cc", "-o", "types.o"],
cwd=directory, check=True, timeout=30)
for value in (17, 41):
(directory / "fixture.cpp").write_text(fixture.replace("Ready = 17", f"Ready = {value}"))
command = [args.gdb, "-nx", "-nh", "-q", "-batch", "-iex", "set auto-load off",
"-iex", "set debuginfod enabled off", "-ex", "add-symbol-file types.o 0",
"-x", str(script), "--args", frontend, "-quiet", "-std=c++26", "-freflection",
"-fsyntax-only", "-nostdinc", "fixture.cpp", "-o", "/dev/null"]
output = subprocess.check_output(command, cwd=directory, text=True, timeout=20)
prefix = "VLS_STOCK_RETURNS "
rows, = (json.loads(line[len(prefix):]) for line in output.splitlines() if line.startswith(prefix))
pairs = [(inner[2], outer[2]) for inner, outer in zip(rows, rows[1:])
if inner[:2] == ["reflected_value", ["twice"]] and outer[:2] == ["twice", []]]
if pairs != [(value, 2 * value), (value + 5, 2 * (value + 5))] or len({row[3] for row in rows}) != 1:
raise RuntimeError(f"Unexpected stock compiler observations {rows}")
print(f"Stock GCC 16.2 returned {pairs} live in PID {rows[0][3]}.")
if "gdb" in sys.modules:
observe(sys.modules["gdb"])
elif __name__ == "__main__":
main()
+399
View File
@@ -0,0 +1,399 @@
#!/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) == {"path", "line", "startByte", "endByte"},
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")
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}")