diff --git a/.claude/hooks/bca-check.mjs b/.claude/hooks/bca-check.mjs index 17c6e60fb..8b71d9b0b 100644 --- a/.claude/hooks/bca-check.mjs +++ b/.claude/hooks/bca-check.mjs @@ -39,8 +39,9 @@ export async function checkHook(input, signal) { const { named, cwd } = context health.root = context.root health.cwd = cwd - const bca = await analyzer(context.root) + const { path: bca, reason } = await analyzer(context.root, { signal }) health.analyzer = bca + health.analyzerReason = reason if (signal?.aborted) { health.outcome = "cancelled" return diff --git a/.claude/hooks/bca-common.mjs b/.claude/hooks/bca-common.mjs index 326474f02..8d1b149ad 100644 --- a/.claude/hooks/bca-common.mjs +++ b/.claude/hooks/bca-common.mjs @@ -1,10 +1,14 @@ import { execFile, spawn } from "node:child_process" import { constants } from "node:fs" import { access, open, realpath, stat } from "node:fs/promises" -import { dirname, isAbsolute, relative, resolve, sep } from "node:path" +import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path" +import { fileURLToPath } from "node:url" const TIMEOUT = 3_000 +const DISCOVERY_BUDGET = 4_000 const MAX_REPORT = 4_000 +const BUILD_INPUTS = "build inputs: " +const DIGEST_SCRIPT = fileURLToPath(new URL("../../utils/self_scan_digest.py", import.meta.url)) const FALLBACK = "Review findings relevant to your change; do not move complexity just to lower a score.\n" + "These are current file findings, not proof of an edit-caused regression. Keep the task-boundary gate." @@ -70,16 +74,110 @@ export function inside(root, file) { return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path) } -export async function analyzer(root) { - if (process.env.BCA) return process.env.BCA - const local = resolve(root, "target/release", process.platform === "win32" ? "bca.exe" : "bca") +async function executableFile(path) { try { - await access(local, constants.X_OK) - if ((await stat(local)).isFile()) return local + await access(path, constants.X_OK) + const info = await stat(path) + return info.isFile() ? { path, mtimeMs: info.mtimeMs, identity: await realpath(path) } : undefined } catch { - // This checkout has no executable release build; use the installed analyzer. + return undefined + } +} + +async function localBuilds(root) { + const name = process.platform === "win32" ? "bca.exe" : "bca" + const builds = await Promise.all(["debug", "release"].map((profile) => executableFile(resolve(root, "target", profile, name)))) + return builds.filter(Boolean) +} + +// The executable a bare `name` would spawn with `cwd` as the working +// directory: PATH entries are resolved against `cwd` — a relative entry, +// or an empty one, which `spawn` reads as the child's cwd — so the file +// probed here is the file the check later runs. +async function installed(name, cwd) { + const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""] + for (const directory of (process.env.PATH ?? "").split(delimiter)) { + for (const extension of extensions) { + const found = await executableFile(resolve(cwd, directory, name + extension)) + if (found) return found + } + } + return undefined +} + +async function probe(file, args, cwd, signal) { + const result = await run(file, args, cwd, signal) + if (!result.failed && result.code === 0) return { stdout: result.stdout } + const detail = result.stderr.split(/\r?\n/).map((line) => line.trim()).find(Boolean)?.slice(0, 200) + const status = Number.isInteger(result.code) ? `exited ${result.code}` : result.code ?? "signal" + return { failure: detail ? `${file} ${status}: ${detail}` : `${file} ${status}` } +} + +// Every failure of the digest step is a discovery failure, never a thrown +// error, so a check can lose at most the match step — never itself. +async function treeDigest(script, root, signal) { + let present + try { present = (await stat(script)).isFile() } catch (error) { return { failure: `digest script ${error.code ?? "unreadable"}` } } + if (!present) return { failure: "no digest script" } + const { stdout, failure } = await probe("python3", ["-B", script, root], root, signal) + .catch((error) => ({ failure: `python3 ${error.code ?? error.message}` })) + if (failure) return { failure } + const digest = stdout.split(/\r?\n/).map((line) => line.trim()).find((line) => /^[0-9a-f]{64}$/.test(line)) + return digest ? { digest } : { failure: "python3 printed no digest" } +} + +function reportedInputs(stdout) { + return stdout.split(/\r?\n/).find((line) => line.startsWith(BUILD_INPUTS))?.slice(BUILD_INPUTS.length).trim() +} + +// Order: `$BCA` unprobed; else the first of `target/debug/bca`, `target/release/bca` +// and PATH `bca` whose `--version` reports a `build inputs:` digest equal to the +// one `utils/self_scan_digest.py` computes over `root` — the same test +// `utils/self-scan-bca.py` applies, so the hook agrees with `make self-scan` +// (#1776); else the newest local build by mtime; else PATH `bca`. +// Probing executes each candidate, which is the trust level the old order already +// granted `target/release/bca` by running it unconditionally. The script is +// resolved relative to this module, never to `root`: `checkContext` can hand over +// a nested checkout, and that checkout must not supply the Python the parent's +// hook runs. `BCA_DIGEST_SCRIPT` is the tests' seam for that path, like +// `BCA_SELF_SCAN_WORKSPACE` in self-scan-bca.py. PATH `bca` is probed and +// returned as the resolved file, so the binary that answered `--version` is +// the one the check runs and the one the health line names. Discovery shares +// one budget so the check itself keeps room: the digest plus three probes at +// TIMEOUT each could otherwise spend more. The `checkout()` git call before +// this is not under the budget; its 3 s TIMEOUT plus this 4 s plus the +// check's 3 s is 10 s, which is why `.claude/settings.json` registers 15. +export async function analyzer(root, options = {}) { + if (process.env.BCA) return { path: process.env.BCA, reason: "BCA environment variable" } + const budget = new AbortController() + const expire = () => budget.abort() + const timer = setTimeout(expire, DISCOVERY_BUDGET) + options.signal?.addEventListener("abort", expire, { once: true }) + if (options.signal?.aborted) expire() + try { + const builds = await localBuilds(root) + const script = process.env.BCA_DIGEST_SCRIPT || DIGEST_SCRIPT + let { digest, failure } = await treeDigest(script, root, budget.signal) + if (digest) { + const candidates = builds.map((build) => build.path) + const onPath = await installed("bca", root) + if (onPath && !builds.some((build) => build.identity === onPath.identity)) candidates.push(onPath.path) + for (const candidate of candidates) { + if (budget.signal.aborted) break + const { stdout } = await probe(candidate, ["--version"], root, budget.signal) + if (stdout !== undefined && reportedInputs(stdout) === digest) { + return { path: candidate, reason: "build inputs match this tree" } + } + } + failure = budget.signal.aborted ? "discovery budget exhausted" : "no candidate reports this tree's build inputs" + } + const [newest] = builds.sort((a, b) => b.mtimeMs - a.mtimeMs) + if (newest) return { path: newest.path, reason: `newest local build (${failure})` } + return { path: "bca", reason: `PATH bca (no local build; ${failure})` } + } finally { + clearTimeout(timer) + options.signal?.removeEventListener("abort", expire) } - return "bca" } export async function checkout(directory) { diff --git a/.claude/settings.json b/.claude/settings.json index 2d70a75a8..0c4e830d7 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -8,7 +8,7 @@ "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/bca-check.mjs"], - "timeout": 10 + "timeout": 15 } ] } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a126d1db7..6bb0036d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -904,6 +904,16 @@ jobs: run: python3 utils/check-safety-doc-pin.py - name: check-safety-doc-pin self-tests (explicit) run: python3 -m unittest -q utils/check-safety-doc-pin-test.py + # Each vendored grammar build.rs carries a hand-maintained block + # that rerun-if-changed-watches src/tree_sitter/ (#1773); a + # regeneration does not restore it, and losing it leaves a stale + # parser object behind a fresh build-inputs digest. Its self-tests + # run as their own step for the usual reason: a source-scanning + # gate that stops matching reports a clean tree (#1778). + - name: check-grammar-build-watch (explicit) + run: python3 -B utils/check-grammar-build-watch.py + - name: check-grammar-build-watch self-tests (explicit) + run: python3 -B -m unittest -q utils/check-grammar-build-watch-test.py # Defensive twin for the grammar-marker-sync gate (#400): bumping # the notification-only marker in tree-sitter-{mozjs,mozcpp}/ # Cargo.toml without re-running the matching generate-*.sh diff --git a/.opencode/plugins/bca-check.js b/.opencode/plugins/bca-check.js index bb58a84e9..fd7d22c23 100644 --- a/.opencode/plugins/bca-check.js +++ b/.opencode/plugins/bca-check.js @@ -137,6 +137,13 @@ export default { const root = await checkout(directory) audit.root = root + // Per event, not per plugin load: a rebuild between events must be seen. + const analyzers = new Map() + const resolveAnalyzer = (checkoutRoot) => { + let resolved = analyzers.get(checkoutRoot) + if (!resolved) analyzers.set(checkoutRoot, resolved = analyzer(checkoutRoot, { signal: lifetime.signal })) + return resolved + } const pending = [] const selected = [...paths].slice(0, MAX_FILES) const omitted = paths.size - selected.length @@ -156,14 +163,15 @@ export default { } const context = await checkContext(directory, root, lexical, file) const { named, cwd } = context - const bca = await analyzer(context.root) + const { path: bca, reason } = await resolveAnalyzer(context.root) audit.analyzer = bca + audit.analyzerReason = reason audit.cwd = cwd - const binaryKey = JSON.stringify([context.root, bca]) + const binaryKey = JSON.stringify([context.root, bca, reason]) if (!binaries.has(binaryKey)) { if (binaries.size >= 256) binaries.clear() binaries.add(binaryKey) - console.info(`[bca-check] analyzer=${bca} cwd=${cwd}`) + console.info(`[bca-check] analyzer=${bca} cwd=${cwd} reason=${reason}`) } const state = fileState(file, lexical, version) if (!held.has(state)) state.users++ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index eee1ad296..adb3a1d09 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -587,6 +587,30 @@ repos: entry: python3 -m unittest -q utils/check-safety-doc-pin-test.py pass_filenames: false + # The five vendored grammar build scripts carry a hand-maintained + # block that rerun-if-changed-watches src/tree_sitter/ (#1773). + # A regeneration does not restore it, and losing it leaves a + # stale parser object behind a fresh build-inputs digest. Fires + # on the root manifest too, since that is where the crate list + # comes from, and on any crate whose name contains `tree-sitter`, + # which is the gate's own discovery rule (#1778). + - id: check-grammar-build-watch + name: check-grammar-build-watch + language: system + files: '^(Cargo\.toml|[^/]*tree-sitter[^/]*/bindings/rust/build\.rs|utils/check-grammar-build-watch\.py)$' + entry: python3 -B utils/check-grammar-build-watch.py + pass_filenames: false + + # Self-tests for the grammar-build-watch gate, for the same reason + # as the pairs above: a source-scanning gate that stops matching + # reports a clean tree. + - id: check-grammar-build-watch-test + name: check-grammar-build-watch-test + language: system + files: '^utils/check-grammar-build-watch(-test)?\.py$' + entry: python3 -B -m unittest -q utils/check-grammar-build-watch-test.py + pass_filenames: false + # The `enums/` crate is workspace-excluded, so the workspace # clippy/test hooks above never touch it. Add a dedicated check # so warnings here cannot drift (see #164). diff --git a/AGENTS.md b/AGENTS.md index 467bc0656..b53df3289 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,6 +81,7 @@ and `cargo run -p big-code-analysis-web --`. `check-snapshot-anchors.py`, `check-rustfmt-bail.py`, `check-manpage-assets.py`, `check-manpage-drift.py`, `check-diagnostic-prefix.py`, `check-safety-doc-pin.py`, + `check-grammar-build-watch.py`, `check-grammar-marker-sync.py`, `check-enums-codegen-drift.sh`, `check-grammar-crate.py`, `check-grammars-crates.sh`, `check-excluded-manifests.py`, `check-ruff-lockstep.py`, @@ -304,10 +305,14 @@ and `cargo run -p big-code-analysis-web --`. `lints.workspace = true`. A **workspace-excluded** crate roots its own workspace and inherits nothing, so it needs its own copy of those tables; `enums` carries one, and the five vendored `tree-sitter-*` - crates are exempt by decision (generated binding boilerplate that a - regeneration replaces wholesale). `utils/check-excluded-manifests.py` - gates this — without it a crate gated at `-D warnings` is measured - against the compiler defaults and still reads as fully linted (#1228). + crates are exempt by decision, because a regeneration replaces their + generated sources wholesale — with one exception, + `bindings/rust/build.rs`, which carries a hand-maintained + `src/tree_sitter/` header watch (#1773) that no regeneration + restores and that `make check-grammar-build-watch` gates (#1778). + `utils/check-excluded-manifests.py` gates the lint tables — without + it a crate gated at `-D warnings` is measured against the compiler + defaults and still reads as fully linted (#1228). Additional `allow`s go at file or function level, so the carve-out stays visible at the affected site. @@ -354,7 +359,12 @@ the safety-doc pin gate version cited by the `unsafe` soundness argument in `big-code-analysis-py/src/node.rs` is not the version `[workspace.dependencies]` pins, or when the citation is dropped -altogether — #1057), the bca self-scan threshold gate at both +altogether — #1057), the grammar build-watch gate +(`make check-grammar-build-watch`, which fails when the +`bindings/rust/build.rs` of any `[workspace].exclude` entry naming +`tree-sitter` no longer carries the hand-maintained `src/tree_sitter/` +header watch verbatim, or is missing outright — #1778), the bca +self-scan threshold gate at both tiers (`make self-scan` mirroring the `Threshold gate` step in `.github/workflows/pages.yml`, plus `make self-scan-headroom` which scales every limit by `BCA_HEADROOM` — default `0.95` — so @@ -932,7 +942,14 @@ Three things to know before quoting a number at anyone: This repo dogfoods its own analyzer: a `bca check` threshold violation may surface mid-edit (via the Claude Code `PostToolUse` hook in `.claude/hooks/bca-check.mjs`, enabled by `.claude/settings.json`) or at -the task boundary (`make self-scan`, `make pre-commit`). A violation (cognitive, cyclomatic, ABC, …) means +the task boundary (`make self-scan`, `make pre-commit`). The hook runs +`$BCA` if set; otherwise the candidate — `target/debug/bca`, +`target/release/bca`, then PATH `bca` — whose `build inputs:` digest +matches the tree, the same test `utils/self-scan-bca.py` applies, so it +agrees with `make self-scan`; with no match it takes the newest local +build, then PATH `bca`, and names its choice and why in the +`[bca-check]` health line (#1776). +A violation (cognitive, cyclomatic, ABC, …) means *this function is hard for a human to follow* — the number is a proxy for that, not the goal. Make the code genuinely simpler, not the number smaller. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bc8800f7..6d8b33084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,26 @@ for historical reference. ### Added +- **`bca --version` reads the Mach-O and PE build ids** (#1777). `build + id:` was `unavailable` off Linux because only the ELF reader existed; + two bounded readers now sit beside it — the 16-byte `LC_UUID` of a + thin 64-bit Mach-O, and the `CodeView` `RSDS` GUID plus age of a PE32 + or PE32+ image, fetched with a second bounded read since the debug + directory routinely sits past the 64 KiB head. Each is checked + arithmetic, `get`-bounded reads and fail-closed `None`, with synthetic + fixtures for every malformed shape; a universal (FAT) Mach-O and a PE + without a `CodeView` entry read `unavailable`. The ELF reader now also + refuses an `e_phentsize` below 56, which let one `PT_NOTE` be walked + `phnum` times. +- **`make check-grammar-build-watch`** (`utils/check-grammar-build-watch.py`, + #1778): fails when the `bindings/rust/build.rs` of any + `[workspace].exclude` entry naming `tree-sitter` no longer carries, + token for token, the hand-maintained `src/tree_sitter/` header watch + #1773 added, or is missing outright — the block no regeneration + restores, and whose loss leaves a stale parser object behind a fresh + `build inputs:` digest. Wired into `make lint`, `make pre-commit`, + `make ci`, the pre-commit hooks and CI, with its own self-test. + - **`bca --version` records build provenance** (#1773). `-V` is the unchanged one-line `bca `; `--version` follows it with `build inputs:` (a SHA-256 content digest of every source compiled @@ -36,7 +56,12 @@ for historical reference. on a bare commit would cost the rebuild #1773 removes), `built:` (RFC 3339 UTC, honouring `SOURCE_DATE_EPOCH`, with the profile, `rustc`, target and debug-assertions state) and - `build id:` (the linker's GNU build-id on Linux). Two builds of one + `build id:` (the identifier the linker stamped into the executable, + read back at run time: the GNU build-id note on Linux, the `LC_UUID` + of a thin 64-bit Mach-O on macOS, and the `CodeView` GUID plus age on + Windows — each only when the linker emitted it; lowercase hex of the + raw bytes, `unavailable` for a universal Mach-O or any other shape, + #1777). Two builds of one tree share a digest whatever their mtimes or branch, and two binaries that both print `2.4.0` from different commits do not — which is the question "is this installed `bca` the one this checkout @@ -747,6 +772,21 @@ for historical reference. repository's Rust and the `serde` corpus); the new `nom/deep-one-attribute-items` scaling probe reads 2.00 before and 1.08 after. +- **The agent hooks run the analyzer whose build inputs match the + tree** (#1776). Since #1773 nothing in the ordinary workflow builds + release, so the `target/release/bca` the Claude Code hook and the + OpenCode plugin preferred was routinely a stale binary and the + per-edit advisory reported offenders a different `bca` computed than + `make self-scan`. `analyzer()` now takes `$BCA` unprobed; else the + first of `target/debug/bca`, `target/release/bca` and PATH `bca` whose + `--version` `build inputs:` equals the digest `utils/self_scan_digest.py` + computes over the checkout — the test the self-scan applies; else the + newest local build; else PATH `bca`. The `[bca-check]` health line + names the choice and why. Discovery shares one 4 s budget under the + hook's signal, the digest script is resolved from the hook module + rather than a nested checkout, and the plugin resolves once per + checkout root per event. + - `utils/check-role-coverage.py`: the "no baseline section" error named `--report` as the way to list a new language's residue entries, but `--report` prints only per-language counts; it now names diff --git a/Makefile b/Makefile index 3cf1b5589..877e9850d 100644 --- a/Makefile +++ b/Makefile @@ -88,7 +88,7 @@ find-by-ext = $(if $(FD),$(FD) --extension $(1) $(FD_EXCLUDE) $(2),find . -name NEXTEST := $(shell command -v cargo-nextest 2>/dev/null) TEST_CMD = $(if $(NEXTEST),$(NEXTEST) nextest run --workspace --all-features,cargo test --workspace --all-features --lib --bins --tests) -.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest +.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test check-grammar-build-watch check-grammar-build-watch-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest .PHONY: plugin-test _pc-plugin-test _ci-plugin-test @@ -172,6 +172,8 @@ help: @echo " check-test-lang-gates-test Self-tests for the test-language gate" @echo " check-safety-doc-pin Assert node.rs's unsafe soundness doc cites the live tree-sitter pin" @echo " check-safety-doc-pin-test Self-tests for the safety-doc-pin gate" + @echo " check-grammar-build-watch Assert every vendored grammar build.rs watches src/tree_sitter/ headers" + @echo " check-grammar-build-watch-test Self-tests for the grammar-build-watch gate" @echo " worktree-setup-test Self-tests for the worktree-setup submodule classifier" @echo " gate-status-test Self-tests for the pre-commit/ci BCA_GATE verdict line" @echo " check-tools-test Self-tests for the check-tools tool probes and hints" @@ -832,6 +834,22 @@ check-safety-doc-pin-test: @echo "Running check-safety-doc-pin self-tests..." @(cd $(BASE_DIR) && python3 -m unittest -q utils/check-safety-doc-pin-test.py) +# The five vendored grammar build scripts carry a hand-maintained block +# that rerun-if-changed-watches src/tree_sitter/ (#1773); a regeneration +# does not restore it, and losing it leaves a stale parser object behind +# a fresh build-inputs digest. The crate list comes from the root +# manifest's [workspace].exclude. Static lint - no network, no cargo. +check-grammar-build-watch: + @echo "Checking the vendored grammar build scripts' header watch..." + @python3 -B $(BASE_DIR)utils/check-grammar-build-watch.py + +# Self-tests for the grammar-build-watch gate, for the same reason as +# the other gate self-tests: a source-scanning gate that stops matching +# reports a clean tree. +check-grammar-build-watch-test: + @echo "Running check-grammar-build-watch self-tests..." + @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/check-grammar-build-watch-test.py) + plugin-test: @if command -v node >/dev/null 2>&1 && node -e 'const [a,b] = process.versions.node.split(".").map(Number); process.exit(a > 22 || (a === 22 && b >= 7) ? 0 : 1)'; then \ node --test "$(BASE_DIR)utils/bca-check-plugin-test.mjs" "$(BASE_DIR)utils/bca-claude-hook-test.mjs"; \ @@ -1628,7 +1646,7 @@ lint: $(MAKE) -j --output-sync=target \ _ci-clippy _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test # --------------------------------------------------------------------------- # Maintenance @@ -1815,7 +1833,7 @@ _pc-all: $(MAKE) -j --output-sync=target \ _pc-test _pc-plugin-test \ _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check \ - _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ + _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ _pc-manpages \ _pc-self-scan _pc-self-scan-headroom \ _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest @@ -1825,7 +1843,7 @@ _ci-all: $(MAKE) -j --output-sync=target \ _ci-cargo-pipeline _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest # --------------------------------------------------------------------------- @@ -1884,6 +1902,8 @@ _ci-all: # ├── _pc-check-safety-doc-pin # ├── _pc-check-feature-gates-test # ├── _pc-check-safety-doc-pin-test +# ├── _pc-check-grammar-build-watch +# ├── _pc-check-grammar-build-watch-test # ├── _pc-worktree-setup-test # ├── _pc-gate-status-test # ├── _pc-check-tools-test @@ -2077,6 +2097,12 @@ _pc-check-test-lang-gates-test: _pc-fmt _pc-check-safety-doc-pin-test: _pc-fmt $(MAKE) check-safety-doc-pin-test +_pc-check-grammar-build-watch: _pc-fmt + $(MAKE) check-grammar-build-watch + +_pc-check-grammar-build-watch-test: _pc-fmt + $(MAKE) check-grammar-build-watch-test + _pc-worktree-setup-test: _pc-fmt $(MAKE) worktree-setup-test @@ -2339,6 +2365,12 @@ _ci-check-test-lang-gates-test: _ci-check-safety-doc-pin-test: $(MAKE) check-safety-doc-pin-test +_ci-check-grammar-build-watch: + $(MAKE) check-grammar-build-watch + +_ci-check-grammar-build-watch-test: + $(MAKE) check-grammar-build-watch-test + _ci-worktree-setup-test: $(MAKE) worktree-setup-test diff --git a/STABILITY.md b/STABILITY.md index c28aa70a8..258f3c370 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -691,8 +691,20 @@ compiled into the binary, or `unavailable` for a build from the crates.io tarball, where the workspace is not beside the crate), `git:`, `built:` (RFC 3339 UTC, `SOURCE_DATE_EPOCH` when it was set at build time, with the profile, `rustc` version, target and -debug-assertions state) and `build id:` (the linker's GNU build-id -note on Linux; `unavailable` elsewhere). The first line is the stable +debug-assertions state) and `build id:` (the identifier the linker +stamped into the executable, read back from it at run time: the GNU +build-id note on Linux, the `LC_UUID` of a thin 64-bit Mach-O on +macOS, and the `CodeView` record that pairs a PE with its `.pdb` on +Windows — each only when the linker emitted it; `ld64` does so by +default and omits it under `-no_uuid`). The id is the lowercase hex of the raw +bytes, and its length is the format's — the ELF note's descriptor +(whatever the linker wrote: 20 bytes for GNU `ld --build-id`'s SHA-1 +and for `lld` 19+, 8 for older `lld`'s `fast` hash), the 16-byte UUID, +or the PE record's 16-byte GUID as stored plus its 4-byte age, which +is not the byte-swapped spelling `dumpbin` prints. A universal (FAT) +Mach-O, a Mach-O linked with `-no_uuid`, a PE without a `CodeView` +entry, an ELF linked without `--build-id`, and any other format read +`unavailable`. The first line is the stable contract, and so is one thing about the second: a line beginning `build inputs:` followed by a space and either 64 lowercase hex digits or the word `unavailable`, which is what `utils/self-scan-bca.py` — diff --git a/big-code-analysis-book/src/recipes/agent-feedback.md b/big-code-analysis-book/src/recipes/agent-feedback.md index 2b6b4e2af..3df8ee734 100644 --- a/big-code-analysis-book/src/recipes/agent-feedback.md +++ b/big-code-analysis-book/src/recipes/agent-feedback.md @@ -142,7 +142,7 @@ existing settings: "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/bca-check.mjs"], - "timeout": 10 + "timeout": 15 } ] } @@ -170,10 +170,19 @@ How the hook finds its configuration and analyzer: - `CLAUDE_PROJECT_DIR` locates the script, but stays at the original project when Claude enters a worktree. Using it to select the analyzer configuration would check the wrong tree. -- Select `$BCA` first, then the current checkout's executable - `target/release/bca` (`bca.exe` on Windows), then `bca` on `PATH`. - An explicit but unavailable `$BCA` stays unavailable rather than - falling back to another binary. +- Select `$BCA` first, unprobed. Otherwise run `--version` on the + checkout's `target/debug/bca`, `target/release/bca` (`bca.exe` on + Windows) and `bca` on `PATH`, and take the first whose + `build inputs:` digest equals the one `utils/self_scan_digest.py` + computes over the checkout — the same matching criterion `make + self-scan` applies, so a build that satisfies one satisfies the + other (they can still pick different matching files, since the + self-scan prefers a matching `PATH` binary). When none matches, take the + newest local build by modification time, then `bca` on `PATH`. A + copy of the hook without `utils/self_scan_digest.py` beside it + skips the digest step and degrades to that order. An explicit but + unavailable `$BCA` stays unavailable rather than falling back to + another binary. - Within one checkout, the session's manifest also applies when it edits a sibling package. Change the session directory to select that package's own manifest. @@ -212,8 +221,9 @@ no advisory. In `[bca-check]` JSON records distinguish findings, clean/excluded files, out-of-scope paths, superseded results, and unavailable checks. These records go to stderr with exit 0, so Claude does not receive them as -additional context. They record the checkout, analyzer, outcome, and -up to 1,000 characters of analyzer stderr for troubleshooting. +additional context. They record the checkout, the analyzer and why it was chosen +(`analyzerReason`), the outcome, and up to 1,000 characters of +analyzer stderr for troubleshooting. Offender rows remain in the advisory; CI annotations and summary-file side effects are disabled. The reference suite runs with `make plugin-test`, including the shared OpenCode helper regressions. @@ -328,10 +338,14 @@ setup: - **Repo-scope guard.** Resolve the path and skip anything outside the project root, so the hook never runs `bca` on a file the agent edits elsewhere on disk. -- **Local-build resolution.** Prefer `$BCA`, then a - `target/release/bca` in the checkout, then `bca` on `PATH`. A project - that builds `bca` itself then gates against its own analyzer instead - of whatever is installed globally. +- **Local-build resolution.** Prefer `$BCA`; then the candidate among + the checkout's `target/debug/bca`, `target/release/bca` and `bca` on + `PATH` whose `build inputs:` digest matches the checkout; then the + newest local build; then `bca` on `PATH`. A project that builds + `bca` itself then gates against a binary built from the tree it is + editing whenever one exists, rather than a stale one or whatever is + installed globally; with no match it falls back to the newest build + it can find. - **Shared guidance.** Read the guidance text from one file that both this plugin and the Claude Code hook cite, so the two never drift. diff --git a/big-code-analysis-cli/src/build_info/build_id/build_id_tests.rs b/big-code-analysis-cli/src/build_info/build_id/build_id_tests.rs new file mode 100644 index 000000000..2c88c2041 --- /dev/null +++ b/big-code-analysis-cli/src/build_info/build_id/build_id_tests.rs @@ -0,0 +1,929 @@ +use super::elf::build_id; +use super::{HEAD_BYTES, current_build_id, hex_lower, read_at, read_head}; +use super::{macho, pe}; + +/// `read_at` is the one I/O primitive every reader shares: it is short +/// at end of file rather than an error, and `read_head` is the same +/// call capped at `HEAD_BYTES`. Both are exercised here directly so the +/// test build on a platform with no reader of its own still has a +/// caller for them. +#[test] +fn read_at_is_short_at_end_of_file_and_read_head_is_capped() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("exe"); + let mut bytes: Vec = (0..=255u8).cycle().take(HEAD_BYTES + 7).collect(); + std::fs::write(&path, &bytes).expect("write"); + assert_eq!(read_at(&path, 3, 4).as_deref(), Some(&bytes[3..7])); + assert_eq!( + read_at(&path, HEAD_BYTES as u64, 100).as_deref(), + Some(&bytes[HEAD_BYTES..]), + "a read past the end is short, not an error" + ); + // An offset past the end seeks fine and reads nothing: `Some` of no + // bytes, which `read_exact` then rejects. The test double `staged` + // below models exactly this. + assert_eq!(read_at(&path, bytes.len() as u64 + 100, 4), Some(vec![])); + // Whether a seek to `u64::MAX` fails (Linux: `EINVAL`) or succeeds and + // reads nothing is the platform's choice; no bytes come back either way. + assert!(read_at(&path, u64::MAX, 1).is_none_or(|b| b.is_empty())); + assert_eq!(read_head(&path).as_deref(), Some(&bytes[..HEAD_BYTES])); + bytes.truncate(10); + std::fs::write(&path, &bytes).expect("write"); + assert_eq!(read_head(&path).as_deref(), Some(&bytes[..])); + assert_eq!(read_at(&dir.path().join("absent"), 0, 1), None); +} + +/// Linux permits opening and seeking a directory, but reading it fails. +/// Unlike the missing-file row, this reaches `read_to_end`'s error path. +/// Discarding that read error makes this test the only failure. +#[cfg(target_os = "linux")] +#[test] +fn read_at_rejects_an_openable_path_that_cannot_be_read() { + use std::io::{Read as _, Seek as _, SeekFrom}; + + let dir = tempfile::tempdir().expect("tempdir"); + let mut file = std::fs::File::open(dir.path()).expect("opening a directory succeeds"); + file.seek(SeekFrom::Start(0)) + .expect("seeking a directory succeeds"); + assert!(file.read(&mut [0u8; 1]).is_err()); + assert_eq!(read_at(dir.path(), 0, 1), None); +} + +#[test] +fn hex_lower_renders_two_digits_per_byte() { + assert_eq!(hex_lower(&[]), ""); + assert_eq!(hex_lower(&[0x00, 0x0f, 0xf0, 0xff]), "000ff0ff"); +} + +/// A minimal little-endian ELF64 image: header, one program header of +/// `kind`, and a note segment built from `notes`. +fn elf64(kind: u32, notes: &[u8]) -> Vec { + let mut out = vec![0u8; 0x40]; + out[..4].copy_from_slice(b"\x7fELF"); + out[4] = 2; + out[5] = 1; + out[0x20..0x28].copy_from_slice(&0x40u64.to_le_bytes()); + out[0x36..0x38].copy_from_slice(&0x38u16.to_le_bytes()); + out[0x38..0x3a].copy_from_slice(&1u16.to_le_bytes()); + let seg_at = 0x40u64 + 0x38; + let mut ph = vec![0u8; 0x38]; + ph[..4].copy_from_slice(&kind.to_le_bytes()); + ph[0x08..0x10].copy_from_slice(&seg_at.to_le_bytes()); + ph[0x20..0x28].copy_from_slice(&(notes.len() as u64).to_le_bytes()); + out.extend(ph); + out.extend_from_slice(notes); + out +} + +fn note(name: &[u8], kind: u32, desc: &[u8]) -> Vec { + let len = |s: &[u8]| u32::try_from(s.len()).expect("fixture notes are tiny"); + let mut out = Vec::new(); + out.extend(len(name).to_le_bytes()); + out.extend(len(desc).to_le_bytes()); + out.extend(kind.to_le_bytes()); + out.extend(name); + out.resize(out.len().next_multiple_of(4), 0); + out.extend(desc); + out.resize(out.len().next_multiple_of(4), 0); + out +} + +#[test] +fn build_id_is_read_past_an_unrelated_note_and_hex_rendered() { + let id = [0xde, 0xad, 0xbe, 0xef, 0x01]; + let mut notes = note(b"GNU\0", 1, b"\0\0\0\0\x03\0\0\0\x02\0\0\0\0\0\0\0"); + notes.extend(note(b"GNU\0", 3, &id)); + let image = elf64(4, ¬es); + assert_eq!(build_id(&image), Some(&id[..])); + assert_eq!( + build_id(&image).map(hex_lower).as_deref(), + Some("deadbeef01") + ); +} + +#[test] +fn build_id_is_none_for_every_shape_the_reader_does_not_support() { + let id = [1u8, 2, 3]; + let good = elf64(4, ¬e(b"GNU\0", 3, &id)); + assert_eq!( + build_id(&good), + Some(&id[..]), + "the fixture itself must parse" + ); + + let mut wrong_magic = good.clone(); + wrong_magic[0] = 0; + assert_eq!(build_id(&wrong_magic), None, "wrong magic"); + + let mut elf32 = good.clone(); + elf32[4] = 1; + assert_eq!(build_id(&elf32), None, "ELF32"); + + let mut big_endian = good.clone(); + big_endian[5] = 2; + assert_eq!(build_id(&big_endian), None, "big-endian"); + + assert_eq!(build_id(&good[..0x30]), None, "truncated header"); + assert_eq!(build_id(&good[..0x50]), None, "truncated program header"); + assert_eq!( + build_id(&elf64(1, ¬e(b"GNU\0", 3, &id))), + None, + "not a PT_NOTE segment" + ); + assert_eq!( + build_id(&elf64(4, ¬e(b"XYZ\0", 3, &id))), + None, + "not the GNU note" + ); + assert_eq!( + build_id(&elf64(4, ¬e(b"GNU\0", 7, &id))), + None, + "not NT_GNU_BUILD_ID" + ); + + // Every prefix of a valid image must read as absent, not panic and + // not misparse. This walks each `?` in the header and program-header + // readers; it never reaches the note reader, because the shortened + // image keeps the program header's declared segment size and the + // segment slice fails first. + for cut in 0..good.len() { + assert_eq!(build_id(&good[..cut]), None, "truncated at byte {cut}"); + } + // The note reader's own short reads need a segment whose *declared* + // size is honest: 4 bytes reach `descsz`'s read, 8 reach `kind`'s, + // 12 reach the name's. These execute each read's `None` arm; they + // cannot tell a failed read from an infallible one, because the + // next read fails the same way and no id can come out of a note + // that short — the outcome, not the mechanism, is what is pinned. + for short in [&[0u8; 4][..], &[0u8; 8], &[0u8; 12]] { + assert_eq!( + build_id(&elf64(4, short)), + None, + "{}-byte note segment", + short.len() + ); + } + + let mut overflow = good.clone(); + overflow[0x40 + 0x20..0x40 + 0x28].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(build_id(&overflow), None, "segment size past the end"); + let mut far_offset = good.clone(); + far_offset[0x40 + 0x08..0x40 + 0x10].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(build_id(&far_offset), None, "segment offset past the end"); + + let mut more_headers_than_exist = good.clone(); + more_headers_than_exist[0x38..0x3a].copy_from_slice(&7u16.to_le_bytes()); + assert_eq!( + build_id(&more_headers_than_exist), + Some(&id[..]), + "a phnum past the table still finds the note in the headers present" + ); + + // `phentsize` below ELF64's 56 makes every index alias one header, so + // a single `PT_NOTE` would be walked `phnum` times; the reader refuses + // it (and so does `readelf`). Fails if the `< PHENTSIZE` guard is + // removed: index 0 still reads the real header and finds the id. + let mut zero_phentsize = good.clone(); + zero_phentsize[0x36..0x38].copy_from_slice(&0u16.to_le_bytes()); + assert_eq!(build_id(&zero_phentsize), None, "phentsize 0"); + let mut short_phentsize = good.clone(); + short_phentsize[0x36..0x38].copy_from_slice(&0x37u16.to_le_bytes()); + assert_eq!(build_id(&short_phentsize), None, "phentsize 55"); + + let mut huge_phoff = good.clone(); + huge_phoff[0x20..0x28].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!( + build_id(&huge_phoff), + None, + "program-header offset past the end" + ); + + // A name length that overruns the segment: the note walk fails + // closed. (A clamped slice would fail closed too — the name would + // not compare equal — so this pins the outcome, not the mechanism; + // the bounded-read spelling is the module's safety argument.) + let mut lying_namesz = good; + let note_at = 0x40 + 0x38; + lying_namesz[note_at..note_at + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); + assert_eq!(build_id(&lying_namesz), None, "namesz past the segment"); + + // A descriptor length that overruns: same, on the other field. + let mut lying_descsz = elf64(4, ¬e(b"GNU\0", 3, &id)); + lying_descsz[note_at + 4..note_at + 8].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); + assert_eq!(build_id(&lying_descsz), None, "descsz past the segment"); +} + +/// The first program-header lookup is out of bounds; advancing to the +/// second would overflow a 64-bit offset. Both must fail without panicking. +/// Replacing the checked offset sum with plain addition fails this test. +#[test] +fn elf_program_header_offsets_cannot_wrap() { + let mut image = elf64(4, ¬e(b"GNU\0", 3, &[1, 2, 3])); + image[0x20..0x28].copy_from_slice(&(u64::MAX - 0x10).to_le_bytes()); + image[0x38..0x3a].copy_from_slice(&2u16.to_le_bytes()); + assert_eq!(build_id(&image), None); +} + +/// A capability probe, not a contract: the linker on this host is what +/// decides whether the test binary carries an id at all. When it does, +/// the reader must find it and render it as lowercase hex — never a +/// fixed length, since each format's id has its own; when it does not, +/// `unavailable` is the documented answer. +/// On Linux the dispatcher must reach the ELF reader: the answer for the +/// running executable equals what `elf::build_id` reads from its head. +/// Vacuously true on a host whose linker emitted no note (both `None`), +/// and the one test that fails if `current_build_id` is routed to +/// another reader — the capability probe below cannot tell. +#[cfg(target_os = "linux")] +#[test] +fn linux_dispatch_reaches_the_elf_reader() { + let exe = std::env::current_exe().expect("current_exe"); + let expected = read_head(&exe).and_then(|head| build_id(&head).map(hex_lower)); + assert_eq!(current_build_id(), expected); +} + +#[test] +fn running_executable_yields_hex_or_nothing() { + match current_build_id() { + Some(id) => assert!( + !id.is_empty() && id.bytes().all(|b| b.is_ascii_hexdigit()), + "{id}" + ), + None => eprintln!("no build id in the test binary on this host"), + } +} + +// ---------------------------------------------------------------- Mach-O + +const UUID: [u8; 16] = [ + 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, +]; + +fn load_command(cmd: u32, body: &[u8]) -> Vec { + let mut out = cmd.to_le_bytes().to_vec(); + out.extend((8 + u32::try_from(body.len()).expect("fixture commands are tiny")).to_le_bytes()); + out.extend(body); + out +} + +/// A minimal thin little-endian Mach-O 64 image carrying `commands`. +fn macho64(magic: u32, ncmds: u32, commands: &[u8]) -> Vec { + let mut out = vec![0u8; 32]; + out[..4].copy_from_slice(&magic.to_le_bytes()); + out[16..20].copy_from_slice(&ncmds.to_le_bytes()); + out[20..24].copy_from_slice(&u32::try_from(commands.len()).expect("tiny").to_le_bytes()); + out.extend_from_slice(commands); + out +} + +/// Fails if `LC_UUID` is matched by position rather than by `cmd` +/// (the segment command comes first), or if the walk stops at the first +/// command (`at = next` dropped). +#[test] +fn macho_uuid_is_read_past_an_unrelated_load_command_and_hex_rendered() { + let mut commands = load_command(0x19, &[0u8; 64]); + commands.extend(load_command(0x1b, &UUID)); + let image = macho64(0xfeed_facf, 2, &commands); + assert_eq!(macho::build_id(&image), Some(&UUID[..])); + assert_eq!( + macho::build_id(&image).map(hex_lower).as_deref(), + Some("0123456789abcdeffedcba9876543210") + ); +} + +/// Each row names the production guard it exercises; removing that guard +/// turns the row's `None` into `Some`. The `cmdsize 0` and `cmdsize 4` +/// rows are the exception: no guard answers them — the inverted body +/// range does — so they pin the outcome (the walk terminates, with +/// `ncmds = u32::MAX` on offer, and yields `None`) rather than a line. +/// A reader that clamped the range and advanced by the 8-byte header +/// would pass both rows; the image's own end bounds it. +#[test] +fn macho_build_id_is_none_for_every_shape_the_reader_does_not_support() { + let good = macho64(0xfeed_facf, 1, &load_command(0x1b, &UUID)); + assert_eq!( + macho::build_id(&good), + Some(&UUID[..]), + "the fixture itself must parse" + ); + + assert_eq!( + macho::build_id(&macho64(0xfeed_face, 1, &load_command(0x1b, &UUID))), + None, + "MH_MAGIC (32-bit)" + ); + assert_eq!( + macho::build_id(&macho64(0xcffa_edfe, 1, &load_command(0x1b, &UUID))), + None, + "MH_CIGAM_64 (byte-swapped)" + ); + assert_eq!( + macho::build_id(&macho64(0xbeba_feca, 1, &load_command(0x1b, &UUID))), + None, + "FAT_MAGIC (universal)" + ); + assert_eq!( + macho::build_id(&macho64(0, 1, &load_command(0x1b, &UUID))), + None, + "wrong magic" + ); + + for cut in 0..good.len() { + assert_eq!( + macho::build_id(&good[..cut]), + None, + "truncated at byte {cut}" + ); + } + + // `ncmds` past the table: the walk runs off the end of the image + // (nothing follows the one command, so the bounded read, not the + // `sizeofcmds` bound, is what stops it — `past_sizeofcmds` below is + // the row for that bound) and fails closed. + let mut more_commands_than_exist = good.clone(); + more_commands_than_exist[16..20].copy_from_slice(&3u32.to_le_bytes()); + assert_eq!( + macho::build_id(&more_commands_than_exist), + Some(&UUID[..]), + "the id is found before the table runs out" + ); + assert_eq!( + macho::build_id(&macho64(0xfeed_facf, 3, &load_command(0x19, &[0u8; 8]))), + None, + "ncmds past the table, no id" + ); + + // `cmdsize` of 0 must terminate: the body read's inverted range is + // what stops the walk, and `u32::MAX` commands would otherwise spin. + let mut zero_cmdsize = macho64(0xfeed_facf, u32::MAX, &load_command(0x19, &[0u8; 8])); + zero_cmdsize[36..40].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(macho::build_id(&zero_cmdsize), None, "cmdsize 0"); + let mut short_cmdsize = good.clone(); + short_cmdsize[36..40].copy_from_slice(&4u32.to_le_bytes()); + assert_eq!(macho::build_id(&short_cmdsize), None, "cmdsize 4"); + + // `LC_UUID` with a size other than 24 is malformed, not a shorter id. + assert_eq!( + macho::build_id(&macho64(0xfeed_facf, 1, &load_command(0x1b, &[0u8; 24]))), + None, + "LC_UUID with cmdsize 32" + ); + let truncated_uuid = macho64(0xfeed_facf, 1, &load_command(0x1b, &UUID[..8])); + assert_eq!( + macho::build_id(&truncated_uuid), + None, + "LC_UUID with cmdsize 16" + ); + + // A valid `LC_UUID` that lies past the declared `sizeofcmds` is not + // the image's id: the walk stops at the declared end even though the + // bytes are present. Fails if the `next > end` bound is removed — + // the second turn then reads the UUID and returns it. + let mut past_sizeofcmds = macho64(0xfeed_facf, 2, &load_command(0x19, &[0u8; 8])); + past_sizeofcmds.extend(load_command(0x1b, &UUID)); + assert_eq!( + macho::build_id(&past_sizeofcmds), + None, + "LC_UUID past sizeofcmds" + ); + + assert_eq!( + macho::build_id(&macho64(0xfeed_facf, 0, &[])), + None, + "no load commands" + ); +} + +// -------------------------------------------------------------------- PE + +const GUID_AND_AGE: [u8; 20] = [ + 0xa0, 0xa1, 0xa2, 0xa3, 0xb0, 0xb1, 0xc0, 0xc1, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0x07, 0x00, 0x00, 0x00, +]; + +/// One `IMAGE_DEBUG_DIRECTORY` entry of `kind` whose record of `size` +/// bytes sits at file offset `at`. +fn debug_entry(kind: u32, size: u32, at: u32) -> Vec { + let mut out = vec![0u8; 28]; + out[12..16].copy_from_slice(&kind.to_le_bytes()); + out[16..20].copy_from_slice(&size.to_le_bytes()); + out[24..28].copy_from_slice(&at.to_le_bytes()); + out +} + +fn rsds(signature: [u8; 4]) -> Vec { + let mut out = signature.to_vec(); + out.extend(GUID_AND_AGE); + out +} + +struct PeLayout { + plus: bool, + /// `SizeOfOptionalHeader` to declare; `None` is the real size. + optional_len: Option, + /// Where the debug directory sits in the file. Its RVA is this plus + /// `va_shift`: the section's `VirtualAddress` is its `PointerToRawData` + /// plus the shift, and an unrelated section precedes it in the table + /// when the shift is non-zero, so the RVA walk must both pick the + /// right section and translate within it. + directory_at: u32, + va_shift: u32, + directory: Vec, + /// `(file offset, record)` pairs appended after the directory. + records: Vec<(u32, Vec)>, +} + +/// A PE image: DOS stub, `PE\0\0`, COFF header, optional header (PE32 or +/// PE32+), one section whose raw data covers `directory_at ..` the end +/// of the file, then the debug directory and the records at the offsets +/// they name. Everything before the section data stays inside 64 KiB; +/// the directory and records sit wherever `directory_at` says. +fn pe(layout: &PeLayout) -> Vec { + let optional_len: u16 = layout + .optional_len + .unwrap_or(if layout.plus { 240 } else { 224 }); + let mut out = vec![0u8; 0x40]; + out[..2].copy_from_slice(b"MZ"); + out[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); + out.resize(0x80, 0); + out.extend_from_slice(b"PE\0\0"); + let section_count: u16 = if layout.va_shift == 0 { 1 } else { 2 }; + let mut coff = vec![0u8; 20]; + coff[2..4].copy_from_slice(§ion_count.to_le_bytes()); + coff[16..18].copy_from_slice(&optional_len.to_le_bytes()); + out.extend(coff); + let mut optional = vec![0u8; if layout.plus { 240 } else { 224 }]; + let (magic, count_at, table_at) = if layout.plus { + (0x20bu16, 108, 112) + } else { + (0x10b, 92, 96) + }; + optional[..2].copy_from_slice(&magic.to_le_bytes()); + optional[count_at..count_at + 4].copy_from_slice(&16u32.to_le_bytes()); + let debug = table_at + 6 * 8; + optional[debug..debug + 4] + .copy_from_slice(&(layout.directory_at + layout.va_shift).to_le_bytes()); + optional[debug + 4..debug + 8].copy_from_slice( + &u32::try_from(layout.directory.len()) + .expect("tiny") + .to_le_bytes(), + ); + // The declared length decides where the section table starts. A + // short declaration writes the section header into the optional + // header's own bytes and then lays the rest of the real optional + // header (the data directories) behind it, so entry 6 keeps the + // file offset the reader computes for it and is reachable from the + // slice — only the declared bound says it is not the header's. + let declared = usize::from(optional_len); + out.extend(&optional[..declared]); + let tail = optional[declared..].to_vec(); + let file_end = layout + .records + .iter() + .map(|(at, record)| at + u32::try_from(record.len()).expect("tiny")) + .chain([layout.directory_at + u32::try_from(layout.directory.len()).expect("tiny")]) + .max() + .expect("at least the directory"); + if layout.va_shift != 0 { + // An unrelated section whose virtual range ends below the + // directory's RVA: a reader that takes the first section, or + // ignores `VirtualAddress`, lands here. + let mut text = vec![0u8; 40]; + text[..5].copy_from_slice(b".text"); + text[12..16].copy_from_slice(&0x1000u32.to_le_bytes()); + text[16..20].copy_from_slice(&0x200u32.to_le_bytes()); + text[20..24].copy_from_slice(&0x200u32.to_le_bytes()); + out.extend(text); + } + // With a shift the section's raw data starts 0x80 before the + // directory, so the directory sits at a non-zero offset within it and + // `rva - VirtualAddress` is 0x80, not 0 — the translation is observable. + let raw_at = layout.directory_at - if layout.va_shift == 0 { 0 } else { 0x80 }; + let mut section = vec![0u8; 40]; + section[..5].copy_from_slice(b".data"); + section[12..16].copy_from_slice(&(raw_at + layout.va_shift).to_le_bytes()); + section[16..20].copy_from_slice(&(file_end - raw_at).to_le_bytes()); + section[20..24].copy_from_slice(&raw_at.to_le_bytes()); + out.extend(section); + if !tail.is_empty() { + let overlap = 40.min(tail.len()); + out.extend(&tail[overlap..]); + } + assert!( + out.len() <= layout.directory_at as usize, + "headers must precede the section data" + ); + out.resize(file_end as usize, 0); + let dir = layout.directory_at as usize; + out[dir..dir + layout.directory.len()].copy_from_slice(&layout.directory); + for (at, record) in &layout.records { + let at = *at as usize; + out[at..at + record.len()].copy_from_slice(record); + } + out +} + +/// `(head, read_at)` for `image`: the head is the first `HEAD_BYTES`, +/// and the closure serves the rest from the same bytes, short at EOF +/// exactly as the production `read_at` is — including an offset past +/// the end, which that one answers with `Some` of nothing (the seek +/// succeeds and the read returns zero bytes), never `None`. Only an +/// offset `usize` cannot hold is `None`, which stands in for the +/// `u64` seek position the production closure would reject. +fn staged(image: &[u8]) -> (&[u8], impl Fn(u64, usize) -> Option> + '_) { + let head = &image[..image.len().min(HEAD_BYTES)]; + let read_at = move |at: u64, len: usize| { + let at = usize::try_from(at).ok()?; + let bytes = image.get(at..).unwrap_or_default(); + Some(bytes[..bytes.len().min(len)].to_vec()) + }; + (head, read_at) +} + +fn pe_id(image: &[u8]) -> Option> { + let (head, read_at) = staged(image); + pe::build_id(head, read_at) +} + +/// The debug directory and the record both sit past 64 KiB, so this +/// fails if either stage reads from `head` instead of through `read_at` +/// — the fixture is the shape a real `link.exe` image has. +#[test] +fn pe32_plus_codeview_past_the_head_is_read_through_the_second_stage_and_hex_rendered() { + let directory_at = u32::try_from(HEAD_BYTES + 0x100).expect("fits"); + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at, + directory: debug_entry(2, 24, directory_at + 0x40), + records: vec![(directory_at + 0x40, rsds(*b"RSDS"))], + }); + assert!(image.len() > HEAD_BYTES); + assert_eq!(pe_id(&image).as_deref(), Some(&GUID_AND_AGE[..])); + assert_eq!( + pe_id(&image).map(|id| hex_lower(&id)).as_deref(), + Some("a0a1a2a3b0b1c0c1d0d1d2d3d4d5d6d707000000") + ); +} + +/// Fails if the PE32 directory offsets (92/96) are read at the PE32+ +/// positions (108/112): the count then reads 0 and the id is absent. +#[test] +fn pe32_codeview_inside_the_head_is_read() { + let image = pe(&PeLayout { + plus: false, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory: debug_entry(2, 24, 0x440), + records: vec![(0x440, rsds(*b"RSDS"))], + }); + assert!(image.len() < HEAD_BYTES); + assert_eq!(pe_id(&image).as_deref(), Some(&GUID_AND_AGE[..])); +} + +/// Fails if the entry walk returns on the first `CODEVIEW` entry rather +/// than continuing past a non-`RSDS` one, or if an entry of another +/// type is mistaken for `CODEVIEW`: the leading type-16 entry points at +/// a well-formed `RSDS` record whose GUID differs, so a reader without +/// the type filter answers with the decoy rather than `None`. +#[test] +fn pe_walks_past_unrelated_and_non_rsds_entries_to_a_later_codeview() { + let mut decoy = rsds(*b"RSDS"); + decoy[4] ^= 0xff; + let mut directory = debug_entry(16, 24, 0x480); + directory.extend(debug_entry(2, 24, 0x4c0)); + directory.extend(debug_entry(2, 24, 0x500)); + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory, + records: vec![ + (0x480, decoy), + (0x4c0, rsds(*b"NB10")), + (0x500, rsds(*b"RSDS")), + ], + }); + assert_eq!(pe_id(&image).as_deref(), Some(&GUID_AND_AGE[..])); +} + +/// An I/O failure differs from a successful short read. A failed directory +/// read stops the parse; a failed record read still permits a later entry. +/// Making failed reads panic or stopping at the first directory entry fails. +#[test] +fn pe_read_failures_stop_the_directory_but_skip_unreadable_records() { + use std::cell::RefCell; + + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory: [debug_entry(2, 24, 0x480), debug_entry(2, 24, 0x4c0)].concat(), + records: vec![(0x480, rsds(*b"RSDS")), (0x4c0, rsds(*b"RSDS"))], + }); + let (head, read) = staged(&image); + for (failed_offsets, expected_calls, expected_id) in [ + (vec![0x400], vec![(0x400, 56)], None), + ( + vec![0x480, 0x4c0], + vec![(0x400, 56), (0x480, 24), (0x4c0, 24)], + None, + ), + ( + vec![0x480], + vec![(0x400, 56), (0x480, 24), (0x4c0, 24)], + Some(&GUID_AND_AGE[..]), + ), + ] { + let calls = RefCell::new(Vec::new()); + let actual = pe::build_id(head, |offset, len| { + calls.borrow_mut().push((offset, len)); + if failed_offsets.contains(&offset) { + None + } else { + read(offset, len) + } + }); + assert_eq!( + actual.as_deref(), + expected_id, + "failed reads {failed_offsets:x?}" + ); + assert_eq!(calls.into_inner(), expected_calls); + } +} + +/// A short record is skipped before its bytes are requested. The following +/// entry must still be read, rather than ending the search with the first. +/// Limiting the directory walk to one entry fails this test. +#[test] +fn pe_skips_undersized_records_without_reading_them() { + use std::cell::RefCell; + + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory: [debug_entry(2, 20, 0x480), debug_entry(2, 24, 0x4c0)].concat(), + records: vec![(0x480, rsds(*b"RSDS")), (0x4c0, rsds(*b"RSDS"))], + }); + let (head, read) = staged(&image); + let calls = RefCell::new(Vec::new()); + let actual = pe::build_id(head, |offset, len| { + calls.borrow_mut().push((offset, len)); + read(offset, len) + }); + assert_eq!(actual.as_deref(), Some(&GUID_AND_AGE[..])); + assert_eq!(calls.into_inner(), [(0x400, 56), (0x4c0, 24)]); +} + +/// Exercise both stages through the actual file reader, including offsets +/// beyond `HEAD_BYTES`. A closure serving slices alone cannot check seeking. +/// Seeking to zero instead of the requested offset fails this test. +#[test] +fn pe_reads_a_file_backed_codeview_beyond_the_head() { + let directory_at = u32::try_from(HEAD_BYTES + 0x100).expect("fits"); + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at, + directory: debug_entry(2, 24, directory_at + 0x40), + records: vec![(directory_at + 0x40, rsds(*b"RSDS"))], + }); + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("fixture.exe"); + std::fs::write(&path, image).expect("write PE fixture"); + let head = read_head(&path).expect("read head"); + assert_eq!(head.len(), HEAD_BYTES); + let actual = pe::build_id(&head, |offset, len| read_at(&path, offset, len)); + assert_eq!(actual.as_deref(), Some(&GUID_AND_AGE[..])); +} + +/// Keep the directory and record available to the second-stage reader while +/// truncating header fields. Rejection must precede any request for data. +/// Making fixed-width reads assume a complete header fails this test. +#[test] +fn pe_truncated_directory_and_section_fields_never_trigger_io() { + use std::cell::Cell; + + for plus in [false, true] { + let image = pe(&PeLayout { + plus, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory: debug_entry(2, 24, 0x440), + records: vec![(0x440, rsds(*b"RSDS"))], + }); + let (_, read) = staged(&image); + let optional = 0x80 + 4 + 20; + let directory_entry = optional + if plus { 112 } else { 96 } + 6 * 8; + let section = optional + if plus { 240 } else { 224 }; + for cut in [ + directory_entry + 3, + directory_entry + 7, + section + 15, + section + 19, + section + 23, + ] { + let calls = Cell::new(0); + let actual = pe::build_id(&image[..cut], |offset, len| { + calls.set(calls.get() + 1); + read(offset, len) + }); + assert_eq!(actual, None, "PE32+={plus}, header cut at {cut}"); + assert_eq!(calls.get(), 0, "header rejected before second-stage I/O"); + } + } +} + +/// The directory's RVA is not its file offset: the section is mapped +/// 0x2000 above where it sits in the file, its raw data starts 0x80 +/// before the directory, and an unrelated section precedes it in the +/// table. Fails if `file_offset` returns `PointerToRawData` without +/// adding `rva - VirtualAddress` (every other fixture has that +/// difference zero), or takes the first section rather than the one +/// covering the RVA. +#[test] +fn pe_debug_directory_rva_is_translated_through_its_section() { + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0x2000, + directory_at: 0x480, + directory: debug_entry(2, 24, 0x4c0), + records: vec![(0x4c0, rsds(*b"RSDS"))], + }); + assert_eq!(pe_id(&image).as_deref(), Some(&GUID_AND_AGE[..])); +} + +/// The debug-directory read is capped at `MAX_DEBUG_ENTRIES`: it is the +/// only bound between a declared `size` of 4 GiB and a `Vec` of that +/// capacity. Sixty-five entries, the `CodeView` one last, read as absent. +/// Fails if the `.min(…)` on the directory read is dropped: the 65th +/// entry is then reached and its record returned. +#[test] +fn pe_debug_directory_entries_past_the_cap_are_not_read() { + let mut directory = Vec::new(); + for _ in 0..64 { + directory.extend(debug_entry(16, 24, 0x900)); + } + directory.extend(debug_entry(2, 24, 0x900)); + let image = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory, + records: vec![(0x900, rsds(*b"RSDS"))], + }); + assert_eq!(pe_id(&image), None); +} + +/// Each row names the guard it exercises; removing that guard turns the +/// row's `None` into `Some`, because every fixture here keeps the bytes +/// behind the lie in place — the declared-region rows exist precisely +/// so that a reader bounded only by the slice cannot pass them. +#[test] +fn pe_build_id_is_none_for_every_shape_the_reader_does_not_support() { + let layout = |directory: Vec, records: Vec<(u32, Vec)>| PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at: 0x400, + directory, + records, + }; + let good = pe(&layout( + debug_entry(2, 24, 0x440), + vec![(0x440, rsds(*b"RSDS"))], + )); + assert_eq!( + pe_id(&good).as_deref(), + Some(&GUID_AND_AGE[..]), + "the fixture itself must parse" + ); + let optional = 0x80 + 4 + 20; + + let mut wrong_dos = good.clone(); + wrong_dos[0] = 0; + assert_eq!(pe_id(&wrong_dos), None, "no MZ"); + let mut wrong_pe = good.clone(); + wrong_pe[0x80] = 0; + assert_eq!(pe_id(&wrong_pe), None, "no PE signature"); + let mut rom = good.clone(); + rom[optional..optional + 2].copy_from_slice(&0x107u16.to_le_bytes()); + assert_eq!(pe_id(&rom), None, "ROM optional header"); + + for cut in 0..good.len() { + assert_eq!(pe_id(&good[..cut]), None, "truncated at byte {cut}"); + } + + // Declared-region bounds: the bytes are all still there, only the + // headers' description of them shrinks. + let mut six_directories = good.clone(); + six_directories[optional + 108..optional + 112].copy_from_slice(&6u32.to_le_bytes()); + assert_eq!(pe_id(&six_directories), None, "NumberOfRvaAndSizes = 6"); + // The optional header declares 120 bytes, so the data directories + // sit behind the section header — still present, still readable from + // the slice, and not the optional header's to offer. Fails if the + // declared-length bound is removed: the reader then takes entry 6 + // from those bytes and finds the directory. + let short_optional = pe(&PeLayout { + plus: true, + optional_len: Some(120), + va_shift: 0, + directory_at: 0x400, + directory: debug_entry(2, 24, 0x440), + records: vec![(0x440, rsds(*b"RSDS"))], + }); + assert_eq!( + pe_id(&short_optional), + None, + "directory[6] past SizeOfOptionalHeader" + ); + + // RVA mapping through the section table. + let section = optional + 240; + let mut no_section = good.clone(); + no_section[0x84 + 2..0x84 + 4].copy_from_slice(&0u16.to_le_bytes()); + assert_eq!(pe_id(&no_section), None, "no section covers the RVA"); + let mut rva_past_raw = good.clone(); + rva_past_raw[section + 16..section + 20].copy_from_slice(&8u32.to_le_bytes()); + assert_eq!( + pe_id(&rva_past_raw), + None, + "directory past the section's SizeOfRawData" + ); + let mut rva_below_section = good.clone(); + rva_below_section[section + 12..section + 16].copy_from_slice(&0x800u32.to_le_bytes()); + assert_eq!( + pe_id(&rva_below_section), + None, + "directory RVA below the section's VirtualAddress" + ); + + // The directory and the record themselves. + assert_eq!( + pe_id(&pe(&layout( + debug_entry(2, 24, 0x440)[..27].to_vec(), + vec![(0x440, rsds(*b"RSDS"))] + ))), + None, + "debug directory of 27 bytes holds no complete entry" + ); + assert_eq!( + pe_id(&pe(&layout( + debug_entry(2, 20, 0x440), + vec![(0x440, rsds(*b"RSDS"))] + ))), + None, + "CodeView SizeOfData 20" + ); + assert_eq!( + pe_id(&pe(&layout( + debug_entry(2, 24, 0x440), + vec![(0x440, rsds(*b"NB10"))] + ))), + None, + "non-RSDS CodeView only" + ); + assert_eq!( + pe_id(&pe(&layout( + debug_entry(16, 24, 0x440), + vec![(0x440, rsds(*b"RSDS"))] + ))), + None, + "no CodeView entry" + ); + let mut record_past_eof = good.clone(); + record_past_eof.truncate(0x440 + 20); + assert_eq!(pe_id(&record_past_eof), None, "record short at end of file"); + let mut record_far_away = good; + record_far_away[0x400 + 24..0x400 + 28].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(pe_id(&record_far_away), None, "record offset past the end"); + // The directory stage is exact too, not only the record stage: a + // directory declared as two entries with the file ending inside the + // second must not yield the first entry's id, which sits before the + // directory and is fully present. Fails if that read is unchecked. + let mut directory_past_eof = pe(&PeLayout { + plus: true, + optional_len: None, + va_shift: 0, + directory_at: 0x440, + directory: [debug_entry(2, 24, 0x400), debug_entry(16, 24, 0x400)].concat(), + records: vec![(0x400, rsds(*b"RSDS"))], + }); + directory_past_eof.truncate(0x440 + 40); + assert_eq!( + pe_id(&directory_past_eof), + None, + "debug directory short at end of file" + ); +} diff --git a/big-code-analysis-cli/src/build_info/elf.rs b/big-code-analysis-cli/src/build_info/build_id/elf.rs similarity index 50% rename from big-code-analysis-cli/src/build_info/elf.rs rename to big-code-analysis-cli/src/build_info/build_id/elf.rs index 1870aa7fd..3e791e424 100644 --- a/big-code-analysis-cli/src/build_info/elf.rs +++ b/big-code-analysis-cli/src/build_info/build_id/elf.rs @@ -1,71 +1,34 @@ -//! The GNU build-id note of the running executable (#1773). +//! The GNU build-id note of an ELF executable (#1773). //! //! The linker writes a hash of the final object into a `PT_NOTE` //! segment as `NT_GNU_BUILD_ID`; debuggers, `perf` and symbol servers -//! key on it. It is the one provenance field that cannot be baked in by -//! `build.rs`, because it does not exist until the link has finished, -//! so it is read back from the binary at run time. -//! -//! Support is deliberately narrow: ELF64 in the host's byte order, -//! which is every Linux target the gate runs on. Anything else — ELF32, -//! a Mach-O or PE executable, a truncated or hand-edited file, an -//! executable that has been deleted since it started — yields `None` -//! and renders as `unavailable`. Nothing is decided on this field, so -//! every failure is informational. -//! -//! All offsets come from the file and are bounds-checked against the -//! bytes actually read; arithmetic is `checked_*` throughout, so a -//! malformed header cannot panic. +//! key on it. Support is ELF64 in little-endian byte order, which is +//! every Linux target the gate runs on; ELF32 and big-endian images +//! read as absent. -/// How much of the executable to read looking for the note. The -/// program headers and every `PT_NOTE` segment the linker emits sit in -/// the first page or so of a GNU-linked image (`PT_PHDR`, `PT_INTERP` -/// and the notes precede the first `PT_LOAD` of code); 64 KiB covers -/// that with a wide margin and keeps this off the path of reading a -/// 140 MB binary into memory to answer `--version`. A note past the -/// bound reads as absent, the documented answer for every shape the -/// reader does not handle. -#[cfg(target_os = "linux")] -const HEAD_BYTES: u64 = 64 * 1024; #[cfg(target_os = "linux")] -pub(crate) fn current_build_id() -> Option { - use std::io::Read as _; - let exe = std::env::current_exe().ok()?; - let mut head = Vec::with_capacity(usize::try_from(HEAD_BYTES).unwrap_or(0)); - std::fs::File::open(exe) - .ok()? - .take(HEAD_BYTES) - .read_to_end(&mut head) - .ok()?; - reader::build_id(&head).map(reader::hex_lower) -} - -/// Lowercase hex of the running executable's GNU build-id, or `None` — -/// always `None` off Linux, where the executable is not ELF. -#[cfg(not(target_os = "linux"))] -pub(crate) fn current_build_id() -> Option { - None +pub(super) fn current() -> Option { + let head = super::read_head(&std::env::current_exe().ok()?)?; + reader::build_id(&head).map(super::hex_lower) } #[cfg(test)] -pub(crate) use reader::{build_id, hex_lower}; +pub(super) use reader::build_id; /// The parser itself. Compiled only where it has a caller — Linux, and /// the test build on every platform, where the synthetic fixtures /// exercise it — so a macOS or Windows release build under /// `-D warnings` carries no dead code. +/// +/// The `test` alternative also takes this module out of the self-scan: +/// `bca check` under `exclude_tests` prunes a `cfg(any(…, test))` +/// subtree as test code, so the `bca: suppress(nexits)` markers here +/// and in the sibling readers document the intent for an unpruned run +/// (`bca check --no-config --threshold nexits=5 -p `) rather than +/// hold the gate. #[cfg(any(target_os = "linux", test))] mod reader { - /// Lowercase hex, two digits per byte. - pub(crate) fn hex_lower(bytes: &[u8]) -> String { - const DIGITS: &[u8; 16] = b"0123456789abcdef"; - let mut out = String::with_capacity(bytes.len() * 2); - for b in bytes { - out.push(DIGITS[usize::from(b >> 4)] as char); - out.push(DIGITS[usize::from(b & 0x0f)] as char); - } - out - } + use super::super::{u16_at, u32_at, u64_at}; const ELF_MAGIC: &[u8; 4] = b"\x7fELF"; const ELFCLASS64: u8 = 2; @@ -73,6 +36,7 @@ mod reader { const PT_NOTE: u32 = 4; const NT_GNU_BUILD_ID: u32 = 3; const GNU_NOTE_NAME: &[u8] = b"GNU\0"; + const PHENTSIZE: usize = 0x38; /// The raw `NT_GNU_BUILD_ID` descriptor in `elf`, or `None` when the /// bytes are not a little-endian ELF64 image carrying one. @@ -101,15 +65,23 @@ mod reader { // bca: suppress(nexits) — every exit is a `?` on a bounds-checked // read; a binary-format reader that fails closed is clearest as // one straight line of them, not as nested `if let`s. - if elf.get(..4)? != ELF_MAGIC + if !elf.starts_with(ELF_MAGIC) || *elf.get(4)? != ELFCLASS64 || *elf.get(5)? != ELFDATA2LSB { return None; } + // ELF64 fixes `e_phentsize` at 56. A smaller value would make + // every index alias the same header, so one `PT_NOTE` could be + // walked `phnum` times — 272 ms measured for `phentsize = 0` + // against 31 µs — and `readelf` rejects it too. + let phentsize = usize::from(u16_at(elf, 0x36)?); + if phentsize < PHENTSIZE { + return None; + } Some(Self { phoff: usize::try_from(u64_at(elf, 0x20)?).ok()?, - phentsize: usize::from(u16_at(elf, 0x36)?), + phentsize, phnum: usize::from(u16_at(elf, 0x38)?), }) } @@ -135,14 +107,15 @@ mod reader { // argument of the module, and it reads best uninterrupted. let mut at = 0usize; while let Some(namesz) = u32_at(segment, at) { - // `u32_at(segment, at)` succeeded, so `at + 8 <= len`: these - // two plain additions cannot overflow. + // `u32_at(segment, at)` succeeded, so `at + 4 <= len`, and a + // slice is at most `isize::MAX` bytes: neither plain addition + // can overflow. let descsz = usize::try_from(u32_at(segment, at + 4)?).ok()?; let kind = u32_at(segment, at + 8)?; let namesz = usize::try_from(namesz).ok()?; let name_at = at.checked_add(12)?; - let desc_at = name_at.checked_add(align4(namesz)?)?; - let next = desc_at.checked_add(align4(descsz)?)?; + let desc_at = name_at.checked_add(namesz.checked_next_multiple_of(4)?)?; + let next = desc_at.checked_add(descsz.checked_next_multiple_of(4)?)?; if kind == NT_GNU_BUILD_ID && segment.get(name_at..name_at.checked_add(namesz)?)? == GNU_NOTE_NAME { @@ -152,26 +125,4 @@ mod reader { } None } - - fn align4(n: usize) -> Option { - n.checked_add(3).map(|v| v & !3) - } - - /// `N` little-endian bytes at `at`, or `None` past the end or on an - /// overflowing offset. One reader for the three widths below. - fn le_at(bytes: &[u8], at: usize) -> Option<&[u8; N]> { - bytes.get(at..at.checked_add(N)?)?.as_array() - } - - fn u16_at(bytes: &[u8], at: usize) -> Option { - le_at(bytes, at).copied().map(u16::from_le_bytes) - } - - fn u32_at(bytes: &[u8], at: usize) -> Option { - le_at(bytes, at).copied().map(u32::from_le_bytes) - } - - fn u64_at(bytes: &[u8], at: usize) -> Option { - le_at(bytes, at).copied().map(u64::from_le_bytes) - } } diff --git a/big-code-analysis-cli/src/build_info/build_id/macho.rs b/big-code-analysis-cli/src/build_info/build_id/macho.rs new file mode 100644 index 000000000..b915d1b0f --- /dev/null +++ b/big-code-analysis-cli/src/build_info/build_id/macho.rs @@ -0,0 +1,64 @@ +//! The `LC_UUID` load command of a Mach-O executable (#1777). +//! +//! `ld64` and `lld` stamp a 16-byte UUID into every linked image; it is +//! what `dwarfdump --uuid` prints and what Xcode symbolication keys on. +//! Support is a thin little-endian 64-bit image — the one shape the +//! `aarch64-apple-darwin` release carries. A 32-bit image, a +//! byte-swapped one and a universal (FAT) container all read as absent. + +#[cfg(target_os = "macos")] +pub(super) fn current() -> Option { + let head = super::read_head(&std::env::current_exe().ok()?)?; + reader::build_id(&head).map(super::hex_lower) +} + +#[cfg(test)] +pub(super) use reader::build_id; + +/// The parser itself, compiled only where it has a caller (see `elf`). +#[cfg(any(target_os = "macos", test))] +mod reader { + use super::super::u32_at; + + const MH_MAGIC_64: u32 = 0xfeed_facf; + const HEADER_LEN: usize = 32; + const LC_UUID: u32 = 0x1b; + const LC_UUID_LEN: usize = 24; + + /// The 16 UUID bytes of the `LC_UUID` command in `macho`, or `None` + /// when the bytes are not a thin little-endian 64-bit image carrying + /// one. + pub(crate) fn build_id(macho: &[u8]) -> Option<&[u8]> { + // bca: suppress(nexits) — every exit is a `?` on a bounds-checked + // read or a checked add; the load-command walk fails closed and + // reads best as one straight line of them. + if u32_at(macho, 0)? != MH_MAGIC_64 { + return None; + } + let ncmds = u32_at(macho, 16)?; + let sizeofcmds = usize::try_from(u32_at(macho, 20)?).ok()?; + let end = HEADER_LEN.checked_add(sizeofcmds)?; + let mut at = HEADER_LEN; + for _ in 0..ncmds { + let cmd = u32_at(macho, at)?; + // `u32_at(macho, at)` succeeded, so `at + 4 <= len`, and once + // this read succeeds too `at + 8 <= len`: neither plain + // addition can overflow. + let cmdsize = usize::try_from(u32_at(macho, at + 4)?).ok()?; + let next = at.checked_add(cmdsize)?; + if next > end { + return None; + } + // A `cmdsize` under 8 makes this range inverted, so the read + // fails and the walk cannot re-read the same command for every + // one of `ncmds`: each turn advances by at least the 8-byte + // header or stops. + let body = macho.get(at + 8..next)?; + if cmd == LC_UUID { + return (cmdsize == LC_UUID_LEN).then_some(body); + } + at = next; + } + None + } +} diff --git a/big-code-analysis-cli/src/build_info/build_id/mod.rs b/big-code-analysis-cli/src/build_info/build_id/mod.rs new file mode 100644 index 000000000..d1b1c2411 --- /dev/null +++ b/big-code-analysis-cli/src/build_info/build_id/mod.rs @@ -0,0 +1,123 @@ +//! The build id of the running executable (#1773, #1777). +//! +//! The linker writes an identifier into the final image that debuggers +//! and symbol servers key on: the GNU build-id note on ELF, the +//! `LC_UUID` load command on Mach-O, and the `CodeView` record that pairs +//! a PE with its `.pdb`. It is the one provenance field `build.rs` +//! cannot bake in, because it does not exist until the link has +//! finished, so it is read back from the binary at run time. +//! +//! Support is deliberately narrow — one reader per platform, for the +//! executable shape that platform's toolchain produces — and anything +//! else (ELF32, a universal Mach-O, a PE without `CodeView`, a truncated +//! or hand-edited file, an executable deleted since it started) yields +//! `None` and renders as `unavailable`. Nothing is decided on this +//! field, so every failure is informational. +//! +//! All offsets come from the file and are bounds-checked against the +//! bytes actually read; arithmetic is `checked_*` throughout, so a +//! malformed header cannot panic. + +#[cfg(any(target_os = "linux", test))] +mod elf; +#[cfg(any(target_os = "macos", test))] +mod macho; +#[cfg(any(windows, test))] +mod pe; + +#[cfg(test)] +#[path = "build_id_tests.rs"] +mod tests; + +/// Lowercase hex of the running executable's build id, or `None`. +#[cfg(target_os = "linux")] +pub(crate) fn current_build_id() -> Option { + elf::current() +} + +/// Lowercase hex of the running executable's build id, or `None`. +#[cfg(target_os = "macos")] +pub(crate) fn current_build_id() -> Option { + macho::current() +} + +/// Lowercase hex of the running executable's build id, or `None`. +#[cfg(windows)] +pub(crate) fn current_build_id() -> Option { + pe::current() +} + +/// Always `None`: no reader exists for this platform's executable +/// format, so the field renders as `unavailable`. +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +pub(crate) fn current_build_id() -> Option { + None +} + +/// How much of the executable to read looking for the id. Program +/// headers, load commands and the PE headers all sit in the first page +/// or so of a linked image; 64 KiB covers that with a wide margin and +/// keeps this off the path of reading a 140 MB binary into memory to +/// answer `--version`. Headers past the bound read as absent, the +/// documented answer for every shape the readers do not handle; the +/// PE reader fetches the directory and record its headers name with +/// bounded second reads through [`read_at`], since those routinely sit +/// past it. +#[cfg(any(target_os = "linux", target_os = "macos", windows, test))] +const HEAD_BYTES: usize = 64 * 1024; + +/// The first [`HEAD_BYTES`] of `path`. +#[cfg(any(target_os = "linux", target_os = "macos", windows, test))] +fn read_head(path: &std::path::Path) -> Option> { + read_at(path, 0, HEAD_BYTES) +} + +/// Up to `len` bytes of `path` from `offset`, short at end of file. +#[cfg(any(target_os = "linux", target_os = "macos", windows, test))] +fn read_at(path: &std::path::Path, offset: u64, len: usize) -> Option> { + use std::io::{Read as _, Seek as _, SeekFrom}; + let mut file = std::fs::File::open(path).ok()?; + file.seek(SeekFrom::Start(offset)).ok()?; + let mut out = Vec::with_capacity(len); + file.take(u64::try_from(len).ok()?) + .read_to_end(&mut out) + .ok()?; + Some(out) +} + +/// Lowercase hex, two digits per byte. `digest.rs` carries its own copy +/// because `build.rs` includes that file by `#[path]` and can import +/// nothing from the crate. +#[cfg(any(target_os = "linux", target_os = "macos", windows, test))] +fn hex_lower(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push(DIGITS[usize::from(b >> 4)] as char); + out.push(DIGITS[usize::from(b & 0x0f)] as char); + } + out +} + +/// `N` little-endian bytes at `at`, or `None` past the end or on an +/// overflowing offset. One reader behind every fixed-width field the +/// three parsers decode. +#[cfg(any(target_os = "linux", target_os = "macos", windows, test))] +fn le_at(bytes: &[u8], at: usize) -> Option<&[u8; N]> { + bytes.get(at..at.checked_add(N)?)?.as_array() +} + +#[cfg(any(target_os = "linux", windows, test))] +fn u16_at(bytes: &[u8], at: usize) -> Option { + le_at(bytes, at).copied().map(u16::from_le_bytes) +} + +#[cfg(any(target_os = "linux", target_os = "macos", windows, test))] +fn u32_at(bytes: &[u8], at: usize) -> Option { + le_at(bytes, at).copied().map(u32::from_le_bytes) +} + +#[cfg(any(target_os = "linux", test))] +fn u64_at(bytes: &[u8], at: usize) -> Option { + le_at(bytes, at).copied().map(u64::from_le_bytes) +} diff --git a/big-code-analysis-cli/src/build_info/build_id/pe.rs b/big-code-analysis-cli/src/build_info/build_id/pe.rs new file mode 100644 index 000000000..aab49df2c --- /dev/null +++ b/big-code-analysis-cli/src/build_info/build_id/pe.rs @@ -0,0 +1,168 @@ +//! The `CodeView` record of a PE executable (#1777). +//! +//! `link.exe` and `lld-link` write an `IMAGE_DEBUG_DIRECTORY` whose +//! `CODEVIEW` entry points at an `RSDS` record — a 16-byte GUID and an +//! age — that pairs the image with its `.pdb`. Both PE32 and PE32+ are +//! read. The debug directory and the record routinely sit past the +//! first 64 KiB, so this reader is two-stage: the headers come from +//! the head, and the directory and record are each fetched with one +//! bounded read at the file offset the headers name. A PE whose +//! linker emitted no `CodeView` entry reads as absent. + +#[cfg(windows)] +pub(super) fn current() -> Option { + let exe = std::env::current_exe().ok()?; + let head = super::read_head(&exe)?; + reader::build_id(&head, |offset, len| super::read_at(&exe, offset, len)) + .map(|id| super::hex_lower(&id)) +} + +#[cfg(test)] +pub(super) use reader::build_id; + +/// The parser itself, compiled only where it has a caller (see `elf`). +#[cfg(any(windows, test))] +mod reader { + use super::super::{u16_at, u32_at}; + + const PE_SIGNATURE: &[u8; 4] = b"PE\0\0"; + const PE32: u16 = 0x10b; + const PE32_PLUS: u16 = 0x20b; + const IMAGE_DIRECTORY_ENTRY_DEBUG: usize = 6; + const SECTION_LEN: usize = 40; + const DEBUG_ENTRY_LEN: usize = 28; + /// More debug entries than any linker writes; bounds the second-stage read. + const MAX_DEBUG_ENTRIES: usize = 64; + const IMAGE_DEBUG_TYPE_CODEVIEW: u32 = 2; + const RSDS: &[u8; 4] = b"RSDS"; + /// `RSDS` + GUID + age. + const CODEVIEW_LEN: usize = 24; + + /// The 20 bytes after `RSDS` — the GUID as stored, then the age — of + /// the first `CodeView` entry in `head`'s debug directory, or `None`. + /// `read_at(offset, len)` fetches bytes of the image past `head`; + /// it returns what it can, and a short read fails the parse. + pub(crate) fn build_id( + head: &[u8], + read_at: impl Fn(u64, usize) -> Option>, + ) -> Option> { + let headers = Headers::parse(head)?; + let (rva, size) = headers.debug_directory(head)?; + let at = headers.file_offset(head, rva, size)?; + let directory = read_exact(&read_at, at, size.min(DEBUG_ENTRY_LEN * MAX_DEBUG_ENTRIES))?; + directory + .as_chunks::() + .0 + .iter() + .filter(|entry| u32_at(*entry, 12) == Some(IMAGE_DEBUG_TYPE_CODEVIEW)) + .find_map(|entry| codeview_id(&read_at, entry)) + } + + /// The identity of one `CODEVIEW` entry, or `None` for a short one + /// or a record that is not `RSDS`; the caller moves on to the next. + fn codeview_id( + read_at: &impl Fn(u64, usize) -> Option>, + entry: &[u8], + ) -> Option> { + let size = u32_at(entry, 16)?; + if usize::try_from(size).ok()? < CODEVIEW_LEN { + return None; + } + let record = read_exact(read_at, u64::from(u32_at(entry, 24)?), CODEVIEW_LEN)?; + record.strip_prefix(RSDS).map(<[u8]>::to_vec) + } + + fn read_exact( + read_at: &impl Fn(u64, usize) -> Option>, + at: u64, + len: usize, + ) -> Option> { + let bytes = read_at(at, len)?; + (bytes.len() == len).then_some(bytes) + } + + struct Headers { + /// Where the section table starts: the end of the declared + /// optional header. + sections: usize, + section_count: usize, + directories_at: usize, + directory_count: usize, + } + + impl Headers { + fn parse(head: &[u8]) -> Option { + // bca: suppress(nexits) — every exit is a `?` on a bounds-checked + // read; a binary-format reader that fails closed is clearest as + // one straight line of them (see `elf`). + if !head.starts_with(b"MZ") { + return None; + } + let pe = usize::try_from(u32_at(head, 0x3c)?).ok()?; + if !head.get(pe..)?.starts_with(PE_SIGNATURE) { + return None; + } + let coff = pe.checked_add(4)?; + let section_count = usize::from(u16_at(head, coff.checked_add(2)?)?); + let optional_len = usize::from(u16_at(head, coff.checked_add(16)?)?); + let optional = coff.checked_add(20)?; + // The data-directory count and table sit at different offsets in + // the two optional-header layouts; everything before them that + // this reader needs is the magic. + let (count_at, table_at) = match u16_at(head, optional)? { + PE32 => (92, 96), + PE32_PLUS => (108, 112), + _ => return None, + }; + Some(Self { + sections: optional.checked_add(optional_len)?, + section_count, + directories_at: optional.checked_add(table_at)?, + directory_count: usize::try_from(u32_at(head, optional.checked_add(count_at)?)?) + .ok()?, + }) + } + + /// The debug directory's `(rva, size)`, read only when entry 6 + /// lies inside the declared optional header — before the section + /// table, not merely inside the bytes read. + fn debug_directory(&self, head: &[u8]) -> Option<(usize, usize)> { + // bca: suppress(nexits) — two declared-region bounds and `?` on + // each bounded read; the straight line is the safety argument. + if self.directory_count <= IMAGE_DIRECTORY_ENTRY_DEBUG { + return None; + } + let entry = self + .directories_at + .checked_add(IMAGE_DIRECTORY_ENTRY_DEBUG * 8)?; + if entry.checked_add(8)? > self.sections { + return None; + } + let rva = usize::try_from(u32_at(head, entry)?).ok()?; + let size = usize::try_from(u32_at(head, entry.checked_add(4)?)?).ok()?; + Some((rva, size)) + } + + /// The file offset of `[rva, rva + size)`, which must lie within + /// one section's raw data — `SizeOfRawData`, not `VirtualSize`, + /// since the bytes are read from the file, not a mapped image. + fn file_offset(&self, head: &[u8], rva: usize, size: usize) -> Option { + // bca: suppress(nexits) — `?` on each bounded field read. The + // closure is its own space to the gate, so it carries a marker + // too; one alone leaves the other at nexits 14 / 15. + let end = rva.checked_add(size)?; + (0..self.section_count).find_map(|index| { + // bca: suppress(nexits) — see the enclosing fn. + let at = self.sections.checked_add(index.checked_mul(SECTION_LEN)?)?; + let virtual_address = usize::try_from(u32_at(head, at.checked_add(12)?)?).ok()?; + let raw_size = usize::try_from(u32_at(head, at.checked_add(16)?)?).ok()?; + let raw_at = usize::try_from(u32_at(head, at.checked_add(20)?)?).ok()?; + let raw_end = virtual_address.checked_add(raw_size)?; + if virtual_address > rva || end > raw_end { + return None; + } + u64::try_from(raw_at.checked_add(rva - virtual_address)?).ok() + }) + } + } +} diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs index a0824396d..7596d7f5e 100644 --- a/big-code-analysis-cli/src/build_info/build_info_tests.rs +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -1,7 +1,6 @@ use std::path::Path; use super::digest::{DigestError, INPUT_ROOTS, digest, input_files}; -use super::elf::{build_id, hex_lower}; /// The fixture `utils/self-scan-bca-test.py` builds byte-for-byte, and /// the hex both implementations must produce from it. One file per rule @@ -445,166 +444,3 @@ fn the_derive_carries_no_long_version_so_the_man_page_cannot_absorb_one() { use clap::CommandFactory as _; assert!(crate::Cli::command().get_long_version().is_none()); } - -/// A minimal little-endian ELF64 image: header, one program header of -/// `kind`, and a note segment built from `notes`. -fn elf64(kind: u32, notes: &[u8]) -> Vec { - let mut out = vec![0u8; 0x40]; - out[..4].copy_from_slice(b"\x7fELF"); - out[4] = 2; - out[5] = 1; - out[0x20..0x28].copy_from_slice(&0x40u64.to_le_bytes()); - out[0x36..0x38].copy_from_slice(&0x38u16.to_le_bytes()); - out[0x38..0x3a].copy_from_slice(&1u16.to_le_bytes()); - let seg_at = 0x40u64 + 0x38; - let mut ph = vec![0u8; 0x38]; - ph[..4].copy_from_slice(&kind.to_le_bytes()); - ph[0x08..0x10].copy_from_slice(&seg_at.to_le_bytes()); - ph[0x20..0x28].copy_from_slice(&(notes.len() as u64).to_le_bytes()); - out.extend(ph); - out.extend_from_slice(notes); - out -} - -fn note(name: &[u8], kind: u32, desc: &[u8]) -> Vec { - let len = |s: &[u8]| u32::try_from(s.len()).expect("fixture notes are tiny"); - let mut out = Vec::new(); - out.extend(len(name).to_le_bytes()); - out.extend(len(desc).to_le_bytes()); - out.extend(kind.to_le_bytes()); - out.extend(name); - out.resize(out.len().next_multiple_of(4), 0); - out.extend(desc); - out.resize(out.len().next_multiple_of(4), 0); - out -} - -#[test] -fn build_id_is_read_past_an_unrelated_note_and_hex_rendered() { - let id = [0xde, 0xad, 0xbe, 0xef, 0x01]; - let mut notes = note(b"GNU\0", 1, b"\0\0\0\0\x03\0\0\0\x02\0\0\0\0\0\0\0"); - notes.extend(note(b"GNU\0", 3, &id)); - let image = elf64(4, ¬es); - assert_eq!(build_id(&image), Some(&id[..])); - assert_eq!( - build_id(&image).map(hex_lower).as_deref(), - Some("deadbeef01") - ); -} - -#[test] -fn build_id_is_none_for_every_shape_the_reader_does_not_support() { - let id = [1u8, 2, 3]; - let good = elf64(4, ¬e(b"GNU\0", 3, &id)); - assert_eq!( - build_id(&good), - Some(&id[..]), - "the fixture itself must parse" - ); - - let mut wrong_magic = good.clone(); - wrong_magic[0] = 0; - assert_eq!(build_id(&wrong_magic), None, "wrong magic"); - - let mut elf32 = good.clone(); - elf32[4] = 1; - assert_eq!(build_id(&elf32), None, "ELF32"); - - let mut big_endian = good.clone(); - big_endian[5] = 2; - assert_eq!(build_id(&big_endian), None, "big-endian"); - - assert_eq!(build_id(&good[..0x30]), None, "truncated header"); - assert_eq!(build_id(&good[..0x50]), None, "truncated program header"); - assert_eq!( - build_id(&elf64(1, ¬e(b"GNU\0", 3, &id))), - None, - "not a PT_NOTE segment" - ); - assert_eq!( - build_id(&elf64(4, ¬e(b"XYZ\0", 3, &id))), - None, - "not the GNU note" - ); - assert_eq!( - build_id(&elf64(4, ¬e(b"GNU\0", 7, &id))), - None, - "not NT_GNU_BUILD_ID" - ); - - // Every prefix of a valid image must read as absent, not panic and - // not misparse. This walks each `?` in the header and program-header - // readers; it never reaches the note reader, because the shortened - // image keeps the program header's declared segment size and the - // segment slice fails first. - for cut in 0..good.len() { - assert_eq!(build_id(&good[..cut]), None, "truncated at byte {cut}"); - } - // The note reader's own short reads need a segment whose *declared* - // size is honest: 4 bytes reach `descsz`'s read, 8 reach `kind`'s, - // 12 reach the name's. These execute each read's `None` arm; they - // cannot tell a failed read from an infallible one, because the - // next read fails the same way and no id can come out of a note - // that short — the outcome, not the mechanism, is what is pinned. - for short in [&[0u8; 4][..], &[0u8; 8], &[0u8; 12]] { - assert_eq!( - build_id(&elf64(4, short)), - None, - "{}-byte note segment", - short.len() - ); - } - - let mut overflow = good.clone(); - overflow[0x40 + 0x20..0x40 + 0x28].copy_from_slice(&u64::MAX.to_le_bytes()); - assert_eq!(build_id(&overflow), None, "segment size past the end"); - let mut far_offset = good.clone(); - far_offset[0x40 + 0x08..0x40 + 0x10].copy_from_slice(&u64::MAX.to_le_bytes()); - assert_eq!(build_id(&far_offset), None, "segment offset past the end"); - - let mut more_headers_than_exist = good.clone(); - more_headers_than_exist[0x38..0x3a].copy_from_slice(&7u16.to_le_bytes()); - assert_eq!( - build_id(&more_headers_than_exist), - Some(&id[..]), - "a phnum past the table still finds the note in the headers present" - ); - - let mut huge_phoff = good.clone(); - huge_phoff[0x20..0x28].copy_from_slice(&u64::MAX.to_le_bytes()); - assert_eq!( - build_id(&huge_phoff), - None, - "program-header offset past the end" - ); - - // A name length that overruns the segment: the note walk fails - // closed. (A clamped slice would fail closed too — the name would - // not compare equal — so this pins the outcome, not the mechanism; - // the bounded-read spelling is the module's safety argument.) - let mut lying_namesz = good; - let note_at = 0x40 + 0x38; - lying_namesz[note_at..note_at + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); - assert_eq!(build_id(&lying_namesz), None, "namesz past the segment"); - - // A descriptor length that overruns: same, on the other field. - let mut lying_descsz = elf64(4, ¬e(b"GNU\0", 3, &id)); - lying_descsz[note_at + 4..note_at + 8].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); - assert_eq!(build_id(&lying_descsz), None, "descsz past the segment"); -} - -/// A capability probe, not a contract: the linker on this host is what -/// decides whether the test binary carries a note at all. When it does, -/// the reader must find it and render 40 hex digits; when it does not, -/// `unavailable` is the documented answer. -#[cfg(target_os = "linux")] -#[test] -fn running_executable_yields_hex_or_nothing() { - match super::elf::current_build_id() { - Some(id) => assert!( - !id.is_empty() && id.bytes().all(|b| b.is_ascii_hexdigit()), - "{id}" - ), - None => eprintln!("no GNU build-id note in the test binary on this host"), - } -} diff --git a/big-code-analysis-cli/src/build_info/digest.rs b/big-code-analysis-cli/src/build_info/digest.rs index bfb558bbd..0a926c828 100644 --- a/big-code-analysis-cli/src/build_info/digest.rs +++ b/big-code-analysis-cli/src/build_info/digest.rs @@ -264,10 +264,10 @@ pub(crate) fn digest_of(workspace: &Path, files: &[String]) -> Result String { const DIGITS: &[u8; 16] = b"0123456789abcdef"; let mut out = String::with_capacity(bytes.len() * 2); diff --git a/big-code-analysis-cli/src/build_info/mod.rs b/big-code-analysis-cli/src/build_info/mod.rs index ff5130617..81ba6182e 100644 --- a/big-code-analysis-cli/src/build_info/mod.rs +++ b/big-code-analysis-cli/src/build_info/mod.rs @@ -3,14 +3,14 @@ //! `build.rs` bakes the fields in as `BCA_BUILD_*` environment //! variables; this module reads them with `env!` and renders the long //! version block. One field is read at run time rather than build time: -//! the linker's GNU build-id note, which does not exist until the -//! binary has been linked ([`elf`]). +//! the linker's build id, which does not exist until the binary has +//! been linked ([`build_id`]). //! //! Of the fields, only `inputs` ever decides anything — the self-scan //! resolver compares it with the live tree. The others are evidence //! for a human reading a log or a report later. -pub(crate) mod elf; +mod build_id; #[cfg(test)] pub(crate) mod digest; @@ -65,7 +65,7 @@ pub(crate) fn build_git() -> Option<&'static str> { /// for this workspace's release profile. pub(crate) fn long_version() -> String { let assertions = if cfg!(debug_assertions) { "on" } else { "off" }; - let binary_id = elf::current_build_id().unwrap_or_else(|| "unavailable".to_owned()); + let binary_id = build_id::current_build_id().unwrap_or_else(|| "unavailable".to_owned()); format!( "{}\nbuild inputs: {BUILD_INPUTS}\ngit: {BUILD_GIT}\nbuilt: {BUILD_TIME} \ (profile {BUILD_PROFILE}, {BUILD_RUSTC}, {BUILD_TARGET}, debug-assertions \ diff --git a/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index 913dbdfaa..005d118f7 100644 --- a/docs/development/lessons_learned.md +++ b/docs/development/lessons_learned.md @@ -155,6 +155,7 @@ number and the higher number stays as a redirect. | [109](#109-a-resolved-view-printed-at-two-layers-re-layers-itself-when-read-back) | A resolved view printed at two layers re-layers itself when read back | | [110](#110-a-fallback-priced-at-one-call-frequency-is-a-syscall-per-node-at-another) | A fallback priced at one call frequency is a syscall per node at another | | [111](#111-a-tool-that-walks-source-items-does-not-see-what-a-macro-emits) | A tool that walks source items does not see what a macro emits | +| [112](#112-a-test-double-can-intercept-the-wrong-calls) | A test double can intercept the wrong calls | --- @@ -3837,22 +3838,18 @@ three possible resolutions records a different digest. ## 91. A gate can filter out its own subject before the check runs -**Lesson:** When you add a dependency or supply-chain gate, prove it -fails by reintroducing the condition it guards and watching it go red. -A tool that builds a filtered view of its input before applying your -rules can drop the very artifact a rule names, leaving an entry that is -syntactically valid, semantically correct, and permanently silent. When -the tool's view is derived, guard the raw artifact instead — the -lockfile, the manifest — and record at the site where the dead entry -would go why it is not there. - -A config entry reads as coverage. A future maintainer greps `deny.toml`, -finds the crate and the version range spelled out, and stops looking; -the tool exits 0, which is the same output it gives when the tree is -genuinely clean. Nothing distinguishes "no violation" from "the subject -was never in scope", and the gap opens precisely when the guard matters, -because the condition that reintroduces the vulnerable crate is also the -condition that puts it back beyond the filter. +**Lesson:** Before trusting a filtered gate, prove the subject reaches +the check and that reintroducing the guarded condition makes it fail. +A rule cannot protect an artifact the tool removes first. Inspect the +tool's input set; if it omits the subject, use an unfiltered check or +guard the raw artifact directly. Record the gap where a reader would +otherwise mistake a config entry or suppression marker for coverage. + +A successful exit can mean that the subject passed its checks or that +it never reached them. The exit status alone cannot distinguish these +cases. A config entry or suppression marker suggests the subject was +checked, so its presence can end the investigation before anyone +inspects the filter. **cargo-deny cannot guard `h2 0.3.27`** (RUSTSEC-2026-0258, Scorecard alert #776; `3df3b2c3`, `b60943b5` — direct pushes to `main`, no PR). @@ -3880,6 +3877,22 @@ discriminates is the same as this lesson's: remove the memo and watch the exponent leave the bound (`.claude/rules/testing.md`, "Validate a scaling probe by removing what it prices"). +**Production readers were classified as tests** (#1777). PR #1780 +introduced `cfg(any(, test))` for the ELF reader; #1777 reused it +for the Mach-O and PE readers. Their inner `reader` modules compile +on the relevant OS or in tests, keeping unused parsers out of other +targets' builds under `-D warnings`. The self-scan's `exclude_tests` +classifier treats that shape as test code and prunes the parsers, so +their suppression markers were not what made the scan pass. An +unpruned `bca check --no-config --threshold nexits=5 -p ` found +`Headers::debug_directory` at 9 with no marker and `file_offset` at 15 +with its marker attached to the inner closure instead of the function. +The two functions and the closure now carry markers for unpruned +checks. The cfg gates remain, and +`big-code-analysis-cli/src/build_info/build_id/elf.rs` documents the +self-scan's omission. Add `--no-suppress` to the command to inspect +scores behind the current markers as well. + --- ## 92. An optimization's rationale can encode the waste it optimizes for @@ -4931,3 +4944,39 @@ to gate. The `bca.toml` entry that replaced the markers says every function in the glob stays gated and, further down, names this gap. --- + +## 112. A test double can intercept the wrong calls + +**Lesson:** When a test double intercepts calls to fixture files, match +the fixture's own paths rather than a shape that real files can share. +Run the suite with CI's explicit artifacts as well as its defaults. +After production changes a routed call's path or arguments, repeat the +mutation check: the assertion can still pass after the double stops +recording the call. See the perturbation procedure in +[`testing.md`](../../.claude/rules/testing.md). + +An overly broad match can apply a fake's handling to a real artifact. +A stale match can let a call bypass the double and its recording logic. +The first defect may appear only with an artifact absent from local +validation. The second can leave a green test whose call log omits the +very operation its assertion claims to count. + +**The preload intercepted CI's native analyzer** (#1776). The hook +fixture routed any `…/target/{debug,release}/bca` through Node so its +fake binaries could run on every OS. CI supplied the real checkout +binary through `BCA_TEST_BINARY`, and that path matched too. The hook's +`check` invocation tried to execute the native binary as JavaScript. +The historical suites passed 68 of 68 tests with the default PATH +analyzer, but only 65 of 68 with CI's explicit one. The preload now +names the fixture's two exact local-build paths. + +**Resolving the executable path blinded the dedupe test** (#1776). A +production change made the hook probe PATH `bca` by its resolved file +path. The fixture still intercepted only the bare name `bca`. With +deduplication removed, the symlink's extra probe bypassed the fake's +recording logic, and all 71 tests passed under the mutation the test +claimed to catch. Routing the symlink's path made that mutation fail +exactly one test: the assertion that a local build also found on PATH +is probed once. + +--- diff --git a/utils/bca-check-plugin-test.mjs b/utils/bca-check-plugin-test.mjs index 0bfbb0aad..a4b1050d4 100644 --- a/utils/bca-check-plugin-test.mjs +++ b/utils/bca-check-plugin-test.mjs @@ -973,6 +973,53 @@ test("cleanup disables old registrations and explicit BCA takes precedence over assert.equal(unloaded.result.content, "Edited successfully") }) +// #1776: discovery runs once per event per checkout root, not once per file. +// Fails if the per-event cache is removed (the digest and both probes then run +// three times for the three-file patch) or if it is hoisted to plugin scope +// (the second event then reuses the stale selection and runs no digest). +test("a multi-file patch resolves the analyzer once per event and re-resolves next event", async (t) => { + const f = await fixture(t) + delete process.env.BCA + const digest = "5".repeat(64) + const python3 = join(f.directory, "python3.mjs") + await writeFile(python3, `#!${process.execPath}\nconsole.log(${JSON.stringify(digest)});`, { mode: 0o755 }) + const script = join(f.directory, "self_scan_digest.py") + await writeFile(script, "") + process.env.BCA_DIGEST_SCRIPT = script + t.after(() => { delete process.env.BCA_DIGEST_SCRIPT }) + const binary = async (profile, inputs, finding) => { + const file = join(f.root, `target/${profile}/bca${EXE}`) + await mkdir(join(file, ".."), { recursive: true }) + await writeFile(file, `#!${process.execPath} +if (process.argv[2] === "--version") console.log("bca 0.0.0\\nbuild inputs: ${inputs}"); +else { console.log(${JSON.stringify(finding)}); process.exitCode = 2; } +`, { mode: 0o755 }) + f.scripts.add(file) + return file + } + await binary("debug", "6".repeat(64), "debug finding") + const release = await binary("release", digest, "release finding") + const spawned = () => childProcess.spawn.mock.calls.map((call) => call.arguments[0]) + const original = childProcess.spawn + const mock = t.mock.method(childProcess, "spawn", (file, args, options) => { + return file === "python3" ? original(process.execPath, [python3, ...args], options) : original(file, args, options) + }) + syncBuiltinESMExports() + t.after(() => { mock.mock.restore(); syncBuiltinESMExports() }) + const files = await Promise.all(["a.rs", "b.rs", "c.rs"].map((name) => f.file(name))) + const first = event(undefined, { tool: "patch", result: { content: "Patched", metadata: { files: files.map((file) => ({ file })) } } }) + await f.hook(first) + assert.equal((advice(first).match(/release finding/g) ?? []).length, 3) + const discovery = (calls) => calls.filter((file) => file === "python3" || file.endsWith(`${sep}bca${EXE}`) || file === "bca") + const afterFirst = spawned() + assert.deepEqual(discovery(afterFirst).slice(0, 3), ["python3", join(f.root, `target/debug/bca${EXE}`), release]) + assert.equal(discovery(afterFirst).filter((file) => file === "python3").length, 1) + assert.ok(f.messages.some(([, text]) => text === `[bca-check] analyzer=${release} cwd=${f.root} reason=build inputs match this tree`)) + const second = event(files[0], { sessionID: "next-event" }) + await f.hook(second) + assert.equal(discovery(spawned().slice(afterFirst.length)).filter((file) => file === "python3").length, 1) +}) + const integrationBca = process.env.BCA_TEST_BINARY || "bca" const realBca = spawnSync(integrationBca, ["--version"], { encoding: "utf8" }) test("real analyzer respects explicit-path exclusions and a baseline", { skip: !process.env.BCA_TEST_BINARY && realBca.status !== 0 && "bca not found; unit contract tests still run" }, async (t) => { diff --git a/utils/bca-claude-hook-test.mjs b/utils/bca-claude-hook-test.mjs index c7333ef13..4df454b9b 100644 --- a/utils/bca-claude-hook-test.mjs +++ b/utils/bca-claude-hook-test.mjs @@ -1,14 +1,15 @@ import assert from "node:assert/strict" import { execFileSync, spawn, spawnSync } from "node:child_process" import { once } from "node:events" -import { mkdtemp, mkdir, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises" +import { mkdtemp, mkdir, readFile, realpath, rm, symlink, utimes, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" -import { join, resolve, sep } from "node:path" +import { delimiter, join, resolve, sep } from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" import test from "node:test" const REPO = resolve(fileURLToPath(new URL("../", import.meta.url))) const HOOK = join(REPO, ".claude/hooks/bca-check.mjs") +const EXE = process.platform === "win32" ? ".exe" : "" const ROW = '[new] ./sample.rs:1-3: "quoted\\name": cognitive = 20 (limit 15)' const GUIDANCE = "Keep the change focused." const baseEnv = () => Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith("GIT_") && key !== "BCA")) @@ -28,6 +29,7 @@ async function fixture(t) { await writeFile(join(root, ".claude/hooks/bca-guidance.txt"), GUIDANCE) const stub = join(temp, "analyzer.mjs") const calls = join(temp, "calls.jsonl") + const probes = join(temp, "probes.txt") await writeFile(stub, ` import { readFileSync, writeFileSync, appendFileSync, unlinkSync } from "node:fs"; const args = process.argv.slice(2); @@ -44,19 +46,34 @@ else { } `) const preload = join(temp, "preload.mjs") + // Only the fixture's own local builds are routed through node: a shape + // match would also capture the real `target/debug/bca` CI hands the + // real-CLI tests through BCA_TEST_BINARY. + const local = (profile) => join(root, "target", profile, `bca${EXE}`) await writeFile(preload, ` import cp from "node:child_process"; import { syncBuiltinESMExports } from "node:module"; const original = cp.spawn; -cp.spawn = (file, args, options) => file === ${JSON.stringify(stub)} || file.endsWith("/target/release/bca") || file.endsWith("\\\\target\\\\release\\\\bca.exe") +cp.spawn = (file, args, options) => [${JSON.stringify(stub)}, ${JSON.stringify(local("debug"))}, ${JSON.stringify(local("release"))}].includes(file) ? original(process.execPath, [file, ...args], options) : original(file, args, options); syncBuiltinESMExports(); `) const path = join(root, "sample.rs") await writeFile(path, "{}") + // Extends the preload so a spawn of the bare `name` runs `script` under node; + // `{ exec }` instead spawns that path as-is, for the ENOENT case. + const route = async (name, script, { exec } = {}) => writeFile(preload, (await readFile(preload, "utf8")) + ` +{ + const previous = cp.spawn; + cp.spawn = (file, args, options) => file === ${JSON.stringify(name)} + ? original(${exec ? `${JSON.stringify(exec)}, args` : `process.execPath, [${JSON.stringify(script)}, ...args]`}, options) + : previous(file, args, options); + syncBuiltinESMExports(); +} +`) return { - temp, root, path, env, stub, preload, git, + temp, root, path, env, stub, preload, git, route, file: (data) => writeFile(path, JSON.stringify(data)), input: (overrides = {}) => ({ hook_event_name: "PostToolUse", tool_name: "Edit", cwd: root, session_id: "session-a", tool_input: { file_path: path }, ...overrides }), @@ -70,6 +87,41 @@ syncBuiltinESMExports(); try { return (await readFile(calls, "utf8")).trim().split("\n").map(JSON.parse) } catch (error) { if (error.code === "ENOENT") return []; throw error } }, + // A fake `bca` at `file` whose `--version` reports `inputs` and whose `check` + // prints `finding`; `delay` holds `--version` open that long. Routed through + // the preload's spawn patch, so it runs under node on every platform. Each + // `--version` probe appends `file` to `probes()` before the delay starts. + async binary(file, { inputs, finding, delay = 0, mtime } = {}) { + await mkdir(join(file, ".."), { recursive: true }) + await writeFile(file, ` +const [command] = process.argv.slice(2); +if (command === "--version") { + require("node:fs").appendFileSync(${JSON.stringify(probes)}, ${JSON.stringify(file)} + "\\n"); + setTimeout(() => { process.stdout.write("bca 0.0.0\\nbuild inputs: ${inputs ?? "unavailable"}\\n"); }, ${delay}); +} else { console.log(${JSON.stringify(finding ?? ROW)}); process.exitCode = 2; } +`, { mode: 0o755 }) + if (mtime) await utimes(file, mtime, mtime) + return file + }, + async probes() { + try { return (await readFile(probes, "utf8")).trim().split("\n") } + catch (error) { if (error.code === "ENOENT") return []; throw error } + }, + local, + // The digest the hook believes the tree has: a fake `self_scan_digest.py` + // (run by a fake `python3`, routed like the binaries) printing `digest`, or + // exiting 1 with `error:` when `digest` is undefined. + async digest(digest) { + const script = join(temp, "self_scan_digest.py") + await writeFile(script, "") + const python3 = join(temp, "python3.mjs") + await writeFile(python3, digest === undefined + ? 'console.error("error: the tree cannot be digested"); process.exitCode = 1;' + : `console.log(${JSON.stringify(digest)});`) + await route("python3", python3) + return { BCA: "", BCA_DIGEST_SCRIPT: script } + }, + health: (result) => JSON.parse(result.stderr.slice("[bca-check] ".length)), } } @@ -96,7 +148,10 @@ test("configured exec hook sends escaped advisory JSON for every file-writing to const [handler] = group.hooks assert.equal(handler.type, "command") assert.equal(handler.command, "node") - assert.equal(handler.timeout, 10) + // 15 s: the bounded stages — checkout's git (3 s), discovery (4 s), the + // check (3 s) — sum to 10 s, so the registered slot must leave room for + // node startup and the health line on a contended host (#1776). + assert.equal(handler.timeout, 15) const script = handler.args[0].replace("${CLAUDE_PROJECT_DIR}", REPO) assert.equal(resolve(script), HOOK) for (const tool of ["Edit", "Write", "MultiEdit"]) { @@ -203,27 +258,192 @@ test("missing binary, timeout and output overflow remain model-silent", async (t } }) +// A PATH `bca`: `installed()` resolves it to the file in `bin`, which is +// what the hook probes and runs, so the preload routes that path; the bare +// `bca` is routed too, for the no-digest fallback that still spawns by name. +async function onPath(f, options, bin = join(f.temp, "bin")) { + const pathBinary = await f.binary(join(bin, `bca${EXE}`), options) + await f.route(pathBinary, pathBinary) + await f.route("bca", pathBinary) + return { BCA: "", PATH: `${bin}${delimiter}${f.env.PATH}` } +} + test("explicit analyzer wins over the checkout build, which wins over PATH", async (t) => { const f = await fixture(t) - const bin = join(f.temp, "bin") - await mkdir(bin) - const pathBinary = join(bin, process.platform === "win32" ? "bca.exe" : "bca") - await writeFile(pathBinary, 'console.log("PATH-only finding"); process.exitCode = 2;', { mode: 0o755 }) - await writeFile(f.preload, (await readFile(f.preload, "utf8")) + ` -const previous = cp.spawn; -cp.spawn = (file, args, options) => file === "bca" ? original(process.execPath, [${JSON.stringify(pathBinary)}, ...args], options) : previous(file, args, options); -syncBuiltinESMExports(); -`) - const pathEnv = { BCA: "", PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${f.env.PATH}` } + const pathEnv = await onPath(f, { finding: "PATH-only finding" }) assert.match(report(f.run(f.input(), pathEnv)), /PATH-only finding/) - const local = join(f.root, "target/release", process.platform === "win32" ? "bca.exe" : "bca") - await mkdir(join(f.root, "target/release"), { recursive: true }) - await writeFile(local, 'console.log("local finding"); process.exitCode = 3;', { mode: 0o755 }) + await f.binary(f.local("release"), { finding: "local finding" }) assert.ok(report(f.run(f.input())).includes(ROW)) - assert.match(report(f.run(f.input(), pathEnv)), /local finding/) + // The real utils/self_scan_digest.py refuses this fixture checkout (no + // Cargo.toml), so nothing can match: a lone release build is still "newest + // local build", which outranks PATH as before #1776. Only the digest step's + // failure is pinned, not its spelling: `exited 1` here, but a host with no + // `python3` on PATH reports ENOENT (the CLI's own python3 parity test is + // `cfg(not(windows))` for that reason), and the fake-python3 test below + // pins both spellings exactly (audit-tests). + const result = f.run(f.input(), pathEnv) + assert.match(report(result), /local finding/) + assert.match(f.health(result).analyzerReason, /^newest local build \(python3 /) + assert.deepEqual(await f.probes(), []) quiet(f.run(f.input(), { BCA: join(f.temp, "not-installed") }), "unavailable") }) +// #1776: the build whose `build inputs:` equals the tree's digest measures the +// edit, whichever profile it is. Fails if the digest comparison is dropped +// (both candidates then fall to the mtime order and the first row picks the +// newer non-matching release) or if `reportedInputs` reads the wrong line. +test("the local build whose build inputs match the tree wins regardless of profile", async (t) => { + const f = await fixture(t) + const digest = "a".repeat(64) + const env = await f.digest(digest) + const older = new Date(Date.now() - 60_000) + await f.binary(f.local("debug"), { inputs: digest, finding: "debug finding", mtime: older }) + await f.binary(f.local("release"), { inputs: "b".repeat(64), finding: "release finding" }) + let result = f.run(f.input(), env) + assert.match(report(result), /debug finding/) + assert.equal(f.health(result).analyzerReason, "build inputs match this tree") + await f.binary(f.local("debug"), { inputs: "b".repeat(64), finding: "debug finding", mtime: older }) + await f.binary(f.local("release"), { inputs: digest, finding: "release finding" }) + result = f.run(f.input(), env) + assert.match(report(result), /release finding/) + assert.equal(f.health(result).analyzerReason, "build inputs match this tree") +}) + +// Fails if PATH `bca` is left out of the probed candidates: the stale debug +// build is then "newest local build" and its finding is reported instead. +test("a PATH bca whose build inputs match beats stale local builds", async (t) => { + const f = await fixture(t) + const digest = "c".repeat(64) + const env = { ...(await f.digest(digest)), ...(await onPath(f, { inputs: digest, finding: "PATH finding" })) } + await f.binary(f.local("debug"), { inputs: "d".repeat(64), finding: "debug finding" }) + const result = f.run(f.input(), env) + assert.match(report(result), /PATH finding/) + assert.equal(f.health(result).analyzerReason, "build inputs match this tree") +}) + +// Fails if the mtime sort is removed (the debug row then always wins, so the +// second half picks debug) or inverted (the first half picks release). +test("when no candidate matches, the newest local build wins, then PATH", async (t) => { + const f = await fixture(t) + const env = await f.digest("e".repeat(64)) + const older = new Date(Date.now() - 60_000) + await f.binary(f.local("debug"), { inputs: "f".repeat(64), finding: "debug finding" }) + await f.binary(f.local("release"), { inputs: "f".repeat(64), finding: "release finding", mtime: older }) + let result = f.run(f.input(), env) + assert.match(report(result), /debug finding/) + assert.equal(f.health(result).analyzerReason, "newest local build (no candidate reports this tree's build inputs)") + await f.binary(f.local("debug"), { inputs: "f".repeat(64), finding: "debug finding", mtime: older }) + await f.binary(f.local("release"), { inputs: "f".repeat(64), finding: "release finding" }) + assert.match(report(f.run(f.input(), env)), /release finding/) + await rm(join(f.root, "target"), { recursive: true }) + const pathEnv = { ...env, ...(await onPath(f, { inputs: "f".repeat(64), finding: "PATH finding" })) } + result = f.run(f.input(), pathEnv) + assert.match(report(result), /PATH finding/) + assert.equal(f.health(result).analyzerReason, "PATH bca (no local build; no candidate reports this tree's build inputs)") +}) + +// A relative PATH entry names a directory under the checkout the hook runs +// the check in, which is where `spawn` resolves it too. Fails if `installed()` +// resolves PATH against the hook's own cwd (the fixture's temp dir, where +// `bin/` does not exist) or skips the entry: the matching PATH `bca` is then +// never probed and the stale debug build wins. The health line names the +// resolved file, so the binary that matched is the one recorded. +test("a relative PATH entry is resolved against the checkout and reported by file", async (t) => { + const f = await fixture(t) + const digest = "7".repeat(64) + const bin = join(f.root, "bin") + const env = { ...(await f.digest(digest)), ...(await onPath(f, { inputs: digest, finding: "PATH finding" }, bin)) } + env.PATH = `bin${delimiter}${f.env.PATH}` + await f.binary(f.local("debug"), { inputs: "8".repeat(64), finding: "debug finding" }) + const result = f.run(f.input(), env) + assert.match(report(result), /PATH finding/) + assert.equal(f.health(result).analyzer, join(bin, `bca${EXE}`)) + assert.equal(f.health(result).analyzerReason, "build inputs match this tree") +}) + +// A PATH `bca` that resolves to a local build — a `cargo install`ed symlink, +// or `target/release` on PATH — is one candidate, not two. Fails if the +// identity dedupe is dropped: the symlink is then probed again through its +// PATH name, after both local builds (audit-tests). +test("a PATH bca that is a local build is probed once", { skip: process.platform === "win32" && "symlinks need a privilege on Windows" }, async (t) => { + const f = await fixture(t) + const env = await f.digest("0".repeat(64)) + await f.binary(f.local("debug"), { inputs: "f".repeat(64), finding: "debug finding", mtime: new Date(Date.now() - 60_000) }) + await f.binary(f.local("release"), { inputs: "f".repeat(64), finding: "release finding" }) + const bin = join(f.temp, "bin") + await mkdir(bin) + await symlink(f.local("release"), join(bin, "bca")) + // Without the dedupe the symlink is probed by its own path, so that path + // must be routed too, or the extra probe would bypass the fake and go + // unrecorded — which is what made the earlier form of this test blind. + await f.route(join(bin, "bca"), f.local("release")) + const result = f.run(f.input(), { ...env, BCA: "", PATH: `${bin}${delimiter}${f.env.PATH}` }) + assert.match(report(result), /release finding/) + assert.equal(f.health(result).analyzerReason, "newest local build (no candidate reports this tree's build inputs)") + assert.deepEqual(await f.probes(), [f.local("debug"), f.local("release")]) +}) + +// Fails if the `$BCA` return is moved below the digest step: the matching +// debug build is then probed and chosen over the explicit analyzer. +test("explicit BCA is never probed and outranks a matching local build", async (t) => { + const f = await fixture(t) + const digest = "1".repeat(64) + const env = await f.digest(digest) + await f.binary(f.local("debug"), { inputs: digest, finding: "debug finding" }) + const result = f.run(f.input(), { ...env, BCA: f.stub }) + assert.ok(report(result).includes(ROW)) + assert.equal(f.health(result).analyzerReason, "BCA environment variable") + assert.deepEqual(await f.probes(), []) +}) + +// Fails if a failing or absent digest step is allowed to propagate: the hook +// must still pick a binary, by mtime, and say why the digest was skipped. +test("a failing or missing python3 still yields a local build", async (t) => { + const f = await fixture(t) + await f.binary(f.local("release"), { inputs: "2".repeat(64), finding: "release finding" }) + let result = f.run(f.input(), await f.digest(undefined)) + assert.match(report(result), /release finding/) + assert.equal(f.health(result).analyzerReason, "newest local build (python3 exited 1: error: the tree cannot be digested)") + await f.route("python3", undefined, { exec: join(f.temp, "no-such-python3") }) + result = f.run(f.input(), { BCA: "", BCA_DIGEST_SCRIPT: join(f.temp, "self_scan_digest.py") }) + assert.match(report(result), /release finding/) + assert.equal(f.health(result).analyzerReason, "newest local build (python3 ENOENT)") +}) + +// A digest script that cannot even be stat'ed — here a symlink loop, so the +// error is `ELOOP` rather than the `ENOENT` the hook already tolerates — is a +// discovery failure like any other, not a thrown error that turns the whole +// check `unavailable`. Fails if `treeDigest`'s stat is left unguarded. +test("a digest script that cannot be inspected still yields a local build", { skip: process.platform === "win32" && "symlinks need a privilege on Windows" }, async (t) => { + const f = await fixture(t) + await f.binary(f.local("release"), { inputs: "a".repeat(64), finding: "release finding" }) + const loop = join(f.temp, "digest-loop.py") + await symlink(loop, loop) + const result = f.run(f.input(), { BCA: "", BCA_DIGEST_SCRIPT: loop }) + assert.match(report(result), /release finding/) + assert.equal(f.health(result).analyzerReason, "newest local build (digest script ELOOP)") +}) + +// Two candidates each answering `--version` after 2.5 s: the first finishes +// inside `run()`'s 3 s TIMEOUT and does not match, the second would match at +// ~5 s, and the 4 s budget cuts it off first. Fails if the budget is removed +// or its abort is not chained into the probes: the release build then answers, +// matches, and is chosen with "build inputs match this tree". Decided on the +// output, not the clock — an earlier `elapsed < 5_500` form passed the +// unchained abort whenever the reason was read alone, and only its wall-clock +// bound (4.1 s measured against 6 s) told the two apart (audit-tests). +test("candidates that stall on --version are abandoned at the discovery budget", async (t) => { + const f = await fixture(t) + const digest = "3".repeat(64) + const env = await f.digest(digest) + await f.binary(f.local("debug"), { inputs: "4".repeat(64), finding: "debug finding", delay: 2_500 }) + await f.binary(f.local("release"), { inputs: digest, finding: "release finding", delay: 2_500, mtime: new Date(Date.now() - 60_000) }) + const result = f.run(f.input(), env) + assert.match(report(result), /debug finding/) + assert.equal(f.health(result).analyzerReason, "newest local build (discovery budget exhausted)") + assert.deepEqual(await f.probes(), [f.local("debug"), f.local("release")]) +}) + test("retargeting an edited symlink discards the old target's findings", async (t) => { const f = await fixture(t) const old = join(f.root, "old.rs") @@ -238,6 +458,38 @@ console.log(${JSON.stringify(ROW)}); process.exitCode = 2; quiet(f.run(f.input()), "superseded") }) +// Discovery runs under the hook's own signal: a SIGTERM that arrives while a +// candidate is stalling on `--version` ends the hook at once, with the +// stalled probe killed and no check run. Fails if the caller's signal is not +// chained into the discovery budget — the hook then sits out the full 4 s +// budget before exiting. The `--version` fake logs its probe before it +// stalls, which is the ready signal. +test("SIGTERM during discovery ends the hook without waiting out the budget", { skip: process.platform === "win32" }, async (t) => { + const f = await fixture(t) + const env = await f.digest("9".repeat(64)) + await f.binary(f.local("debug"), { inputs: "9".repeat(64), finding: "debug finding", delay: 5_000 }) + const probes = join(f.temp, "probes.txt") + const child = spawn(process.execPath, ["--import", pathToFileURL(f.preload).href, HOOK], { env: { ...f.env, ...env }, cwd: f.temp }) + t.after(() => child.kill("SIGKILL")) + let stdout = "" + let stderr = "" + child.stdout.on("data", (data) => { stdout += data }) + child.stderr.on("data", (data) => { stderr += data }) + const closed = once(child, "close") + child.stdin.end(JSON.stringify(f.input())) + const started = Date.now() + while (!(await f.probes()).length) { + assert.ok(Date.now() - started < 10_000, `no probe logged in ${probes}`) + await new Promise((wake) => setTimeout(wake, 25)) + } + child.kill("SIGTERM") + const [code] = await closed + assert.equal(code, 0) + assert.equal(stdout, "") + assert.ok(Date.now() - started < 3_000, `hook took ${Date.now() - started} ms after SIGTERM`) + assert.equal(JSON.parse(stderr.slice("[bca-check] ".length)).outcome, "cancelled") +}) + test("SIGTERM and SIGINT abort an active analyzer without later context", { skip: process.platform === "win32" }, async (t) => { const f = await fixture(t) await writeFile(f.stub, 'process.on("SIGTERM", () => {}); console.log("ready"); setInterval(() => {}, 1000);') diff --git a/utils/check-excluded-manifests.py b/utils/check-excluded-manifests.py index 4a468a0df..f69b54a11 100644 --- a/utils/check-excluded-manifests.py +++ b/utils/check-excluded-manifests.py @@ -91,10 +91,13 @@ # Excluded crates deliberately exempt from carrying a `[lints]` table. # -# The five vendored grammar forks hold ~60 lines of Rust each, and none -# of it is ours: `bindings/rust/lib.rs` and `build.rs` come out of +# The five vendored grammar forks hold ~60 lines of Rust each, and almost +# none of it is ours: `bindings/rust/lib.rs` and `build.rs` come out of # `tree-sitter generate` from the upstream binding templates, and are -# replaced wholesale when a grammar is regenerated. Applying the +# replaced wholesale when a grammar is regenerated. The one exception is +# the hand-maintained `src/tree_sitter/` header watch in `build.rs` +# (#1773), which `check-grammar-build-watch.py` gates separately +# (#1778); it does not change the lint decision here. Applying the # workspace's `pedantic` + `missing_docs` posture there would buy # annotations on generated code that the next regeneration discards, # against a body of code with no branching to get wrong. Nothing lints diff --git a/utils/check-grammar-build-watch-test.py b/utils/check-grammar-build-watch-test.py new file mode 100755 index 000000000..62caea9fc --- /dev/null +++ b/utils/check-grammar-build-watch-test.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +"""Tests for check-grammar-build-watch.py. + +Three kinds of test, matching the check-safety-doc-pin-test.py pattern: + +* Unit tests over the comment stripper and the manifest reader, weighted + toward the false-clean direction: a stripper that eats the block's own + string literals, or a reader that returns an empty crate list, both + make the gate report a clean tree. +* ``main()`` tests over a scratch repository root built from a minimal + ``Cargo.toml`` and one ``build.rs`` per crate, driven through + ``--root``. Every negative row is a shape a regeneration or a tidy-up + could plausibly leave behind, and each asserts on the message rather + than the exit code alone, so a gate that fails for the wrong reason is + still caught. +* A smoke test running the real gate against the real repository. + +Verified by perturbation (#1778): with ``main()`` patched to return 0 +before it reads anything (an edit to the file on disk, so the +``RealRepository`` subprocess smoke sees it too), every ``Main`` row +that asserts a failure goes red, plus the one ``Main`` row and the one +``RealRepository`` row that assert the ``OK`` line — 13 of 27; the +``canonical_block_is_what_the_tcl_script_carries`` row never calls +``main`` and stays green; with the block deleted from the live +``tree-sitter-mozjs`` script the real gate names that crate, prints +``block absent`` and exits 1. Reverting the crate filter from a +``tree-sitter`` substring to a ``tree-sitter-`` prefix fails exactly +``test_published_name_is_in_scope`` (stage-D M1). The stripper's +literal rules each have a row that fails when the rule is removed: no +``\\`` skip inside a string, a greedy ``'…'`` char-literal regex, a raw +string lexed as an ordinary one, and the ``/* */`` arm disabled — the +last also takes down the three rows whose fixture or expectation +carries a block comment, so the commented-out-block row is the +discriminating one by name rather than by count. + +Run with: + python3 -B -m unittest -q utils/check-grammar-build-watch-test.py +""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import pathlib +import subprocess +import sys +import tempfile +import unittest + +UTILS_DIR = pathlib.Path(__file__).resolve().parent +REPO_ROOT = UTILS_DIR.parent +SCRIPT_SRC = UTILS_DIR / "check-grammar-build-watch.py" + + +def _load_module(): # type: ignore[no-untyped-def] + spec = importlib.util.spec_from_file_location("check_grammar_build_watch", SCRIPT_SRC) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +GATE = _load_module() + +CRATES = ["tree-sitter-alpha", "tree-sitter-beta"] + +MANIFEST = """\ +[workspace] +members = ["big-code-analysis-cli"] +exclude = [ + "enums", + "fuzz", + "tree-sitter-alpha", + "tree-sitter-beta", +] +""" + +# The live block as #1773 wrote it, with its explanatory comment, in +# the tree-sitter-tcl shape (`std::path::Path::new`, no `use`). +PREAMBLE = """\ +fn main() { + let src_dir = std::path::Path::new("src"); + + // The parser and scanner include the headers under `src/tree_sitter/` + // (`parser.h`, and `alloc.h` / `array.h` where present). Watching only + // the two translation units below left a header-only edit with a stale + // object while the CLI's build-inputs digest (#1773) moved on — a + // binary advertising a tree it did not compile. +""" + +WATCH = GATE.CANONICAL_BLOCK + +TAIL = """\ + + let mut c_config = cc::Build::new(); + c_config.include(src_dir); + let parser_path = src_dir.join("parser.c"); + c_config.file(&parser_path); + println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap()); + let scanner_path = src_dir.join("scanner.c"); + c_config.file(&scanner_path); + println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap()); + c_config.compile("parser"); +} +""" + +GOOD = PREAMBLE + WATCH + TAIL + + +class StripComments(unittest.TestCase): + """What the stripper must and must not remove.""" + + def test_line_and_block_comments_go(self) -> None: + source = "a // x\nb /* y */ c\n/* multi\nline */ d" + self.assertEqual(GATE.tokens(source), ["a", "b", "c", "d"]) + + def test_nested_block_comment_is_one_comment(self) -> None: + self.assertEqual(GATE.strip_comments("a /* b /* c */ d */ e"), "a e") + + def test_string_literals_survive(self) -> None: + # The block's own payload: a `//`-free string, and one with `//` + # and `/*` inside it, neither of which may open a comment. + source = 'println!("cargo:rerun-if-changed={path}"); let s = "a // b /* c";' + self.assertEqual(GATE.strip_comments(source), source) + + def test_escaped_quote_does_not_end_the_string(self) -> None: + # One escaped quote, not a pair: with `\"` read as a terminator + # a pair re-opens a string on the second one and the comment + # that follows survives by accident (audit-tests, #1778). + source = 'let s = "say \\" // still string"; // gone' + self.assertEqual(GATE.strip_comments(source), 'let s = "say \\" // still string"; ') + + def test_char_literal_quote_does_not_open_a_string(self) -> None: + # `'"'` read as an unpaired `"` would swallow the rest of the + # file into a string and hide every later comment and token. + source = "let q = '\"'; // gone\nlet r = '\\''; // gone" + self.assertEqual(GATE.strip_comments(source), "let q = '\"'; \nlet r = '\\''; ") + + def test_raw_string_trailing_backslash_does_not_escape_its_quote(self) -> None: + # Lexed as an ordinary string, `r"a\"` would read `\"` as an + # escape, run on to the next `"`, and hide the comment between. + source = 'let r = r"a\\"; // gone\nlet h = r#"x"y"#; // gone\nlet z = 1;' + self.assertEqual( + GATE.strip_comments(source), 'let r = r"a\\"; \nlet h = r#"x"y"#; \nlet z = 1;' + ) + + def test_escaped_newline_continues_the_string(self) -> None: + # `"a\` + newline + `b"` is one Rust string. An escape pattern + # that cannot cross a newline leaves it open at the line end, + # pairs its closing quote with the next string's opening one, + # and everything between reads as code or comment at random + # (stage-E R1, #1778). + source = 'let s = "a\\\n b"; // gone\nlet t = "c"; // gone' + self.assertEqual(GATE.strip_comments(source), 'let s = "a\\\n b"; \nlet t = "c"; ') + + def test_lifetime_is_not_a_char_literal(self) -> None: + # Two lifetimes with the comment between them: a greedy `'…'` + # reading pairs `'a` with `'b` and the comment sits inside the + # phantom literal. `fn f<'a>(x: &'a str)` cannot see that, since + # its two `'a`s pair up before the comment (audit-tests, #1778). + source = "let a: &'a str = x; // gone\nlet b: &'b str = y;" + self.assertEqual(GATE.strip_comments(source), "let a: &'a str = x; \nlet b: &'b str = y;") + + +class VendoredCrates(unittest.TestCase): + def test_filters_to_the_substring_in_manifest_order(self) -> None: + self.assertEqual(GATE.vendored_crates(MANIFEST), CRATES) + + def test_published_name_is_in_scope(self) -> None: + # The five crates publish as `bca-tree-sitter-*`; a sixth laid + # out under that name, or a `dekobon-tree-sitter-*`, must be + # checked rather than silently skipped (stage-D M1, #1778). + manifest = ( + "[workspace]\n" + 'exclude = ["enums", "bca-tree-sitter-x", "fuzz", "dekobon-tree-sitter-y"]\n' + ) + self.assertEqual( + GATE.vendored_crates(manifest), ["bca-tree-sitter-x", "dekobon-tree-sitter-y"] + ) + + def test_missing_exclude_is_rejected(self) -> None: + with self.assertRaises(GATE.ManifestError): + GATE.vendored_crates('[workspace]\nmembers = ["x"]\n') + + def test_no_vendored_entry_is_rejected(self) -> None: + # An empty list would pass the gate with nothing checked. + with self.assertRaises(GATE.ManifestError): + GATE.vendored_crates('[workspace]\nexclude = ["enums", "fuzz"]\n') + + def test_non_string_entry_is_rejected(self) -> None: + with self.assertRaises(GATE.ManifestError): + GATE.vendored_crates('[workspace]\nexclude = ["tree-sitter-a", 1]\n') + + +@contextlib.contextmanager +def _scratch_repo( # type: ignore[no-untyped-def] + scripts: dict[str, str | bytes | None], manifest: str | None = MANIFEST +): + """A throwaway root with one crate per key. + + ``None`` for a crate means no build.rs; ``bytes`` are written raw. + ``manifest=None`` writes no Cargo.toml at all. + """ + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + if manifest is not None: + (root / "Cargo.toml").write_text(manifest, encoding="utf-8") + for crate, source in scripts.items(): + script = root / crate / GATE.BUILD_SCRIPT + script.parent.mkdir(parents=True) + if isinstance(source, bytes): + script.write_bytes(source) + elif source is not None: + script.write_text(source, encoding="utf-8") + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + yield lambda: (GATE.main(["--root", str(root)]), out.getvalue(), err.getvalue()) + + +def _both(source: str | None) -> dict[str, str | None]: + return dict.fromkeys(CRATES, source) + + +class Main(unittest.TestCase): + def test_canonical_block_passes(self) -> None: + with _scratch_repo(_both(GOOD)) as run: + code, out, err = run() + self.assertEqual(code, 0, err) + self.assertIn("grammar-build-watch: OK (2 vendored crate(s)", out) + self.assertEqual(err, "") + + def test_reflowed_block_passes(self) -> None: + # Tokens, not text: a re-indented, re-commented copy is the same + # block, and so is one rustfmt has wrapped at a bracket where the + # canonical spelling has no whitespace at all (`println!(\n"…"`). + reflowed = ( + "fn main() {\n" + 'let src_dir = std::path::Path::new("src");\n' + ' let headers = src_dir.join("tree_sitter"); /* watch */\n' + " if let Ok(entries) =\n" + " std::fs::read_dir(&headers)\n" + " {\n" + " for entry in entries.flatten() { match entry.path().to_str() {\n" + ' Some(path) => println!("cargo:rerun-if-changed={path}"),\n' + " None => println!(\n" + ' "cargo:rerun-if-changed={}",\n' + " headers.display()\n" + " ),\n" + " } }\n" + " }\n" + TAIL + ) + with _scratch_repo(_both(reflowed)) as run: + code, _out, err = run() + self.assertEqual(code, 0, err) + + def test_continued_string_before_the_block_passes(self) -> None: + # End to end: a valid escaped-newline continuation ahead of the + # watch must not make an intact block read as absent (R1). + continued = PREAMBLE.replace( + 'let src_dir = std::path::Path::new("src");', + 'println!("cargo:warning=vendored \\\n grammar");\n' + ' let src_dir = std::path::Path::new("src");', + ) + self.assertNotEqual(continued, PREAMBLE) + with _scratch_repo(_both(continued + WATCH + TAIL)) as run: + code, _out, err = run() + self.assertEqual(code, 0, err) + + def test_block_deleted_but_comment_kept_fails_naming_the_crate(self) -> None: + # The explanatory comment alone must not satisfy the gate — a + # token check that keyed on `tree_sitter` would pass this. + with _scratch_repo({CRATES[0]: GOOD, CRATES[1]: PREAMBLE + TAIL}) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("error: tree-sitter-beta: tree-sitter-beta/bindings/rust/build.rs", err) + self.assertIn("block absent", err) + self.assertNotIn("tree-sitter-alpha", err) + + def test_block_commented_out_fails(self) -> None: + # The block's own tokens, present but dead. Each shape must read + # as absent *because* its comment was stripped: with the + # `/* */` arm disabled the wrapped copy passes the gate, and the + # explanatory-comment row above cannot see that, since its + # comment never carried the block's tokens (audit-tests, #1778). + # The `/* */` wrapper is the shape the upstream template itself + # uses for its disabled C++ scanner block. + wrapped = PREAMBLE + " /*\n" + WATCH + " */\n" + TAIL + lined = PREAMBLE + "".join(f" //{line}\n" for line in WATCH.splitlines()) + TAIL + for label, source in [("/* */", wrapped), ("//", lined)]: + with self.subTest(label): + with _scratch_repo(_both(source)) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("error: tree-sitter-alpha:", err) + self.assertIn("block absent", err) + + def test_read_dir_loop_deleted_fails(self) -> None: + # `let headers = …` survives; nothing is watched. + stub = PREAMBLE + ' let headers = src_dir.join("tree_sitter");\n' + TAIL + with _scratch_repo({CRATES[0]: stub, CRATES[1]: GOOD}) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("error: tree-sitter-alpha:", err) + self.assertIn("does not carry the src/tree_sitter/ header watch", err) + + def test_emission_replaced_fails_with_a_diff(self) -> None: + # The loop runs but watches the wrong thing. The closest region + # is diffed so the reader sees which token moved. + wrong = GOOD.replace( + 'Some(path) => println!("cargo:rerun-if-changed={path}"),', + 'Some(_) => println!("cargo:rerun-if-changed=build.rs"),', + ) + self.assertNotEqual(wrong, GOOD) + with _scratch_repo(_both(wrong)) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("--- expected", err) + self.assertIn('\n -"cargo:rerun-if-changed={path}"\n', err) + self.assertIn('\n +"cargo:rerun-if-changed=build.rs"\n', err) + # Whole tokens on both sides: a region sliced on character + # offsets opened the diff mid-literal (`+rc");`). + for line in err.splitlines(): + if line.startswith((" +", " -")) and not line.startswith((" +++", " ---")): + self.assertEqual(GATE.tokens(line[3:]), [line[3:]], line) + + def test_only_parser_and_scanner_watches_fails(self) -> None: + # The upstream template shape: `rerun-if-changed` is present for + # the two translation units and nothing else. + with _scratch_repo(_both("fn main() {\n" + TAIL)) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("error: tree-sitter-alpha:", err) + self.assertIn("error: tree-sitter-beta:", err) + + def test_missing_build_rs_fails(self) -> None: + with _scratch_repo({CRATES[0]: GOOD, CRATES[1]: None}) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("error: tree-sitter-beta: could not read", err) + + def test_excluded_crate_without_a_directory_fails(self) -> None: + # Discovery is not hardcoded: a sixth entry is checked and, with + # no directory behind it, fails by name. + manifest = MANIFEST.replace( + ' "tree-sitter-beta",\n', ' "tree-sitter-beta",\n "tree-sitter-extra",\n' + ) + self.assertNotEqual(manifest, MANIFEST) + with _scratch_repo(_both(GOOD), manifest) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn( + "error: tree-sitter-extra: listed in [workspace].exclude but is not a directory", + err, + ) + + def test_non_utf8_build_rs_fails_without_a_traceback(self) -> None: + # `UnicodeDecodeError` is not an `OSError`; uncaught it is a + # traceback and an exit of 1 by accident rather than a verdict. + with _scratch_repo({CRATES[0]: GOOD, CRATES[1]: b"fn main() { \xff }\n"}) as run: + code, _out, err = run() + self.assertEqual(code, 1) + self.assertIn("error: tree-sitter-beta: could not read", err) + self.assertNotIn("Traceback", err) + + def test_malformed_exclude_exits_two(self) -> None: + with _scratch_repo(_both(GOOD), manifest="[workspace]\nexclude = 7\n") as run: + code, _out, err = run() + self.assertEqual(code, 2) + self.assertIn("could not derive the vendored crate list", err) + self.assertIn("not a string array", err) + + def test_unparseable_manifest_exits_two(self) -> None: + with _scratch_repo(_both(GOOD), manifest="[workspace\nexclude = [\n") as run: + code, _out, err = run() + self.assertEqual(code, 2) + self.assertIn("could not derive the vendored crate list", err) + + def test_missing_manifest_exits_two(self) -> None: + with _scratch_repo(_both(GOOD), manifest=None) as run: + code, _out, err = run() + self.assertEqual(code, 2) + self.assertIn("could not derive the vendored crate list", err) + self.assertIn("No such file", err) + + +class RealRepository(unittest.TestCase): + def test_gate_passes_on_the_checked_in_tree(self) -> None: + result = subprocess.run( + [sys.executable, "-B", str(SCRIPT_SRC)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("grammar-build-watch: OK (5 vendored crate(s)", result.stdout) + + def test_canonical_block_is_what_the_tcl_script_carries(self) -> None: + # The constant's provenance claim: it is lifted from tcl's + # build.rs. Compared as tokens, exactly as the gate compares, so + # a comment-only edit or a reindent of tcl's block changes + # neither verdict; a change to the watch itself changes both. + tcl = REPO_ROOT / "tree-sitter-tcl" / GATE.BUILD_SCRIPT + self.assertTrue( + GATE.contains_run(GATE.tokens(tcl.read_text(encoding="utf-8")), GATE.canonical()) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/check-grammar-build-watch.py b/utils/check-grammar-build-watch.py new file mode 100755 index 000000000..003dc30b0 --- /dev/null +++ b/utils/check-grammar-build-watch.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +"""check-grammar-build-watch + +Guard that every vendored grammar crate's ``bindings/rust/build.rs`` +still carries the hand-maintained block that ``rerun-if-changed``-watches +the headers under ``src/tree_sitter/``. + +#1773 added that block to the five vendored build scripts. Before it, a +header-only edit (``parser.h``, ``alloc.h``, ``array.h``) left a stale +parser object behind a fresh ``build inputs:`` digest — a binary +advertising a tree it did not compile. The block is the one thing in +those files that is *not* generated binding boilerplate: AGENTS.md +exempts the vendored crates from the workspace lint tables because a +regeneration replaces their sources wholesale, and ``recreate-grammars.sh`` +/ ``generate-grammars/*.sh`` happen to leave ``build.rs`` alone today. +Nothing but this gate would notice if a future regeneration, an upstream +template refresh, or a tidy-up dropped the block, and the symptom is +exactly the one it exists to prevent (#1778). + +The check is verbatim, not shape-based. Each ``build.rs`` is stripped of +``//`` and ``/* */`` comments (string and char literals are left intact — +the block itself prints ``cargo:rerun-if-changed=``) and lexed into +tokens: a literal, a word, or one punctuation character each, with the +whitespace between them discarded. The canonical block, lexed the same +way, must appear as a contiguous run of that token sequence. Comparing +tokens rather than whitespace-collapsed text is what makes a rustfmt +re-wrap at a bracket (``println!(\n"…",\n…\n)``) a no-op without +admitting anything else; a shape check — "names ``tree_sitter`` +somewhere near a ``rerun-if-changed``" — was considered and rejected, +since it admits a file that names the path but never watches it. + +The crate list is derived from the root ``Cargo.toml``'s +``[workspace].exclude`` array, keeping every entry whose name contains +``tree-sitter``, so a sixth vendored grammar is in scope the moment it +is excluded. A listed crate with no directory, or one with no +``build.rs`` at all, fails: the latter *is* the regeneration-dropped-it +case and is never skipped. + +``--root `` points the gate at another checkout, which is how the +self-tests drive it over scratch layouts. + +See AGENTS.md "Rust conventions" for the exemption this qualifies. +""" + +from __future__ import annotations + +import argparse +import difflib +import pathlib +import re +import sys +import tomllib + +# `parents[1]`, not `parent`: these gates live in `utils/` but every +# path they read is anchored at the repository root. +REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] + +BUILD_SCRIPT = pathlib.Path("bindings") / "rust" / "build.rs" + +# An excluded entry whose name contains this is a vendored grammar. A +# substring rather than a `tree-sitter-` prefix, for the reason +# `check-excluded-manifests.py` gives for its dependency rule: the five +# crates are published as `bca-tree-sitter-*`, and a sixth laid out under +# its published name — or a `dekobon-tree-sitter-*` — would otherwise be +# silently out of scope while the gate printed OK. The other excluded +# entries (`enums`, `fuzz`, `.claude/worktrees`) contain no such substring. +VENDORED_SUBSTRING = "tree-sitter" + +# Lifted verbatim from tree-sitter-tcl/bindings/rust/build.rs (lines 9-19 +# at #1773), where the other four crates carry the identical statement. +# Comments and whitespace are irrelevant to the comparison — both sides +# go through `tokens(…)` — so the block is kept in its source spelling +# for readability. A deliberate change to the watch in the build scripts +# is also a change to this constant; the gate fails until the two agree +# again, which is the point. +CANONICAL_BLOCK = """\ + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { + for entry in entries.flatten() { + match entry.path().to_str() { + Some(path) => println!("cargo:rerun-if-changed={path}"), + // A name cargo cannot be told exactly: watch the directory + // instead, which changes whenever that file is replaced. + None => println!("cargo:rerun-if-changed={}", headers.display()), + } + } + } +""" + +# One string or char literal, matched at the current position. In order: +# a raw string `r"…"` / `r#"…"#` (the `\1` backreference closes it on the +# same number of hashes, and nothing inside is an escape), an ordinary +# string with `\"` skipped, and a char literal `'x'` / `'\n'` / `'\''`. +# Anything else after a `'` is a lifetime or label and carries no closing +# quote to pair with. The escape is `\\[\s\S]`, not `\\.`: a backslash +# at end of line is Rust's string continuation, and `.` without DOTALL +# stops at the newline, leaves the string unterminated, and mispairs +# every quote after it (stage-E R1). +LITERAL = r'b?r(#*)"[\s\S]*?"\1|"(?:\\[\s\S]|[^"\\])*"|\'(?:\\[\s\S]|[^\\\'])\'' +LITERAL_AT = re.compile(LITERAL) + +# A token is a literal, a word, or one punctuation character; whitespace +# separates tokens and is otherwise meaningless. +TOKEN = re.compile(LITERAL + r"|\w+|[^\w\s]") + +# A candidate region less similar than this to the canonical block is +# not a damaged copy of it; the file simply does not carry the block. +# The anchor alone cannot decide that: every grammar build.rs shares +# `println!("cargo:rerun-if-changed={}",` with the block through its +# parser.c / scanner.c watches, so an anchor always exists. +MIN_SIMILARITY = 0.5 + + +class ManifestError(Exception): + """The root manifest did not yield a usable vendored-crate list.""" + + +def vendored_crates(manifest_text: str) -> list[str]: + """Return the ``[workspace].exclude`` entries naming ``tree-sitter``. + + Raises :class:`ManifestError` when the array is absent, malformed, + or names no vendored grammar at all — an empty list would make the + gate pass vacuously, which is the one verdict it must never give. + """ + data = tomllib.loads(manifest_text) + workspace = data.get("workspace") + exclude = workspace.get("exclude") if isinstance(workspace, dict) else None + if not isinstance(exclude, list) or not all(isinstance(e, str) for e in exclude): + raise ManifestError("[workspace].exclude is missing or is not a string array") + crates = [entry for entry in exclude if VENDORED_SUBSTRING in entry] + if not crates: + raise ManifestError(f"[workspace].exclude names no `*{VENDORED_SUBSTRING}*` crate") + return crates + + +def strip_comments(source: str) -> str: + """Remove ``//`` line comments and (nested) ``/* */`` block comments. + + String and char literals are copied through untouched, so a ``//`` + or ``/*`` inside ``"cargo:rerun-if-changed=…"`` cannot open a + comment, a ``'"'`` char literal cannot open a string, and a raw + string's trailing backslash cannot escape its closing quote. An + unterminated literal is copied one character at a time, so it + hides nothing after it. + """ + out: list[str] = [] + i, n = 0, len(source) + while i < n: + two = source[i : i + 2] + if m := LITERAL_AT.match(source, i): + out.append(m.group(0)) + i = m.end() + elif two == "//": + end = source.find("\n", i) + i = n if end == -1 else end + elif two == "/*": + depth, i = 1, i + 2 + while i < n and depth: + if source.startswith("/*", i): + depth, i = depth + 1, i + 2 + elif source.startswith("*/", i): + depth, i = depth - 1, i + 2 + else: + i += 1 + else: + out.append(source[i]) + i += 1 + return "".join(out) + + +def tokens(source: str) -> list[str]: + """Lex comment-stripped Rust into literal / word / punctuation tokens.""" + return [m.group(0) for m in TOKEN.finditer(strip_comments(source))] + + +def canonical() -> list[str]: + return tokens(CANONICAL_BLOCK) + + +def contains_run(haystack: list[str], needle: list[str]) -> bool: + """True when ``needle`` occurs as a contiguous run inside ``haystack``.""" + width = len(needle) + return any(haystack[i : i + width] == needle for i in range(len(haystack) - width + 1)) + + +def closest_region(expected: list[str], haystack: list[str]) -> list[str] | None: + """The run of ``haystack`` that best lines up with ``expected``. + + Anchored on the longest common token run; ``None`` when the region + that anchor selects is not recognisably a copy of the block. + """ + match = difflib.SequenceMatcher(None, expected, haystack, autojunk=False) + longest = match.find_longest_match(0, len(expected), 0, len(haystack)) + start = max(0, longest.b - longest.a) + region = haystack[start : start + len(expected)] + if difflib.SequenceMatcher(None, expected, region, autojunk=False).ratio() < MIN_SIMILARITY: + return None + return region + + +def report_diff(expected: list[str], actual: list[str] | None, label: str) -> str: + if actual is None: + return " block absent\n" + lines = difflib.unified_diff(expected, actual, fromfile="expected", tofile=label, lineterm="") + return "".join(f" {line}\n" for line in lines) + + +def check_crate(root: pathlib.Path, crate: str) -> str | None: + """Return a failure message for ``crate``, or ``None`` when it passes.""" + script = root / crate / BUILD_SCRIPT + rel = script.relative_to(root) + if not (root / crate).is_dir(): + return f"error: {crate}: listed in [workspace].exclude but is not a directory\n" + try: + source = script.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as exc: + return f"error: {crate}: could not read {rel}: {exc}\n" + expected = canonical() + haystack = tokens(source) + if contains_run(haystack, expected): + return None + return ( + f"error: {crate}: {rel} does not carry the src/tree_sitter/ header watch\n" + + report_diff(expected, closest_region(expected, haystack), str(rel)) + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--root", + type=pathlib.Path, + default=REPO_ROOT, + help="repository root to check (default: the checkout this script lives in)", + ) + root = parser.parse_args(argv).root.resolve() + manifest = root / "Cargo.toml" + + try: + crates = vendored_crates(manifest.read_text(encoding="utf-8")) + except (OSError, ManifestError, tomllib.TOMLDecodeError) as exc: + sys.stderr.write( + f"error: could not derive the vendored crate list from {manifest}: {exc}\n" + ) + return 2 + + failures = [msg for crate in crates if (msg := check_crate(root, crate))] + if failures: + sys.stderr.writelines(failures) + sys.stderr.write( + "\nEach vendored grammar's bindings/rust/build.rs must watch every file\n" + "under src/tree_sitter/ with cargo:rerun-if-changed, or a header-only\n" + "edit leaves a stale parser object behind a fresh `build inputs:`\n" + "digest (#1773). The block is hand-maintained — a regeneration does\n" + "not restore it. Re-apply it from a sibling crate, or if the change\n" + "is deliberate, update CANONICAL_BLOCK in utils/check-grammar-build-watch.py\n" + "and every build.rs together (#1778).\n" + ) + return 1 + + print(f"grammar-build-watch: OK ({len(crates)} vendored crate(s) watch src/tree_sitter/)") + return 0 + + +if __name__ == "__main__": + sys.exit(main())