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:
1 parent
ca04975d54
commit
da8003f6d4
310 files changed
+47552
-480
No files matched your search
Executable
+201
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the local stock GCC occurrence observer with a scrubbed environment.
|
||||
|
||||
The artifact is a development-only GCC plugin. Its ELF dynamic section is
|
||||
checked before publication: no mutable or relative loader search entries, and
|
||||
every DT_NEEDED resolves inside the selected compiler's immutable runtime.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "experiments/frontend/gcc-observer/Observer.cpp"
|
||||
STORE = re.compile(r"/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._?=-]+")
|
||||
ENV_DROP = re.compile(r"^(NIX_|LD_|LIBRARY_PATH$|CPATH$|C_INCLUDE_PATH$|CPLUS_INCLUDE_PATH$|"
|
||||
r"GCC_EXEC_PREFIX$|COMPILER_PATH$|.*FLAGS$|.*_FLAGS$)")
|
||||
|
||||
|
||||
def scrubbed_environment(temp):
|
||||
base = {"PATH": "/usr/bin:/bin", "LC_ALL": "C", "TZ": "UTC0", "TMPDIR": str(temp)}
|
||||
for key, value in os.environ.items():
|
||||
if key not in base and not ENV_DROP.match(key):
|
||||
base[key] = value
|
||||
return base
|
||||
|
||||
|
||||
def run(argv, env, what, timeout=120):
|
||||
result = subprocess.run(argv, env=env, stdin=subprocess.DEVNULL, capture_output=True,
|
||||
text=True, timeout=timeout)
|
||||
if result.returncode:
|
||||
raise ValueError(f"{what} exited {result.returncode}: {result.stderr[-1200:]}")
|
||||
return result
|
||||
|
||||
|
||||
def find_gmp(compiler, env, explicit):
|
||||
if explicit:
|
||||
header = Path(explicit).resolve(strict=True)
|
||||
if header.is_dir():
|
||||
header /= "gmp.h"
|
||||
if not header.is_file():
|
||||
raise ValueError(f"no gmp.h under {explicit}")
|
||||
return header.parent
|
||||
candidates = sorted(Path("/nix/store").glob("*-gmp-with-cxx-*-dev/include/gmp.h"))
|
||||
if not candidates:
|
||||
raise ValueError("could not locate a GMP development header; pass --gmp-include")
|
||||
digests = set()
|
||||
for header in candidates:
|
||||
with header.open("rb") as stream:
|
||||
digests.add(hashlib.file_digest(stream, "sha256").hexdigest())
|
||||
if len(digests) != 1:
|
||||
raise ValueError("multiple distinct GMP headers are installed; pass --gmp-include")
|
||||
return candidates[0].parent
|
||||
|
||||
|
||||
def dynamic_section(readelf, elf):
|
||||
result = subprocess.run([readelf, "-d", str(elf)], capture_output=True, text=True,
|
||||
timeout=30)
|
||||
if result.returncode:
|
||||
raise ValueError(f"readelf failed for {elf}: {result.stderr[-400:]}")
|
||||
needed, runpath, rpath = [], [], []
|
||||
for line in result.stdout.splitlines():
|
||||
if "(NEEDED)" in line:
|
||||
needed.append(line.rsplit("[", 1)[1].rstrip("]"))
|
||||
elif "(RUNPATH)" in line:
|
||||
runpath.extend(line.split(":", 1)[1].strip().strip("[]").split(":"))
|
||||
elif "(RPATH)" in line:
|
||||
rpath.extend(line.split(":", 1)[1].strip().strip("[]").split(":"))
|
||||
return needed, runpath, rpath
|
||||
|
||||
|
||||
def soname(readelf, library):
|
||||
result = subprocess.run([readelf, "-d", str(library)], capture_output=True, text=True,
|
||||
timeout=30)
|
||||
match = re.search(r"\(SONAME\).*\[(.+)\]", result.stdout)
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def verify_elf(readelf, artifact, frontend, compiler, env):
|
||||
needed, runpath, rpath = dynamic_section(readelf, artifact)
|
||||
if rpath:
|
||||
raise ValueError(f"rejected RPATH in {artifact}: {rpath}")
|
||||
closure = set()
|
||||
package = Path(*frontend.parts[:4])
|
||||
nix_store = shutil.which("nix-store")
|
||||
if nix_store and package.is_dir():
|
||||
closure = {Path(p) for p in run([nix_store, "-qR", str(package)], env,
|
||||
"nix-store query", timeout=60).stdout.splitlines()}
|
||||
if not closure:
|
||||
raise ValueError("could not establish the selected compiler runtime closure")
|
||||
for entry in runpath:
|
||||
path = Path(entry)
|
||||
match = STORE.match(entry)
|
||||
if (not entry or not path.is_absolute() or ".." in path.parts or match is None
|
||||
or not path.is_dir()):
|
||||
raise ValueError(f"unapproved loader search entry {entry!r}")
|
||||
if Path(match.group(0)) not in closure:
|
||||
raise ValueError(f"loader search entry outside the compiler runtime: {entry}")
|
||||
if not needed:
|
||||
raise ValueError("the observer has no dynamic dependencies")
|
||||
frontend_runpath = dynamic_section(readelf, frontend)[1]
|
||||
search = [*frontend_runpath, *[str(p) for p in sorted(closure) if (p / "lib").is_dir()]]
|
||||
for name in needed:
|
||||
printed = run([compiler, f"-print-file-name={name}"], env, "compiler search").stdout.strip()
|
||||
candidates = [Path(printed)] if printed and printed != name else []
|
||||
candidates += [Path(directory) / name for directory in search]
|
||||
resolved = None
|
||||
for candidate in candidates:
|
||||
if not candidate.is_file():
|
||||
continue
|
||||
actual = candidate.resolve()
|
||||
match = STORE.match(str(actual))
|
||||
if match is None or Path(match.group(0)) not in closure:
|
||||
continue
|
||||
if soname(readelf, candidate) == name:
|
||||
resolved = actual
|
||||
break
|
||||
if resolved is None:
|
||||
raise ValueError(f"unresolved dynamic dependency {name}")
|
||||
return needed, runpath
|
||||
|
||||
|
||||
def plugin_abi(include):
|
||||
text = (include / "plugin-version.h").read_text(encoding="utf-8")
|
||||
values = dict(re.findall(r"#define\s+GCCPLUGIN_VERSION_(\w+)\s+(\d+)", text))
|
||||
return f"{values['MAJOR']}.{values['MINOR']}.{values['PATCHLEVEL']}"
|
||||
|
||||
|
||||
def prepare(args):
|
||||
compiler = Path(shutil.which(args.cxx) or "").resolve(strict=True)
|
||||
readelf = shutil.which("readelf")
|
||||
if not readelf:
|
||||
raise ValueError("readelf is required")
|
||||
if args.inspect:
|
||||
with tempfile.TemporaryDirectory(prefix="vls-gcc-observer-") as temp:
|
||||
env = scrubbed_environment(Path(temp))
|
||||
frontend = Path(run([compiler, "-print-prog-name=cc1plus"], env,
|
||||
"frontend search").stdout.strip()).resolve(strict=True)
|
||||
needed, runpath = verify_elf(readelf, Path(args.inspect).resolve(strict=True),
|
||||
frontend, compiler, env)
|
||||
print(f"needed {', '.join(needed)}")
|
||||
print(f"runpath {':'.join(runpath) if runpath else '(none)'}")
|
||||
return
|
||||
if not args.output:
|
||||
raise ValueError("--output is required unless --inspect is used")
|
||||
if not SOURCE.is_file():
|
||||
raise ValueError(f"missing observer source {SOURCE}")
|
||||
output = Path(args.output).absolute()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="vls-gcc-observer-", dir=output.parent) as temp:
|
||||
work = Path(temp)
|
||||
env = scrubbed_environment(work)
|
||||
plugin = Path(run([compiler, "-print-file-name=plugin"], env, "plugin search").stdout.strip())
|
||||
include = plugin / "include"
|
||||
if not (include / "gcc-plugin.h").is_file():
|
||||
raise ValueError(f"no GCC plugin headers under {include}")
|
||||
gmp = find_gmp(compiler, env, args.gmp_include)
|
||||
version = run([compiler, "-dumpfullversion"], env, "compiler version").stdout.strip()
|
||||
target = run([compiler, "-dumpmachine"], env, "compiler target").stdout.strip()
|
||||
frontend = Path(run([compiler, "-print-prog-name=cc1plus"], env,
|
||||
"frontend search").stdout.strip()).resolve(strict=True)
|
||||
temporary = work / "occurrences.so"
|
||||
run([compiler, "-std=c++17", "-fPIC", "-fno-rtti", "-fno-exceptions", "-shared",
|
||||
"-I", str(include), "-I", str(gmp), str(SOURCE), "-o", str(temporary)],
|
||||
env, "observer build")
|
||||
needed, runpath = verify_elf(readelf, temporary, frontend, compiler, env)
|
||||
with temporary.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
os.chmod(temporary, 0o755)
|
||||
os.replace(temporary, output)
|
||||
print(f"GCC {version} ({target}) plugin ABI {plugin_abi(include)}")
|
||||
print(f"sha256 {digest}")
|
||||
print(f"needed {', '.join(needed)}")
|
||||
print(f"runpath {':'.join(runpath) if runpath else '(none)'}")
|
||||
print(output)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
parser.add_argument("--gmp-include", type=Path,
|
||||
help="GMP development include directory (default: verified Nix candidate)")
|
||||
parser.add_argument("--output", type=Path,
|
||||
help="published observer artifact (required for a build)")
|
||||
parser.add_argument("--inspect", type=Path,
|
||||
help="validate the dynamic section of an existing artifact and exit")
|
||||
args = parser.parse_args()
|
||||
prepare(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
raise SystemExit(f"prepare-gcc-observer: {exc}")
|
||||
Executable
+133
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare a local Linux/Nix stock GCC diagnostics profile in the project's dev shell."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def run(args):
|
||||
p = subprocess.run(args, capture_output=True, text=True, timeout=30)
|
||||
if p.returncode:
|
||||
raise ValueError(f"{Path(args[0]).name} exited {p.returncode}: {p.stderr[-600:]}")
|
||||
return p
|
||||
|
||||
|
||||
def store_package(path):
|
||||
parts = path.parts
|
||||
if (len(parts) < 4 or parts[:3] != ("/", "nix", "store")
|
||||
or not re.fullmatch(r"[0-9a-z]{32}-[A-Za-z0-9+._?=-]+", parts[3])):
|
||||
raise ValueError(f"expected an immutable Nix store input for {path.name}")
|
||||
return Path(*parts[:4])
|
||||
|
||||
|
||||
def executable(name):
|
||||
selected = shutil.which(name)
|
||||
if not selected:
|
||||
raise ValueError(f"could not locate {name}")
|
||||
path = Path(selected).resolve(strict=True)
|
||||
store_package(path)
|
||||
with path.open("rb") as f:
|
||||
return {"path": str(path), "sha256": hashlib.file_digest(f, "sha256").hexdigest()}
|
||||
|
||||
|
||||
def plan(command):
|
||||
lines = run(command).stderr.splitlines()
|
||||
stages = [shlex.split(line) for line in lines if line.lstrip().startswith(("/", '"/'))]
|
||||
if len(stages) != 1 or Path(stages[0][0]).name != "cc1plus":
|
||||
raise ValueError("expected exactly one GCC C++ frontend in the driver dry run")
|
||||
return stages[0]
|
||||
|
||||
|
||||
def prepare(cxx, observer=None):
|
||||
driver, bwrap, tracer, limiter = (executable(name) for name in (cxx, "bwrap", "strace", "prlimit"))
|
||||
version = run([driver["path"], "-dumpfullversion"]).stdout.strip()
|
||||
target = run([driver["path"], "-dumpmachine"]).stdout.strip()
|
||||
if version != "16.2.0" or not re.fullmatch(r"[a-zA-Z0-9_-]{1,128}", target):
|
||||
raise ValueError("the verified profile requires GCC 16.2.0 with a known target")
|
||||
probe = ["-###", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr",
|
||||
"-frandom-seed=vls-probe", "-std=c++26", "-freflection", "/vls-check/sample.cpp"]
|
||||
reference = plan([driver["path"], *probe])
|
||||
frontend = executable(reference[0])
|
||||
roots = {store_package(Path(x["path"])) for x in (driver, frontend, tracer)}
|
||||
system = {Path(reference[i + 1]) for i, word in enumerate(reference[:-1])
|
||||
if word in ("-isystem", "-idirafter", "-I")}
|
||||
for path in system:
|
||||
store_package(path)
|
||||
if not path.is_dir():
|
||||
raise ValueError("the compiler reported a missing system include directory")
|
||||
closure = set(run(["nix-store", "-qR", *sorted(roots)]).stdout.splitlines())
|
||||
if not 0 < len(closure) <= 128 or any(store_package(Path(p)) != Path(p) for p in closure):
|
||||
raise ValueError("unexpected tool runtime closure")
|
||||
mounts = sorted(closure | {str(p) for p in system if str(store_package(p)) not in closure})
|
||||
key = "NIX_CFLAGS_COMPILE_" + target.replace("-", "_")
|
||||
# Reproduce the cc-wrapper's target-specific include/seed settings with a closed environment.
|
||||
words = shlex.split(os.environ.get(key, os.environ.get("NIX_CFLAGS_COMPILE", "")))
|
||||
i = 0
|
||||
while i < len(words):
|
||||
if re.fullmatch(r"-frandom-seed=[A-Za-z0-9._-]+", words[i]):
|
||||
i += 1
|
||||
elif i + 1 < len(words) and words[i] in ("-isystem", "-idirafter", "-I"):
|
||||
p = Path(words[i + 1])
|
||||
store_package(p)
|
||||
if p not in system or not re.fullmatch(r"/[A-Za-z0-9_+./=-]+", str(p)):
|
||||
raise ValueError("unverified toolchain include option")
|
||||
i += 2
|
||||
else:
|
||||
raise ValueError("the toolchain includes an unsupported environment flag")
|
||||
sandbox = [bwrap["path"], "--unshare-all", "--die-with-parent", "--new-session",
|
||||
"--clearenv", "--setenv", "LC_ALL", "C", "--setenv", "TZ", "UTC0",
|
||||
"--setenv", "TZDIR", str(Path(frontend["path"]).parent),
|
||||
"--dev", "/dev", "--tmpfs", "/tmp"]
|
||||
for mount in mounts:
|
||||
sandbox += ["--ro-bind", mount, mount]
|
||||
sandbox += ["--setenv", key, " ".join(words), "--dir", "/vls-check", "--chdir", "/vls-check", "--"]
|
||||
for flags in (probe, [*probe, "-DPROFILE_CHECK=1", "-pthread", "-O2", "-fPIC"]):
|
||||
if plan([driver["path"], *flags]) != plan([*sandbox, driver["path"], *flags]):
|
||||
raise ValueError("isolated compiler options differ from the selected dev shell")
|
||||
data = {"schema": 1, "version": version, "target": target, "driver": driver,
|
||||
"frontend": frontend, "bubblewrap": bwrap, "strace": tracer, "prlimit": limiter, "mounts": mounts,
|
||||
"toolchainFlags": words}
|
||||
if observer is not None:
|
||||
path = Path(observer).resolve(strict=True)
|
||||
if not path.is_absolute() or not path.is_file():
|
||||
raise ValueError("--observer must be an absolute regular artifact")
|
||||
with path.open("rb") as binary:
|
||||
data["observer"] = {"path": str(path), "sha256": hashlib.file_digest(binary, "sha256").hexdigest()}
|
||||
return data
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cxx", default="g++")
|
||||
parser.add_argument("--observer", type=Path,
|
||||
help="absolute stock occurrence observer artifact to select")
|
||||
parser.add_argument("--output", type=Path, default=Path("build/gcc-profile.json"))
|
||||
args = parser.parse_args()
|
||||
data = prepare(args.cxx, args.observer)
|
||||
output = args.output.absolute()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile(mode="w", dir=output.parent, delete=False) as f:
|
||||
try:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(f.name, output)
|
||||
finally:
|
||||
Path(f.name).unlink(missing_ok=True)
|
||||
print(f"GCC {data['version']} ({data['target']}), verified {len(data['mounts'])} mounts. {output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
raise SystemExit(f"prepare-gcc-profile: {exc}")
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproduce the private GCC 16.2.0 frontend from the versioned compiler patches."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PATCHES = ROOT / "compiler-patches/gcc-16.2.0"
|
||||
VERSION = "16.2.0"
|
||||
TOOLS = {"CC": "gcc", "CXX": "g++", "AR": "ar", "AS": "as", "LD": "ld", "NM": "nm",
|
||||
"RANLIB": "ranlib", "STRIP": "strip", "OBJCOPY": "objcopy", "OBJDUMP": "objdump",
|
||||
"READELF": "readelf"}
|
||||
OPTIMIZATION = {"CFLAGS": "-O1 -g1", "CXXFLAGS": "-O1 -g1"}
|
||||
|
||||
|
||||
def configure_options(prefix):
|
||||
lines = (PATCHES / "configure.args").read_text(encoding="utf-8").splitlines()
|
||||
text = " ".join(line for line in lines if line and not line.startswith("#"))
|
||||
return shlex.split(text.replace("@PREFIX@", str(prefix)))
|
||||
|
||||
|
||||
def patch_state(source, patch):
|
||||
"""Forward and reverse dry runs distinguish a pristine, applied or foreign tree."""
|
||||
base = ["patch", "--dry-run", "-p1", "--directory", str(source), "-i", str(patch)]
|
||||
if subprocess.run([*base, "--forward"], capture_output=True).returncode == 0:
|
||||
return "unpatched"
|
||||
if subprocess.run([*base, "--reverse"], capture_output=True).returncode == 0:
|
||||
return "already-applied"
|
||||
return "mismatch"
|
||||
|
||||
|
||||
def validate_series(source, patches):
|
||||
"""Apply the ordered series to a scratch copy: patches depend on their predecessors."""
|
||||
with tempfile.TemporaryDirectory(prefix="vls-gcc-series-") as temp:
|
||||
scratch = Path(temp) / "source"
|
||||
shutil.copytree(source, scratch, symlinks=True)
|
||||
results = []
|
||||
for patch in patches:
|
||||
if patch_state(scratch, patch) == "already-applied":
|
||||
results.append((patch.name, True))
|
||||
continue
|
||||
applied = subprocess.run(
|
||||
["patch", "-p1", "--directory", str(scratch), "-i", str(patch)],
|
||||
capture_output=True)
|
||||
results.append((patch.name, applied.returncode == 0))
|
||||
if applied.returncode != 0:
|
||||
break
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source", type=Path, default=Path("build/gcc-gate/gcc-16.2.0"),
|
||||
help="GCC 16.2.0 source tree")
|
||||
parser.add_argument("--output", type=Path, default=Path("build/private-gcc"),
|
||||
help="private build root (source copy, build and install)")
|
||||
parser.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
|
||||
parser.add_argument("--check-only", action="store_true",
|
||||
help="validate the source and patch set, print the recipe, build nothing")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
source = args.source.resolve(strict=True)
|
||||
version = source / "gcc/BASE-VER"
|
||||
if not version.is_file() or version.read_text(encoding="utf-8").strip() != VERSION:
|
||||
raise ValueError(f"expected a GCC {VERSION} source tree at {source}")
|
||||
patches = sorted(PATCHES.glob("*.patch"))
|
||||
if not patches:
|
||||
raise ValueError(f"no patches under {PATCHES}")
|
||||
states = {}
|
||||
for patch in patches:
|
||||
states[patch.name] = patch_state(source, patch)
|
||||
print(f"{patch.name}: {states[patch.name]}")
|
||||
if not args.check_only and any(state == "mismatch" for state in states.values()):
|
||||
raise ValueError("the patch set does not match this source tree")
|
||||
prefix = args.output.absolute() / "install"
|
||||
command = [str(source / "configure"), *configure_options(prefix)]
|
||||
print("configure:", shlex.join(command))
|
||||
if args.check_only:
|
||||
series = validate_series(source, patches)
|
||||
for name, ok in series:
|
||||
print(f"series {name}: {'ok' if ok else 'failed'}")
|
||||
if len(series) != len(patches) or not all(ok for _, ok in series):
|
||||
raise ValueError("the ordered patch series does not apply")
|
||||
print(f"check passed: {len(patches)} patches, GCC {VERSION}, prefix {prefix}")
|
||||
return 0
|
||||
output = args.output.absolute()
|
||||
tree, build = output / "source", output / "build"
|
||||
if output.exists():
|
||||
raise ValueError(f"output already exists: {output}")
|
||||
shutil.copytree(source, tree, symlinks=True)
|
||||
for patch in patches:
|
||||
if states[patch.name] == "already-applied":
|
||||
continue
|
||||
subprocess.run(["patch", "-p1", "--directory", str(tree), "-i", str(patch)],
|
||||
check=True)
|
||||
build.mkdir(parents=True)
|
||||
environment = {**os.environ, **TOOLS, **OPTIMIZATION}
|
||||
subprocess.run(command, cwd=build, env=environment, check=True)
|
||||
subprocess.run(["make", f"-j{args.jobs}"], cwd=build, check=True)
|
||||
print(f"private GCC built under {build}; selected frontend is in gcc/cc1plus")
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
||||
print(f"prepare-private-gcc: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+273
@@ -0,0 +1,273 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare the tracked VoidLibrary sources consumed by VLS's native VBS recipe."""
|
||||
|
||||
import argparse
|
||||
from contextlib import ExitStack, contextmanager
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
UPSTREAM = "https://git.faumaray.com/Void/VoidLibrary.git"
|
||||
PROJECT = Path(__file__).resolve().parents[1]
|
||||
|
||||
# The VBS recipe's module closure, including the Crypto and Text foundations.
|
||||
MODULES = ("Async", "Configuration", "Core", "Crypto", "Data", "Functional", "LogState",
|
||||
"Math", "System", "Testing", "Text", "Time", "Unicode")
|
||||
SOURCE_DIRS = {f"src/{module}" for module in MODULES}
|
||||
PUBLIC_DIRS = {f"include/Void/{module}" for module in MODULES if module != "LogState"}
|
||||
SUPPORT = {"include/Void/Detail/Enum.hpp", "include/Void/Log/Log.hpp", "include/Void/Stacktrace/Color.hpp"}
|
||||
# These co-located public headers belong to optional modules outside the closure.
|
||||
OPTIONAL = {
|
||||
"include/Void/Configuration/ReloadController.hpp", "include/Void/Crypto/AsyncHash.hpp",
|
||||
"include/Void/System/AsyncProcess.hpp", "include/Void/System/AsyncWatcher.hpp",
|
||||
}
|
||||
REQUIRED = SUPPORT | {
|
||||
"include/Void/Configuration/Argparse.hpp", "include/Void/Core/Hash.hpp",
|
||||
"include/Void/Crypto/Crypto.hpp", "include/Void/Data/StrictJson.hpp",
|
||||
"include/Void/System/Process.hpp", "include/Void/Testing/Test.hpp",
|
||||
"include/Void/Text/Url.hpp", "include/Void/Unicode/Utf.hpp",
|
||||
"src/Configuration/Argparse.cpp", "src/Crypto/Crypto.cpp", "src/LogState/State.cpp",
|
||||
"src/System/Process.cpp", "src/Testing/Main.cpp",
|
||||
}
|
||||
SCOPES = sorted({"build.cpp"} | SOURCE_DIRS | PUBLIC_DIRS | SUPPORT)
|
||||
PRIVATE_NAMES = {"keys", "secrets", "credentials"}
|
||||
DIRECTORY = os.O_DIRECTORY | os.O_NOFOLLOW | os.O_RDONLY
|
||||
|
||||
|
||||
class PreparationError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
# Plumbing reads raw objects/index entries. Never check out or run a dependency's
|
||||
# filters, fsmonitor, hooks, submodule commands or lazy object fetches.
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_NO_LAZY_FETCH="1",
|
||||
GIT_NO_REPLACE_OBJECTS="1", GIT_OPTIONAL_LOCKS="0",
|
||||
GIT_ALLOW_PROTOCOL="https" if args[0] == "fetch" else "",
|
||||
GIT_TERMINAL_PROMPT="0")
|
||||
cmd = ["git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
|
||||
"-c", "credential.helper=", "-C", str(repo), *args]
|
||||
result = subprocess.run(cmd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL)
|
||||
if result.returncode:
|
||||
raise PreparationError(f"git {args[0]} failed (exit {result.returncode})")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def selected(path):
|
||||
if path in SUPPORT:
|
||||
return True
|
||||
parent, _, name = path.rpartition("/")
|
||||
if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*\.(cpp|h|hh|hpp|hxx|ipp|inl|tpp)", name)
|
||||
or name.partition(".")[0].lower() in PRIVATE_NAMES):
|
||||
return False
|
||||
parts = parent.split("/")
|
||||
if any(not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_-]*", part)
|
||||
or part.lower() in PRIVATE_NAMES for part in parts):
|
||||
return False
|
||||
# VBS recursively collects translation units under each selected module.
|
||||
return ("/".join(parts[:2]) in SOURCE_DIRS or
|
||||
("/".join(parts[:3]) in PUBLIC_DIRS and not name.endswith(".cpp") and path not in OPTIONAL))
|
||||
|
||||
|
||||
def inventory(repo, revision=None):
|
||||
if revision:
|
||||
rows = git(repo, "ls-tree", "-rz", revision, "--", *SCOPES)
|
||||
else:
|
||||
rows = git(repo, "ls-files", "--stage", "-z", "--", *SCOPES)
|
||||
blobs = {}
|
||||
for row in rows.split(b"\0"):
|
||||
if not row:
|
||||
continue
|
||||
fields, name = row.split(b"\t", 1)
|
||||
path = os.fsdecode(name)
|
||||
if path == "build.cpp" or path.startswith("build.cpp/"):
|
||||
raise PreparationError("tracked root build.cpp requires recipe review")
|
||||
if not selected(path):
|
||||
if path.endswith(".cpp") and "/".join(path.split("/")[:2]) in SOURCE_DIRS:
|
||||
raise PreparationError("unsupported tracked translation unit in a recipe source directory")
|
||||
continue
|
||||
mode, second, third = fields.split()
|
||||
if mode not in (b"100644", b"100755") or (not revision and third != b"0"):
|
||||
raise PreparationError("selected Git input is a link, special file or unmerged entry")
|
||||
blobs[path] = (mode, (third if revision else second).decode("ascii"))
|
||||
return blobs
|
||||
|
||||
|
||||
def commit(repo, ref):
|
||||
value = git(repo, "rev-parse", "--verify", ref + "^{commit}").strip().decode("ascii")
|
||||
if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", value):
|
||||
raise PreparationError("invalid Git revision")
|
||||
return value
|
||||
|
||||
|
||||
@contextmanager
|
||||
def directory(path, parent=None):
|
||||
fd = os.open(path, DIRECTORY, dir_fd=parent)
|
||||
try:
|
||||
yield fd
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def local_file(root, path):
|
||||
# Pin every directory component and refuse links on every open, including the
|
||||
# leaf. O_NONBLOCK keeps a substituted FIFO from hanging before fstat.
|
||||
with ExitStack() as stack:
|
||||
parts = path.split("/")
|
||||
for part in parts[:-1]:
|
||||
root = stack.enter_context(directory(part, root))
|
||||
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=root)
|
||||
with os.fdopen(fd, "rb") as stream:
|
||||
info = os.fstat(fd)
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
|
||||
raise PreparationError("local input must be a regular, singly linked file")
|
||||
stamp = (info.st_dev, info.st_ino, info.st_size, info.st_ctime_ns, info.st_mtime_ns)
|
||||
mode = b"100755" if info.st_mode & stat.S_IXUSR else b"100644"
|
||||
return stream.read(), stamp, mode
|
||||
|
||||
|
||||
def materialize(work, tree, source):
|
||||
local = source is not None
|
||||
if local:
|
||||
repo = Path(source).resolve(strict=True)
|
||||
top = os.fsdecode(git(repo, "rev-parse", "--show-toplevel").removesuffix(b"\n"))
|
||||
if Path(top) != repo:
|
||||
raise PreparationError("--source must name the root of a Git working tree")
|
||||
ref = "HEAD"
|
||||
else:
|
||||
repo = work / "upstream.git"
|
||||
git(work, "init", "--bare", "--template=", str(repo))
|
||||
git(repo, "fetch", "--no-tags", "--no-recurse-submodules", "--no-auto-maintenance",
|
||||
"--depth=1", UPSTREAM, "refs/heads/main")
|
||||
ref = "FETCH_HEAD"
|
||||
|
||||
revision = commit(repo, ref)
|
||||
committed = inventory(repo, revision)
|
||||
inputs = inventory(repo) if local else committed
|
||||
if not REQUIRED.issubset(inputs) or not PUBLIC_DIRS.issubset({p.rpartition("/")[0] for p in inputs}):
|
||||
raise PreparationError("incomplete VoidLibrary recipe inputs for the required modules")
|
||||
dirty = inputs != committed
|
||||
digest = hashlib.sha256()
|
||||
captured = {}
|
||||
with ExitStack() as stack:
|
||||
root = stack.enter_context(directory(repo)) if local else None
|
||||
for path, (mode, oid) in sorted(inputs.items()):
|
||||
if local:
|
||||
data, stamp, file_mode = local_file(root, path)
|
||||
algorithm = "sha1" if len(oid) == 40 else "sha256"
|
||||
blob = hashlib.new(algorithm, f"blob {len(data)}\0".encode())
|
||||
blob.update(data)
|
||||
dirty |= file_mode != mode or blob.hexdigest() != oid
|
||||
else:
|
||||
data = git(repo, "cat-file", "blob", oid)
|
||||
target = tree / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
content_hash = hashlib.sha256(data).digest()
|
||||
digest.update(path.encode("ascii") + b"\0" + content_hash)
|
||||
if local:
|
||||
captured[path] = (stamp, content_hash)
|
||||
if local:
|
||||
# All captured files existed together between these two passes. A rename,
|
||||
# write, symlink substitution or tracking change invalidates the capture.
|
||||
for path, expected in captured.items():
|
||||
data, stamp, _ = local_file(root, path)
|
||||
if (stamp, hashlib.sha256(data).digest()) != expected:
|
||||
raise PreparationError("local sources changed during preparation; retry")
|
||||
if (not os.path.samestat(os.fstat(root), repo.stat()) or commit(repo, ref) != revision
|
||||
or inventory(repo) != inputs):
|
||||
raise PreparationError("local Git checkout changed during preparation; retry")
|
||||
(tree / "src/Core").mkdir(parents=True, exist_ok=True) # VBS recipe detection; Core is header-only.
|
||||
provenance = {"format": 1, "source_kind": "local" if local else "main", "revision": revision,
|
||||
"dirty": dirty, "content_sha256": digest.hexdigest()}
|
||||
if local:
|
||||
try:
|
||||
provenance["source_path"] = os.fsencode(repo).decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise PreparationError("local source path must be valid UTF-8") from None
|
||||
else:
|
||||
provenance["source_url"] = UPSTREAM
|
||||
metadata = (json.dumps(provenance, sort_keys=True) + "\n").encode("utf-8")
|
||||
if len(metadata) > 32768:
|
||||
raise PreparationError("provenance exceeds 32 KiB")
|
||||
(tree / "provenance.json").write_bytes(metadata)
|
||||
return hashlib.sha256(metadata).hexdigest()
|
||||
|
||||
|
||||
def check_existing(tree, target):
|
||||
# Only read expected regular files in the tool's store. Reject any extra
|
||||
# entry (especially a descriptor) before selecting an existing generation.
|
||||
for base, dirs, files in os.walk(tree):
|
||||
peer = target / Path(base).relative_to(tree)
|
||||
info = peer.lstat()
|
||||
if (info.st_uid != os.geteuid() or info.st_mode != (stat.S_IFDIR | 0o555)
|
||||
or set(os.listdir(peer)) != set(dirs + files)):
|
||||
raise PreparationError("existing generation has unexpected entries or permissions")
|
||||
for name in files:
|
||||
src, dst = Path(base) / name, peer / name
|
||||
info = dst.lstat()
|
||||
if (info.st_uid != os.geteuid() or info.st_nlink != 1 or info.st_mode != (stat.S_IFREG | 0o444)
|
||||
or info.st_size != src.stat().st_size
|
||||
or src.read_bytes() != dst.read_bytes()):
|
||||
raise PreparationError("existing generation has unexpected file contents or permissions")
|
||||
|
||||
|
||||
def prepare(source):
|
||||
build = PROJECT / "build"
|
||||
store = build / "voidlibrary"
|
||||
sources = store / "sources"
|
||||
for path in (build, store, sources):
|
||||
path.mkdir(mode=0o700, exist_ok=True)
|
||||
info = path.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
|
||||
raise PreparationError(f"expected an owned directory protected from other writers: {path}")
|
||||
# Stage beside the final directory. Renaming a sealed directory across parents
|
||||
# can require write access to its ".." entry.
|
||||
with (tempfile.TemporaryDirectory(dir=store, prefix=".prepare-") as temp,
|
||||
tempfile.TemporaryDirectory(dir=sources, prefix=".stage-") as stage):
|
||||
work, tree = Path(temp), Path(stage)
|
||||
key = materialize(work, tree, source)
|
||||
target = sources / key
|
||||
with directory(store) as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
current = store / "current"
|
||||
if os.path.lexists(current) and (not current.is_symlink() or
|
||||
not re.fullmatch(r"sources/[0-9a-f]{64}", os.readlink(current))):
|
||||
raise PreparationError("current is outside the preparation tool's managed layout")
|
||||
if os.path.lexists(target):
|
||||
check_existing(tree, target)
|
||||
else:
|
||||
for base, _, files in os.walk(tree, topdown=False):
|
||||
for name in files:
|
||||
(Path(base) / name).chmod(0o444)
|
||||
Path(base).chmod(0o555)
|
||||
tree.rename(target)
|
||||
link = work / "current"
|
||||
link.symlink_to(Path("sources") / key)
|
||||
link.replace(current)
|
||||
return target
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description=__doc__,
|
||||
epilog="Defaults to the official refs/heads/main. Prints the immutable source directory "
|
||||
"and atomically points build/voidlibrary/current at it. Local dirty status covers "
|
||||
"the selected tracked build inputs.",
|
||||
)
|
||||
parser.add_argument("--source", default=os.environ.get("VLS_VOID_SOURCE_DIR") or None,
|
||||
metavar="CHECKOUT", help="development checkout (also VLS_VOID_SOURCE_DIR)")
|
||||
try:
|
||||
print(prepare(parser.parse_args().source))
|
||||
except (PreparationError, OSError) as exc:
|
||||
sys.exit("prepare-voidlibrary: " + (exc.strerror if isinstance(exc, OSError) else str(exc)))
|
||||
Reference in new issue
Block a user