diff options
Diffstat (limited to 'tools/release-surface-probe.py')
| -rw-r--r-- | tools/release-surface-probe.py | 149 |
1 files changed, 149 insertions, 0 deletions
diff --git a/tools/release-surface-probe.py b/tools/release-surface-probe.py new file mode 100644 index 0000000..2f6830b --- /dev/null +++ b/tools/release-surface-probe.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Prove what the release build actually exports, by compiling against it. + +`tools/test-surface.py` reads the source and *infers* which `pub` items exist +only for tests. Inference can be wrong — it already was, twice: a detector that +matched names inside string literals called `review::approve::withdraw` +production-used, and a detector keyed by bare name merged +`pipeline::dispatch::Pool::shutdown` into the gated `db::Writer::shutdown` row. + +This tool does not infer. It writes a throwaway crate that depends on +`aur-build` twice over — once without `test-support`, once with — and tries to +name every dispositioned item from outside. An item is honest only if: + + * at least one candidate path compiles **with** the feature, which proves the + path is real and the item is genuinely reachable to the test tier, and + * every path that compiles with the feature fails **without** it, which proves + a release build does not export it. + +A path that compiles in both builds is a leak and this tool exits non-zero. + +An item with no nameable path at all is not a pass and not a failure: a method +(`Config::store_dir`) or a const inside a private submodule cannot be named by a +`use` line whatever its visibility. Those are reported separately with the +source line that states their visibility, for a human to read. + +Usage: + python3 tools/release-surface-probe.py # report + python3 tools/release-surface-probe.py --quiet # exit code only +""" +import argparse +import json +import os +import re +import shutil +import subprocess +import sys + +ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.." +CACHE = os.path.join(ROOT, "target", "release-surface-probe") + + +def table(): + out = subprocess.run([sys.executable, os.path.join(ROOT, "tools", "test-surface.py"), + "--json"], capture_output=True, text=True, cwd=ROOT) + if out.returncode != 0: + sys.exit("tools/test-surface.py failed: " + out.stderr) + return json.loads(out.stdout)["rows"] + + +def candidates(row): + """Paths an outside crate could try for this item. + + The declaring file's module path, and the top-level module the census groups + it under, because most items are re-exported up to the module door. Neither + reaches a method or an item inside a nested private module; those are + reported as not nameable rather than guessed at. + """ + f = row["where"].rsplit(":", 1)[0] + mod = f[len("src/"):-len(".rs")] + if mod.endswith("/mod"): + mod = mod[: -len("/mod")] + top = mod.split("/")[0] + paths = {"aur_build::%s::%s" % (mod.replace("/", "::"), row["name"]), + "aur_build::%s::%s" % (top, row["name"])} + return sorted(paths) + + +def build(feature): + """Compile one probe binary per candidate path; return the set that failed.""" + d = os.path.join(CACHE, "with" if feature else "no") + shutil.rmtree(d, ignore_errors=True) + os.makedirs(os.path.join(d, "src", "bin")) + with open(os.path.join(d, "Cargo.toml"), "w") as h: + h.write('[package]\nname="surface-probe"\nversion="0.0.0"\nedition="2021"\n\n' + '[dependencies]\naur-build = { path = "%s"%s }\n' + % (os.path.abspath(os.path.join(ROOT, ".")), + ', features = ["test-support"]' if feature else "")) + with open(os.path.join(d, "src", "main.rs"), "w") as h: + h.write("fn main() {}\n") + + units = {} + rows = table() + for i, row in enumerate(rows): + for j, path in enumerate(candidates(row)): + name = "x%02d_%d" % (i, j) + units[name] = (row["module"], row["name"], path, row["disp"]) + with open(os.path.join(d, "src", "bin", name + ".rs"), "w") as h: + h.write("#![allow(unused_imports, dead_code)]\nuse %s;\nfn main() {}\n" % path) + + r = subprocess.run(["cargo", "build", "--bins", "--keep-going", "--message-format=short", + "--target-dir", os.path.join(CACHE, "tgt-" + ("with" if feature else "no"))], + cwd=d, capture_output=True, text=True) + if "error: could not compile `surface-probe`" not in r.stdout + r.stderr and not units: + sys.exit("probe build produced no output; cargo is not working") + failed = set(re.findall(r"\b(x\d+_\d+)\.rs", r.stdout + r.stderr)) + return units, failed + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--quiet", action="store_true", help="print nothing unless something leaked") + args = ap.parse_args() + + units_with, failed_with = build(True) + _, failed_without = build(False) + + real = set(units_with) - failed_with # paths that really exist + # An `interface` item is reachable in a release build on purpose: a public + # signature requires it and no test asked for it. The probe's job is to + # confirm the reachability is the declared kind, not to pretend it is gone. + declared = {u for u in real if units_with[u][3] == "interface"} + leaked = sorted(real - failed_without - declared) # ...and a release build still exports + unexpected = sorted(declared - real) # declared public, but not reachable + nameable = {} + for u in real: + mod, name, path, disp = units_with[u] + nameable.setdefault((mod, name), []).append(path) + silent = sorted({(units_with[u][0], units_with[u][1]) for u in failed_with} - set(nameable)) + + if not args.quiet: + print("candidate paths probed: %d" % len(units_with)) + print("real external paths: %d (compile with test-support)" % len(real)) + print("of those, unreachable in a release build: %d" % len([u for u in real if u in failed_without])) + print("declared public interface (reachable on purpose): %d" % len(declared)) + print("items with a nameable path: %d" % len(nameable)) + print("items no `use` line can name (methods, private submodules): %d" % len(silent)) + for mod, name in silent: + print(" %s.%s" % (mod, name)) + print() + + if unexpected: + print("DECLARED PUBLIC BUT NOT REACHABLE — the interface file is stale:") + for u in unexpected: + print(" %s.%s %s" % (units_with[u][0], units_with[u][1], units_with[u][2])) + return 1 + + if leaked: + print("LEAKED INTO THE RELEASE BUILD — these paths compile with and without the feature:") + for u in leaked: + mod, name, path, disp = units_with[u] + print(" %-14s %-22s %s (disposition: %s)" % (mod, name, path, disp)) + return 1 + if not args.quiet: + print("nothing leaked: every path that reaches the test tier is closed in a release build") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) |
