From 22552525d54f349571c1e9d43d9535abea3df9b7 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:21:10 +0800 Subject: [PATCH 01/12] fix(ci): preserve per-job findings and unavailable blob evidence --- scripts/ci/artifacts.mjs | 14 ++- scripts/ci/failure-report.mjs | 50 ++++---- .../filesystem/ciFailureReport.test.ts | 16 +++ .../filesystem/ciFailureReportBudget.test.ts | 117 ++++++++++++++++++ 4 files changed, 170 insertions(+), 27 deletions(-) diff --git a/scripts/ci/artifacts.mjs b/scripts/ci/artifacts.mjs index 9a7cc1c21..250a15872 100644 --- a/scripts/ci/artifacts.mjs +++ b/scripts/ci/artifacts.mjs @@ -87,10 +87,13 @@ export function classifyFailure({ "unknown", "main_run_does_not_contain_the_same_structured_diagnostic", ); - if (!sameBlobEvidence(diagnostics, blobs)) + const blobStatus = blobIdentityStatus(diagnostics, blobs); + if (blobStatus !== "identical") return outcome( "unknown", - "diagnostic_source_content_not_identical_at_main_and_tested_base", + blobStatus === "different" + ? "diagnostic_source_content_not_identical_at_main_and_tested_base" + : "diagnostic_source_blob_identity_unavailable", ); return outcome( "matching-main-diagnostics", @@ -366,9 +369,12 @@ function diagnosticKey(item) { return JSON.stringify([item.kind, ...[...item.paths].sort()]); return null; } -function sameBlobEvidence(diagnostics, blobs) { +function blobIdentityStatus(diagnostics, blobs) { const paths = [...new Set(diagnostics.flatMap(diagnosticPaths))]; - return paths.length > 0 && paths.every((path) => blobs?.[path] === true); + if (paths.some((path) => blobs?.[path] === false)) return "different"; + return paths.length > 0 && paths.every((path) => blobs?.[path] === true) + ? "identical" + : "unavailable"; } function sameTaskHashes(diagnostics, left, right) { return diagnostics.every((diagnostic) => { diff --git a/scripts/ci/failure-report.mjs b/scripts/ci/failure-report.mjs index 2ce6d813c..12364c59f 100644 --- a/scripts/ci/failure-report.mjs +++ b/scripts/ci/failure-report.mjs @@ -153,16 +153,21 @@ async function analyzeFailedRun({ ]; const failures = []; for (const job of failedJobs) { - const evidence = await api.getStaticEvidence(repository, run, job); - const classification = await attributeToMain({ - repository, - defaultBranch, - run, - job, - evidence, - mainCandidates, - api, - }); + let classification; + try { + const evidence = await api.getStaticEvidence(repository, run, job); + classification = await attributeToMain({ + repository, + defaultBranch, + run, + job, + evidence, + mainCandidates, + api, + }); + } catch (error) { + classification = outcome("unknown", errorCode(error)); + } failures.push({ runId: entry.id, runAttempt: entry.runAttempt, @@ -415,26 +420,25 @@ export function createGitHubApi({ for (const path of paths) { if (!validRepoPath(path)) continue; const [left, right] = await Promise.all([ - getContent(repository, ancestor, path, request), - getContent(repository, descendant, path, request), + getContentBlobSha(repository, ancestor, path, request), + getContentBlobSha(repository, descendant, path, request), ]); - result[path] = left !== null && left === right; + result[path] = left === right; } return result; }, }; } -async function getContent(repository, ref, path, request) { - try { - const encodedPath = path.split("/").map(encodeURIComponent).join("/"); - const value = await request( - `repos/${repository}/contents/${encodedPath}?ref=${encodeURIComponent(ref)}`, - ); - return typeof value.sha === "string" ? value.sha : null; - } catch { - return null; - } +async function getContentBlobSha(repository, ref, path, request) { + const encodedPath = path.split("/").map(encodeURIComponent).join("/"); + const value = await request( + `repos/${repository}/contents/${encodedPath}?ref=${encodeURIComponent(ref)}`, + ); + const sha = safeSha(value?.sha); + if (value?.type !== "file" || sha === null) + throw new Error("github_content_blob_identity_unavailable"); + return sha; } function outcome(classification, reason) { diff --git a/tests/boundary/filesystem/ciFailureReport.test.ts b/tests/boundary/filesystem/ciFailureReport.test.ts index 26feb3ee2..c2a282906 100644 --- a/tests/boundary/filesystem/ciFailureReport.test.ts +++ b/tests/boundary/filesystem/ciFailureReport.test.ts @@ -120,6 +120,22 @@ it.each([ expect(result.classification).toBe("unknown"); }); +it.each([ + [{}, "diagnostic_source_blob_identity_unavailable"], + [ + { "src/example.ts": false }, + "diagnostic_source_content_not_identical_at_main_and_tested_base", + ], +] as const)( + "distinguishes unavailable blob identity from verified differences (%s)", + (blobs, reason) => { + expect(classifyFailure({ ...comparison(), blobs })).toEqual({ + classification: "unknown", + reason, + }); + }, +); + it("writes informational JSON and Markdown from the supplied manifest using only read API calls", async () => { const directory = await createTestTempDirectory("rea-ci-failure-test-"); const calls: string[] = []; diff --git a/tests/boundary/filesystem/ciFailureReportBudget.test.ts b/tests/boundary/filesystem/ciFailureReportBudget.test.ts index 92fe3e4ae..1caacde16 100644 --- a/tests/boundary/filesystem/ciFailureReportBudget.test.ts +++ b/tests/boundary/filesystem/ciFailureReportBudget.test.ts @@ -2,6 +2,7 @@ import { expect, it } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { reportCiFailures, + createGitHubApi, type CiRun, type FailureReportApi, type StaticDiagnostic, @@ -235,6 +236,10 @@ it.each([1, 51])( expect(result.failures[0]!.classification).toBe( count === 1 ? "matching-main-diagnostics" : "unknown", ); + if (count > 50) + expect(result.failures[0]!.reason).toBe( + "diagnostic_source_blob_identity_unavailable", + ); }, ); @@ -288,3 +293,115 @@ it.each(["jobs", "artifact", "comparison"])( expect(input.artifacts.filter((id) => id === 21)).toHaveLength(1); }, ); + +it.each([0, 1, 2])( + "preserves every failed job when artifact analysis fails at position %s", + async (position) => { + const input = fixture([20], 1); + const jobs = [ + { name: "Python producer", conclusion: "failure" }, + { name: "Test shard (1)", conclusion: "timed_out" }, + ]; + jobs.splice(position, 0, { name: "Static checks", conclusion: "failure" }); + input.api.getJobs = async (_repository, id, attempt) => + jobs.map((job) => ({ + ...job, + status: "completed", + run_id: Number(id), + run_attempt: attempt, + })); + input.api.getStaticEvidence = async (_repository, _run, job) => { + if (job.name === "Static checks") + throw new Error("static_artifact_unavailable"); + return null; + }; + const result = await report(input); + expect(result.counts.unknown).toBe(3); + expect(result.failures).toEqual( + jobs.map((job) => ({ + runId: 100, + runAttempt: 1, + runHead: prSha, + event: "pull_request", + job: job.name, + conclusion: job.conclusion, + classification: "unknown", + reason: + job.name === "Static checks" + ? "static_artifact_unavailable" + : "no_matching_verified_main_failure", + })), + ); + }, +); + +it("keeps unavailable job inventories at run scope", async () => { + const input = fixture([], 1); + input.api.getJobs = async () => { + throw new Error("job_inventory_unavailable"); + }; + expect((await report(input)).failures).toEqual([ + { + runId: 100, + runAttempt: 1, + classification: "unknown", + reason: "job_inventory_unavailable", + }, + ]); +}); + +it.each([ + ["request", "github_api_temporarily_unavailable"], + ["budget", "github_api_request_budget_exhausted"], + ["missing sha", "github_content_blob_identity_unavailable"], + ["invalid sha", "github_content_blob_identity_unavailable"], + ["directory", "github_content_blob_identity_unavailable"], +] as const)( + "retains unavailable blob evidence as a comparison error: %s", + async (failure, reason) => { + const input = fixture([20], 1); + const contentApi = createGitHubApi({ + token: "fixture-token", + apiRequest: async () => { + if (failure === "request") throw new Error(reason); + if (failure === "missing sha") return { type: "file" }; + if (failure === "invalid sha") + return { type: "file", sha: "not-a-sha" }; + if (failure === "directory") return []; + return { type: "file", sha: "e".repeat(40) }; + }, + }); + if (failure === "budget") { + for (let id = 1; id <= 250; id++) await contentApi.getRun(repository, id); + } + input.api.getBlobIdentity = contentApi.getBlobIdentity; + const result = await report(input); + expect(result.failures).toMatchObject([ + { + job: "Static checks", + classification: "unknown", + reason: "no_matching_verified_main_failure", + candidateFailures: [{ runId: 20, runAttempt: 1, reason }], + }, + ]); + }, +); + +it.each([true, false])( + "reports blob equality only from verified file SHAs (equal: %s)", + async (equal) => { + const api = createGitHubApi({ + token: "fixture-token", + apiRequest: async (_method, endpoint) => ({ + type: "file", + sha: + equal || endpoint.includes(`ref=${mainSha}`) + ? "e".repeat(40) + : "f".repeat(40), + }), + }); + expect( + await api.getBlobIdentity(repository, mainSha, prSha, ["src/example.ts"]), + ).toEqual({ "src/example.ts": equal }); + }, +); From cd740a6764d24e466f31613c2cef3368c3f64cba Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:23:08 +0800 Subject: [PATCH 02/12] test(hopper): fix fixture context and cleanup assumptions --- .../acceptance/providers/hopperStartupRecovery.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/acceptance/providers/hopperStartupRecovery.test.ts b/tests/acceptance/providers/hopperStartupRecovery.test.ts index 842fdaa07..f35ec68d6 100644 --- a/tests/acceptance/providers/hopperStartupRecovery.test.ts +++ b/tests/acceptance/providers/hopperStartupRecovery.test.ts @@ -306,7 +306,7 @@ test.for(["handoff", "not-found"] as const)( const token = setting("REA_TOKEN"); const runId = setting("REA_RUN_ID"); runtime = dirname(socket); - const lateBridge = async (identity: string, credential = token) => { + const lateBridge = (identity: string, credential = token) => { const child = spawn( process.execPath, [ @@ -318,14 +318,14 @@ test.for(["handoff", "not-found"] as const)( { stdio: "ignore" }, ); children.push(child); - await vi.waitFor(() => access(socket)); return child; }; for (const [identity, credential] of [ ["different-run", token], [runId, "different-token"], ] as const) { - const wrong = await lateBridge(identity, credential); + const wrong = lateBridge(identity, credential); + await vi.waitFor(() => access(socket)); expect(parseMcpToolError(await call("close_binary")).error.code).toBe( "cleanup_incomplete", ); @@ -336,7 +336,9 @@ test.for(["handoff", "not-found"] as const)( } const closing = call("close_binary"); await delay(150); - const owned = await lateBridge(runId); + // A verified close may remove the socket before the fixture can poll it. + // The successful close and child exit establish the owned bridge outcome. + const owned = lateBridge(runId); expect((await closing).isError).not.toBe(true); await vi.waitFor(() => expect(owned.exitCode).toBe(0)); await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" }); From 7e9fb6f1bbea8aad1704627d5961d88067680051 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:32:39 +0800 Subject: [PATCH 03/12] test(javascript): run native type bindings with compiled boundary prerequisites --- .../javascript/nativeTypeBindings.test.ts | 27 ++++++------------- 1 file changed, 8 insertions(+), 19 deletions(-) rename {src/application => tests/boundary}/javascript/nativeTypeBindings.test.ts (77%) diff --git a/src/application/javascript/nativeTypeBindings.test.ts b/tests/boundary/javascript/nativeTypeBindings.test.ts similarity index 77% rename from src/application/javascript/nativeTypeBindings.test.ts rename to tests/boundary/javascript/nativeTypeBindings.test.ts index 6fcf8791e..b0ec74d81 100644 --- a/src/application/javascript/nativeTypeBindings.test.ts +++ b/tests/boundary/javascript/nativeTypeBindings.test.ts @@ -1,27 +1,16 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { afterEach, expect, it } from "vitest"; +import { expect, it } from "vitest"; -import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js"; -import type { JavaScriptApplicationAnalysisResult } from "../../domain/javascript/javascriptApplicationAnalysis.js"; -import { buildJavaScriptNativeHandoffs } from "../../domain/javascript/javascriptNativeHandoff.js"; -import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js"; - -const fixtures: string[] = []; - -afterEach(async () => { - await Promise.all( - fixtures - .splice(0) - .map((path) => rm(path, { recursive: true, force: true })), - ); -}); +import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js"; +import type { JavaScriptApplicationAnalysisResult } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; +import { buildJavaScriptNativeHandoffs } from "../../../src/domain/javascript/javascriptNativeHandoff.js"; +import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; const analyzeFixture = async (source: string) => { - const fixture = await mkdtemp(join(tmpdir(), "rea-native-types-")); - fixtures.push(fixture); + const fixture = await createTestTempDirectory("rea-native-types-"); const scope = new ArtifactResourceScope(); try { await writeFile(join(fixture, "main.ts"), `${source}\n`); From c86b09a1095ffd360cd8851ff20a7b6aeb19b198 Mon Sep 17 00:00:00 2001 From: Ariel Fikru Avicenna <71917936+arielfikru@users.noreply.github.com> Date: Wed, 14 Oct 2026 05:35:55 +0700 Subject: [PATCH 04/12] feat(ghidra): admit 32-bit big-endian PowerPC ELF (#1747) * feat(ghidra): admit 32-bit big-endian PowerPC ELF Recognize EM_PPC as a provider-neutral `powerpc` family that keeps its ELF class, byte order, type and flags, and admit ELF32 big-endian ET_EXEC through a bounded Ghidra lane. ELF64, little-endian, relocatable/shared objects and EF_PPC_EMB are refused with a specific reason; Hopper and IDA do not gain PowerPC support, and Windows Ghidra P0 is unchanged. Ghidra's ELF loader selects PowerPC:BE:32:e500:default for a plain EM_PPC header, which misreads 750-family code. The lane binds PowerPC:BE:32:default/default in the profile (language_selection "admitted-lane-v1"), imports with it and checks the reported language. A language set through REA_GHIDRA_LANGUAGE_ID still replaces the lane default. Add a source-owned fixture, fixed-encoding probe, GNU readelf cross-check and the optional `verify:ghidra:ppc` real-provider lane, plus docs/ghidra-ppc.md. Refs #1741 * style(ghidra): format shared PowerPC profile integration * fix(ghidra): preserve caller-selected PowerPC languages --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/.vitepress/config.ts | 1 + docs/ghidra-ppc.md | 90 ++++++ package.json | 1 + scripts/verify-real-ghidra-ppc.mjs | 282 ++++++++++++++++++ src/domain/binaryTarget.powerpc.test.ts | 58 ++++ src/domain/binaryTarget.ts | 22 +- src/domain/binaryTargetTypes.ts | 14 + src/ghidra/GhidraAnalysisProfile.ts | 10 +- src/ghidra/GhidraPowerPcProfile.test.ts | 166 +++++++++++ src/ghidra/GhidraPowerPcProfile.ts | 67 +++++ src/ghidra/GhidraProvider.ts | 1 + src/ghidra/GhidraPspProfile.ts | 3 + src/hopper/HopperAnalysisProfile.ts | 1 + src/hopper/HopperProvider.ts | 6 +- src/ida/IdaProvider.ts | 6 +- .../powerpc-identity.test.ts | 93 ++++++ tests/conformance/c/ppc.c | 14 + tests/conformance/ghidra/ppc-checks.d.mts | 29 ++ tests/conformance/ghidra/ppc-checks.mjs | 132 ++++++++ tests/conformance/ghidra/ppc-checks.test.ts | 187 ++++++++++++ tests/conformance/ghidra/ppc-fixture.mjs | 62 ++++ tests/conformance/ghidra/ppc-probe.S | 17 ++ 22 files changed, 1258 insertions(+), 4 deletions(-) create mode 100644 docs/ghidra-ppc.md create mode 100644 scripts/verify-real-ghidra-ppc.mjs create mode 100644 src/domain/binaryTarget.powerpc.test.ts create mode 100644 src/ghidra/GhidraPowerPcProfile.test.ts create mode 100644 src/ghidra/GhidraPowerPcProfile.ts create mode 100644 tests/composition/analysis-sessions/powerpc-identity.test.ts create mode 100644 tests/conformance/c/ppc.c create mode 100644 tests/conformance/ghidra/ppc-checks.d.mts create mode 100644 tests/conformance/ghidra/ppc-checks.mjs create mode 100644 tests/conformance/ghidra/ppc-checks.test.ts create mode 100644 tests/conformance/ghidra/ppc-fixture.mjs create mode 100644 tests/conformance/ghidra/ppc-probe.S diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index b4cf2e4ad..dd562d813 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -63,6 +63,7 @@ export default defineConfig({ { text: "Ghidra DOS analysis", link: "/ghidra-dos" }, { text: "Ghidra raw binary", link: "/raw-binary" }, { text: "Ghidra NativeAOT", link: "/ghidra-nativeaot" }, + { text: "Ghidra PowerPC", link: "/ghidra-ppc" }, { text: "Ghidra semantics", link: "/ghidra-provider" }, ], }, diff --git a/docs/ghidra-ppc.md b/docs/ghidra-ppc.md new file mode 100644 index 000000000..034158378 --- /dev/null +++ b/docs/ghidra-ppc.md @@ -0,0 +1,90 @@ +# PowerPC ELF analysis through Ghidra + +This lane extends native ELF analysis to 32-bit big-endian PowerPC; it does +not execute PowerPC code. It is the first milestone of +[#1741](https://github.com/morluto/rea/issues/1741). GameCube/Wii DOL +executables, PPC64 and other PowerPC variants are separate follow-ups. + +## Admission boundary + +ELF `EM_PPC` (20) is retained as the provider-neutral `powerpc` family. The +target also retains class, byte order, `e_type` and raw `e_flags`. Recognition +does not mean every provider or PowerPC variant is supported. `EM_PPC64` (21) +is not recognized as this family. + +The Ghidra lane admits ELF32 `ET_EXEC`, big endian. ELF64, little-endian, +relocatable and shared objects are refused with a specific unsupported +constraint. `EF_PPC_EMB` declares an embedded variant and is refused; the +remaining `e_flags` bits only declare relocation conventions and do not change +instruction decoding. + +## Bound language + +Ghidra's ELF loader selects `PowerPC:BE:32:e500:default` for a plain `EM_PPC` +header with `e_flags` 0. e500 is the embedded Book-E variant whose SPE unit +replaces the classic floating-point unit, so it misinterprets ordinary +750-family code. Nothing in the header distinguishes the two. + +The lane therefore imports with `PowerPC:BE:32:default` and compiler spec +`default`, commits that choice in the analysis profile as +`language_selection: "provider-pinned-v1"`, and checks the language Ghidra +reports after import. A different language set through +`REA_GHIDRA_LANGUAGE_ID` (and optionally `REA_GHIDRA_COMPILER_SPEC_ID`) +replaces the lane default and is admitted against the installed language +catalog as usual; for example `PowerPC:BE:32:e500` for genuine e500 code. + +PowerPC header facts are committed in the analysis profile so interpretation +changes invalidate profile-bound snapshots. The support-lane identity is +versioned independently of file identity. Evidence, lifecycle outputs and saved +snapshots preserve the `powerpc` family. Hopper and IDA adapters do not +implicitly gain PowerPC support. Windows Ghidra P0 remains PE x86/x86-64 only. + +## Use + +With a caller-installed Ghidra and compatible JDK on a supported Linux/macOS host: + +```bash +rea analyze /absolute/path/to/ppc.elf --provider ghidra --json +rea function /absolute/path/to/ppc.elf function_name --provider ghidra --json +``` + +MCP uses the existing tools, including `open_binary` with an absolute path and +`provider_id: "ghidra"`. No PowerPC-specific tool catalog or emulator is +introduced. + +## Verification + +The source-owned freestanding fixture is `tests/conformance/c/ppc.c`. The +optional cross-target lane requires a caller-supplied Clang with the PowerPC +target, LLD, GNU `readelf`, Ghidra and its compatible JDK; ordinary host-native +checks do not acquire these tools. `REA_PPC_CLANG` selects Clang and +`REA_PPC_READELF` selects GNU readelf (for example +`/opt/homebrew/opt/binutils/bin/readelf` on macOS). These are test-time +prerequisites, not REA runtime providers. + +```bash +GHIDRA_INSTALL_DIR=/absolute/path/to/ghidra npm run verify:ghidra:ppc +``` + +The lane compiles the fixture for a 750-family core (`-mcpu=750`) and never +executes it. GNU readelf independently supplies header facts and symbol +addresses, compared with the production REA target resolver before provider +startup. Its version, bounded command output and selected tool path are +retained in the verification report. The parser deliberately recognizes only +this fixture's GNU output, rejecting missing, ambiguous or unexpected fields +rather than substituting defaults. + +Existing public MCP operations check Ghidra's **observed** language and +compiler specification and loaded-file hashes; an e500 import fails the lane. +The source-owned `ppc-probe.S` supplies fixed `addi` and conditional-branch +encodings: verification checks bytes, length, immediate and direct destination, +independent of decompiler variable names. Global and string bytes are checked at +independently reported symbol addresses. + +CLI/MCP discovery and decompilation, direct calls, target/profile/Evidence +identity, snapshot round-trip and final process cleanup remain covered. +Pseudocode presence is a liveness check, not proof of semantic equivalence. +Instruction decoding and reader agreement do not establish runtime or complete +floating-point semantics. Parser/profile tests are narrower checks, not +substitutes for this real-provider run. Report the actual lanes run and leave +unexecuted verification pending. diff --git a/package.json b/package.json index e09e51366..5ccf53c99 100644 --- a/package.json +++ b/package.json @@ -186,6 +186,7 @@ "verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs", "verify:ghidra:seeds": "npm run build:cached && node scripts/verify/ghidra/seeds.mjs", "verify:ghidra:mips": "npm run build:cached && node scripts/verify-real-ghidra-mips.mjs", + "verify:ghidra:ppc": "npm run build:cached && node scripts/verify-real-ghidra-ppc.mjs", "verify:ghidra:riscv": "npm run build:cached && node scripts/verify-real-ghidra-riscv.mjs", "verify:ghidra:6502": "npm run build:cached && node scripts/verify-real-ghidra-6502.mjs", "verify:ghidra:mips-shared": "npm run build:cached && node scripts/verify-real-ghidra-mips-shared.mjs", diff --git a/scripts/verify-real-ghidra-ppc.mjs b/scripts/verify-real-ghidra-ppc.mjs new file mode 100644 index 000000000..591d32b2b --- /dev/null +++ b/scripts/verify-real-ghidra-ppc.mjs @@ -0,0 +1,282 @@ +#!/usr/bin/env node +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdtemp, mkdir, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js"; +import { + inspectPowerPcReadelf, + assertPowerPcLoadedImage, + assertPowerPcProbe, + assertPowerPcGlobal, +} from "../tests/conformance/ghidra/ppc-checks.mjs"; +import { parseEvidence } from "../dist/domain/evidence.js"; +import { parseAnalysisSnapshot } from "../dist/domain/analysisSnapshot.js"; +import { functionDossierSchema } from "../dist/domain/hopperValues.js"; +import { inspectGhidraInstallation } from "../dist/ghidra/GhidraInstallation.js"; +import { buildPowerPcFixture } from "../tests/conformance/ghidra/ppc-fixture.mjs"; +import { requireMcpOperationResult } from "./lib/mcp-verifier-results.mjs"; +import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs"; + +// Optional cross-target lane. No tool acquisition and no target execution. +if (process.argv.length !== 2) + throw new Error("Usage: node scripts/verify-real-ghidra-ppc.mjs"); +if (!["linux", "darwin"].includes(process.platform)) + throw new Error( + "PowerPC verification requires a supported Linux/macOS Ghidra host", + ); +if (process.env.GHIDRA_INSTALL_DIR === undefined) + throw new Error("Missing prerequisite: caller-supplied GHIDRA_INSTALL_DIR"); +const installation = inspectGhidraInstallation({ + environment: process.env, + installDir: process.env.GHIDRA_INSTALL_DIR, + ...(process.env.JAVA_HOME === undefined + ? {} + : { javaHome: process.env.JAVA_HOME }), +}); +if (installation.status !== "available") + throw new Error( + `Ghidra prerequisite unavailable: ${JSON.stringify(installation)}`, + ); +const execute = promisify(execFile); +const entrypoint = fileURLToPath(new URL("./rea.mjs", import.meta.url)); +const run = createVerifierRun(); +const workspace = await mkdtemp(join(tmpdir(), "rea-ppc-proof-")); +const runtime = join(workspace, "runtime"); +await mkdir(runtime); +const env = { + PATH: process.env.PATH ?? "/usr/bin:/bin", + TMPDIR: runtime, + REA_LOG_LEVEL: "silent", + REA_ANALYSIS_PROVIDER: "ghidra", + REA_PROCESS_RUN_ID: run.run_id, + GHIDRA_INSTALL_DIR: installation.installDir, + JAVA_HOME: installation.javaHome, + HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper", +}; +for (const setting of ["GHIDRA_HEADLESS_MAXMEM", "GHIDRA_MAXMEM"]) { + if (process.env[setting] !== undefined) env[setting] = process.env[setting]; +} +const reports = []; +let primaryFailure; +try { + { + const fixture = await buildPowerPcFixture(workspace); + const independent = await inspectPowerPcReadelf(fixture.path); + const resolved = await parseBinaryTarget(fixture.path); + if (!resolved.ok) throw resolved.error; + assert.deepEqual( + resolved.value.powerpc, + independent.powerpc, + "REA ELF interpretation disagrees with GNU readelf", + ); + assert.equal(resolved.value.sha256, fixture.sha256); + const snapshotPath = join(workspace, "ppc.snapshot.json"); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [entrypoint, "mcp"], + env, + stderr: "pipe", + }); + const client = new Client({ name: "rea-real-ppc-proof", version: "1" }); + let stderr = ""; + transport.stderr?.on("data", (chunk) => { + stderr = (stderr + chunk.toString()).slice(-65536); + }); + const call = async (name, args = {}) => { + const reply = await client.callTool( + { name, arguments: args }, + undefined, + { timeout: 180000 }, + ); + return requireMcpOperationResult(reply, name); + }; + try { + await client.connect(transport); + const target = await call("open_binary", { + path: fixture.path, + provider_id: "ghidra", + }); + assert.equal(target.architecture, "powerpc"); + assert.equal(target.sha256, fixture.sha256); + // ELF load-image verification is not the DOS comparison lane. Its retained + // observations still expose the actual Ghidra language and loaded bytes; + // the plain loader would have chosen e500 for this header. + const image = await call("inspect_native_load_image"); + assertPowerPcLoadedImage(image.observations, fixture.sha256); + const procedures = await call("list_procedures"); + const entry = procedures.find((p) => p.value === "rea_ppc_entry"); + const leaf = procedures.find((p) => p.value === "rea_ppc_leaf"); + assert.ok(entry, "Entry function missing from real Ghidra inventory"); + assert.ok(leaf, "Leaf function missing from real Ghidra inventory"); + assert.equal( + BigInt(entry.address), + BigInt(independent.symbols.rea_ppc_entry), + ); + assert.equal( + BigInt(leaf.address), + BigInt(independent.symbols.rea_ppc_leaf), + ); + const probe = independent.symbols.rea_ppc_probe; + assert.ok( + procedures.some( + (p) => + p.value === "rea_ppc_probe" && BigInt(p.address) === BigInt(probe), + ), + ); + const move = await call("inspect_native_instruction", { address: probe }); + const branch = await call("inspect_native_instruction", { + address: `0x${(BigInt(probe) + 8n).toString(16)}`, + }); + assertPowerPcProbe(move, branch, probe); + const global = await call("read_bytes", { + address: independent.symbols.rea_ppc_global, + length: 4, + }); + assert.equal(global.returned_bytes, 4); + assertPowerPcGlobal(global.bytes_hex); + const marker = await call("read_bytes", { + address: independent.symbols.rea_ppc_marker, + length: 29, + }); + assert.equal( + marker.bytes_hex, + Buffer.from("rea-ppc-source-owned-fixture\0").toString("hex"), + ); + const callees = await call("procedure_callees", { + procedure: entry.address, + }); + assert.ok( + callees.includes(leaf.address), + "Expected direct call not recovered", + ); + const assembly = await call("procedure_assembly", { + procedure: entry.address, + }); + assert.ok(assembly.trim().length > 0); + const dossier = functionDossierSchema.parse( + await call("analyze_function", { procedure: entry.address }), + ); + assert.ok(dossier.pseudocode.trim().length > 0); + const mapping = await call("address_to_file_offset", { + address: entry.address, + }); + const memory = await call("read_bytes", { + address: entry.address, + length: 16, + }); + const sourceBytes = await readFile(fixture.path); + assert.equal(memory.returned_bytes, 16); + assert.equal( + memory.bytes_hex, + sourceBytes + .subarray(mapping.file_offset, mapping.file_offset + 16) + .toString("hex"), + ); + const saved = await call("close_binary", { + snapshot_path: snapshotPath, + }); + assert.ok(saved.evidence_records > 0); + const snapshot = parseAnalysisSnapshot( + JSON.parse(await readFile(snapshotPath, "utf8")), + ); + assert.equal(snapshot.target.architecture, "powerpc"); + assert.equal( + snapshot.binding.analysis_profile.parameters.language_id, + "PowerPC:BE:32:default", + ); + assert.ok(snapshot.evidence_bundle.records.length > 0); + for (const evidence of snapshot.evidence_bundle.records) + assert.equal(parseEvidence(evidence).subject?.architecture, "powerpc"); + await call("open_binary", { + path: fixture.path, + provider_id: "ghidra", + snapshot_path: snapshotPath, + }); + assert.deepEqual(await call("list_procedures"), procedures); + await call("close_binary"); + + // Same public operation through CLI, not a private injected provider. + const cli = await execute( + process.execPath, + [ + entrypoint, + "function", + fixture.path, + "rea_ppc_entry", + "--provider", + "ghidra", + "--json", + ], + { env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 }, + ); + const evidence = parseEvidence(JSON.parse(cli.stdout)); + assert.equal(evidence.subject?.architecture, "powerpc"); + assert.equal(evidence.subject?.digest.sha256, fixture.sha256); + const cliDossier = functionDossierSchema.parse( + evidence.normalized_result, + ); + assert.equal(cliDossier.procedure.address, dossier.procedure.address); + assert.ok(cliDossier.pseudocode.trim().length > 0); + assert.equal( + createHash("sha256") + .update(await readFile(fixture.path)) + .digest("hex"), + fixture.sha256, + "Analysis modified the source executable", + ); + reports.push({ + ...fixture, + independent_reader: independent, + effective_language: image.observations.language_id, + effective_compiler_spec: image.observations.compiler_spec_id, + checks: [ + "independent ELF header and symbols", + "loaded Ghidra identity and bound language", + "fixed instruction bytes and immediate", + "conditional branch destination", + "global word and marker bytes", + "CLI/MCP and snapshot identity", + ], + procedures: procedures.length, + status: "passed", + }); + } catch (cause) { + throw new Error(`PowerPC verification failed; MCP stderr: ${stderr}`, { + cause, + }); + } finally { + try { + await client.close(); + } finally { + await transport.close(); + } + } + } +} catch (cause) { + primaryFailure = cause; +} +const completed = await completeVerifierRun(run); +if ( + completed.process_lineage.status !== "verified" || + completed.process_lineage.descendants.length !== 0 +) + throw new Error( + `Cleanup unverified; retained diagnostic workspace: ${workspace}`, + { cause: primaryFailure }, + ); +if (primaryFailure !== undefined) + throw new Error( + `PowerPC verification failed; retained workspace: ${workspace}`, + { + cause: primaryFailure, + }, + ); +await rm(workspace, { recursive: true, force: true }); +console.log(JSON.stringify({ ...completed, fixtures: reports }, null, 2)); diff --git a/src/domain/binaryTarget.powerpc.test.ts b/src/domain/binaryTarget.powerpc.test.ts new file mode 100644 index 000000000..f32b4f367 --- /dev/null +++ b/src/domain/binaryTarget.powerpc.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest"; +import { parseExecutableHeader } from "./binaryTarget.js"; + +const header = (little: boolean, bits: 32 | 64 = 32, machine = 20): Buffer => { + const bytes = Buffer.alloc(bits === 32 ? 52 : 64); + bytes.set([0x7f, 0x45, 0x4c, 0x46, bits === 32 ? 1 : 2, little ? 1 : 2, 1]); + if (little) { + bytes.writeUInt16LE(2, 16); + bytes.writeUInt16LE(machine, 18); + bytes.writeUInt32LE(1, 20); + bytes.writeUInt16LE(bytes.length, bits === 32 ? 40 : 52); + } else { + bytes.writeUInt16BE(2, 16); + bytes.writeUInt16BE(machine, 18); + bytes.writeUInt32BE(1, 20); + bytes.writeUInt16BE(bytes.length, bits === 32 ? 40 : 52); + } + return bytes; +}; + +describe("PowerPC ELF header boundaries", () => { + it.each([false, true])( + "retains source endian and flags (little=%s)", + (little) => { + const parsed = parseExecutableHeader(header(little), "x64"); + if (!parsed.ok) throw new Error(parsed.error); + expect(parsed.value).toEqual({ + format: "elf", + architecture: "powerpc", + availableArchitectures: ["powerpc"], + powerpc: { + elfClass: 32, + byteOrder: little ? "little" : "big", + type: 2, + flags: 0, + }, + }); + }, + ); + + it("reads ELF64 flags at their own offset without claiming support", () => { + const bytes = header(false, 64); + bytes.writeUInt32BE(0x80000000, 48); + const parsed = parseExecutableHeader(bytes, "x64"); + if (!parsed.ok) throw new Error(parsed.error); + expect(parsed.value).toMatchObject({ + architecture: "powerpc", + powerpc: { elfClass: 64, byteOrder: "big", flags: 0x80000000 }, + }); + }); + + it("does not recognize EM_PPC64 as the 32-bit family", () => { + expect(parseExecutableHeader(header(false, 64, 21), "x64")).toEqual({ + ok: false, + error: "unsupported ELF architecture", + }); + }); +}); diff --git a/src/domain/binaryTarget.ts b/src/domain/binaryTarget.ts index 4e668e460..54798e1d1 100644 --- a/src/domain/binaryTarget.ts +++ b/src/domain/binaryTarget.ts @@ -5,6 +5,7 @@ import type { MipsElfMetadata, PeCodeViewRecord, RiscvElfMetadata, + PowerPcElfMetadata, UniversalMachOSlice, } from "./binaryTargetTypes.js"; import { err, ok, type Result } from "./result.js"; @@ -30,6 +31,12 @@ export type ExecutableMetadata = readonly availableArchitectures: readonly "riscv"[]; readonly riscv: RiscvElfMetadata; } + | { + readonly format: "elf"; + readonly architecture: "powerpc"; + readonly availableArchitectures: readonly "powerpc"[]; + readonly powerpc: PowerPcElfMetadata; + } | { readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com"; readonly architecture: HeaderArchitecture; @@ -201,7 +208,11 @@ const parseElf = ( const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18); const architecture = elfArchitecture(machine); if (architecture === undefined) return err("unsupported ELF architecture"); - if (architecture === "mips" || architecture === "riscv") { + if ( + architecture === "mips" || + architecture === "riscv" || + architecture === "powerpc" + ) { const flagsOffset = elfClass === 32 ? 36 : 48; const metadata: ElfFamilyMetadata = { elfClass, @@ -211,6 +222,13 @@ const parseElf = ( ? bytes.readUInt32LE(flagsOffset) : bytes.readUInt32BE(flagsOffset), }; + if (architecture === "powerpc") + return ok({ + format: "elf", + architecture, + availableArchitectures: [architecture], + powerpc: metadata, + }); return architecture === "mips" ? ok({ format: "elf", @@ -532,6 +550,8 @@ const elfArchitecture = ( return "x86_64"; case 8: // EM_MIPS: ISA, ABI and byte order remain separate ELF facts. return "mips"; + case 20: // EM_PPC; byte order and processor variant remain ELF declarations. + return "powerpc"; case 40: return "arm"; case 183: diff --git a/src/domain/binaryTargetTypes.ts b/src/domain/binaryTargetTypes.ts index 8c16612bc..2cd6ae207 100644 --- a/src/domain/binaryTargetTypes.ts +++ b/src/domain/binaryTargetTypes.ts @@ -9,6 +9,7 @@ export const BINARY_ARCHITECTURES = [ "mips", "6502", "riscv", + "powerpc", ] as const; export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number]; @@ -36,6 +37,7 @@ export interface PeCodeViewRecord { export const ELF_METADATA_ARCHITECTURES = [ "mips", "riscv", + "powerpc", ] as const satisfies readonly BinaryArchitecture[]; export type ElfMetadataArchitecture = (typeof ELF_METADATA_ARCHITECTURES)[number]; @@ -90,6 +92,9 @@ export interface MipsAbiFlags { */ export type RiscvElfMetadata = ElfFamilyMetadata; +/** Raw PowerPC declarations; family identity does not select a processor variant. */ +export type PowerPcElfMetadata = ElfFamilyMetadata; + /** Byte range of the selected slice inside its universal Mach-O container. */ export interface UniversalMachOSlice { readonly offset: number; @@ -140,6 +145,15 @@ export type BinaryTarget = readonly executableRole?: never; readonly managed?: never; }) + | (BinaryTargetIdentity & { + readonly kind: "executable"; + readonly format: "elf"; + readonly architecture: "powerpc"; + readonly availableArchitectures: readonly "powerpc"[]; + readonly powerpc: PowerPcElfMetadata; + readonly executableRole?: never; + readonly managed?: never; + }) | (ExecutableTarget & { readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com"; readonly universalSlice?: never; diff --git a/src/ghidra/GhidraAnalysisProfile.ts b/src/ghidra/GhidraAnalysisProfile.ts index d4bd5a433..8175b776b 100644 --- a/src/ghidra/GhidraAnalysisProfile.ts +++ b/src/ghidra/GhidraAnalysisProfile.ts @@ -21,6 +21,10 @@ import { ghidraRiscvLanguageOverride, ghidraRiscvProfileParameters, } from "./GhidraRiscvProfile.js"; +import { + ghidraPowerPcLanguage, + ghidraPowerPcProfileParameters, +} from "./GhidraPowerPcProfile.js"; import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js"; import { @@ -44,7 +48,9 @@ import { export const ghidraPinnedLanguage = ( target: BinaryTarget, ): GhidraLanguageOverride | undefined => - ghidraMipsLanguageOverride(target) ?? ghidraRiscvLanguageOverride(target); + ghidraMipsLanguageOverride(target) ?? + ghidraRiscvLanguageOverride(target) ?? + ghidraPowerPcLanguage(target); /** Resolve version-bound, deterministic semantics before Ghidra imports a target. */ export const resolveGhidraAnalysisProfile = async ( @@ -155,6 +161,7 @@ export const resolveGhidraAnalysisProfile = async ( const pinnedLanguage = ghidraPinnedLanguage(target); if ( pinnedLanguage !== undefined && + target.architecture !== "powerpc" && languageOverride !== undefined && (languageOverride.languageId !== pinnedLanguage.languageId || (languageOverride.compilerSpecId !== undefined && @@ -277,6 +284,7 @@ export const resolveGhidraAnalysisProfile = async ( ...analyzerParameters, ...ghidraMipsProfileParameters(target, languageOverride), ...ghidraRiscvProfileParameters(target), + ...ghidraPowerPcProfileParameters(target), ...(pspExtension?.ok === true ? { mips_support_lane: "psp-elf32-exec-eabi32-allegrex-v2", diff --git a/src/ghidra/GhidraPowerPcProfile.test.ts b/src/ghidra/GhidraPowerPcProfile.test.ts new file mode 100644 index 000000000..831a47f3b --- /dev/null +++ b/src/ghidra/GhidraPowerPcProfile.test.ts @@ -0,0 +1,166 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { parseConfig } from "../config/parseConfig.js"; +import type { + BinaryTarget, + PowerPcElfMetadata, +} from "../domain/binaryTargetTypes.js"; +import { silentLogger } from "../logger.js"; +import { HopperProvider } from "../hopper/HopperProvider.js"; +import { hopperLoaderArgsForTarget } from "../hopper/HopperAnalysisProfile.js"; +import { IdaProvider } from "../ida/IdaProvider.js"; +import { + ghidraPinnedLanguage, + ghidraProfileLanguageOverride, +} from "./GhidraAnalysisProfile.js"; +import { GhidraProvider } from "./GhidraProvider.js"; +import type { GhidraInstallationHost } from "./GhidraInstallation.js"; + +// Abbreviated from Ghidra 12.1.4 Processors/PowerPC/data/languages/ppc.ldefs. +const PPC_LDEFS = ` + + + + + + + + +`; + +// Fake installation inspection tests admission/profile contracts, not Ghidra. +const host: GhidraInstallationHost = { + platform: "linux", + architecture: "x64", + readText: () => "application.version=12.1.4\n", + executable: () => true, + probeJava: () => ({ + version: "21.0.11", + major: 21, + home: "/jdk-21", + bits: 64, + runtime: "jdk", + }), +}; +const configFor = (environment: NodeJS.ProcessEnv) => { + const parsed = parseConfig({ GHIDRA_INSTALL_DIR: "/ghidra", ...environment }); + if (!parsed.ok) throw parsed.error; + return parsed.value; +}; +const config = configFor({}); +const target = (change: Partial = {}): BinaryTarget => ({ + path: "/fixture.elf", + sha256: "a".repeat(64), + kind: "executable", + format: "elf", + architecture: "powerpc", + availableArchitectures: ["powerpc"], + powerpc: { elfClass: 32, byteOrder: "big", type: 2, flags: 0, ...change }, +}); + +describe("bounded Ghidra PowerPC admission", () => { + it("binds the generic language instead of the loader's e500 choice", async () => { + const ghidra = new GhidraProvider(config, silentLogger, {}, host); + expect(ghidra.inspectTargetSupport(target()).status).toBe("supported"); + const resolved = await ghidra.resolveAnalysisProfile(target()); + if (!resolved.ok) throw resolved.error; + const parameters = resolved.value.profile?.parameters ?? {}; + expect(parameters).toMatchObject({ + architecture: "powerpc", + language_id: "PowerPC:BE:32:default", + compiler_spec_id: "default", + language_selection: "provider-pinned-v1", + powerpc_elf: { elf_class: 32, byte_order: "big", type: 2, flags: 0 }, + powerpc_support_lane: "elf32-be-exec-generic-v1", + }); + expect(ghidraPinnedLanguage(target())).toEqual({ + languageId: "PowerPC:BE:32:default", + compilerSpecId: "default", + }); + expect(ghidraProfileLanguageOverride(parameters)).toEqual( + ghidraPinnedLanguage(target()), + ); + }); + + it("lets a configured language replace the lane default", async () => { + const installDir = await createTestTempDirectory("rea-ghidra-ppc-"); + const languages = join( + installDir, + "Ghidra/Processors/PowerPC/data/languages", + ); + await mkdir(languages, { recursive: true }); + await writeFile(join(languages, "ppc.ldefs"), PPC_LDEFS); + const ghidra = new GhidraProvider( + configFor({ + GHIDRA_INSTALL_DIR: installDir, + REA_GHIDRA_LANGUAGE_ID: "PowerPC:BE:32:e500", + }), + silentLogger, + {}, + host, + ); + const resolved = await ghidra.resolveAnalysisProfile(target()); + if (!resolved.ok) throw resolved.error; + const parameters = resolved.value.profile?.parameters ?? {}; + expect(parameters).toMatchObject({ + language_id: "PowerPC:BE:32:e500", + language_selection: "configured-v1", + }); + expect(ghidraProfileLanguageOverride(parameters)).toEqual({ + languageId: "PowerPC:BE:32:e500", + }); + }); + + it("commits header flags so a changed interpretation changes the profile", async () => { + const ghidra = new GhidraProvider(config, silentLogger, {}, host); + const left = await ghidra.resolveAnalysisProfile(target()); + const right = await ghidra.resolveAnalysisProfile( + target({ flags: 0x00010000 }), + ); + if (!left.ok) throw left.error; + if (!right.ok) throw right.error; + expect(left.value.profile?.digest).not.toBe(right.value.profile?.digest); + }); + + it("does not widen Windows P0", () => { + const windows = new GhidraProvider( + config, + silentLogger, + {}, + { ...host, platform: "win32" }, + ); + expect(windows.inspectTargetSupport(target()).status).toBe("unsupported"); + }); + + it.each([ + [{ elfClass: 64 }, "ELF32"], + [{ byteOrder: "little" }, "big-endian"], + [{ type: 1 }, "ET_EXEC"], + [{ type: 3 }, "ET_EXEC"], + [{ flags: 0x80000000 }, "EF_PPC_EMB"], + ] satisfies [Partial, string][])( + "refuses an unverified PowerPC interpretation %j", + async (change, reason) => { + const ghidra = new GhidraProvider(config, silentLogger, {}, host); + const value = target(change); + expect(ghidra.inspectTargetSupport(value)).toMatchObject({ + status: "unsupported", + reason: expect.stringContaining(reason), + }); + const resolved = await ghidra.resolveAnalysisProfile(value); + expect(resolved.ok).toBe(false); + }, + ); + + it("keeps PowerPC out of unverified Hopper and IDA adapter lanes", () => { + const hopper = new HopperProvider(config, silentLogger, {}, "linux"); + expect(hopper.inspectTargetSupport(target()).status).toBe("unsupported"); + expect(hopperLoaderArgsForTarget(target()).ok).toBe(false); + const ida = new IdaProvider(config, {}); + expect(ida.inspectTargetSupport(target()).status).toBe("unsupported"); + }); +}); diff --git a/src/ghidra/GhidraPowerPcProfile.ts b/src/ghidra/GhidraPowerPcProfile.ts new file mode 100644 index 000000000..c1655f252 --- /dev/null +++ b/src/ghidra/GhidraPowerPcProfile.ts @@ -0,0 +1,67 @@ +import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js"; +import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; +import type { JsonValue } from "../domain/jsonValue.js"; + +/** + * Generic 32-bit big-endian PowerPC. Ghidra's ELF loader selects the e500 + * (Book-E/SPE) variant for a plain EM_PPC header, so the lane binds this + * language instead of accepting the loader's choice. + */ +export const GHIDRA_POWERPC_LANGUAGE: GhidraLanguageOverride = { + languageId: "PowerPC:BE:32:default", + compilerSpecId: "default", +}; + +/** Keep family recognition separate from the deliberately bounded Ghidra lane. */ +export const ghidraPowerPcUnsupportedReason = ( + target: BinaryTarget, +): string | null => { + if (target.kind !== "executable" || target.architecture !== "powerpc") + return null; + const metadata = target.powerpc; + if (target.format !== "elf" || metadata === undefined) + return "PowerPC analysis requires ELF header metadata; a family name alone does not select a processor variant."; + if (metadata.elfClass !== 32) + return "This Ghidra PowerPC lane supports ELF32 only; PPC64 remains unsupported."; + if (metadata.byteOrder !== "big") + return "This Ghidra PowerPC lane supports big-endian ELF32 only; little-endian PowerPC needs separate verification."; + if (metadata.type !== 2) + return "This Ghidra PowerPC lane supports ET_EXEC only; relocatable objects and shared images need separate load verification."; + // EF_PPC_EMB (0x80000000) marks embedded variants; other bits only declare + // relocation conventions that do not change instruction decoding. + if ((metadata.flags & 0x80000000) !== 0) + return "EF_PPC_EMB declares an embedded PowerPC variant that needs a separately supported processor profile."; + return null; +}; + +/** + * The language the lane imports with, unless REA_GHIDRA_LANGUAGE_ID already + * selected one through the committed profile. + */ +export const ghidraPowerPcLanguage = ( + target: BinaryTarget, +): GhidraLanguageOverride | undefined => + target.kind === "executable" && target.architecture === "powerpc" + ? GHIDRA_POWERPC_LANGUAGE + : undefined; + +/** Commit source ELF interpretation without confusing target ISA with host CPU. */ +export const ghidraPowerPcProfileParameters = ( + target: BinaryTarget, +): Readonly> => { + if ( + target.kind !== "executable" || + target.architecture !== "powerpc" || + target.powerpc === undefined + ) + return {}; + return { + powerpc_elf: { + elf_class: target.powerpc.elfClass, + byte_order: target.powerpc.byteOrder, + type: target.powerpc.type, + flags: target.powerpc.flags, + }, + powerpc_support_lane: "elf32-be-exec-generic-v1", + }; +}; diff --git a/src/ghidra/GhidraProvider.ts b/src/ghidra/GhidraProvider.ts index 0a1cde0f0..b0ee8787d 100644 --- a/src/ghidra/GhidraProvider.ts +++ b/src/ghidra/GhidraProvider.ts @@ -68,6 +68,7 @@ const SUPPORTED_ARCHITECTURES = new Set([ "mips", "6502", "riscv", + "powerpc", ]); /** Ghidra candidate backed by an isolated ephemeral headless import. */ diff --git a/src/ghidra/GhidraPspProfile.ts b/src/ghidra/GhidraPspProfile.ts index 17260d038..3550d62ab 100644 --- a/src/ghidra/GhidraPspProfile.ts +++ b/src/ghidra/GhidraPspProfile.ts @@ -1,5 +1,6 @@ import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { ghidraMipsUnsupportedReason } from "./GhidraMipsProfile.js"; +import { ghidraPowerPcUnsupportedReason } from "./GhidraPowerPcProfile.js"; import { ghidraRiscvUnsupportedReason } from "./GhidraRiscvProfile.js"; /** Allegrex's ELF machine declaration, not a filename or inferred instruction. */ @@ -14,6 +15,8 @@ export const isGhidraPspTarget = (target: BinaryTarget): boolean => export const ghidraProcessorUnsupportedReason = ( target: BinaryTarget, ): string | null => { + if (target.kind === "executable" && target.architecture === "powerpc") + return ghidraPowerPcUnsupportedReason(target); if (target.kind === "executable" && target.architecture === "riscv") return ghidraRiscvUnsupportedReason(target); if ( diff --git a/src/hopper/HopperAnalysisProfile.ts b/src/hopper/HopperAnalysisProfile.ts index a4848533f..79ba3ab50 100644 --- a/src/hopper/HopperAnalysisProfile.ts +++ b/src/hopper/HopperAnalysisProfile.ts @@ -110,6 +110,7 @@ const HOPPER_DECLINED_ARCHITECTURE_LABELS: Record< > = { mips: "MIPS", riscv: "RISC-V", + powerpc: "PowerPC", }; /** Derive Hopper's complete non-interactive CLI loader selection. */ diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index aec8c2082..f9826575b 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -126,7 +126,11 @@ export class HopperProvider implements AnalysisProviderCandidate { status: "unsupported", code: "architecture_unsupported", reason: `REA's Hopper adapter does not admit ${ - target.architecture === "mips" ? "MIPS" : "RISC-V" + target.architecture === "mips" + ? "MIPS" + : target.architecture === "riscv" + ? "RISC-V" + : "PowerPC" } targets.`, diagnostics, }; diff --git a/src/ida/IdaProvider.ts b/src/ida/IdaProvider.ts index 09011caa5..5ce924fcd 100644 --- a/src/ida/IdaProvider.ts +++ b/src/ida/IdaProvider.ts @@ -113,7 +113,11 @@ export class IdaProvider implements AnalysisProviderCandidate { status: "unsupported", code: "architecture_unsupported", reason: `REA's IDA adapter has no verified ${ - target.architecture === "mips" ? "MIPS" : "RISC-V" + target.architecture === "mips" + ? "MIPS" + : target.architecture === "riscv" + ? "RISC-V" + : "PowerPC" } lane. Select a supported Ghidra profile instead.`, diagnostics, }; diff --git a/tests/composition/analysis-sessions/powerpc-identity.test.ts b/tests/composition/analysis-sessions/powerpc-identity.test.ts new file mode 100644 index 000000000..3dd1d374a --- /dev/null +++ b/tests/composition/analysis-sessions/powerpc-identity.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import type { BinaryTarget } from "../../../src/domain/binaryTargetTypes.js"; +import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js"; +import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js"; +import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js"; +import { + createAnalysisSnapshotEntry, + parseAnalysisSnapshot, + serializeAnalysisSnapshot, + snapshotBinding, + snapshotTarget, + snapshotMatchesProfile, +} from "../../../src/domain/analysisSnapshot.js"; +import { sessionOutputSchemas } from "../../../src/contracts/toolOutputSchemaGroups.js"; + +const target: BinaryTarget = { + path: "/source-owned.elf", + sha256: "a".repeat(64), + kind: "executable", + format: "elf", + architecture: "powerpc", + availableArchitectures: ["powerpc"], + powerpc: { elfClass: 32, byteOrder: "big", type: 2, flags: 0 }, +}; +const provider = { id: "ghidra", name: "Ghidra", version: "12.1.4" }; +const profile = createAnalysisProfile(provider, { + powerpc_elf: { elf_class: 32, byte_order: "big", type: 2, flags: 0 }, +}); + +describe("PowerPC identity through lifecycle, Evidence and snapshot consumers", () => { + it("round-trips query bindings without relaxing integrity", () => { + const result = [{ address: "0x100101b0", value: "rea_ppc_entry" }]; + const parameters = {}; + const evidence = createEvidence(target, provider, { + operation: "list_procedures", + parameters, + result, + analysisProfile: profile, + }); + const binding = snapshotBinding(profile); + const entry = createAnalysisSnapshotEntry({ + target: snapshotTarget(target), + binding, + operation: "list_procedures", + parameters, + execution: { + result, + rawResult: null, + provider, + analysisProfile: profile, + limitations: [], + locations: [], + subject: target, + }, + }); + const snapshot = { + target: snapshotTarget(target), + binding, + entries: [entry], + workflow_entries: [], + evidence_bundle: createEvidenceBundle([evidence]), + }; + const restored = parseAnalysisSnapshot( + JSON.parse(serializeAnalysisSnapshot(snapshot)), + ); + expect(restored.target.architecture).toBe("powerpc"); + expect(restored.evidence_bundle.records[0]?.subject?.architecture).toBe( + "powerpc", + ); + expect(restored.entries[0]?.execution.subject?.architecture).toBe( + "powerpc", + ); + expect( + sessionOutputSchemas.open_binary.parse({ result: target }).result + .architecture, + ).toBe("powerpc"); + expect(() => + parseEvidence({ + ...evidence, + subject: { ...evidence.subject, architecture: "x86" }, + }), + ).toThrow("semantic identifier"); + const changed = createAnalysisProfile(provider, { + powerpc_elf: { + elf_class: 32, + byte_order: "big", + type: 2, + flags: 0x00010000, + }, + }); + expect(snapshotMatchesProfile(binding, changed)).toBe(false); + }); +}); diff --git a/tests/conformance/c/ppc.c b/tests/conformance/c/ppc.c new file mode 100644 index 000000000..3f62ca57e --- /dev/null +++ b/tests/conformance/c/ppc.c @@ -0,0 +1,14 @@ +/* Freestanding, source-owned static-analysis fixture. Never executed by REA. */ +volatile unsigned int rea_ppc_global = 7; +const char rea_ppc_marker[] = "rea-ppc-source-owned-fixture"; + +__attribute__((noinline)) unsigned int rea_ppc_leaf(unsigned int value) +{ + return value * 3u + rea_ppc_global; +} + +__attribute__((noinline)) unsigned int rea_ppc_entry(unsigned int selector) +{ + unsigned int adjusted = selector > 10u ? selector : selector + 1u; + return rea_ppc_leaf(adjusted) + (unsigned char)rea_ppc_marker[0]; +} diff --git a/tests/conformance/ghidra/ppc-checks.d.mts b/tests/conformance/ghidra/ppc-checks.d.mts new file mode 100644 index 000000000..38609de45 --- /dev/null +++ b/tests/conformance/ghidra/ppc-checks.d.mts @@ -0,0 +1,29 @@ +import type { PowerPcElfMetadata } from "../../../src/domain/binaryTargetTypes.js"; + +export interface PowerPcReadelfFacts { + powerpc: PowerPcElfMetadata; + symbols: Record< + | "rea_ppc_entry" + | "rea_ppc_leaf" + | "rea_ppc_probe" + | "rea_ppc_global" + | "rea_ppc_marker", + string + >; +} +export function parsePowerPcReadelf(text: string): PowerPcReadelfFacts; +export function inspectPowerPcReadelf( + path: string, +): Promise< + PowerPcReadelfFacts & { command: string; version: string; raw: string } +>; +export function assertPowerPcLoadedImage( + observations: unknown, + sha256: string, +): void; +export function assertPowerPcProbe( + move: unknown, + branch: unknown, + address: string, +): void; +export function assertPowerPcGlobal(bytes: string): void; diff --git a/tests/conformance/ghidra/ppc-checks.mjs b/tests/conformance/ghidra/ppc-checks.mjs new file mode 100644 index 000000000..1136f2602 --- /dev/null +++ b/tests/conformance/ghidra/ppc-checks.mjs @@ -0,0 +1,132 @@ +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; + +const execute = promisify(execFile); +// The lane binds this language; Ghidra's ELF loader alone selects e500. +const LANGUAGE = "PowerPC:BE:32:default"; +const wordHex = (value) => { + const bytes = Buffer.alloc(4); + bytes.writeUInt32BE(value); + return bytes.toString("hex"); +}; + +/** Parse only the documented GNU readelf fields needed by our tiny fixture. */ +export function parsePowerPcReadelf(text) { + const field = (expression, label) => { + const matches = [...text.matchAll(expression)]; + assert.equal(matches.length, 1, `Missing or ambiguous readelf ${label}`); + return matches[0][1].trim(); + }; + assert.equal(field(/^\s*Class:\s*(.+)$/gmu, "class"), "ELF32"); + assert.equal( + field(/^\s*Data:.*?,\s*(little|big) endian\s*$/gmu, "byte order"), + "big", + ); + assert.match(field(/^\s*Type:\s*(.+)$/gmu, "type"), /^EXEC\b/u); + assert.equal(field(/^\s*Machine:\s*(.+)$/gmu, "machine"), "PowerPC"); + const flags = Number(field(/^\s*Flags:\s*(0x[\da-f]+)\s*$/gmu, "flags")); + assert.equal(flags, 0, "Fixture ELF flags differ from build intent"); + const symbols = {}; + for (const name of [ + "rea_ppc_entry", + "rea_ppc_leaf", + "rea_ppc_probe", + "rea_ppc_global", + "rea_ppc_marker", + ]) { + const value = field( + new RegExp( + `^\\s*\\d+:\\s+([\\da-f]+)\\s+\\d+\\s+(?:FUNC|OBJECT)\\s+GLOBAL\\s+\\S+\\s+\\d+\\s+${name}\\s*$`, + "gmu", + ), + `symbol ${name}`, + ); + symbols[name] = `0x${BigInt(`0x${value}`).toString(16)}`; + } + return { + powerpc: { elfClass: 32, byteOrder: "big", type: 2, flags }, + symbols, + }; +} + +/** Independent reader is a bounded test prerequisite, never an REA provider. */ +export async function inspectPowerPcReadelf(path) { + const command = process.env.REA_PPC_READELF ?? "readelf"; + const options = { + env: { ...process.env, LC_ALL: "C" }, + timeout: 10000, + maxBuffer: 1024 * 1024, + }; + const version = await execute(command, ["--version"], options); + assert.match( + version.stdout, + /^GNU readelf\b/u, + "This lane requires GNU readelf", + ); + const result = await execute(command, ["-h", "-s", "-W", path], options); + assert.equal( + result.stderr.trim(), + "", + `readelf diagnostics: ${result.stderr}`, + ); + return { + ...parsePowerPcReadelf(result.stdout), + command, + version: version.stdout.split("\n")[0], + raw: result.stdout, + }; +} + +/** Check effective Ghidra observations, not the requested analysis profile. */ +export function assertPowerPcLoadedImage(observations, sha256) { + assert.equal(observations.language_id, LANGUAGE); + assert.equal(observations.compiler_spec_id, "default"); + assert.ok( + observations.source_files.some( + (file) => + file.original_sha256 === sha256 && file.modified_sha256 === sha256, + ), + "Ghidra loaded source identity changed", + ); +} + +/** Verify the exact constant/conditional destination in ppc-probe.S. */ +export function assertPowerPcProbe(move, branch, address) { + const start = BigInt(address); + for (const [instruction, offset, word] of [ + [move, 0n, 0x38641234], + [branch, 8n, 0x41820008], + ]) { + assert.equal(instruction.status, "decoded"); + assert.equal(BigInt(instruction.address), start + offset); + assert.equal(instruction.architecture, LANGUAGE); + assert.equal(instruction.length, 4); + assert.equal(instruction.bytes, wordHex(word)); + } + assert.match(move.mnemonic, /^ADDI$/iu); + assert.ok( + move.operands.some((operand) => + operand.components.some( + (part) => + part.kind === "immediate" && + part.value !== null && + BigInt(part.value) === 0x1234n, + ), + ), + "ADDI immediate was not recovered", + ); + assert.match(branch.mnemonic, /^BEQ$/iu); + assert.equal(branch.flow.kind, "jump"); + assert.equal(branch.flow.conditional, true); + assert.equal(branch.flow.computed, false); + assert.deepEqual( + branch.flow.direct_destinations.map((value) => BigInt(value)), + [start + 16n], + ); +} + +/** Four bytes must encode the known source-owned global in big-endian order. */ +export function assertPowerPcGlobal(bytes) { + assert.equal(bytes, wordHex(7)); +} diff --git a/tests/conformance/ghidra/ppc-checks.test.ts b/tests/conformance/ghidra/ppc-checks.test.ts new file mode 100644 index 000000000..6328ce029 --- /dev/null +++ b/tests/conformance/ghidra/ppc-checks.test.ts @@ -0,0 +1,187 @@ +import { describe, expect, it } from "vitest"; +import { + assertPowerPcGlobal, + assertPowerPcLoadedImage, + assertPowerPcProbe, + parsePowerPcReadelf, +} from "./ppc-checks.mjs"; + +// GNU readelf 2.47 output for the source-owned Clang 23 / LLD fixture. +// This tests the reader boundary, not Ghidra; the real lane rebuilds it. +const readelf = `ELF Header: + Magic: 7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00 + Class: ELF32 + Data: 2's complement, big endian + Version: 1 (current) + OS/ABI: UNIX - System V + ABI Version: 0 + Type: EXEC (Executable file) + Machine: PowerPC + Version: 0x1 + Entry point address: 0x100101b0 + Start of program headers: 52 (bytes into file) + Start of section headers: 2188 (bytes into file) + Flags: 0x0 + Size of this header: 52 (bytes) + Size of program headers: 32 (bytes) + Number of program headers: 6 + Size of section headers: 40 (bytes) + Number of section headers: 18 + Section header string table index: 16 + +Symbol table '.symtab' contains 7 entries: + Num: Value Size Type Bind Vis Ndx Name + 0: 00000000 0 NOTYPE LOCAL DEFAULT UND + 1: 00000000 0 FILE LOCAL DEFAULT ABS ppc.c + 2: 10010180 48 FUNC GLOBAL DEFAULT 4 rea_ppc_leaf + 3: 1002023c 4 OBJECT GLOBAL DEFAULT 5 rea_ppc_global + 4: 100101b0 116 FUNC GLOBAL DEFAULT 4 rea_ppc_entry + 5: 100000f4 29 OBJECT GLOBAL DEFAULT 1 rea_ppc_marker + 6: 10010224 24 FUNC GLOBAL DEFAULT 4 rea_ppc_probe +`; +const sha256 = "a".repeat(64); +const image = { + language_id: "PowerPC:BE:32:default", + compiler_spec_id: "default", + source_files: [{ original_sha256: sha256, modified_sha256: sha256 }], +}; +const move = { + address: "0x10010224", + status: "decoded", + architecture: "PowerPC:BE:32:default", + length: 4, + bytes: "38641234", + mnemonic: "addi", + operands: [ + { index: 2, components: [{ kind: "immediate", value: "0x1234" }] }, + ], +}; +const branch = { + address: "0x1001022c", + status: "decoded", + architecture: "PowerPC:BE:32:default", + length: 4, + bytes: "41820008", + mnemonic: "beq", + flow: { + kind: "jump", + conditional: true, + computed: false, + direct_destinations: ["0x10010234"], + }, +}; + +describe("PowerPC real-verifier independent expectations", () => { + it("reads GNU header and defined symbols without a Ghidra-derived oracle", () => { + const parsed = parsePowerPcReadelf(readelf); + expect(parsed.powerpc).toEqual({ + elfClass: 32, + byteOrder: "big", + type: 2, + flags: 0, + }); + expect(parsed.symbols.rea_ppc_probe).toBe("0x10010224"); + }); + + it.each([ + ["wrong class", "ELF32", "ELF64"], + ["wrong byte order", "big endian", "little endian"], + [ + "wrong machine", + "Machine: PowerPC", + "Machine: PowerPC64", + ], + ["wrong object type", "EXEC (Executable file)", "DYN (Shared object file)"], + [ + "wrong flags", + "Flags: 0x0", + "Flags: 0x80000000", + ], + ["missing symbol", "rea_ppc_probe", "unrelated_probe"], + ])( + "rejects %s instead of returning a guessed fixture interpretation", + (_name, from, to) => { + expect(() => parsePowerPcReadelf(readelf.replace(from, to))).toThrow(); + }, + ); + + it("rejects ambiguous producer fields", () => { + expect(() => parsePowerPcReadelf(`${readelf}\nClass: ELF32\n`)).toThrow( + /ambiguous/u, + ); + }); + + it("checks the effective loaded image, including Ghidra's e500 default", () => { + assertPowerPcLoadedImage(image, sha256); + expect(() => + assertPowerPcLoadedImage( + { ...image, language_id: "PowerPC:BE:32:e500" }, + sha256, + ), + ).toThrow(); + expect(() => + assertPowerPcLoadedImage( + { ...image, compiler_spec_id: "macosx" }, + sha256, + ), + ).toThrow(); + expect(() => + assertPowerPcLoadedImage( + { + ...image, + source_files: [ + { original_sha256: sha256, modified_sha256: "b".repeat(64) }, + ], + }, + sha256, + ), + ).toThrow(); + }); + + it("checks exact probe bytes, immediate and conditional destination", () => { + assertPowerPcProbe(move, branch, "0x10010224"); + }); + + it("rejects plausible nonempty but incorrect instruction observations", () => { + expect(() => + assertPowerPcProbe({ ...move, bytes: "38641235" }, branch, "0x10010224"), + ).toThrow(); + expect(() => + assertPowerPcProbe({ ...move, length: 2 }, branch, "0x10010224"), + ).toThrow(); + expect(() => + assertPowerPcProbe( + { + ...move, + operands: [ + { index: 2, components: [{ kind: "immediate", value: "0x1235" }] }, + ], + }, + branch, + "0x10010224", + ), + ).toThrow(); + expect(() => + assertPowerPcProbe( + move, + { + ...branch, + flow: { ...branch.flow, direct_destinations: ["0x10010230"] }, + }, + "0x10010224", + ), + ).toThrow(); + expect(() => + assertPowerPcProbe( + move, + { ...branch, flow: { ...branch.flow, conditional: false } }, + "0x10010224", + ), + ).toThrow(); + }); + + it("checks the big-endian global word", () => { + assertPowerPcGlobal("00000007"); + expect(() => assertPowerPcGlobal("07000000")).toThrow(); + }); +}); diff --git a/tests/conformance/ghidra/ppc-fixture.mjs b/tests/conformance/ghidra/ppc-fixture.mjs new file mode 100644 index 000000000..202c0dacf --- /dev/null +++ b/tests/conformance/ghidra/ppc-fixture.mjs @@ -0,0 +1,62 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +const execute = promisify(execFile); + +/** Build a source-owned freestanding ELF; never execute its target code. */ +export async function buildPowerPcFixture(directory) { + const compiler = process.env.REA_PPC_CLANG ?? "clang"; + const target = "powerpc-unknown-linux-gnu"; + const source = fileURLToPath(new URL("../c/ppc.c", import.meta.url)); + const probe = fileURLToPath(new URL("./ppc-probe.S", import.meta.url)); + const path = join(directory, `${target}.elf`); + const args = [ + `--target=${target}`, + // A 750-family core with the classic FPU, unlike the e500 SPE variant. + "-mcpu=750", + "-fno-pic", + "-fuse-ld=lld", + "-nostdlib", + "-static", + "-O0", + "-g", + "-Wl,-e,rea_ppc_entry", + "-Wl,--build-id=none", + source, + probe, + "-o", + path, + ]; + const version = await execute(compiler, ["--version"], { timeout: 10000 }); + await execute(compiler, args, { timeout: 60000 }); + const bytes = await readFile(path); + if ( + bytes.length < 52 || + bytes.toString("hex", 0, 4) !== "7f454c46" || + bytes[4] !== 1 || + bytes[5] !== 2 || + bytes.readUInt16BE(16) !== 2 || + bytes.readUInt16BE(18) !== 20 || + bytes.readUInt32BE(36) !== 0 + ) + throw new Error( + "Compiler did not produce the declared ELF32 big-endian PowerPC fixture", + ); + return { + path, + flags: bytes.readUInt32BE(36), + sha256: createHash("sha256").update(bytes).digest("hex"), + source_sha256: createHash("sha256") + .update(await readFile(source)) + .digest("hex"), + probe_sha256: createHash("sha256") + .update(await readFile(probe)) + .digest("hex"), + compiler: version.stdout.trim(), + arguments: args, + }; +} diff --git a/tests/conformance/ghidra/ppc-probe.S b/tests/conformance/ghidra/ppc-probe.S new file mode 100644 index 000000000..f67793942 --- /dev/null +++ b/tests/conformance/ghidra/ppc-probe.S @@ -0,0 +1,17 @@ +/* Source-owned 32-bit PowerPC instructions with fixed, reviewable encodings. + * No target execution. The conditional branch at +8 targets +16. + */ +.text +.p2align 2 +.globl rea_ppc_probe +.type rea_ppc_probe, @function +rea_ppc_probe: + addi 3, 4, 0x1234 + cmpwi 0, 4, 0 + beq 0, .Lzero + blr +.Lzero: + li 3, 7 + blr +.size rea_ppc_probe, .-rea_ppc_probe +.section .note.GNU-stack,"",@progbits From 1ebbc3b3714a83f10950eaa09bee5d4490bd572e Mon Sep 17 00:00:00 2001 From: Jeremy Levartovsky <140487034+JayOfTheKeyboard@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:36:43 +1100 Subject: [PATCH 05/12] fix(managed): pair members by declared identity before name-free remaps (#2116) * fix(managed): pair members by declared identity before name-free remaps The first matching round keyed methods on signature and normalized CIL, and fields on signature, without the declared type or name. Identical members of different types fell into one ambiguous group, so a file compared with itself reported unknowns, and a lone match across types was reported as an unchanged exact pair while the member's own counterpart went unpaired. Pair by declared type, name, and exact CIL/signature first, then by declared type, name, and raw signature. The name-free CIL/signature, field-signature, and structural rounds now run last, as remaps, and skip a pair across declared identities while either member's own type and name remain unpaired on the other side. Nested types that share a bare name still share one declared identity, so their identical members stay ambiguous in a self-comparison. * fix(managed): keep members with kept identities out of remap rounds The cross-identity check applied only to one-to-one groups. A member whose own declared type and name were still unpaired on the other side could fall into a larger remap group and be reported ambiguous, and a blocked candidate could make an otherwise unique remap ambiguous. A remap round now drops such members before grouping, along with members whose declaring type is unresolved. Same-identity structural pairs get their own round before the remaps. Each member's declared identity is computed once. Ambiguity limitations now name the evidence a group shares, which stays true whether the round keyed on names or not. * fix(managed): keep names in unresolved identities and hold ambiguous ones A member of an unresolved declaring type had no declared identity, so the declared-identity rounds keyed it by CIL or signature alone. Two unresolved members with different names paired as an exact match, and a file compared with itself reported unresolved members ambiguous. The declared identity now always includes the name, with a null type for an unresolved one. Remap rounds still leave such members out. A remap round now also leaves out a member whose own identity sits in an ambiguous group on the other side, not only one left one-sided. The undecoded-counterpart check uses the same declared identity. * fix(managed): keep remap groups with unresolved owners ambiguous Remap rounds dropped members of an unresolved declaring type before grouping. Such a member can be another member's own counterpart, so a resolved member could remap to a copy in another type while its unresolved counterpart was reported added. Unresolved members now join remap grouping, and a group that contains one stays ambiguous instead of pairing. The undecoded-counterpart set reuses each member's computed identity. * fix(managed): keep ownerless members out of declared rounds when shared A member whose declaring type did not resolve has a declared identity of a null type and its name. The declared rounds paired two such same-named members even when the other side also held a resolved member with the same CIL and signature, which could be the owner. The old name-free first round reported that group as ambiguous. An ownerless member now enters the declared rounds only when no other member on either side shares its exact CIL/signature key, and never the declared structural round. Otherwise it reaches the remap rounds, which keep any group with an unresolved member ambiguous. * fix(managed): keep competitors of an ownerless member out of the declared round When an ownerless member shares its exact CIL/signature key with another member on the same side, its owner may be that member. The resolved members holding the key now stay out of the declared round too, so they cannot pair and consume the candidate the ownerless member may own, and the remap round keeps the whole group ambiguous as main does. A lone ownerless member still pairs with its lone counterpart. * test(managed): split the ownerless comparison tests under the function length limit The ownerless describe block reached 181 lines, past oxlint's max-lines-per-function limit of 150. Move the structural-competitor case into its own block. * fix(managed): contest signatures and remap only open candidates * fix(managed): retain blocked raw-signature choices as unknown * fix(managed): keep member names in signature contention * fix(managed): scope residual signature contention by name once ownerlessContested applies competitionIdentityKey itself, but unresolvedSignatureAmbiguities passed it keys that were already name-scoped, so the contested set never matched the groups and the same-signature, different-body case reported additions and removals instead of one unknown group. Pass the raw signature key. * fix(managed): constrain matchObserved to declared members matchObserved passes its items to matchByKeys, which needs Declared, so its looser { declaring_type } bound failed typecheck (TS2344, TS2322). * fix(managed): retain held ownership contention for residual matches * fix(test): bind workspace fixture in Hopper launch cases * fix(ci): prepare worker tests and preserve Hopper cleanup ordering --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/managed-code-analysis.md | 34 +- .../managed/managedWorkflowToolContracts.ts | 2 +- .../managedMemberComparisonCoverage.ts | 4 +- .../managed/managedMemberComparisonItems.ts | 38 +- .../managed/managedMemberComparisonMatch.ts | 274 +++++- .../providers/hopperStartupRecovery.test.ts | 2 + ...anagedMemberComparisonFromMetadata.test.ts | 896 +++++++++++++++++- 7 files changed, 1192 insertions(+), 58 deletions(-) diff --git a/docs/managed-code-analysis.md b/docs/managed-code-analysis.md index 9f86551d7..05782b4a2 100644 --- a/docs/managed-code-analysis.md +++ b/docs/managed-code-analysis.md @@ -209,19 +209,27 @@ native/runtime questions retain their own authority and coverage. Names and semantic labels do not establish durable member identity. Comparison preserves observed differences, structural inferences, and unknowns separately. -Cross-version matching first prefers exact raw CIL/signature identity, with -equal decoded fingerprints. Equal decoded fingerprints alone cannot establish -an exact match: they omit switch targets and collapse distinct NaN encodings. -When that does not match, it pairs an exact declared type, method name, and raw -signature before trying structural body shape. The exact-signature key uses names only -as part of that full tuple; names alone never select a pair. Duplicate tuples -remain ambiguous rather than being paired by token order. Fields follow the -same exact tiers. The raw signature is exact whether or not REA decoded it, so -undecoded signatures pair by that tuple too, but they never enter structural -rounds. An unmatched member is therefore reported as `unknown`, not added or -removed, when its own signature was not decoded or when the other side has an -unpaired member, one-sided or ambiguous, with the same declared type and name -whose signature was not decoded. +Cross-version matching first pairs members of the same declared type and name: +methods by exact CIL/signature identity, then by raw signature, then by +structural body shape; fields by raw signature. Exact CIL/signature identity +requires equal raw CIL digests and decoded fingerprints. Equal decoded +fingerprints alone cannot establish an exact match: they omit switch targets +and collapse distinct NaN encodings. Only then may a remap pair a +renamed or moved member across declared types or names: a method by exact +CIL/signature identity or structural body shape, a field by exact decoded +signature. A remap never takes a member whose own declared type and name remain +unpaired on the other side, so a member is never taken from its own changed +counterpart. A member whose declaring type is unresolved could belong to any +type, so it pairs by name only when no other member shares its exact +CIL/signature key, never by structural shape alone, and any remap group it +joins stays ambiguous. The exact-signature key uses names only as part of that +full tuple; names alone never select a pair. Duplicate tuples remain ambiguous +rather than being paired by token order. The raw signature is exact whether or +not REA decoded it, so undecoded signatures pair by that tuple too, but they +never enter structural rounds. An unmatched member is therefore reported as +`unknown`, not added or removed, when its own signature was not decoded or when +the other side has an unpaired member, one-sided or ambiguous, with the same +declared type and name whose signature was not decoded. For a matched method, an unavailable or partial body makes body-shape facets unknown while preserving observed signature differences. For complete bodies, diff --git a/src/contracts/managed/managedWorkflowToolContracts.ts b/src/contracts/managed/managedWorkflowToolContracts.ts index 519c2e125..18d78a310 100644 --- a/src/contracts/managed/managedWorkflowToolContracts.ts +++ b/src/contracts/managed/managedWorkflowToolContracts.ts @@ -98,7 +98,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [ name: "compare_managed_members", ...toolContractMetadata("compare_managed_members"), description: - "Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact CIL/signature, exact declared type, name, and raw signature (decoded or not), and decoded structural method shape. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.", + "Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact declared type, name, and CIL/signature; exact declared type, name, and raw signature (decoded or not); exact declared type, name, and decoded structural method shape; then exact CIL/signature or decoded structural method shape alone, which never takes a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.", kind: "application", inputSchema: compareManagedMembersReferenceInputSchema, outputSchema: comparisonOutputSchema, diff --git a/src/domain/managed/managedMemberComparisonCoverage.ts b/src/domain/managed/managedMemberComparisonCoverage.ts index 85da3b4eb..fce7b25fb 100644 --- a/src/domain/managed/managedMemberComparisonCoverage.ts +++ b/src/domain/managed/managedMemberComparisonCoverage.ts @@ -107,8 +107,8 @@ export const comparisonLimitations = ( ): string[] => { const limitations: string[] = [ "Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.", - "Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.", - "Fields pair by exact signature, then declared type, name, and signature; an undecoded signature is compared only by its raw bytes, and an unmatched member with one stays unknown.", + "Methods pair within one declared type and name by exact CIL/signature, then signature, then structural shape; only then may exact CIL/signature or structural shape alone remap across declared types or names, never taking a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Names alone are never a matching basis.", + "Fields pair by declared type, name, and signature, then remap by exact decoded signature alone under the same rule; an undecoded signature is compared only by its raw bytes, and an unmatched member with one stays unknown.", ]; if (left.coverage.state !== "complete" || right.coverage.state !== "complete") limitations.push("At least one managed member observation is partial."); diff --git a/src/domain/managed/managedMemberComparisonItems.ts b/src/domain/managed/managedMemberComparisonItems.ts index 26331be08..61bfd7c18 100644 --- a/src/domain/managed/managedMemberComparisonItems.ts +++ b/src/domain/managed/managedMemberComparisonItems.ts @@ -5,6 +5,7 @@ import type { ManagedMemberComparisonResult } from "./managedMemberComparison.js import { type ManagedFieldMatches, type ManagedMethodMatches, + identityOf, sha256, } from "./managedMemberComparisonMatch.js"; @@ -211,33 +212,36 @@ const absenceLimitations = ( `signature-not-decoded: The member's ${member.signature.parse_status} signature was compared only by exact declared type, name, and raw bytes, so a changed or renamed counterpart could not be sought.`, ]), ...(member.signature.parse_status === "decoded" && - opposite.oppositeUndecodedNames.has(declaredName(member)) + opposite.oppositeUndecodedNames.size > 0 && + opposite.oppositeUndecodedNames.has(identityOf(member)) ? [ `counterpart-signature-not-decoded: The ${opposite.opposite} ${opposite.inventory} inventory has an unpaired member with the same declared type and name whose signature was not decoded, so it may be this member with a changed signature.`, ] : []), ]; -const declaredName = (member: Method | Field): string => - JSON.stringify([member.declaring_type, member.name]); - /** * Declared names of unpaired members whose signature was not decoded: one-sided * members and candidates of ambiguous groups, which also remain unpaired. */ +interface Unpaired { + readonly item: Method | Field; + readonly identity: string; +} + const undecodedOneSidedNames = (members: { - readonly leftOnly: readonly { readonly item: Method | Field }[]; - readonly rightOnly: readonly { readonly item: Method | Field }[]; + readonly leftOnly: readonly Unpaired[]; + readonly rightOnly: readonly Unpaired[]; readonly ambiguous: readonly { - readonly left: readonly { readonly item: Method | Field }[]; - readonly right: readonly { readonly item: Method | Field }[]; + readonly left: readonly Unpaired[]; + readonly right: readonly Unpaired[]; }[]; }): UndecodedOneSidedNames => { - const names = (side: readonly { readonly item: Method | Field }[]) => + const names = (side: readonly Unpaired[]) => new Set( side .filter(({ item }) => item.signature.parse_status !== "decoded") - .map(({ item }) => declaredName(item)), + .map(({ identity }) => identity), ); return { left: names([ @@ -300,18 +304,20 @@ const fieldOnlyItem = ( }; /** - * Name the identity key an ambiguous group shares. The exact-signature key - * already includes the declared type and name, so names cannot separate it. + * Name only evidence shared by the whole group. Exact-signature ambiguities + * include both declared-identity collisions and unresolved raw-signature choices. */ const ambiguityLimitation = ( members: "methods" | "fields", basis: MethodItem["match"]["basis"], ): string => basis === "exact-signature" - ? `Multiple managed ${members} share the same declared type, name, and raw signature; REA did not guess a token remap.` - : members === "methods" - ? "Multiple managed methods share the same non-name identity key; REA did not guess a token remap." - : "Multiple managed fields share the same signature; REA did not guess a token remap from names."; + ? `Multiple managed ${members} share the same raw signature; REA did not guess declared ownership or a token remap.` + : basis === "exact-il-signature" + ? "Multiple managed methods share the same CIL and signature; REA did not guess a token remap." + : members === "methods" + ? "Multiple managed methods share the same structural shape; REA did not guess a token remap." + : "Multiple managed fields share the same signature; REA did not guess a token remap."; export const buildMethodItems = ( matches: ManagedMethodMatches, diff --git a/src/domain/managed/managedMemberComparisonMatch.ts b/src/domain/managed/managedMemberComparisonMatch.ts index 90106a17c..2cbe32a4a 100644 --- a/src/domain/managed/managedMemberComparisonMatch.ts +++ b/src/domain/managed/managedMemberComparisonMatch.ts @@ -28,8 +28,11 @@ type ConcreteMatchBasis = Exclude; interface Keyed { readonly item: Item; + /** Declared type and name; an unresolved type is null, the name remains. */ + readonly identity: string; readonly exactKey: string | null; readonly signatureKey: string | null; + readonly rawSignatureKey: string; readonly structuralKey: string | null; } @@ -48,6 +51,8 @@ interface Ambiguous { const keyMethod = (item: Method): Keyed => ({ item, + identity: identityOf(item), + rawSignatureKey: item.signature.raw_sha256, exactKey: item.body.status === "present" && item.body.il_sha256 !== null && @@ -99,6 +104,8 @@ const keyMethod = (item: Method): Keyed => ({ const keyField = (item: Field): Keyed => ({ item, + identity: identityOf(item), + rawSignatureKey: item.signature.raw_sha256, exactKey: item.signature.parse_status === "decoded" ? sha256(["field-exact", item.signature.raw_sha256]) @@ -126,15 +133,34 @@ const matchMethods = ( matchByKeys({ left, right, - exactBasis: "exact-il-signature", - fallbackBases: [ + rounds: [ + { + basis: "exact-il-signature", + key: declaredAs(({ exactKey }) => exactKey), + }, { basis: "exact-signature", key: ({ signatureKey }) => signatureKey, + competitionKey: ({ rawSignatureKey }) => rawSignatureKey, + }, + { + basis: "structural-method-shape", + // An unresolved owner has no declared shape match to prove. + key: declaredAs((keyed) => + keyed.item.declaring_type === null ? null : keyed.structuralKey, + ), + competitionKey: ({ structuralKey }) => structuralKey, + }, + { + basis: "exact-il-signature", + key: ({ exactKey }) => exactKey, + remap: true, }, { basis: "structural-method-shape", key: ({ structuralKey }) => structuralKey, + competitionKey: ({ structuralKey }) => structuralKey, + remap: true, }, ], }); @@ -146,11 +172,20 @@ const matchFields = ( matchByKeys({ left, right, - exactBasis: "field-signature", - fallbackBases: [ + rounds: [ + { + basis: "field-signature", + key: declaredAs(({ exactKey }) => exactKey), + }, { basis: "exact-signature", key: ({ signatureKey }) => signatureKey, + competitionKey: ({ rawSignatureKey }) => rawSignatureKey, + }, + { + basis: "field-signature", + key: ({ exactKey }) => exactKey, + remap: true, }, ], }); @@ -158,21 +193,47 @@ const matchFields = ( export type ManagedMethodMatches = ReturnType; export type ManagedFieldMatches = ReturnType; +interface MatchRound { + readonly basis: ConcreteMatchBasis; + readonly key: (item: Keyed) => string | null; + /** Name-free evidence paired with the retained member name for contesting. */ + readonly competitionKey?: (item: Keyed) => string | null; + /** + * The key omits the declared type, so a pair may join different declared + * identities; same-identity pairs were taken by earlier rounds. Contention + * still retains the member name, which unresolved owners keep as evidence. + * A member whose own identity is still unpaired on the other side does not + * take part, and a group with a member of an unresolved type stays ambiguous. + */ + readonly remap?: true; +} + interface MatchByKeysInput { readonly left: readonly Keyed[]; readonly right: readonly Keyed[]; - readonly exactBasis: ConcreteMatchBasis; - readonly fallbackBases: readonly { - readonly basis: ConcreteMatchBasis; - readonly key: (item: Keyed) => string | null; - }[]; + readonly rounds: readonly MatchRound[]; } -const matchByKeys = ({ +export const identityOf = ({ + declaring_type, + name, +}: { + readonly declaring_type: string | null; + readonly name: string; +}): string => sha256([declaring_type, name]); + +/** Narrow a key to members of one declared type and name. */ +const declaredAs = + (key: (item: Keyed) => string | null) => + (item: Keyed): string | null => { + const value = key(item); + return value === null ? null : sha256([item.identity, value]); + }; + +const matchByKeys = ({ left, right, - exactBasis, - fallbackBases, + rounds, }: MatchByKeysInput): { readonly pairs: readonly MatchedPair[]; readonly ambiguous: readonly Ambiguous[]; @@ -181,33 +242,58 @@ const matchByKeys = ({ } => { const usedLeft = new Set>(); const usedRight = new Set>(); + const pairedLeft = new Set>(); + const pairedRight = new Set>(); const pairs: MatchedPair[] = []; const ambiguous: Ambiguous[] = []; - const rounds: readonly { - readonly basis: ConcreteMatchBasis; - readonly key: (item: Keyed) => string | null; - }[] = [ - { basis: exactBasis, key: ({ exactKey }) => exactKey }, - ...fallbackBases, - ]; for (const round of rounds) { + const competitionKey = round.competitionKey ?? ((item) => item.exactKey); + const unpairedLeft = unpairedOf(left, pairedLeft); + const unpairedRight = unpairedOf(right, pairedRight); + const declarable = ownerlessDeclarable( + unpairedLeft, + unpairedRight, + competitionKey, + ); + const openLeft = left.filter((item) => !usedLeft.has(item)); + const openRight = right.filter((item) => !usedRight.has(item)); + // Only open candidates can justify overriding a held declared identity: + // consumed ambiguous rows remain identity barriers, but cannot join a + // later remap group to establish its ambiguity. + const remapContested = + round.remap === true + ? ownerlessContested([openLeft, openRight], competitionKey) + : new Set(); const leftGroups = groupBy( - left.filter((item) => !usedLeft.has(item)), + round.remap === true + ? remappable(openLeft, unpairedRight, competitionKey, remapContested) + : openLeft.filter(declarable), round.key, ); const rightGroups = groupBy( - right.filter((item) => !usedRight.has(item)), + round.remap === true + ? remappable(openRight, unpairedLeft, competitionKey, remapContested) + : openRight.filter(declarable), round.key, ); for (const [key, leftItems] of leftGroups) { const rightItems = rightGroups.get(key); if (rightItems === undefined) continue; - if (leftItems.length === 1 && rightItems.length === 1) { + // An unresolved owner may be either member's own counterpart, so a + // remap group it joins stays ambiguous. + const refused = + round.remap === true && + [...leftItems, ...rightItems].some( + ({ item }) => item.declaring_type === null, + ); + if (!refused && leftItems.length === 1 && rightItems.length === 1) { const [leftItem] = leftItems; const [rightItem] = rightItems; if (leftItem === undefined || rightItem === undefined) continue; usedLeft.add(leftItem); usedRight.add(rightItem); + pairedLeft.add(leftItem); + pairedRight.add(rightItem); pairs.push({ left: leftItem, right: rightItem, @@ -230,6 +316,22 @@ const matchByKeys = ({ } } } + // Contention can prevent a declared signature pair even when CIL/shape + // evidence cannot form a later remap. Held ambiguities still contest + // ownership; only proven pairs leave that evidence pool. Group only open + // candidates so held members retain their original ambiguity and provenance. + for (const group of unresolvedSignatureAmbiguities( + left.filter((item) => !usedLeft.has(item)), + right.filter((item) => !usedRight.has(item)), + ownerlessContested( + [unpairedOf(left, pairedLeft), unpairedOf(right, pairedRight)], + (member) => member.rawSignatureKey, + ), + )) { + for (const item of group.left) usedLeft.add(item); + for (const item of group.right) usedRight.add(item); + ambiguous.push(group); + } return { pairs, ambiguous, @@ -238,6 +340,132 @@ const matchByKeys = ({ }; }; +/** Open signature choices contested by unresolved owners, including held rows. */ +const unresolvedSignatureAmbiguities = ( + left: readonly Keyed[], + right: readonly Keyed[], + contested: ReadonlySet, +): Ambiguous[] => { + const key = (member: Keyed): string => + competitionIdentityKey(member, member.rawSignatureKey) ?? ""; + const leftGroups = groupBy(left, key); + const rightGroups = groupBy(right, key); + const groups: Ambiguous[] = []; + for (const [signature, leftItems] of leftGroups) { + const rightItems = rightGroups.get(signature); + if (!contested.has(signature) || rightItems === undefined) continue; + groups.push({ + left: leftItems, + right: rightItems, + basis: "exact-signature", + }); + } + return groups; +}; + +interface Declared { + readonly declaring_type: string | null; + readonly name: string; +} + +const unpairedOf = ( + items: readonly Keyed[], + paired: ReadonlySet>, +): Keyed[] => items.filter((item) => !paired.has(item)); + +/** + * Round-specific evidence keys an unresolved owner competes for, paired with + * its retained member name. Another same-name member on the same side can be + * the unresolved row's owner; a different name cannot. Contested candidates + * stay in remap rounds rather than pairing by declared identity. + */ +const competitionIdentityKey = ( + member: Keyed, + evidenceKey: string | null, +): string | null => + evidenceKey === null ? null : JSON.stringify([member.item.name, evidenceKey]); + +const ownerlessContested = ( + sides: readonly (readonly Keyed[])[], + keyOf: (item: Keyed) => string | null, +): ReadonlySet => { + const contested = new Set(); + for (const side of sides) { + const seen = new Map(); + const ownerless = new Set(); + for (const member of side) { + const key = competitionIdentityKey(member, keyOf(member)); + if (key === null) continue; + seen.set(key, (seen.get(key) ?? 0) + 1); + if (member.item.declaring_type === null) ownerless.add(key); + } + for (const key of ownerless) + if ((seen.get(key) ?? 0) > 1) contested.add(key); + } + return contested; +}; + +/** + * Members a remap round may group: an unresolved owner, which keeps its group + * ambiguous; a member whose selected key an unresolved owner competes for, so the + * group that preserved the base matcher's ambiguity can form; or no member of + * the same declared identity left unpaired on the other side, whether + * one-sided or in an ambiguous group. The sets are taken before grouping, so + * no group order decides a remap. + */ +const remappable = ( + items: readonly Keyed[], + others: readonly Keyed[], + keyOf: (item: Keyed) => string | null, + contested: ReadonlySet, +): Keyed[] => { + const kept = new Set(others.map(({ identity }) => identity)); + return items.filter((member) => { + const key = keyOf(member); + return ( + (key !== null && + contested.has(competitionIdentityKey(member, key) ?? "")) || + member.item.declaring_type === null || + !kept.has(member.identity) + ); + }); +}; + +/** + * Whether a member may pair in a declared-identity round. A member with an + * unresolved owner may, only when no other member on either side shares its + * selected evidence key: its owner might be any of them, so a shared key + * leaves it to the remap rounds, which keep such a group ambiguous. The + * resolved members that share such a key stay out too, so they cannot pair and + * consume the candidate the ownerless member might own. + */ +const ownerlessDeclarable = ( + left: readonly Keyed[], + right: readonly Keyed[], + keyOf: (item: Keyed) => string | null, +): ((member: Keyed) => boolean) => { + const count = (side: readonly Keyed[]) => { + const seen = new Map(); + for (const member of side) { + const key = keyOf(member); + if (key !== null) seen.set(key, (seen.get(key) ?? 0) + 1); + } + return seen; + }; + const leftSeen = count(left); + const rightSeen = count(right); + const contested = ownerlessContested([left, right], keyOf); + return (member) => { + const key = keyOf(member); + return key !== null && + contested.has(competitionIdentityKey(member, key) ?? "") + ? false + : member.item.declaring_type !== null || + key === null || + ((leftSeen.get(key) ?? 0) <= 1 && (rightSeen.get(key) ?? 0) <= 1); + }; +}; + const groupBy = ( items: readonly Item[], keyOf: (item: Item) => string | null, @@ -266,7 +494,7 @@ const observedBy = * the other side's selection stays one-sided, so a type selection never yields * a remap to a member of a type the other side did not inspect. */ -const matchObserved = ( +const matchObserved = ( left: readonly Item[], right: readonly Item[], sides: { diff --git a/tests/acceptance/providers/hopperStartupRecovery.test.ts b/tests/acceptance/providers/hopperStartupRecovery.test.ts index f35ec68d6..bd4a2d0f1 100644 --- a/tests/acceptance/providers/hopperStartupRecovery.test.ts +++ b/tests/acceptance/providers/hopperStartupRecovery.test.ts @@ -282,6 +282,8 @@ test.for(["handoff", "not-found"] as const)( const status = z.object({ result: z.object({ provider_operation_health: z.object({ + // A timeout observes incomplete startup; a failed launcher without + // confirmed ownership leaves the provider's state unknown. state: z.literal( launchMode === "handoff" ? "not_started" : "unknown", ), diff --git a/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts b/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts index 7866b978b..5ffabdd59 100644 --- a/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts +++ b/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts @@ -47,7 +47,7 @@ describe("managed member comparison", () => { }), ]); expect(result.limitations).toContain( - "Methods pair by exact CIL/signature, then declared type, name, and signature, then structural shape; names alone are never a matching basis.", + "Methods pair within one declared type and name by exact CIL/signature, then signature, then structural shape; only then may exact CIL/signature or structural shape alone remap across declared types or names, never taking a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Names alone are never a matching basis.", ); expect( managedMemberComparisonResultSchema.safeParse({ @@ -339,10 +339,12 @@ describe("managed member comparison uncertainty", () => { const rightField = right.result.fields[0]; expect(rightField).toBeDefined(); if (rightField === undefined) return; + // Both right fields are renamed, so neither left field keeps its declared + // identity and only the shared signature links them. const duplicatedRight = { ...right.result, fields: [ - rightField, + { ...rightField, name: "moved" }, { ...rightField, token: "0x04000002", @@ -365,6 +367,9 @@ describe("managed member comparison uncertainty", () => { candidate_left_tokens: ["0x04000001", "0x04000002"], candidate_right_tokens: ["0x04000001", "0x04000002"], }), + limitations: [ + "Multiple managed fields share the same signature; REA did not guess a token remap.", + ], }), ]); }); @@ -582,7 +587,7 @@ describe("managed member comparison of ambiguous undecoded signatures", () => { basis: "exact-il-signature", }), limitations: [ - "Multiple managed methods share the same non-name identity key; REA did not guess a token remap.", + "Multiple managed methods share the same CIL and signature; REA did not guess a token remap.", ], }), expect.objectContaining({ @@ -670,6 +675,891 @@ describe("managed member comparison of selected types", () => { }); }); +describe("managed member comparison of one signature in several types", () => { + it("pairs a file with itself when two types hold identical members", () => { + const inspected = withTwin( + inspect(buildManagedPeFixture(), "/tmp/twin.dll"), + ); + const result = compareManagedMembers(inspected, inspected); + + expect(result.matching.ambiguous).toBe(0); + expect(result.summary).toMatchObject({ + unchanged: 4, + changed: 0, + added: 0, + removed: 0, + unknown: 0, + }); + for (const item of [...result.methods, ...result.fields]) + expect(item.right?.token).toBe(item.left?.token); + }); + + it.each([1, 2])( + "keeps a member with its own changed counterpart beside %i identical members of other types", + (twins) => { + const left = inspect(buildManagedPeFixture(), "/tmp/own-before.dll"); + const changed = withTwin( + inspect( + buildManagedPeFixture({ + ilBody: Buffer.from([ + 0x32, 0x02, 0x7b, 0x02, 0x00, 0x00, 0x04, 0x28, 0x02, 0x00, 0x00, + 0x0a, 0x2a, + ]), + }), + "/tmp/own-after.dll", + ), + left, + twins, + ); + const result = compareManagedMembers(left, changed); + + expect(result.methods).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + status: "changed", + left: expect.objectContaining({ + declaring_type: "Fixture.Program", + }), + right: expect.objectContaining({ + declaring_type: "Fixture.Program", + }), + match: expect.objectContaining({ basis: "exact-signature" }), + dimensions: expect.arrayContaining(["cil"]), + }), + expect.objectContaining({ + status: "added", + right: expect.objectContaining({ declaring_type: "Other.Twin" }), + }), + ]), + ); + expect(result.fields).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + status: "unchanged", + left: expect.objectContaining({ + declaring_type: "Fixture.Program", + }), + right: expect.objectContaining({ + declaring_type: "Fixture.Program", + }), + }), + expect.objectContaining({ + status: "added", + right: expect.objectContaining({ declaring_type: "Other.Twin" }), + }), + ]), + ); + expect(result.summary).toMatchObject({ unknown: 0, removed: 0 }); + }, + ); + + it("does not remap a member whose own identity remains on the other side", () => { + const left = inspect(buildManagedPeFixture(), "/tmp/sig-before.dll"); + const changed = withTwin( + inspect( + buildManagedPeFixture({ + methodSignature: Buffer.from([0x00, 0x00, 0x08]), + fieldSignature: Buffer.from([0x06, 0x0a]), + }), + "/tmp/sig-after.dll", + ), + left, + ); + // Either side may hold the member whose own identity is left behind. + const forward = compareManagedMembers(left, changed); + const backward = compareManagedMembers(changed, left); + + for (const item of [ + ...forward.methods, + ...forward.fields, + ...backward.methods, + ...backward.fields, + ]) + expect(item.match.status).not.toBe("matched"); + expect(forward.summary).toMatchObject({ removed: 2, added: 4 }); + expect(backward.summary).toMatchObject({ removed: 4, added: 2 }); + }); + + it("does not remap by structural shape a method whose own identity remains on the other side", () => { + const left = inspect(buildManagedPeFixture(), "/tmp/shape-before.dll"); + const changed = withTwin( + inspect( + buildManagedPeFixture({ + methodSignature: Buffer.from([0x00, 0x00, 0x08]), + }), + "/tmp/shape-after.dll", + ), + left, + ); + const [own, twin] = changed.result.methods; + if (own === undefined || twin === undefined) + throw new Error("Expected two methods"); + // Same body shape, different CIL digest: only the structural round links + // the left method to the twin. + const result = compareManagedMembers(left, { + ...changed, + result: { + ...changed.result, + methods: [ + own, + { + ...twin, + body: { ...twin.body, normalized_il_sha256: "0".repeat(64) }, + }, + ], + }, + }); + + for (const item of result.methods) + expect(item.match.status).not.toBe("matched"); + }); +}); + +describe("managed member comparison remaps around kept identities", () => { + it("does not hide a member whose own identity remains in an ambiguous remap group", () => { + const left = inspect(buildManagedPeFixture(), "/tmp/group-before.dll"); + const changed = withTwin( + inspect( + buildManagedPeFixture({ + methodSignature: Buffer.from([0x00, 0x00, 0x08]), + fieldSignature: Buffer.from([0x06, 0x0a]), + }), + "/tmp/group-after.dll", + ), + left, + 2, + ); + const result = compareManagedMembers(left, changed); + + expect(result.matching.ambiguous).toBe(0); + expect(result.summary).toMatchObject({ removed: 2, added: 6 }); + }); + + it("remaps to the one candidate whose own identity is not kept elsewhere", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/kept-base.dll"); + const changedSignature = inspect( + buildManagedPeFixture({ + methodSignature: Buffer.from([0x00, 0x00, 0x08]), + }), + "/tmp/kept-signature.dll", + ); + // Left: Fixture.Program.Main, plus Other.Twin.Main with another signature. + const left = withTwin(base, changedSignature); + // Right: Other.Twin.Main and Other.Twin3.Main, both identical to the + // left Fixture.Program.Main, which the right no longer has. + const twins = withTwin(base, base, 2); + const right = { + ...twins, + result: { ...twins.result, methods: twins.result.methods.slice(1) }, + }; + const result = compareManagedMembers(left, right); + + expect(result.methods).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + left: expect.objectContaining({ declaring_type: "Fixture.Program" }), + right: expect.objectContaining({ declaring_type: "Other.Twin3" }), + match: expect.objectContaining({ + status: "matched", + basis: "exact-il-signature", + }), + }), + ]), + ); + expect( + result.methods.filter(({ match }) => match.status === "ambiguous"), + ).toEqual([]); + }); + + it("names the shared structural shape of an ambiguous remap group", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/shape-group.dll"); + const twins = withTwin(base, base, 2); + // Two right methods share the left method's shape but not its CIL digest, + // and the right no longer declares the left method's identity. + const right = { + ...twins, + result: { + ...twins.result, + methods: twins.result.methods.slice(1).map((method) => ({ + ...method, + body: { ...method.body, normalized_il_sha256: "0".repeat(64) }, + })), + fields: [], + }, + }; + const left = { ...base, result: { ...base.result, fields: [] } }; + const result = compareManagedMembers(left, right); + + expect(result.methods).toEqual([ + expect.objectContaining({ + match: expect.objectContaining({ + status: "ambiguous", + basis: "structural-method-shape", + }), + limitations: [ + "Multiple managed methods share the same structural shape; REA did not guess a token remap.", + ], + }), + ]); + }); +}); + +describe("managed member comparison of unresolved and held identities", () => { + it("does not remap past an unresolved member that may be the counterpart", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/orphan-copy.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const left = { ...base, result: { ...base.result, fields: [] } }; + // The right keeps Main with an unresolved owner, and an identical copy + // in another type; either could be the left Main. + const right = { + ...base, + result: { + ...base.result, + methods: [ + { ...method, declaring_type: null, declaring_type_token: null }, + { + ...method, + declaring_type: "Other.Twin", + declaring_type_token: "0x02000003", + name: "Copy", + token: "0x06000002", + }, + ], + fields: [], + }, + }; + + for (const result of [ + compareManagedMembers(left, right), + compareManagedMembers(right, left), + ]) { + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + expect(result.summary).toMatchObject({ added: 0, removed: 0 }); + } + }); +}); + +describe("managed member comparison of raw-signature contention", () => { + it("contests same-signature methods even when their bodies differ", () => { + const base = inspect( + buildManagedPeFixture(), + "/tmp/ownerless-signatures.dll", + ); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const changedBody = (hash: string, stack: number) => ({ + ...method.body, + normalized_il_sha256: hash.repeat(64), + max_stack: stack, + }); + const withOwnerless = { + ...base, + result: { + ...base.result, + fields: [], + methods: [ + { ...method, body: changedBody("a", 1) }, + { + ...method, + token: "0x06000002", + declaring_type: null, + declaring_type_token: null, + body: changedBody("b", 2), + }, + ], + }, + }; + const resolvedOnly = { + ...base, + result: { + ...base.result, + fields: [], + methods: [{ ...method, body: changedBody("c", 3) }], + }, + }; + for (const result of [ + compareManagedMembers(withOwnerless, resolvedOnly), + compareManagedMembers(resolvedOnly, withOwnerless), + ]) { + expect(result.methods).toHaveLength(1); + const [item] = result.methods; + if (item === undefined) + throw new Error("Expected uncertain signature group"); + expect(item).toMatchObject({ + status: "unknown", + match: { status: "ambiguous", basis: "exact-signature" }, + }); + expect(result.summary).toMatchObject({ + added: 0, + removed: 0, + unknown: 1, + }); + expect( + item.match.candidate_left_tokens.length + + item.match.candidate_right_tokens.length, + ).toBe(3); + } + }); + + it("contests ownerless undecoded fields by raw signature", () => { + const base = inspect( + buildManagedPeFixture({ fieldSignature: Buffer.from([0x06, 0x7f]) }), + "/tmp/ownerless-field-signatures.dll", + ); + const [field] = base.result.fields; + if (field === undefined) throw new Error("Expected a fixture field"); + expect(field.signature.parse_status).toBe("unsupported"); + const withOwnerless = { + ...base, + result: { + ...base.result, + methods: [], + fields: [ + field, + { + ...field, + token: "0x04000002", + declaring_type: null, + declaring_type_token: null, + }, + ], + }, + }; + const resolvedOnly = { + ...base, + result: { ...base.result, methods: [], fields: [field] }, + }; + for (const result of [ + compareManagedMembers(withOwnerless, resolvedOnly), + compareManagedMembers(resolvedOnly, withOwnerless), + ]) + expect( + result.fields.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + }); +}); + +describe("managed member comparison of consumed ownerless ambiguity", () => { + it("keeps a consumed ownerless ambiguity from authorizing a later remap", () => { + const base = inspect( + buildManagedPeFixture(), + "/tmp/consumed-ownerless.dll", + ); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const candidate = ( + raw: string, + token: string, + owner: string | null, + name: string, + stack: number, + ) => ({ + ...method, + token, + declaring_type: owner, + declaring_type_token: owner === null ? null : method.declaring_type_token, + name, + signature: { ...method.signature, raw_sha256: raw.repeat(64) }, + body: { + ...method.body, + normalized_il_sha256: raw.repeat(64), + max_stack: stack, + }, + }); + const left = { + ...base, + result: { + ...base.result, + fields: [], + methods: [ + candidate("a", "0x06000001", "T", "M", 1), + candidate("b", "0x06000002", null, "M", 1), + candidate("b", "0x06000003", "D", "D", 2), + ], + }, + }; + const right = { + ...base, + result: { + ...base.result, + fields: [], + methods: [ + candidate("c", "0x06000001", "U", "N", 1), + candidate("b", "0x06000002", null, "M", 1), + candidate("d", "0x06000003", "T", "M", 3), + ], + }, + }; + for (const result of [ + compareManagedMembers(left, right), + compareManagedMembers(right, left), + ]) { + expect(result.matching.ambiguous).toBeGreaterThan(0); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + } + }); +}); + +describe("managed member comparison of retained ownership contention", () => { + it("keeps changed counterparts unknown after an ownerless candidate is held", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/held-ownerless.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const body = (hash: string, stack: number) => ({ + ...method.body, + il_sha256: hash.repeat(64), + normalized_il_sha256: hash.repeat(64), + max_stack: stack, + }); + const ownerless = { + ...method, + token: "0x06000002", + declaring_type: null, + declaring_type_token: null, + body: body("b", 2), + }; + const left = { + ...base, + result: { + ...base.result, + fields: [], + methods: [{ ...method, body: body("a", 1) }, ownerless], + }, + }; + const right = { + ...base, + result: { + ...base.result, + fields: [], + methods: [ + { ...method, body: body("c", 3) }, + { + ...method, + token: "0x06000002", + declaring_type: "Other.Twin", + name: "Copy", + body: ownerless.body, + }, + ], + }, + }; + for (const result of [ + compareManagedMembers(left, right), + compareManagedMembers(right, left), + ]) { + expect(result.summary).toEqual({ + unchanged: 0, + changed: 0, + added: 0, + removed: 0, + unknown: 2, + }); + expect(result.methods).toEqual([ + expect.objectContaining({ + status: "unknown", + match: { + status: "ambiguous", + basis: "exact-il-signature", + confidence: "unknown", + candidate_left_tokens: ["0x06000002"], + candidate_right_tokens: ["0x06000002"], + }, + }), + expect.objectContaining({ + status: "unknown", + match: { + status: "ambiguous", + basis: "exact-signature", + confidence: "unknown", + candidate_left_tokens: ["0x06000001"], + candidate_right_tokens: ["0x06000001"], + }, + }), + ]); + } + }); +}); + +describe("managed member comparison of ownerless structural competitors", () => { + it("keeps structural competitors of an ownerless method ambiguous in both directions", () => { + const base = inspect( + buildManagedPeFixture(), + "/tmp/ownerless-shape-competitors.dll", + ); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const withSignature = (raw: string, token: string) => ({ + ...method, + token, + signature: { ...method.signature, raw_sha256: raw.repeat(64) }, + }); + const withOwnerless = { + ...base, + result: { + ...base.result, + methods: [ + withSignature("a", "0x06000001"), + { + ...withSignature("b", "0x06000002"), + declaring_type: null, + declaring_type_token: null, + }, + ], + fields: [], + }, + }; + const resolvedOnly = { + ...base, + result: { + ...base.result, + methods: [withSignature("c", "0x06000001")], + fields: [], + }, + }; + for (const result of [ + compareManagedMembers(withOwnerless, resolvedOnly), + compareManagedMembers(resolvedOnly, withOwnerless), + ]) { + expect(result.matching.ambiguous).toBe(1); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + expect(result.summary).toMatchObject({ added: 0, removed: 0 }); + } + }); +}); + +describe("managed member comparison of ownerless members", () => { + it("keeps an ownerless member ambiguous beside a resolved copy, as main does", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/ownerless-copy.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const ownerless = { + ...method, + declaring_type: null, + declaring_type_token: null, + }; + const left = { + ...base, + result: { ...base.result, methods: [ownerless], fields: [] }, + }; + // The right keeps the ownerless Foo and a resolved copy with the same + // CIL and signature; the left Foo's owner may be either one. + const right = { + ...base, + result: { + ...base.result, + methods: [ownerless, { ...method, token: "0x06000002" }], + fields: [], + }, + }; + + for (const result of [ + compareManagedMembers(left, right), + compareManagedMembers(right, left), + ]) { + expect(result.matching.ambiguous).toBe(1); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + expect(result.summary).toMatchObject({ added: 0, removed: 0 }); + } + }); + + it("still pairs a lone ownerless member with its lone counterpart", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/ownerless-lone.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const ownerless = { + ...method, + declaring_type: null, + declaring_type_token: null, + }; + const side = { + ...base, + result: { ...base.result, methods: [ownerless], fields: [] }, + }; + + const result = compareManagedMembers(side, side); + + expect(result.matching.ambiguous).toBe(0); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toHaveLength(1); + }); + + it("keeps a resolved copy out of the declared round when an ownerless competitor is on the left, as main does", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/ownerless-left.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const ownerless = { + ...method, + declaring_type: null, + declaring_type_token: null, + }; + // The left holds the resolved Foo and an ownerless Foo with the same CIL + // and signature; the right holds only the resolved Foo. The ownerless + // Foo's owner may be the resolved one, so the three stay ambiguous. + const withOwnerless = { + ...base, + result: { ...base.result, methods: [method, ownerless], fields: [] }, + }; + const resolvedOnly = { + ...base, + result: { ...base.result, methods: [method], fields: [] }, + }; + + const result = compareManagedMembers(withOwnerless, resolvedOnly); + + expect(result.matching.ambiguous).toBe(1); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + expect(result.summary).toMatchObject({ added: 0, removed: 0 }); + }); + + it("keeps a resolved copy out of the declared round when an ownerless competitor is on the right, as main does", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/ownerless-right.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const ownerless = { + ...method, + declaring_type: null, + declaring_type_token: null, + }; + const withOwnerless = { + ...base, + result: { ...base.result, methods: [method, ownerless], fields: [] }, + }; + const resolvedOnly = { + ...base, + result: { ...base.result, methods: [method], fields: [] }, + }; + + const result = compareManagedMembers(resolvedOnly, withOwnerless); + + expect(result.matching.ambiguous).toBe(1); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + expect(result.summary).toMatchObject({ added: 0, removed: 0 }); + }); + + it("keeps an ownerless method ambiguous beside a resolved method of the same shape", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/ownerless-shape.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const ownerless = { + ...method, + declaring_type: null, + declaring_type_token: null, + }; + // Raw signature digests differ, so only the decoded shape links them. + const reshaped = (raw: string, token: string) => ({ + signature: { ...method.signature, raw_sha256: raw.repeat(64) }, + token, + }); + const left = { + ...base, + result: { ...base.result, methods: [ownerless], fields: [] }, + }; + const right = { + ...base, + result: { + ...base.result, + methods: [ + { ...ownerless, ...reshaped("e", "0x06000001") }, + { ...method, name: "Bar", ...reshaped("d", "0x06000002") }, + ], + fields: [], + }, + }; + const result = compareManagedMembers(left, right); + + expect(result.matching.ambiguous).toBe(1); + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + }); +}); + +describe("managed member comparison of unresolved owners", () => { + it("does not pair members of unresolved types under different names", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/orphan-names.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const orphan = { declaring_type: null, declaring_type_token: null }; + const side = (name: string) => ({ + ...base, + result: { + ...base.result, + methods: [{ ...method, ...orphan, name }], + fields: [], + }, + }); + const result = compareManagedMembers(side("Main"), side("Renamed")); + + for (const item of result.methods) + expect(item.match.status).not.toBe("matched"); + }); + + it("keeps ownerless members that share a body ambiguous, as main does", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/orphan-self.dll"); + const [method] = base.result.methods; + const [field] = base.result.fields; + if (method === undefined || field === undefined) + throw new Error("Expected a fixture method and field"); + const orphan = { declaring_type: null, declaring_type_token: null }; + const inspected = { + ...base, + result: { + ...base.result, + methods: [ + { ...method, ...orphan, name: "p" }, + { ...method, ...orphan, name: "q", token: "0x06000002" }, + ], + fields: [ + { ...field, ...orphan, name: "a" }, + { ...field, ...orphan, name: "b", token: "0x04000002" }, + ], + }, + }; + const result = compareManagedMembers(inspected, inspected); + + // Their owners are unknown, so `p` may be `q`; names alone cannot tell. + expect(result.matching.ambiguous).toBe(2); + expect( + [...result.methods, ...result.fields].filter( + ({ match }) => match.status === "matched", + ), + ).toEqual([]); + }); + + it("does not remap a member whose own identity is in an ambiguous group", () => { + const undecoded = { methodSignature: Buffer.from([0x00, 0x00, 0x7f]) }; + const decoded = inspect(buildManagedPeFixture(), "/tmp/held-decoded.dll"); + const held = inspect(buildManagedPeFixture(undecoded), "/tmp/held.dll"); + const [undecodedMethod] = held.result.methods; + const [decodedMethod] = decoded.result.methods; + if (undecodedMethod === undefined || decodedMethod === undefined) + throw new Error("Expected fixture methods"); + // The right keeps two identical undecoded Fixture.Program.Main, which + // stay ambiguous, and a copy of the decoded Main in another type. + const left = { + ...held, + result: { + ...held.result, + methods: [{ ...undecodedMethod, token: "0x06000002" }, decodedMethod], + }, + }; + const right = { + ...held, + result: { + ...held.result, + methods: [ + undecodedMethod, + { ...undecodedMethod, token: "0x06000002" }, + { + ...decodedMethod, + declaring_type: "Other.Twin", + declaring_type_token: "0x02000003", + token: "0x06000003", + }, + ], + }, + }; + + for (const result of [ + compareManagedMembers(left, right), + compareManagedMembers(right, left), + ]) + expect( + result.methods.filter(({ match }) => match.status === "matched"), + ).toEqual([]); + }); + + it("does not remap a member whose declaring type is unresolved", () => { + const base = inspect(buildManagedPeFixture(), "/tmp/orphan.dll"); + const [method] = base.result.methods; + if (method === undefined) throw new Error("Expected a fixture method"); + const left = { + ...base, + result: { + ...base.result, + methods: [ + { ...method, declaring_type: null, declaring_type_token: null }, + ], + fields: [], + }, + }; + const right = { + ...base, + result: { + ...base.result, + methods: [ + { ...method, declaring_type: "Other.Twin", token: "0x06000002" }, + ], + fields: [], + }, + }; + + for (const result of [ + compareManagedMembers(left, right), + compareManagedMembers(right, left), + ]) + for (const item of result.methods) + expect(item.match.status).not.toBe("matched"); + }); +}); + +/** + * Add copies of the fixture's method and field, each pair declared by another + * type, to an inspection. The copies come from `source`, so they can carry + * the bytes of a different build than the inspection they join. + */ +const withTwin = ( + inspected: ReturnType, + source: ReturnType = inspected, + count = 1, +): ReturnType => { + const [method] = source.result.methods; + const [field] = source.result.fields; + if (method === undefined || field === undefined) + throw new Error("Expected a fixture method and field"); + const rows = Array.from({ length: count }, (_, index) => index + 2); + const twin = (row: number) => ({ + declaring_type: row === 2 ? "Other.Twin" : `Other.Twin${String(row)}`, + declaring_type_token: `0x0200000${String(row + 1)}`, + }); + return { + ...inspected, + result: { + ...inspected.result, + methods: [ + ...inspected.result.methods, + ...rows.map((row) => ({ + ...method, + ...twin(row), + token: `0x0600000${String(row)}`, + })), + ], + fields: [ + ...inspected.result.fields, + ...rows.map((row) => ({ + ...field, + ...twin(row), + token: `0x0400000${String(row)}`, + })), + ], + }, + }; +}; + const inspect = (bytes: Buffer, path: string, typeNames?: string[]) => { const target = managedPeFixtureTarget(bytes, path); const result = inspectManagedMembersBytes( From 7072f87baf096eb944f15bc52e3925653d459cba Mon Sep 17 00:00:00 2001 From: xin zhuang <65798732+1052326311@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:38:32 +0800 Subject: [PATCH 06/12] fix(artifacts): preserve Mach-O load-command string identity (#2110) * fix(artifacts): preserve Mach-O load-command string identity * fix(process): report no remaining time after a provider deadline fires Node timers can fire while performance.now() is still a fraction of a millisecond short of the monotonic deadline. ProviderStartupDeadline then reported interruption "timeout" and an aborted signal while remainingMs() returned ceil(0.x) = 1, so polling loops guarded by remainingMs() > 0 (Hopper and Ghidra startup) could run past an elapsed deadline, and the real-timer test "aborts a bounded wait when its real monotonic deadline expires" failed intermittently in CI (expected 1 to be 0). Once the deadline's own timer has classified a timeout, report zero remaining time. A deterministic regression test fires the timer with the monotonic clock 0.4 ms short of the deadline. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit dfdaa0ca74cc84a45dcb186422a0f51aa61bc427) * fix(ci): isolate Linux Hopper process fixture inventory * fix(comparison): recheck historical calls-only changes (#2223) * fix(comparison): preserve incomplete function call evidence Keep missing, unknown, partial and unresolved call relationships unknown in function comparisons and reconstruction claims. Aggregate IDA caller and callee coverage without overwriting uncertainty. Validate with 144 focused tests, typecheck/lint, docs checks and test discovery. Real providers were not verified; the full headless IDA session suite requires unavailable Windows native controls. * fix(comparison): recheck historical calls-only changes --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> * style: format identity comparison and IDA runner --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Lucien <164857476+dakjdakd@users.noreply.github.com> --- .../apple/MachoLoadCommandReader.test.ts | 21 ++++++++ src/artifacts/apple/MachoLoadCommandReader.ts | 3 +- tests/boundary/cli/dylibResolutionCli.test.ts | 51 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/src/artifacts/apple/MachoLoadCommandReader.test.ts b/src/artifacts/apple/MachoLoadCommandReader.test.ts index 97bceb672..3dc6334d7 100644 --- a/src/artifacts/apple/MachoLoadCommandReader.test.ts +++ b/src/artifacts/apple/MachoLoadCommandReader.test.ts @@ -229,6 +229,27 @@ it("selects matching arm64e subtype slices when tracing a mixed FAT image", asyn }); describe("Mach-O load command reader: decodes thin-image load commands", () => { + it("preserves leading U+FEFF in load-command strings", async () => { + const image = machoImage({ + commands: [ + dylibCommand(LC.ID_DYLIB, "\uFEFF@rpath/libself.dylib"), + dylibCommand(LC.LOAD_DYLIB, "\uFEFF@rpath/libother.dylib"), + rpathCommand("\uFEFF@loader_path/Frameworks"), + dyldEnvironmentCommand("\uFEFFDYLD_LIBRARY_PATH=/example"), + ], + }); + expect(await read(image)).toMatchObject({ + status: "parsed", + slices: [ + { + install_name: "\uFEFF@rpath/libself.dylib", + dependencies: [{ install_name: "\uFEFF@rpath/libother.dylib" }], + rpaths: ["\uFEFF@loader_path/Frameworks"], + dyld_environment: ["\uFEFFDYLD_LIBRARY_PATH=/example"], + }, + ], + }); + }); it("decodes dylib loading commands of a thin image", async () => { const image = machoImage({ fileType: FILE_TYPE.dylib, diff --git a/src/artifacts/apple/MachoLoadCommandReader.ts b/src/artifacts/apple/MachoLoadCommandReader.ts index 27f7ec283..55b134cf5 100644 --- a/src/artifacts/apple/MachoLoadCommandReader.ts +++ b/src/artifacts/apple/MachoLoadCommandReader.ts @@ -456,7 +456,8 @@ const commandString = ( `load command ${index} has an unterminated string`, ); try { - return new TextDecoder("utf-8", { fatal: true }).decode( + // lc_str contains name/path data, so a leading U+FEFF is part of its identity. + return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode( body.subarray(offset, end), ); } catch { diff --git a/tests/boundary/cli/dylibResolutionCli.test.ts b/tests/boundary/cli/dylibResolutionCli.test.ts index 21ea99a9c..6d72e4de6 100644 --- a/tests/boundary/cli/dylibResolutionCli.test.ts +++ b/tests/boundary/cli/dylibResolutionCli.test.ts @@ -106,6 +106,57 @@ const withBrokenHelper = async (app: string): Promise => { await writeFiles(app, { "Contents/Helpers/broken": broken }); }; +cliTest( + "does not turn U+FEFF-prefixed strings into dyld path tokens", + async ({ cli }) => { + const app = await fixtureApp(); + await writeFiles(app, { + "Contents/MacOS/App": machoImage({ + commands: [ + buildVersionCommand(1), + rpathCommand("@executable_path/../Frameworks"), + dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"), + dylibCommand(LC.LOAD_DYLIB, "\uFEFF@rpath/libcore.dylib"), + ], + }), + "Contents/Helpers/tool": machoImage({ + commands: [ + buildVersionCommand(1), + rpathCommand("\uFEFF@loader_path/../Frameworks"), + dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"), + ], + }), + }); + const output = await cli.run({ + arguments: ["trace-dylib-resolution", app, "--json"], + environment: ENVIRONMENT, + }); + expect(output.exitCode, output.stderr).toBe(0); + const trace = dylibResolutionResultSchema.parse( + parseEvidence(output.json).normalized_result, + ); + const ordinary = trace.edges.find( + ({ loader, install_name }) => + loader === "Contents/MacOS/App" && + install_name === "@rpath/libcore.dylib", + ); + expect(ordinary?.resolution).toMatchObject({ + status: "resolved", + image: "Contents/Frameworks/libcore.dylib", + }); + const marked = trace.edges.find( + ({ install_name }) => install_name === "\uFEFF@rpath/libcore.dylib", + ); + expect(marked).toBeDefined(); + expect(marked?.resolution.image).toBeNull(); + const helper = trace.edges.find( + ({ loader }) => loader === "Contents/Helpers/tool", + ); + expect(helper).toBeDefined(); + expect(helper?.resolution.image).toBeNull(); + }, +); + describe("trace-dylib-resolution CLI", () => { cliTest("traces every executable root of an app bundle", async ({ cli }) => { const app = await fixtureApp(); From 3a4d49406a4f3c0b566b6a16f3655c08b1354e19 Mon Sep 17 00:00:00 2001 From: Avocado Date: Wed, 14 Oct 2026 09:39:17 +1100 Subject: [PATCH 07/12] fix(javascript): preserve Electron runtime entrypoint paths (#2742) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(javascript): preserve Electron runtime entrypoint paths * fix(javascript): resolve runtime entrypoints before modules * fix(javascript): preserve Electron runtime path semantics * fix(javascript): resolve Electron renderers exactly * fix(javascript): retain runtime package aliases * fix(javascript): retain missing renderer URL paths * fix(javascript): resolve Electron URL and utility entries correctly * fix(javascript): reject suffix-only worker URLs * fix(javascript): respect Electron URL and utility path semantics * fix(javascript): separate Node runtime entrypoints from source imports * fix(comparison): recheck historical calls-only changes (#2223) * fix(comparison): preserve incomplete function call evidence Keep missing, unknown, partial and unresolved call relationships unknown in function comparisons and reconstruction claims. Aggregate IDA caller and callee coverage without overwriting uncertainty. Validate with 144 focused tests, typecheck/lint, docs checks and test discovery. Real providers were not verified; the full headless IDA session suite requires unavailable Windows native controls. * fix(comparison): recheck historical calls-only changes --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> (cherry picked from commit 688defca0f4a3de04eb199f7754f323c68896c3c) * fix(ci): isolate Linux Hopper process fixture inventory (cherry picked from commit 8cac51e12184d56a9ba80a4427b3e6082ddac1ec) * fix(android): make DEX descriptor pattern portable (cherry picked from commit 1335bcddc569a1cfb34b6efedcb6f2e3aaaa3357) * fix: repair the static-check failures on the default branch (#2895) * fix: repair the static-check failures on the default branch The default branch fails its own required `Static checks` job three ways, so every pull request reports that job as failed regardless of its own change. - `npm run format:check` reports `src/domain/functionComparison.test.ts` and `src/ida/IdaOperationRunner.ts`. - `npm run lint` reports a duplicate `import { join } from "node:path"` in `tests/boundary/mcp/ghidraInventoryMcp.test.ts` (lines 4 and 17). - `npm run typecheck` reports `format: "devin"` missing from the client format union in `src/application/SupportedClients.ts`, and an unchecked index in `tests/boundary/cli/clientProfileLifecycle.test.ts`, whose pair array is inferred as `string[][]`. Apply the pinned formatter, drop the duplicate import, list the `"devin"` format that its own definition already uses, and mark the pair array `as const`. Validation: `npm run check:fast` and `npm run format:check` pass. * fix(setup): keep Devin on the JSON configuration dialect --------- Co-authored-by: 吴佳浩 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> (cherry picked from commit df3d96da801976fdbe37a726c2f4f84af8ffbf90) --------- Co-authored-by: morluto Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Lucien <164857476+dakjdakd@users.noreply.github.com> Co-authored-by: 吴佳浩Alben <35291372+XiaoBinGan@users.noreply.github.com> Co-authored-by: 吴佳浩 --- .../javascript/ElectronBoundaryAnalysis.ts | 10 +- .../ElectronBoundaryGraphWindows.ts | 33 ++- .../JavaScriptArtifactGraphContext.ts | 2 + .../JavaScriptArtifactGraphFindings.ts | 8 + .../JavaScriptArtifactPathResolution.test.ts | 218 ++++++++++++++++++ .../JavaScriptArtifactPathResolution.ts | 92 ++++++++ .../javascriptWorkerUrlCli.test.ts | 6 + .../electronApplicationAnalysis.test.ts | 206 +++++++++++++++++ 8 files changed, 567 insertions(+), 8 deletions(-) diff --git a/src/application/javascript/ElectronBoundaryAnalysis.ts b/src/application/javascript/ElectronBoundaryAnalysis.ts index bd090f709..f2721a083 100644 --- a/src/application/javascript/ElectronBoundaryAnalysis.ts +++ b/src/application/javascript/ElectronBoundaryAnalysis.ts @@ -3,7 +3,10 @@ import type { ElectronIpcFinding } from "../../domain/javascript/electronStaticA import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js"; import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js"; import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; -import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js"; +import { + resolveArtifactPathByContext, + type ResolveArtifactPathInput, +} from "./JavaScriptArtifactPathResolution.js"; /** One IPC fact retaining its exact owning artifact for graph projection. */ export interface ElectronIpcRecord { @@ -160,6 +163,7 @@ export const summarizeElectronBoundaries = ( specifier: finding.module_path, context: finding.module_resolution_context, files, + runtimePathKind: "node-entrypoint", }), ).length, native_addon_bindings: nativeBindings.length, @@ -204,6 +208,7 @@ interface ResolveToFileInput { readonly files: ReadonlyMap; readonly kind?: JavaScriptArtifactFile["kind"]; readonly moduleKind?: "import" | "require"; + readonly runtimePathKind?: ResolveArtifactPathInput["runtimePathKind"]; } const resolvesToFile = (input: ResolveToFileInput): boolean => { @@ -212,6 +217,9 @@ const resolvesToFile = (input: ResolveToFileInput): boolean => { sourcePath: input.file.path, context: input.context, files: input.files, + ...(input.runtimePathKind === undefined + ? {} + : { runtimePathKind: input.runtimePathKind }), ...(input.moduleKind === undefined ? {} : { moduleKind: input.moduleKind }), }).resolved_path; return ( diff --git a/src/application/javascript/ElectronBoundaryGraphWindows.ts b/src/application/javascript/ElectronBoundaryGraphWindows.ts index 63f62bd12..2ffe550c6 100644 --- a/src/application/javascript/ElectronBoundaryGraphWindows.ts +++ b/src/application/javascript/ElectronBoundaryGraphWindows.ts @@ -23,7 +23,10 @@ import { electronFindingSourceNode, electronRangeKey, } from "./ElectronBoundaryGraphContext.js"; -import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js"; +import { + artifactPathResolutionProperties, + resolveArtifactPathByContext, +} from "./JavaScriptArtifactPathResolution.js"; interface FindingInput { readonly context: JavaScriptArtifactGraphContext; @@ -137,6 +140,7 @@ const addWindowPreload = ( sourcePath: input.file.path, context: resolutionContext, files: input.context.filesByPath, + runtimePathKind: "exact-file", }); const role = createElectronRoleNode(input.context, { kind: "electron-preload", @@ -160,6 +164,7 @@ const addWindowPreload = ( resolved_path: resolution.resolved_path, resolution_status: resolution.resolution_status, limitations: resolution.limitations, + ...artifactPathResolutionProperties(resolution), }, }); linkElectronRoleToAsset(input.context, { @@ -253,6 +258,16 @@ const addUtilityProcess = ( }, ], }); + const resolution = + value.module_path === null + ? undefined + : resolveArtifactPathByContext({ + declaredPath: value.module_path, + sourcePath: file.path, + context: value.module_resolution_context, + files: context.filesByPath, + runtimePathKind: "node-entrypoint", + }); addElectronInferenceEdge(context, { source: input.source, target: utility, @@ -264,15 +279,19 @@ const addUtilityProcess = ( properties: { declared_path: value.module_path, expression: value.module_expression, + ...(resolution === undefined + ? {} + : { + resolution_context: resolution.resolution_context, + resolved_path: resolution.resolved_path, + resolution_status: resolution.resolution_status, + limitations: resolution.limitations, + ...artifactPathResolutionProperties(resolution), + }), }, }); if (value.module_path === null) return; - const resolution = resolveArtifactPathByContext({ - declaredPath: value.module_path, - sourcePath: file.path, - context: value.module_resolution_context, - files: context.filesByPath, - }); + if (resolution === undefined) return; const resolved = resolution.resolved_path; const target = resolved === null diff --git a/src/application/javascript/JavaScriptArtifactGraphContext.ts b/src/application/javascript/JavaScriptArtifactGraphContext.ts index 1779bdaae..1070c8ae0 100644 --- a/src/application/javascript/JavaScriptArtifactGraphContext.ts +++ b/src/application/javascript/JavaScriptArtifactGraphContext.ts @@ -22,6 +22,7 @@ import { unavailableAstEvidence, } from "./JavaScriptArtifactGraphEvidence.js"; import { + artifactPathResolutionProperties, resolveArtifactPathByContext, type ArtifactPathResolution, } from "./JavaScriptArtifactPathResolution.js"; @@ -273,6 +274,7 @@ export const createElectronRoleNode = ( resolved_path: input.resolution.resolved_path, resolution_status: input.resolution.resolution_status, limitations: input.resolution.limitations, + ...artifactPathResolutionProperties(input.resolution), mechanism: input.mechanism, }, evidence: staticInferenceEvidence({ diff --git a/src/application/javascript/JavaScriptArtifactGraphFindings.ts b/src/application/javascript/JavaScriptArtifactGraphFindings.ts index 0020ef577..5e939d0f9 100644 --- a/src/application/javascript/JavaScriptArtifactGraphFindings.ts +++ b/src/application/javascript/JavaScriptArtifactGraphFindings.ts @@ -283,6 +283,14 @@ const addDiscoveredRole = ( sourcePath: input.file.path, context: input.value.resolution_context, files: context.filesByPath, + ...(input.value.role === "preload" || + (input.value.role === "renderer" && + input.value.resolution_context === "filesystem-expression") + ? { runtimePathKind: "exact-file" as const } + : input.value.role === "renderer" && + input.value.resolution_context === "module-specifier" + ? { runtimePathKind: "url-resource" as const } + : {}), }); const role = createElectronRoleNode(context, { kind: diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.test.ts b/src/application/javascript/JavaScriptArtifactPathResolution.test.ts index b746d7e97..6f40767ef 100644 --- a/src/application/javascript/JavaScriptArtifactPathResolution.test.ts +++ b/src/application/javascript/JavaScriptArtifactPathResolution.test.ts @@ -1318,6 +1318,29 @@ describe("package import alias resolution", () => { }); }); + it("keeps package import aliases available for runtime entrypoints", () => { + const files = aliasFiles({ + "package.json": JSON.stringify({ + imports: { "#worker": "./worker.js" }, + }), + "main.cjs": "", + "worker.js": "", + }); + expect( + resolve({ + declaredPath: "#worker", + sourcePath: "main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "resolved", + resolved_path: "worker.js", + declared_path: "#worker", + }); + }); + it("uses a nested package imports map rather than the application root", () => { const files = aliasFiles({ "package.json": JSON.stringify({ @@ -2093,6 +2116,26 @@ describe("url-reference directory and empty-segment semantics", () => { }); }); +describe("suffix-only non-runtime URL references", () => { + it.each(["", "?cache=1", "#worker"])( + "rejects URL reference %s without a path or known base document", + (declaredPath) => { + expect( + resolve({ + declaredPath, + sourcePath: "dist/app.mjs", + context: "url-reference", + files: fileMap([file("dist/app.mjs", "root")]), + }), + ).toMatchObject({ + declared_path: declaredPath, + resolution_status: "rejected", + resolved_path: null, + }); + }, + ); +}); + describe("url-reference JavaScript artifact path resolution", () => { it.each([ ["C|?cache=1#entry", "dist/C|"], @@ -2327,3 +2370,178 @@ describe("exact HTML resource resolution", () => { }); }); }); + +describe("exact Electron runtime entrypoint resolution", () => { + it("requires a protocol for Electron URL resources", () => { + const files = fileMap([ + file("app/main.cjs", "root"), + file("app/renderer", "root"), + file("app/renderer.js", "root"), + ]); + expect( + resolve({ + declaredPath: "./renderer", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "url-resource", + }), + ).toMatchObject({ + resolution_status: "unavailable", + resolved_path: null, + limitations: [expect.stringContaining("requires a URL protocol")], + }); + expect( + resolve({ + declaredPath: "file:///app/renderer", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "url-resource", + }), + ).toMatchObject({ + resolution_status: "resolved", + resolved_path: "app/renderer", + }); + }); + + it("checks local paths exactly while preserving bare package lookup", () => { + const files = fileMap([ + file("app/main.cjs", "root"), + file("app/worker.js", "root"), + file("app/worker", "root"), + file("app/worker#v1.js", "root"), + file( + "node_modules/exported/package.json", + "root", + '{"exports":{"./parser":"./parser.cjs"}}', + ), + file("node_modules/exported/parser.cjs", "root"), + file("app/fallback/index.js", "root"), + ]); + expect( + resolve({ + declaredPath: "./worker.js", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "resolved", + resolved_path: "app/worker.js", + }); + expect( + resolve({ + declaredPath: "exported/parser", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "resolved", + resolved_path: "node_modules/exported/parser.cjs", + }); + expect( + resolve({ + declaredPath: "./worker#v1.js", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "resolved", + resolved_path: "app/worker#v1.js", + }); + expect( + resolve({ + declaredPath: "./fallback", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "not-found", + resolved_path: null, + }); + }); + + it("accepts an exact extensionless file but not a directory index", () => { + const files = fileMap([ + file("app/main.cjs", "root"), + file("app/preload", "root"), + file("app/preload.js", "root"), + file("app/fallback/index.js", "root"), + ]); + expect( + resolve({ + declaredPath: "./preload", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "resolved", + resolved_path: "app/preload", + }); + expect( + resolve({ + declaredPath: "./fallback", + sourcePath: "app/main.cjs", + context: "module-specifier", + files, + runtimePathKind: "exact-file", + }), + ).toMatchObject({ + resolution_status: "not-found", + resolved_path: null, + }); + }); +}); + +it.each(["#home", "?theme=dark", ""])( + "does not invent a document base for runtime URL %s", + (declaredPath) => { + expect( + resolve({ + declaredPath, + sourcePath: "main.cjs", + context: "url-reference", + runtimePathKind: "url-resource", + files: fileMap([file("main.cjs", "root")]), + }), + ).toMatchObject({ + declared_path: declaredPath, + resolution_status: "unavailable", + resolved_path: null, + }); + }, +); + +it("resolves Node runtime entrypoints without substituting emitted TypeScript sources", () => { + const files = fileMap([ + file("main.ts", "root"), + file("worker.ts", "root"), + file("worker.js", "other-container"), + file("runtime.js", "root"), + file("directory/index.js", "root"), + ]); + for (const [declaredPath, status, path] of [ + ["./worker.js", "not-found", null], + ["./runtime", "resolved", "runtime.js"], + ["./directory", "resolved", "directory/index.js"], + ] as const) + expect( + resolve({ + declaredPath, + sourcePath: "main.ts", + context: "module-specifier", + files, + runtimePathKind: "node-entrypoint", + }), + ).toMatchObject({ resolution_status: status, resolved_path: path }); +}); diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts index 88aa1508f..04172cf65 100644 --- a/src/application/javascript/JavaScriptArtifactPathResolution.ts +++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts @@ -78,6 +78,8 @@ export interface ResolveArtifactPathInput { readonly htmlBaseHref?: string | null; /** Import/require semantics; runtime resource paths omit this provenance. */ readonly moduleKind?: JavaScriptModuleResolutionMode; + /** Runtime paths retain their loader owner independently of source imports. */ + readonly runtimePathKind?: "exact-file" | "node-entrypoint" | "url-resource"; } /** Preserve an explicitly retained loader mode on graph relationships. */ @@ -189,6 +191,8 @@ const conditionalResolution = ( }); const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => { + if (input.runtimePathKind === "node-entrypoint") + return resolveNodeRuntimeEntrypoint(input); if (input.moduleKind === "compiler-dependent") { const imported = resolvePath({ ...input, moduleKind: "import" }); const required = resolvePath({ ...input, moduleKind: "require" }); @@ -222,6 +226,10 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => { ], }; } + if (input.runtimePathKind === "url-resource") + return resolveExactUrlResource(input); + if (input.runtimePathKind === "exact-file" && isRuntimePathDeclaration(input)) + return resolveRuntimeEntrypoint(input); // Package import keys are literal lookup identities, not artifact paths. // The selected target is admitted separately by resolveExportTarget. if ( @@ -260,6 +268,82 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => { return resolveCandidate(input, confined, new Set(), emittedSourceCandidates); }; +const resolveExactUrlResource = ( + input: ResolveArtifactPathInput, +): CandidateResolution => { + // Electron loadURL requires a protocol. A scheme-less string is not relative + // to the calling script; filesystem paths belong to loadFile. + if (!hasScheme(input.declaredPath)) + return unresolvedCandidate("unavailable", [ + "Electron loadURL requires a URL protocol; relative filesystem paths belong to loadFile.", + ]); + if (!/^file:/iu.test(input.declaredPath)) + return unresolvedCandidate("external", [ + "Only file URLs can be mapped to selected local application artifacts.", + ]); + const urlContextCandidate = contextualCandidate(input); + if (typeof urlContextCandidate !== "string") return urlContextCandidate; + const confined = confineCandidate(urlContextCandidate); + if (typeof confined !== "string") return confined; + return ( + resolveFileCandidates(input, [confined]) ?? { + resolvedPath: null, + status: "not-found", + candidatePath: confined, + limitations: [ + `The exact URL resource ${confined} was not found among the selected application files.`, + ], + } + ); +}; + +const isRuntimePathDeclaration = (input: ResolveArtifactPathInput): boolean => + input.context === "filesystem-expression" || + (input.context === "module-specifier" && + (isRelativeJavaScriptModuleSpecifier(input.declaredPath) || + input.declaredPath.startsWith("/") || + fileUrlPath(input.declaredPath) !== undefined)); + +const resolveNodeRuntimeEntrypoint = ( + input: ResolveArtifactPathInput, +): CandidateResolution => { + const { runtimePathKind: _runtimePathKind, ...sourceInput } = input; + const runtimeInput = { ...sourceInput, moduleKind: "require" as const }; + if (!isRuntimePathDeclaration(runtimeInput)) return resolvePath(runtimeInput); + const candidate = contextualCandidate(runtimeInput); + if (typeof candidate !== "string") return candidate; + const confined = confineCandidate(candidate); + if (typeof confined !== "string") return confined; + // Node entrypoints use runtime file/directory probes. They do not originate + // in emitted TypeScript import syntax and cannot select a source substitute. + return resolveCandidate(runtimeInput, confined, new Set()); +}; + +const resolveRuntimeEntrypoint = ( + input: ResolveArtifactPathInput, +): CandidateResolution => { + const rejected = rejectDeclaration(input.declaredPath); + if (rejected !== null) return rejected; + if (hasScheme(input.declaredPath) || looksExternal(input.declaredPath)) + return unresolvedCandidate("external", [ + "Electron runtime entrypoints must identify local paths, not external URLs.", + ]); + const candidate = confineCandidate( + relativeCandidate(input.sourcePath, input.declaredPath), + ); + if (typeof candidate !== "string") return candidate; + return ( + resolveFileCandidates(input, [candidate]) ?? { + resolvedPath: null, + status: "not-found", + candidatePath: candidate, + limitations: [ + `The declared Electron runtime entrypoint ${candidate} was not found as an exact file among the selected application files; extension and directory fallback were not attempted.`, + ], + } + ); +}; + const resolveRuntimeSourceCandidates = ( input: ResolveArtifactPathInput, exactPath: string, @@ -316,6 +400,14 @@ const contextualCandidate = ( context === "url-reference" ? stripQueryAndFragment(input.declaredPath) : input.declaredPath; + if (context === "url-reference" && declared.length === 0) + return input.runtimePathKind === "url-resource" + ? unresolvedCandidate("unavailable", [ + "A suffix-only runtime URL requires the window's current document URL; the calling script does not establish that base.", + ]) + : unresolvedCandidate("rejected", [ + "The URL reference contains no pathname, and its base document is not established by this analysis.", + ]); if (context === "module-specifier" && /^file:/iu.test(declared)) { const fileUrl = fileUrlPath(declared); if (fileUrl === null) diff --git a/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts b/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts index 6d9b62a63..977083c76 100644 --- a/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts +++ b/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts @@ -390,6 +390,9 @@ cliTest( ]), ), "dynamic-base.mjs": 'new Worker(new URL("./worker.js", base));', + "empty-worker-url.mjs": 'new Worker("");', + "query-only-worker-url.mjs": 'new Worker("?cache=1");', + "fragment-only-worker-url.mjs": 'new Worker("#worker");', "shadowed.mjs": 'function start(URL) { return new Worker(new URL("./worker.js", import.meta.url)); }', "typed-shadowed.ts": @@ -428,6 +431,9 @@ cliTest( "directory-dot.mjs": "./worker.js/.", "directory-parent.mjs": "./worker.js/child/..", "empty-segment.mjs": "./child//../worker.js", + "empty-worker-url.mjs": "", + "query-only-worker-url.mjs": "?cache=1", + "fragment-only-worker-url.mjs": "#worker", "package.mjs": "./package-worker", "external.mjs": "https://example.test/worker.js", }; diff --git a/tests/boundary/filesystem/javascript-applications/electronApplicationAnalysis.test.ts b/tests/boundary/filesystem/javascript-applications/electronApplicationAnalysis.test.ts index 795075c99..c2eb1070e 100644 --- a/tests/boundary/filesystem/javascript-applications/electronApplicationAnalysis.test.ts +++ b/tests/boundary/filesystem/javascript-applications/electronApplicationAnalysis.test.ts @@ -67,6 +67,11 @@ describe("static Electron application analysis", () => { }); }); + it( + "keeps Electron runtime entrypoints on their declared filenames", + exactRuntimeEntrypointFixture, + ); + it("keeps computed identifier member keys unknown", async () => { const root = await computedMemberFixtureDirectory(); @@ -153,9 +158,210 @@ describe("static Electron application analysis", () => { }); }); +const exactRuntimeEntrypointFixture = async (): Promise => { + const root = await createTestTempDirectory("rea-electron-exact-entrypoints-"); + await mkdir(join(root, "renderer/page"), { recursive: true }); + await Promise.all([ + writeFile( + join(root, "main.cjs"), + String.raw` +const { BrowserWindow, utilityProcess } = require("electron"); +const path = require("node:path"); +new BrowserWindow({ webPreferences: { preload: "./entry" } }); +new BrowserWindow().loadURL("file:///renderer/index.html"); +new BrowserWindow().loadURL("renderer/bare.html"); +new BrowserWindow().loadURL("#home"); +new BrowserWindow().loadURL(""); +new BrowserWindow().loadURL("./renderer/other.html?theme=dark#home"); +new BrowserWindow().loadURL("./renderer/missing.html"); +new BrowserWindow().loadFile("./renderer/page"); +new BrowserWindow({ webPreferences: { preload: path.join(__dirname, "preload") } }); +new BrowserWindow({ webPreferences: { preload: "./explicit-preload.js" } }); +utilityProcess.fork("./worker"); +utilityProcess.fork("./worker#v1.js"); +utilityProcess.fork("./service.js"); +`, + ), + writeFile(join(root, "entry.html"), "sibling"), + writeFile(join(root, "preload.html"), "sibling"), + writeFile(join(root, "worker.js"), "module.exports = {};"), + writeFile(join(root, "renderer/index.html"), "renderer"), + writeFile( + join(root, "renderer/bare.html"), + "bare renderer URL", + ), + writeFile(join(root, "renderer/other.html"), "other"), + writeFile(join(root, "renderer/missing.html.js"), "module.exports = {};"), + writeFile( + join(root, "renderer/page/index.html"), + "directory", + ), + writeFile(join(root, "explicit-preload.js"), "module.exports = {};"), + writeFile(join(root, "service.js"), "module.exports = {};"), + ]); + + const result = await reconstructJavaScriptArtifact({ input_path: root }); + const graph = parseJavaScriptApplicationGraph(result.graph); + expectSuffixOnlyRenderersUnresolved(graph); + expectExactRendererPaths(graph); + const roles = graph.nodes.filter(({ kind }) => kind === "electron-preload"); + const roleByDeclaration = new Map( + roles.map((role) => [role.observations[0]?.properties.declared_path, role]), + ); + + expect(result.electron_summary.resolved_utility_entrypoints).toBe(2); + for (const [declaredPath, candidatePath] of [ + ["./entry", "entry"], + ["preload", "preload"], + ]) { + const role = roleByDeclaration.get(declaredPath); + expect(role?.observations[0]?.properties).toMatchObject({ + declared_path: declaredPath, + resolved_path: null, + resolution_status: "not-found", + candidate_path: candidatePath, + limitations: [ + expect.stringContaining( + "extension and directory fallback were not attempted", + ), + ], + }); + expect( + graph.edges.some( + (edge) => + edge.source_node_id === role?.node_id && edge.relation === "maps_to", + ), + ).toBe(false); + } + expect( + roleByDeclaration.get("./explicit-preload.js")?.observations[0]?.properties, + ).toMatchObject({ + resolved_path: "explicit-preload.js", + resolution_status: "resolved", + }); + + const utilityLaunches = graph.edges.filter( + (edge) => + edge.evidence.extractor.operation === "map-utility-process-launch", + ); + const resolvedWorker = utilityLaunches.find( + (edge) => edge.properties.declared_path === "./worker", + ); + expect(resolvedWorker?.evidence).toMatchObject({ + authority: "static-relationship-inference", + state: "inferred", + limitations: expect.arrayContaining([ + "Static syntax does not prove that this relationship executes at runtime.", + ]), + }); + expect(utilityLaunches).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + properties: expect.objectContaining({ + declared_path: "./worker", + resolved_path: "worker.js", + resolution_status: "resolved", + }), + }), + expect.objectContaining({ + properties: expect.objectContaining({ + declared_path: "./worker#v1.js", + resolved_path: null, + resolution_status: "not-found", + }), + }), + expect.objectContaining({ + properties: expect.objectContaining({ + declared_path: "./service.js", + resolved_path: "service.js", + resolution_status: "resolved", + }), + }), + ]), + ); + expect( + graph.edges.some( + (edge) => + edge.evidence.extractor.operation === + "resolve-utility-process-entrypoint" && + edge.properties.resolved_path === "worker.html", + ), + ).toBe(false); +}; + type Reconstruction = Awaited>; type ApplicationGraph = ReturnType; +const expectSuffixOnlyRenderersUnresolved = (graph: ApplicationGraph): void => { + const renderers = new Map( + graph.nodes + .filter(({ kind }) => kind === "electron-renderer") + .map((renderer) => [ + renderer.observations[0]?.properties.declared_path, + renderer, + ]), + ); + expect( + renderers.get("file:///renderer/index.html")?.observations[0]?.properties, + ).toMatchObject({ + resolved_path: "renderer/index.html", + resolution_status: "resolved", + }); + for (const declaredPath of [ + "./renderer/other.html?theme=dark#home", + "renderer/bare.html", + "./renderer/missing.html", + "#home", + "", + ]) { + const renderer = renderers.get(declaredPath); + expect(renderer?.observations[0]?.properties).toMatchObject({ + resolved_path: null, + resolution_status: "unavailable", + }); + expect(renderer?.observations[0]?.properties.limitations).toEqual( + expect.arrayContaining([ + expect.stringContaining("requires a URL protocol"), + ]), + ); + expect( + graph.edges.some( + (edge) => + edge.source_node_id === renderer?.node_id && + edge.relation === "maps_to", + ), + ).toBe(false); + } +}; + +const expectExactRendererPaths = (graph: ApplicationGraph): void => { + const renderers = new Map( + graph.nodes + .filter(({ kind }) => kind === "electron-renderer") + .map((renderer) => [ + renderer.observations[0]?.properties.declared_path, + renderer, + ]), + ); + for (const [declaredPath, candidatePath] of [ + ["./renderer/page", "renderer/page"], + ]) { + const renderer = renderers.get(declaredPath); + expect(renderer?.observations[0]?.properties).toMatchObject({ + resolved_path: null, + resolution_status: "not-found", + candidate_path: candidatePath, + }); + expect( + graph.edges.some( + (edge) => + edge.source_node_id === renderer?.node_id && + edge.relation === "maps_to", + ), + ).toBe(false); + } +}; + const expectElectronSummary = (result: Reconstruction): void => { expect(result.electron_summary).toMatchObject({ browser_windows: 3, From c6166d4b56d6c6e4ad33980464edc8697672168a Mon Sep 17 00:00:00 2001 From: Avocado Date: Wed, 14 Oct 2026 09:39:27 +1100 Subject: [PATCH 08/12] fix(javascript): retain bridge conditions on IPC joins (#2747) * fix(javascript): retain bridge conditions on IPC joins * fix(javascript): retain IPC condition ownership * style(javascript): format bridge path regression * fix(process): report no remaining time after a provider deadline fires Node timers can fire while performance.now() is still a fraction of a millisecond short of the monotonic deadline. ProviderStartupDeadline then reported interruption "timeout" and an aborted signal while remainingMs() returned ceil(0.x) = 1, so polling loops guarded by remainingMs() > 0 (Hopper and Ghidra startup) could run past an elapsed deadline, and the real-timer test "aborts a bounded wait when its real monotonic deadline expires" failed intermittently in CI (expected 1 to be 0). Once the deadline's own timer has classified a timeout, report zero remaining time. A deterministic regression test fires the timer with the monotonic clock 0.4 ms short of the deadline. Co-Authored-By: Claude Opus 5.5 * fix(javascript): preserve Electron join condition coverage --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Codex --- .../ElectronBoundaryGraphCallPaths.ts | 3 +- .../cli/electronWrappedCallPaths.test.ts | 44 ++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/application/javascript/ElectronBoundaryGraphCallPaths.ts b/src/application/javascript/ElectronBoundaryGraphCallPaths.ts index b815e82bf..d1f1886db 100644 --- a/src/application/javascript/ElectronBoundaryGraphCallPaths.ts +++ b/src/application/javascript/ElectronBoundaryGraphCallPaths.ts @@ -165,7 +165,8 @@ export const addElectronCallPaths = ( pairing_basis: "unique-exact-literal-channel", resolution: "candidate", handler_path: to.file.path, - conditions: to.path.conditions, + bridge_conditions: from.path.conditions, + handler_conditions: to.path.conditions, }, limitations: [ "The unique static channel match does not establish runtime registration, sender acceptance, or dispatch.", diff --git a/tests/boundary/cli/electronWrappedCallPaths.test.ts b/tests/boundary/cli/electronWrappedCallPaths.test.ts index 4dd0d02a8..186abcbbe 100644 --- a/tests/boundary/cli/electronWrappedCallPaths.test.ts +++ b/tests/boundary/cli/electronWrappedCallPaths.test.ts @@ -55,7 +55,8 @@ cliTest( expect( byId.get(edge.target_node_id)?.observations[0]?.properties.channel, ).toBe(edge.properties.channel); - expect(edge.properties.conditions).toEqual([ + expect(edge.properties.bridge_conditions).toEqual([]); + expect(edge.properties.handler_conditions).toEqual([ expect.objectContaining({ expression: "allowed(event)" }), ]); } @@ -495,3 +496,44 @@ cliTest( ).toEqual(["empty:key"]); }, ); + +cliTest( + "retains bridge and handler conditions on Electron IPC join edges", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-electron-join-conditions-"); + await writeFixtureFiles(root, { + "preload.js": `const e=require("electron"); + e.contextBridge.exposeInMainWorld("desktop", { + choose: flag + ? () => e.ipcRenderer.send("test:copy") + : () => e.ipcRenderer.send("test:cut") + });`, + "main.js": `const e=require("electron"); + if(!flag)e.ipcMain.on("test:copy",event=>allowed(event)&&event.sender.copy()); + if(flag)e.ipcMain.on("test:cut",event=>allowed(event)&&event.sender.cut());`, + }); + const { graph } = await analyzeJavaScriptDirectory("CLI", cli, root); + const joins = graph.edges.filter( + (edge) => + edge.evidence.extractor.operation === "join-electron-wrapper-paths", + ); + expect(joins).toHaveLength(2); + for (const [channel, bridgeCondition] of [ + ["test:copy", "flag"], + ["test:cut", "!(flag)"], + ]) { + const edge = joins.find( + (candidate) => candidate.properties.channel === channel, + ); + expect(edge?.properties.bridge_conditions).toEqual([ + expect.objectContaining({ expression: bridgeCondition }), + ]); + expect(edge?.properties.handler_conditions).toEqual([ + expect.objectContaining({ + expression: channel === "test:copy" ? "!flag" : "flag", + }), + expect.objectContaining({ expression: "allowed(event)" }), + ]); + } + }, +); From bcb60c179e30c6e7caa1113cb98e91744bfea3a6 Mon Sep 17 00:00:00 2001 From: Shubham Ahuja <157806066+shubhamahuja9999@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:10:25 +0530 Subject: [PATCH 09/12] fix(browser): read expression-free template literals as module specifiers (#2842) Captured-bundle chunk edges and source-map original module edges only accepted quoted string literals as import()/require() specifiers. Bundlers such as rolldown emit plain constants as expression-free template literals (import(`./chunk.js`)), so statically known dependencies were dropped while completeness stayed complete. Read both sites through the shared exact-literal reader (stringValue); template literals with substitutions stay unrecognized. On OWASP Juice Shop v20.3.0 this recovers 8 lazy chunk edges (previously 0). Fixes #2841 Fixes #2599 Co-authored-by: Claude Opus 5.5 Co-authored-by: morluto <17176810+morluto@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- src/browser/WebSourceMapFetcher.ts | 24 +++++++------ src/domain/webBundleAnalyzer.test.ts | 22 ++++++++++++ src/domain/webBundleAnalyzerInspection.ts | 19 +++++----- .../browser/webSourceMapFetcher.test.ts | 35 +++++++++++++++++++ 4 files changed, 82 insertions(+), 18 deletions(-) diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts index 5c8f86ea0..5dbbe2ad1 100644 --- a/src/browser/WebSourceMapFetcher.ts +++ b/src/browser/WebSourceMapFetcher.ts @@ -11,6 +11,7 @@ import { isUrlLikeModuleSpecifier } from "../domain/webBundleAnalyzerAst.js"; import { analyzeParsedJavaScriptReferences } from "../domain/javascript/javascriptSemanticAnalysis.js"; import { traverseJavaScriptAst } from "../domain/javascript/javascriptSemanticTraversal.js"; import { parseJavaScriptSource } from "../domain/javascript/javascriptSourceParser.js"; +import { stringValue } from "../domain/javascript/javascriptStaticAnalysisHelpers.js"; import type { AnalyzeWebBundleInput, WebSourceMapItem, @@ -1049,18 +1050,21 @@ const originalDependency = ( return node.source === null || node.source === undefined ? null : { kind: "static_import", specifier: node.source.value }; - if (t.isImportExpression(node) && t.isStringLiteral(node.source)) - return { kind: "dynamic_import", specifier: node.source.value }; + if (t.isImportExpression(node)) { + const specifier = stringValue(node.source); + return specifier === undefined + ? null + : { kind: "dynamic_import", specifier }; + } if ( (t.isCallExpression(node) || t.isOptionalCallExpression(node)) && - t.isIdentifier(node.callee, { name: "require" }) && - t.isStringLiteral(node.arguments[0]) - ) - return { - kind: "require", - specifier: node.arguments[0].value, - requireCallee: node.callee, - }; + t.isIdentifier(node.callee, { name: "require" }) + ) { + const specifier = stringValue(node.arguments[0]); + return specifier === undefined + ? null + : { kind: "require", specifier, requireCallee: node.callee }; + } // `import x = require("m")` is only legal at module top level and always // refers to the host loader, so it needs no unbound-`require` check. The // `moduleReference` is an entity name for a local alias instead, which diff --git a/src/domain/webBundleAnalyzer.test.ts b/src/domain/webBundleAnalyzer.test.ts index edcb37a20..93bb24fdc 100644 --- a/src/domain/webBundleAnalyzer.test.ts +++ b/src/domain/webBundleAnalyzer.test.ts @@ -662,6 +662,28 @@ describe("web metadata key semantics", () => { }); }); +it("reads expression-free template dynamic imports as chunk edges", () => { + const result = analyzeCapturedWebBundle( + inspection(` + import(\`./lazy.js\`); + import("./quoted.js"); + import(\`./\${name}.js\`); + `), + ); + + expect(result.observations.chunks.edges).toEqual([ + expect.objectContaining({ + kind: "dynamic_import", + specifier: "./lazy.js", + resolved_url: `${origin}/assets/lazy.js`, + }), + expect.objectContaining({ + kind: "dynamic_import", + specifier: "./quoted.js", + }), + ]); +}); + it("does not infer call names from dynamic computed identifiers", () => { const result = analyzeCapturedWebBundle( inspection(` diff --git a/src/domain/webBundleAnalyzerInspection.ts b/src/domain/webBundleAnalyzerInspection.ts index 12c35109c..f48faf552 100644 --- a/src/domain/webBundleAnalyzerInspection.ts +++ b/src/domain/webBundleAnalyzerInspection.ts @@ -123,14 +123,17 @@ const inspectNode = ( node, accumulator, }); - else if (t.isImportExpression(node) && t.isStringLiteral(node.source)) - addEdge({ - script, - specifier: node.source.value, - kind: "dynamic_import", - node, - accumulator, - }); + else if (t.isImportExpression(node)) { + const specifier = stringValue(node.source); + if (specifier !== undefined) + addEdge({ + script, + specifier, + kind: "dynamic_import", + node, + accumulator, + }); + } if (t.isObjectProperty(node)) inspectRouteProperty(script, node, accumulator); if ( t.isCallExpression(node) || diff --git a/tests/boundary/browser/webSourceMapFetcher.test.ts b/tests/boundary/browser/webSourceMapFetcher.test.ts index 5fab66f58..b5a15e120 100644 --- a/tests/boundary/browser/webSourceMapFetcher.test.ts +++ b/tests/boundary/browser/webSourceMapFetcher.test.ts @@ -988,6 +988,41 @@ describe("source-map original dependency syntax", () => { result.items[0]?.original_module_edges.map(({ specifier }) => specifier), ).toEqual(["./real.js", "./dynamic.js", "./common.cjs"]); }); + + it("reads expression-free template module specifiers as literals", async () => { + const text = [ + "import(`./dep.js`);", + "import(`./dep.${name}.js`);", + "require(`./common.cjs`);", + "require(`./${name}.cjs`);", + ].join("\n"); + const result = await fetchWebSourceMaps([request], input(), undefined, { + fetch: () => + Promise.resolve( + new Response( + JSON.stringify({ + version: 3, + names: [], + sources: ["main.ts"], + sourcesContent: [text], + mappings: "AAAA", + }), + ), + ), + }); + const item = result.items[0]; + if (item?.status !== "included") throw new Error("map not included"); + expect(item.original_module_edges).toEqual([ + expect.objectContaining({ + kind: "dynamic_import", + specifier: "./dep.js", + resolved_source: `${origin}/assets/dep.js`, + }), + expect.objectContaining({ kind: "require", specifier: "./common.cjs" }), + ]); + expect(item.original_sources[0]?.artifact?.text).toBe(text); + expect(item.mappings).toHaveLength(1); + }); }); describe("source-map original syntax boundaries", () => { From 1f122c02b71dae7f4109f35ed834f82b96fbf247 Mon Sep 17 00:00:00 2001 From: Yann Roberto <165009858+shoyann@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:41:22 +0800 Subject: [PATCH 10/12] fix(javascript): exclude HTML URL suffixes from path admission (#2833) --- .../JavaScriptArtifactPathResolution.ts | 19 +-- .../javascriptHtmlUrlSuffixesCli.test.ts | 136 ++++++++++++++++++ 2 files changed, 146 insertions(+), 9 deletions(-) create mode 100644 tests/acceptance/applications/javascriptHtmlUrlSuffixesCli.test.ts diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts index 04172cf65..f56623f2e 100644 --- a/src/application/javascript/JavaScriptArtifactPathResolution.ts +++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts @@ -376,8 +376,11 @@ const resolveRuntimeSourceCandidates = ( return null; }; -const rejectDeclaration = (declared: string): CandidateResolution | null => { - if (declared.length === 0) +const rejectDeclaration = ( + declared: string, + allowEmptyPath = false, +): CandidateResolution | null => { + if (declared.length === 0 && !allowEmptyPath) return unresolvedCandidate("rejected", ["The declared path is empty."]); if (declared.includes("\0") || declared.includes("\\")) return unresolvedCandidate("rejected", [ @@ -394,6 +397,7 @@ const contextualCandidate = ( input: ResolveArtifactPathInput, ): string | CandidateResolution => { const { context } = input; + if (context === "html-reference") return htmlCandidate(input); // URL suffixes are evidence, not pathname bytes. Admit only the path while // retaining the complete declaration on the resolution result. let declared = @@ -426,7 +430,6 @@ const contextualCandidate = ( } const rejected = rejectDeclaration(declared); if (rejected !== null) return rejected; - if (context === "html-reference") return htmlCandidate(input); if (context === "module-specifier") { if (hasScheme(declared)) return unresolvedCandidate("external", [ @@ -907,6 +910,10 @@ const htmlCandidate = ( input: ResolveArtifactPathInput, ): string | CandidateResolution => { const declared = stripQueryAndFragment(htmlUrlText(input.declaredPath)); + // HTML owns URL-text normalization and pathname admission. A nonempty URL + // reference may have no pathname; suffix bytes remain declaration evidence. + const rejected = rejectDeclaration(declared, input.declaredPath !== ""); + if (rejected !== null) return rejected; if (looksExternal(declared)) return unresolvedCandidate("external", [ "External HTML references are not mapped to local artifact assets.", @@ -920,12 +927,6 @@ const htmlCandidate = ( return unresolvedCandidate("external", [ "The document base href is external, so its script reference is not a local artifact path.", ]); - // Removing URL tabs and newlines can join an encoded dot or separator that - // the raw declaration split, so admit the parsed URL text again. - if (!admitsCanonicalPathSyntax(declared)) - return unresolvedCandidate("rejected", [ - "Encoded dot or separator bytes are rejected before artifact path resolution.", - ]); const declaredPath = percentDecodeUrlPath(declared); if (declaredPath === null) return unresolvedCandidate("rejected", [ diff --git a/tests/acceptance/applications/javascriptHtmlUrlSuffixesCli.test.ts b/tests/acceptance/applications/javascriptHtmlUrlSuffixesCli.test.ts new file mode 100644 index 000000000..88e94144f --- /dev/null +++ b/tests/acceptance/applications/javascriptHtmlUrlSuffixesCli.test.ts @@ -0,0 +1,136 @@ +import { expect } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; +import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js"; + +cliTest.for(["CLI", "stdio MCP"] as const)( + "admits HTML script pathnames without treating URL suffixes as paths through %s", + async (surface, { cli }) => { + const root = await createTestTempDirectory("rea-html-url-suffixes-"); + const cases = [ + { + source: "query.html", + script: "./app.js?redirect=%2Ffoo", + resolved: "app.js", + }, + { + source: "fragment.html", + script: "./app.js#route=%2Ffoo", + resolved: "app.js", + }, + { + source: "suffix-bytes.html", + script: "./app.js?value=%2e%5c%00%ff\\tail", + resolved: "app.js", + }, + { + source: "url-text.html", + script: " \n./a\tpp.js?redirect=%2\nfassets ", + resolved: "app.js", + }, + { + source: "self.html", + script: "?redirect=%2Ffoo", + resolved: "self.html", + }, + { + source: "self-fragment.html", + script: "#route=%5Cfoo", + resolved: "self-fragment.html", + }, + { + source: "base.html", + base: "assets/?redirect=%2Froot", + script: "app.js#route=%2Ffoo", + resolved: "assets/app.js", + }, + { + source: "base-self.html", + base: "assets/app.js?redirect=%5Croot", + script: "?redirect=%2Ffoo", + resolved: "assets/app.js", + }, + { + source: "path-separator.html", + script: "./assets%2Fapp.js?valid=1", + resolved: null, + }, + { source: "path-dot.html", script: "./%2e/app.js#valid", resolved: null }, + { + source: "path-backslash.html", + script: "./assets\\app.js?valid=1", + resolved: null, + }, + { + source: "path-nul.html", + script: "./app%00.js?valid=1", + resolved: null, + }, + { + source: "split-separator.html", + script: "./assets%2\nfapp.js?valid=1", + resolved: null, + }, + { + source: "base-separator.html", + base: "assets%2F?valid=1", + script: "app.js?redirect=%2Ffoo", + resolved: null, + }, + ]; + await writeFixtureFiles(root, { + ...Object.fromEntries( + cases.map(({ source, base, script }) => [ + source, + `${base === undefined ? "" : ``}`, + ]), + ), + "app.js": "globalThis.rootApp = true;", + "assets/app.js": "globalThis.nestedApp = true;", + }); + + const result = await analyzeJavaScriptDirectory(surface, cli, root); + const loads = result.graph.edges.filter( + ({ relation }) => relation === "loads", + ); + const unresolved = result.graph.nodes + .flatMap(({ observations }) => observations) + .filter( + ({ properties }) => properties.mechanism === "html-script-reference", + ); + for (const { source, base, script, resolved } of cases) { + const load = loads.find( + ({ evidence }) => + evidence.location.available && + evidence.location.value.kind === "source-range" && + evidence.location.value.source === source, + ); + if (resolved === null) { + expect( + unresolved.find( + ({ properties }) => properties.script_path === script, + ), + ).toMatchObject({ + properties: { + script_path: script, + resolved_path: null, + resolution_status: "rejected", + }, + }); + expect(load).toBeUndefined(); + continue; + } + expect(load).toMatchObject({ + properties: { + script_path: script, + base_href: base ?? null, + resolved_path: resolved, + resolution_context: "html-reference", + resolution_status: "resolved", + }, + }); + } + }, +); From b9b3a9098b072313119eccb3ae574faa57c3e517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E4=BD=B3=E6=B5=A9Alben?= <35291372+XiaoBinGan@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:43:03 +0800 Subject: [PATCH 11/12] fix(gemini): compare consolidated allowlists through one normalizer (#2495) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(gemini): compare consolidated allowlists through one normalizer geminiServerPolicyBlock consolidates allowlists by normalized intersection but tested the consolidated list against the raw server key. Because the intersection keeps the spelling of whichever policy came first, the same pair of policies blocked the server in one arrangement and allowed it in the other, and the excluded test had the mirror-image asymmetry. Normalize the comparison key once and use the same normalizer for the exclusion test, the intersection and the membership test. The messages keep the caller-facing server key, so lookup and display stay separate. Verified with 88 client profile, lifecycle and registration tests, check:fast and verify:test-discovery on macOS arm64. The regression test drives setup twice with the same policies in both arrangements; before the change one arrangement failed and the other passed. * test(gemini): cover normalized exclusions and padded allowlist entries The regression case added with the fix drove the allowlist intersection in both spellings but left the other two comparisons the change touches uncovered: the exclusion membership test and the trimming applied to padded names. Reverting either behaviour kept the suite green, so neither was pinned. Greptile raised exactly this on the PR. An exclusion is now exercised as " REA " against the selected server, and a padded allowlist entry is exercised as the only policy, so a padded entry has to permit the same server its exact spelling permits rather than fall to the membership test. Verified with `npm run test:focused -- tests/boundary/cli/clientProfiles.test.ts`: 14 passed with the change; reverting only ClientConfigurationDocument.ts to main fails both cases, the arrangement case with `rea+REA: expected 1 to be +0` and the new one on both the excluded and the padded-allowlist assertions. * fix(process): report no remaining time after a provider deadline fires Node timers can fire while performance.now() is still a fraction of a millisecond short of the monotonic deadline. ProviderStartupDeadline then reported interruption "timeout" and an aborted signal while remainingMs() returned ceil(0.x) = 1, so polling loops guarded by remainingMs() > 0 (Hopper and Ghidra startup) could run past an elapsed deadline, and the real-timer test "aborts a bounded wait when its real monotonic deadline expires" failed intermittently in CI (expected 1 to be 0). Once the deadline's own timer has classified a timeout, report zero remaining time. A deterministic regression test fires the timer with the monotonic clock 0.4 ms short of the deadline. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: 吴佳浩 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../ClientConfigurationDocument.ts | 23 +++-- tests/boundary/cli/clientProfiles.test.ts | 85 +++++++++++++++++++ 2 files changed, 102 insertions(+), 6 deletions(-) diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index a226f8cb6..f7ab8f0e2 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -1520,12 +1520,25 @@ export const parseGeminiMcpPolicy = (parsed: ClientConfigurationDocument) => .passthrough() .parse(parsed.document.mcp ?? {}); +/** One server-name comparison for the exclusion, intersection and membership rules below. */ +const normalizeGeminiServerName = (name: string): string => + name.toLowerCase().trim(); + /** Gemini consolidates excludes by union and allowlists by normalized intersection. */ export const geminiServerPolicyBlock = ( policies: readonly ReturnType[], serverKey: string, ): string | undefined => { - if (policies.some(({ excluded }) => excluded?.includes(serverKey))) + // Hand-authored settings cannot be assumed to spell the product key exactly, + // so every rule compares normalized names. Testing the consolidated list + // against the raw key instead would make the outcome depend on which policy + // supplied the spelling that survived the intersection. + const key = normalizeGeminiServerName(serverKey); + if ( + policies.some(({ excluded }) => + excluded?.some((name) => normalizeGeminiServerName(name) === key), + ) + ) return `Gemini mcp.excluded blocks ${serverKey}. Review the selected settings policies before rerunning setup.`; const allowlists = policies.flatMap(({ allowed }) => allowed === undefined ? [] : [allowed], @@ -1533,11 +1546,9 @@ export const geminiServerPolicyBlock = ( const allowed = allowlists.reduce( (previous, current) => { if (previous === undefined) return current; - const normalized = new Set( - current.map((name) => name.toLowerCase().trim()), - ); + const normalized = new Set(current.map(normalizeGeminiServerName)); return previous.filter((name) => - normalized.has(name.toLowerCase().trim()), + normalized.has(normalizeGeminiServerName(name)), ); }, undefined, @@ -1546,7 +1557,7 @@ export const geminiServerPolicyBlock = ( if ( allowed !== undefined && allowed.length > 0 && - !allowed.includes(serverKey) + !allowed.some((name) => normalizeGeminiServerName(name) === key) ) return `Gemini mcp.allowed does not include ${serverKey}. Review the selected settings policies before rerunning setup.`; return undefined; diff --git a/tests/boundary/cli/clientProfiles.test.ts b/tests/boundary/cli/clientProfiles.test.ts index bab6dedd8..092ce65d0 100644 --- a/tests/boundary/cli/clientProfiles.test.ts +++ b/tests/boundary/cli/clientProfiles.test.ts @@ -262,6 +262,91 @@ cliTest( }, ); +cliTest( + "Gemini matches allowlist spellings independently of their policy order", + async ({ cli }) => { + const home = await createTestTempDirectory("rea-gemini-case-"); + const system = join(home, "system.json"); + const defaults = join(home, "defaults.json"); + await writeFile(system, JSON.stringify({ mcp: { allowed: ["REA"] } })); + const environment = { + HOME: home, + USERPROFILE: home, + GEMINI_CLI_SYSTEM_SETTINGS_PATH: system, + GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults, + }; + const run = () => + cli.run({ + arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"], + cwd: home, + environment, + }); + // The intersection compares names case-insensitively, so the spelling that + // survives must not decide the outcome: the same pair of policies in + // either arrangement has to consolidate to the same decision. + for (const [systemSpelling, defaultSpelling] of [ + ["REA", "rea"], + ["rea", "REA"], + ]) { + await writeFile( + system, + JSON.stringify({ mcp: { allowed: [systemSpelling] } }), + ); + await writeFile( + defaults, + JSON.stringify({ mcp: { allowed: [defaultSpelling] } }), + ); + const result = await run(); + expect(result.exitCode, `${systemSpelling}+${defaultSpelling}`).toBe(0); + expect(result.json, `${systemSpelling}+${defaultSpelling}`).toMatchObject( + { + status: "ready", + }, + ); + } + }, +); + +cliTest( + "Gemini compares exclusions and padded allowlist entries through one normalization", + async ({ cli }) => { + const home = await createTestTempDirectory("rea-gemini-normalized-"); + const system = join(home, "system.json"); + const defaults = join(home, "defaults.json"); + const environment = { + HOME: home, + USERPROFILE: home, + GEMINI_CLI_SYSTEM_SETTINGS_PATH: system, + GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults, + }; + const run = () => + cli.run({ + arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"], + cwd: home, + environment, + }); + await writeFile(defaults, JSON.stringify({ mcp: {} })); + // An exclusion is a membership test over the same names the intersection + // compares, so a differently spelled and padded entry blocks setup rather + // than slipping past the raw comparison. + await writeFile(system, JSON.stringify({ mcp: { excluded: [" REA "] } })); + const blocked = await run(); + expect(blocked.exitCode).toBe(1); + expect(blocked.json).toMatchObject({ + status: "needs_human", + plannedActions: [], + appliedActions: [], + remediation: expect.stringContaining("mcp.excluded"), + }); + // Padding is presentation, not identity: a padded allowlist entry permits + // the same server its exact spelling permits. + await writeFile(system, JSON.stringify({ mcp: { allowed: [" REA "] } })); + const allowed = await run(); + expect(allowed.exitCode).toBe(0); + expect(allowed.json).toMatchObject({ status: "ready" }); + }, +); + cliTest( "OpenCode doctor sees a global registration when the custom directory is absent", async ({ cli }) => { From 80592b82a6f854886862978533bb405e3f2e38c5 Mon Sep 17 00:00:00 2001 From: Shivek <152221558+ShivekRanjan@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:20:29 +0530 Subject: [PATCH 12/12] fix(javascript): keep CommonJS percent bytes literal (#3001) Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- .../JavaScriptArtifactPathResolution.ts | 25 +++++-- .../javascriptRequireLiteralPaths.test.ts | 67 ++++++++++++++++++- 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts index f56623f2e..b51eeebda 100644 --- a/src/application/javascript/JavaScriptArtifactPathResolution.ts +++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts @@ -378,6 +378,7 @@ const resolveRuntimeSourceCandidates = ( const rejectDeclaration = ( declared: string, + literalPercent = false, allowEmptyPath = false, ): CandidateResolution | null => { if (declared.length === 0 && !allowEmptyPath) @@ -386,13 +387,23 @@ const rejectDeclaration = ( return unresolvedCandidate("rejected", [ "NUL and backslash path syntax are not admitted for canonical artifact paths.", ]); - if (!admitsCanonicalPathSyntax(declared)) + if (!literalPercent && !admitsCanonicalPathSyntax(declared)) return unresolvedCandidate("rejected", [ "Encoded dot or separator bytes are rejected before artifact path resolution.", ]); return null; }; +/** + * Node's CommonJS loader never percent-decodes a request or a legacy package + * main, so `%2e` and `%2f` there are literal filename bytes, not encoded dots + * or separators. Root confinement still applies to the joined candidate. + */ +const declaresLiteralPercent = (input: ResolveArtifactPathInput): boolean => + input.moduleKind === "require" && + (input.context === "module-specifier" || + input.context === "package-entrypoint"); + const contextualCandidate = ( input: ResolveArtifactPathInput, ): string | CandidateResolution => { @@ -428,7 +439,7 @@ const contextualCandidate = ( "File URL authorities or invalid file URL forms cannot be mapped to artifact-local paths.", ]); } - const rejected = rejectDeclaration(declared); + const rejected = rejectDeclaration(declared, declaresLiteralPercent(input)); if (rejected !== null) return rejected; if (context === "module-specifier") { if (hasScheme(declared)) @@ -831,7 +842,8 @@ const resolveExportTarget = ( const encodedPath = target.url.pathname.slice( PACKAGE_ARTIFACT_ROOT_URL.pathname.length, ); - const rejected = rejectDeclaration(encodedPath); + // Package targets are URLs for both loaders, so their percent bytes encode. + const rejected = rejectDeclaration(encodedPath, false); if (rejected !== null) return withTargetSource(rejected); const decoded = decodeModuleUrlPath(encodedPath); if (typeof decoded !== "string") return withTargetSource(decoded); @@ -912,7 +924,12 @@ const htmlCandidate = ( const declared = stripQueryAndFragment(htmlUrlText(input.declaredPath)); // HTML owns URL-text normalization and pathname admission. A nonempty URL // reference may have no pathname; suffix bytes remain declaration evidence. - const rejected = rejectDeclaration(declared, input.declaredPath !== ""); + // HTML references are URL text, so percent bytes still encode. + const rejected = rejectDeclaration( + declared, + false, + input.declaredPath !== "", + ); if (rejected !== null) return rejected; if (looksExternal(declared)) return unresolvedCandidate("external", [ diff --git a/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts b/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts index 65349b8e4..d5495a7f2 100644 --- a/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts +++ b/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts @@ -1,6 +1,6 @@ -import { writeFile } from "node:fs/promises"; +import { mkdir, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; -import { join, relative, sep } from "node:path"; +import { dirname, join, relative, sep } from "node:path"; import { describe, expect, it } from "vitest"; @@ -133,3 +133,66 @@ describe("literal CommonJS paths in application graphs", () => { }, ); }); + +describe("literal CommonJS percent bytes in application graphs", () => { + it("agrees with Node for requests whose literal names contain %2e or %2F", async () => { + const root = await createTestTempDirectory("rea-literal-percent-require-"); + const files = { + "app/lit%2eb.js": "module.exports = 'lit%2eb.js';", + "app/x%2Fy.js": "module.exports = 'x%2Fy.js';", + "app/sub/%2e%2e/x.js": "module.exports = 'sub/%2e%2e/x.js';", + "app/x.js": "module.exports = 'decoy for a decoded parent';", + "app/pkg/package.json": JSON.stringify({ main: "lit%2eb" }), + "app/pkg/lit%2eb.js": "module.exports = 'pkg/lit%2eb.js';", + "app/node_modules/dep/package.json": JSON.stringify({ name: "dep" }), + "app/node_modules/dep/lit%2eb.js": "module.exports = 'dep/lit%2eb.js';", + "escape.js": "module.exports = 'decoy outside the request directory';", + }; + const specifiers = [ + "./lit%2eb", + "./x%2Fy", + "./sub/%2e%2e/x", + "./pkg", + "dep/lit%2eb", + ]; + // CommonJS reads %2e%2e as a directory name, never as a parent segment. + const literalSegment = "./%2e%2e/escape"; + for (const [path, text] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), text); + } + const main = join(root, "app", "main.cjs"); + await writeFile( + main, + [...specifiers, literalSegment] + .map((specifier) => `require(${JSON.stringify(specifier)});`) + .join("\n"), + ); + const nodeRequire = createRequire(main); + const nodePath = (specifier: string) => + relative(root, nodeRequire.resolve(specifier)).split(sep).join("/"); + expect(() => nodeRequire.resolve(literalSegment)).toThrow( + /Cannot find module/u, + ); + + const { graph } = await analyze(root); + const requests = (specifier: string) => + graph.edges.filter( + (edge) => + edge.relation === "imports" && + edge.properties.specifier === specifier, + ); + for (const specifier of specifiers) { + const edges = requests(specifier); + expect(edges.length, specifier).toBeGreaterThan(0); + for (const edge of edges) + expect(edge.properties.resolved_path, specifier).toBe( + nodePath(specifier), + ); + } + const unresolved = requests(literalSegment); + expect(unresolved.length).toBeGreaterThan(0); + for (const edge of unresolved) + expect(edge.properties.resolved_path).toBeNull(); + }); +});