test(ci): isolate blob-report summary output
The blob-report regression inherited GITHUB_STEP_SUMMARY on hosted CI, so its child wrote diagnostics to the workflow summary while the test expected stdout. Select stdout once in the fixture environment and use it for every child in that case; retain report-content, no-reexecution, timing and failed-history assertions. Integrate upstream main through80592b82, including the native type bindings move to compiled boundary prerequisites. Preserve all11 reviewed experiment/Windows files. The original report case passes with GITHUB_STEP_SUMMARY set;7 unrelated cases are unselected and the parent summary path is untouched. No product behavior or original performance data changes. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
commit
5d58a98a1f
@@ -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 ? "" : `<base href="${base}">`}<script src="${script}"></script>`,
|
||||
]),
|
||||
),
|
||||
"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",
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -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",
|
||||
};
|
||||
|
||||
@@ -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",
|
||||
),
|
||||
@@ -306,7 +308,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 +320,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 +338,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" });
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -106,6 +106,57 @@ const withBrokenHelper = async (app: string): Promise<void> => {
|
||||
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();
|
||||
|
||||
@@ -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)" }),
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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[] = [];
|
||||
|
||||
@@ -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 });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -381,6 +381,7 @@ it("exports portable timing history and removes it on a failed, partial, or inva
|
||||
});
|
||||
|
||||
it("recovers complete module costs from real blob reports without executing tests again", async () => {
|
||||
const reportEnvironment = { ...process.env, GITHUB_STEP_SUMMARY: "" };
|
||||
const root = await createTestTempDirectory("rea-ci-module-timing-");
|
||||
const config = join(root, "vitest.config.mjs");
|
||||
await writeFile(
|
||||
@@ -405,7 +406,7 @@ it("recovers complete module costs from real blob reports without executing test
|
||||
const run = (args: string[]) =>
|
||||
execute(process.execPath, [vitest, ...args, "--config", config], {
|
||||
cwd: root,
|
||||
env: process.env,
|
||||
env: reportEnvironment,
|
||||
timeout: 20_000,
|
||||
});
|
||||
await run(["run", "--reporter=blob"]);
|
||||
@@ -461,7 +462,7 @@ it("recovers complete module costs from real blob reports without executing test
|
||||
const partial = await execute(process.execPath, [fileURLToPath(script)], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
...reportEnvironment,
|
||||
SHARD_RESULT: "skipped",
|
||||
SOURCE_REQUIRED: "true",
|
||||
SOURCE_RESULT: "success",
|
||||
@@ -475,7 +476,11 @@ it("recovers complete module costs from real blob reports without executing test
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await execute(process.execPath, [fileURLToPath(script)], {
|
||||
cwd: root,
|
||||
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
|
||||
env: {
|
||||
...reportEnvironment,
|
||||
SHARD_RESULT: "success",
|
||||
MERGE_RESULT: "success",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseTestDurations(
|
||||
@@ -510,7 +515,11 @@ it("recovers complete module costs from real blob reports without executing test
|
||||
// Even a caller accidentally marking the merge successful cannot publish this report.
|
||||
await execute(process.execPath, [fileURLToPath(script)], {
|
||||
cwd: root,
|
||||
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
|
||||
env: {
|
||||
...reportEnvironment,
|
||||
SHARD_RESULT: "success",
|
||||
MERGE_RESULT: "success",
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
readFile(join(root, ".cache/ci-test-history/test-results.json")),
|
||||
|
||||
+206
@@ -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<void> => {
|
||||
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"), "<title>sibling</title>"),
|
||||
writeFile(join(root, "preload.html"), "<title>sibling</title>"),
|
||||
writeFile(join(root, "worker.js"), "module.exports = {};"),
|
||||
writeFile(join(root, "renderer/index.html"), "<title>renderer</title>"),
|
||||
writeFile(
|
||||
join(root, "renderer/bare.html"),
|
||||
"<title>bare renderer URL</title>",
|
||||
),
|
||||
writeFile(join(root, "renderer/other.html"), "<title>other</title>"),
|
||||
writeFile(join(root, "renderer/missing.html.js"), "module.exports = {};"),
|
||||
writeFile(
|
||||
join(root, "renderer/page/index.html"),
|
||||
"<title>directory</title>",
|
||||
),
|
||||
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<ReturnType<typeof reconstructJavaScriptArtifact>>;
|
||||
type ApplicationGraph = ReturnType<typeof parseJavaScriptApplicationGraph>;
|
||||
|
||||
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,
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
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 createTestTempDirectory("rea-native-types-");
|
||||
const scope = new ArtifactResourceScope();
|
||||
try {
|
||||
await writeFile(join(fixture, "main.ts"), `${source}\n`);
|
||||
await writeFile(join(fixture, "addon.node"), "");
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: fixture, format: "directory" },
|
||||
scope,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value
|
||||
.normalized_result as unknown as JavaScriptApplicationAnalysisResult;
|
||||
} finally {
|
||||
await scope.close();
|
||||
}
|
||||
};
|
||||
|
||||
it("does not request native-addon members from erased TypeScript names", async () => {
|
||||
const typeImport = await analyzeFixture(
|
||||
'import type { NativeThing } from "./addon.node";',
|
||||
);
|
||||
expect(typeImport.summary.native_addon_bindings).toBe(0);
|
||||
expect(typeImport.summary.resolved_native_addon_bindings).toBe(0);
|
||||
expect(
|
||||
typeImport.graph.nodes.filter((node) => node.kind === "native-export"),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
buildJavaScriptNativeHandoffs(
|
||||
typeImport.graph.nodes,
|
||||
typeImport.graph.edges,
|
||||
[],
|
||||
).flatMap((handoff) => handoff.requested_exports),
|
||||
).toEqual([]);
|
||||
|
||||
const typeReexport = await analyzeFixture(
|
||||
'export type { Extra } from "./addon.node";',
|
||||
);
|
||||
expect(typeReexport.summary.native_addon_bindings).toBe(0);
|
||||
expect(
|
||||
typeReexport.graph.nodes.filter((node) => node.kind === "native-export"),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
buildJavaScriptNativeHandoffs(
|
||||
typeReexport.graph.nodes,
|
||||
typeReexport.graph.edges,
|
||||
[],
|
||||
).flatMap((handoff) => handoff.requested_exports),
|
||||
).toEqual([]);
|
||||
|
||||
const mixed = await analyzeFixture(
|
||||
'import { type OtherThing, load } from "./addon.node"; load();',
|
||||
);
|
||||
expect(mixed.summary.native_addon_bindings).toBe(1);
|
||||
const mixedExports = mixed.graph.nodes.filter(
|
||||
(node) => node.kind === "native-export",
|
||||
);
|
||||
expect(mixedExports).toHaveLength(1);
|
||||
expect(
|
||||
mixedExports[0]?.observations[0]?.properties.requested_members,
|
||||
).toEqual(["load"]);
|
||||
expect(
|
||||
buildJavaScriptNativeHandoffs(mixed.graph.nodes, mixed.graph.edges, []).map(
|
||||
(handoff) => handoff.requested_exports,
|
||||
),
|
||||
).toEqual([["load"]]);
|
||||
|
||||
const value = await analyzeFixture(
|
||||
'import { load } from "./addon.node"; load();',
|
||||
);
|
||||
expect(value.summary.native_addon_bindings).toBe(1);
|
||||
expect(
|
||||
value.graph.nodes.filter((node) => node.kind === "native-export")[0]
|
||||
?.observations[0]?.properties.requested_members,
|
||||
).toEqual(["load"]);
|
||||
}, 30_000);
|
||||
@@ -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<typeof inspect>,
|
||||
source: ReturnType<typeof inspect> = inspected,
|
||||
count = 1,
|
||||
): ReturnType<typeof inspect> => {
|
||||
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(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user