chore: sync current main into the CI baseline repair
Validate the formatting and reconstruction fixture repairs against the latest merged feature and correctness changes. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
@@ -1127,6 +1127,68 @@ exit 1`,
|
||||
expect(projected.message).toContain("not installed for 0");
|
||||
});
|
||||
|
||||
// adb exits 1 on a refused package change: `adb install` after printing the
|
||||
// status line to stderr, `cmd package uninstall` after printing it to stdout.
|
||||
it("preserves the device's install refusal when adb exits nonzero", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "install" ]; then
|
||||
printf 'Performing Streamed Install\\n'
|
||||
printf 'adb: failed to install app.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example without first uninstalling.]\\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 1`,
|
||||
);
|
||||
const apk = join(root, "app.apk");
|
||||
await writeFile(apk, "apk");
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "install_adb_package",
|
||||
input: { serial: "emulator-5554", apk_path: apk, replace: false },
|
||||
});
|
||||
expect(projected).toMatchObject({
|
||||
code: "unsupported_target",
|
||||
details: {
|
||||
reason:
|
||||
"INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example without first uninstalling.",
|
||||
},
|
||||
});
|
||||
expect(projected.message).toContain(
|
||||
"INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example without first uninstalling.",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves the device's uninstall refusal when adb exits nonzero", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "uninstall" ]; then printf 'Failure [not installed for 0]\\n'; exit 1; fi
|
||||
exit 1`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "uninstall_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.absent" },
|
||||
});
|
||||
expect(projected).toMatchObject({
|
||||
code: "unsupported_target",
|
||||
details: { reason: "not installed for 0" },
|
||||
});
|
||||
expect(projected.message).toContain("not installed for 0");
|
||||
});
|
||||
|
||||
it("keeps a nonzero install without a device verdict as an unreadable result", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "install" ]; then printf 'adb: failed to install app.apk: closed\\n' >&2; exit 1; fi
|
||||
exit 1`,
|
||||
);
|
||||
const apk = join(root, "app.apk");
|
||||
await writeFile(apk, "apk");
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "install_adb_package",
|
||||
input: { serial: "emulator-5554", apk_path: apk, replace: false },
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unreadable_output" });
|
||||
});
|
||||
|
||||
it("starts an app through resolved launcher component and force-stops it", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
|
||||
+36
-2
@@ -71,6 +71,7 @@ import {
|
||||
parseBugreportCopiedPath,
|
||||
parseDumpsysPackageOutput,
|
||||
parseFeatureListOutput,
|
||||
packageChangeFailureReason,
|
||||
parsePackageChangeOutput,
|
||||
parseProcessListOutput,
|
||||
parsePngDimensions,
|
||||
@@ -248,6 +249,31 @@ const runAdb = async (
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* adb exits nonzero when the device refuses a package change, printing the
|
||||
* `Failure [...]` verdict to stderr (install) or stdout (uninstall). Read the
|
||||
* refusal from that failed run so it is not reported as unreadable output.
|
||||
*/
|
||||
const packageChangeRefusal = (
|
||||
operation: string,
|
||||
serial: string,
|
||||
error: AnalysisError,
|
||||
): Result<never, AnalysisError> | undefined => {
|
||||
if (!(error instanceof AnalysisProtocolError)) return undefined;
|
||||
const failure = execFileOutputFailure(error.cause);
|
||||
if (failure === undefined) return undefined;
|
||||
const reason = packageChangeFailureReason(
|
||||
`${failure.stdout}\n${failure.stderr}`,
|
||||
);
|
||||
return reason === null
|
||||
? undefined
|
||||
: err(
|
||||
new AnalysisUnsupportedTargetError(operation, serial, reason, {
|
||||
cause: error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const clientIdentityResult = (
|
||||
selection: AdbBinarySelection,
|
||||
identity: AdbClientIdentity,
|
||||
@@ -1754,7 +1780,11 @@ export class AdbProvider {
|
||||
{ timeoutMs: PULL_TIMEOUT_MS, maxOutputBytes: PULL_MAX_OUTPUT_BYTES },
|
||||
signal,
|
||||
);
|
||||
if (!installed.ok) return installed;
|
||||
if (!installed.ok)
|
||||
return (
|
||||
packageChangeRefusal(operation, input.serial, installed.error) ??
|
||||
installed
|
||||
);
|
||||
const verdict = parsePackageChangeOutput(installed.value.stdout);
|
||||
if (verdict.status === "failure")
|
||||
return err(
|
||||
@@ -1803,7 +1833,11 @@ export class AdbProvider {
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (!uninstalled.ok) return uninstalled;
|
||||
if (!uninstalled.ok)
|
||||
return (
|
||||
packageChangeRefusal(operation, input.serial, uninstalled.error) ??
|
||||
uninstalled
|
||||
);
|
||||
const verdict = parsePackageChangeOutput(uninstalled.value.stdout);
|
||||
if (verdict.status === "failure")
|
||||
return err(
|
||||
|
||||
@@ -293,6 +293,10 @@ export const parseBugreportCopiedPath = (stdout: string): string | null => {
|
||||
return match === null ? null : match[1]!;
|
||||
};
|
||||
|
||||
/** Read the device's `Failure [REASON]` verdict from package-change output. */
|
||||
export const packageChangeFailureReason = (output: string): string | null =>
|
||||
/Failure \[([^\]]+)\]/u.exec(output)?.[1] ?? null;
|
||||
|
||||
/**
|
||||
* Parse `adb install`/`adb uninstall` output. adb can print `Failure [...]`
|
||||
* with a zero exit code, so the text decides, not the exit status.
|
||||
@@ -305,10 +309,11 @@ export const parsePackageChangeOutput = (
|
||||
} => {
|
||||
const text = stdout.trim();
|
||||
if (/^Success$/mu.test(text)) return { status: "success", reason: null };
|
||||
const failure = /Failure \[([^\]]+)\]/u.exec(text);
|
||||
return {
|
||||
status: "failure",
|
||||
reason: failure?.[1] ?? (text === "" ? null : text.slice(0, 512)),
|
||||
reason:
|
||||
packageChangeFailureReason(text) ??
|
||||
(text === "" ? null : text.slice(0, 512)),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -162,6 +162,12 @@ export const parseBinaryTarget = async (
|
||||
availableArchitectures: ["x86"],
|
||||
});
|
||||
}
|
||||
// Probe WASM content before suffix-only database routing; an explicit
|
||||
// database selection keeps the caller's chosen interpretation.
|
||||
const artifactFormat =
|
||||
targetKind === "database"
|
||||
? undefined
|
||||
: await detectArtifactFormat(path, handle, signal);
|
||||
if (
|
||||
targetKind === "database" ||
|
||||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
|
||||
@@ -173,7 +179,6 @@ export const parseBinaryTarget = async (
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
const artifactFormat = await detectArtifactFormat(path, handle, signal);
|
||||
if (artifactFormat !== undefined) {
|
||||
const identity = {
|
||||
path,
|
||||
|
||||
@@ -30,6 +30,29 @@ it("labels an envelope containing debugger-derived maps as derived", async () =>
|
||||
expect(evidence.raw_result).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["x86_64-little-endian", "x86_64"],
|
||||
["aarch64-little-endian", "arm64"],
|
||||
] as const)(
|
||||
"names the CPU family carried by a %s core on created Evidence",
|
||||
async (architecture, expected) => {
|
||||
const fixture = recordedCrashFixture("/selected.core", architecture);
|
||||
const service = new RecordedCrashService({
|
||||
inspectAndClose(input, options) {
|
||||
return this.inspect(input, options);
|
||||
},
|
||||
identity: RECORDED_CRASH_TEST_PROVIDER,
|
||||
inspect: () => Promise.resolve(ok(fixture)),
|
||||
});
|
||||
const result = await service.inspect({
|
||||
path: fixture.artifact.path,
|
||||
include_debugger_context: false,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(parseEvidence(result.value).subject?.architecture).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ path: "relative.elf" },
|
||||
{ path: "/selected.core", approval: true },
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
inspectRecordedCrashInputSchema,
|
||||
RECORDED_LINUX_CORE_PROFILES,
|
||||
recordedCrashSchema,
|
||||
} from "../../domain/native/recordedCrash.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
@@ -101,7 +102,9 @@ export class RecordedCrashService {
|
||||
{
|
||||
path: value.artifact.path,
|
||||
format: "elf",
|
||||
architecture: "x86_64",
|
||||
architecture:
|
||||
RECORDED_LINUX_CORE_PROFILES[value.architecture]
|
||||
.evidenceArchitecture,
|
||||
sha256: value.artifact.sha256,
|
||||
},
|
||||
this.provider.identity,
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import { wasmInterfaceComparisonSchema } from "../../contracts/wasm/wasmComparisonContracts.js";
|
||||
import { compareWasmInterfaces } from "./WasmInterfaceComparisonService.js";
|
||||
import type { WasmInterface } from "../../domain/wasm/wasmInterface.js";
|
||||
import { wasmArtifactFixture } from "../../../tests/fixtures/wasm/artifact.js";
|
||||
|
||||
const facts = (
|
||||
name: string,
|
||||
parameter: "i32" | "i64" = "i32",
|
||||
): WasmInterface => ({
|
||||
state: "complete",
|
||||
issues: [],
|
||||
entries: [
|
||||
{
|
||||
direction: "export",
|
||||
module: null,
|
||||
name,
|
||||
kind: "func",
|
||||
index: 0,
|
||||
signature: { kind: "func", params: [parameter], results: [] },
|
||||
wat_form: `(export "${name}" (func 0))`,
|
||||
issue: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
const evidence = (interfaceFacts?: WasmInterface) => {
|
||||
const report = wasmArtifactFixture();
|
||||
if (interfaceFacts !== undefined) report.interface = interfaceFacts;
|
||||
return createEvidence(
|
||||
{
|
||||
path: report.artifact.path,
|
||||
sha256: report.artifact.sha256,
|
||||
format: "file",
|
||||
},
|
||||
{ id: "fixture", name: "typed fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_wasm_artifact",
|
||||
parameters: { path: report.artifact.path },
|
||||
result: report,
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
};
|
||||
const compare = async (
|
||||
left: ReturnType<typeof evidence>,
|
||||
right: ReturnType<typeof evidence>,
|
||||
) => {
|
||||
const result = await compareWasmInterfaces({ left, right, scope: "both" });
|
||||
if (!result.ok) throw result.error;
|
||||
return wasmInterfaceComparisonSchema.parse(result.value.normalized_result);
|
||||
};
|
||||
|
||||
it("reports all five comparison states, including duplicate ambiguity and explicit selected scope", async () => {
|
||||
const left = facts("changed");
|
||||
const right = facts("changed", "i64");
|
||||
left.entries.push(
|
||||
...facts("unchanged").entries,
|
||||
...facts("removed").entries,
|
||||
...facts("dup").entries,
|
||||
...facts("dup").entries,
|
||||
);
|
||||
right.entries.push(
|
||||
...facts("unchanged").entries,
|
||||
...facts("added").entries,
|
||||
...facts("dup").entries,
|
||||
);
|
||||
const report = await compare(evidence(left), evidence(right));
|
||||
expect(report.summary).toEqual({
|
||||
changed: 1,
|
||||
unchanged: 1,
|
||||
removed: 1,
|
||||
added: 1,
|
||||
unknown: 1,
|
||||
});
|
||||
expect(report.changes.find((c) => c.name === "dup")).toMatchObject({
|
||||
state: "unknown",
|
||||
left: [expect.anything(), expect.anything()],
|
||||
right: [expect.anything()],
|
||||
});
|
||||
const selected = await compareWasmInterfaces({
|
||||
left: evidence(left),
|
||||
right: evidence(right),
|
||||
scope: "imports",
|
||||
});
|
||||
if (!selected.ok) throw selected.error;
|
||||
expect(selected.value.normalized_result).toMatchObject({
|
||||
changes: [],
|
||||
coverage: "complete-within-inputs",
|
||||
});
|
||||
});
|
||||
|
||||
it("withholds absence claims for historical or partial inventories and unsupported signatures", async () => {
|
||||
const known = facts("f");
|
||||
const absent = await compare(evidence(), evidence(known));
|
||||
expect(absent).toMatchObject({
|
||||
coverage: "partial",
|
||||
changes: [{ state: "unknown" }],
|
||||
});
|
||||
const partial: WasmInterface = {
|
||||
state: "partial",
|
||||
issues: ["unread import table"],
|
||||
entries: [],
|
||||
};
|
||||
expect(await compare(evidence(partial), evidence(known))).toMatchObject({
|
||||
changes: [{ state: "unknown" }],
|
||||
});
|
||||
const unsupported = facts("f");
|
||||
unsupported.entries[0]!.signature = null;
|
||||
expect(await compare(evidence(known), evidence(unsupported))).toMatchObject({
|
||||
changes: [{ state: "unknown" }],
|
||||
});
|
||||
const partialMatch = facts("f");
|
||||
partialMatch.state = "partial";
|
||||
partialMatch.issues = ["Later imports were not examined"];
|
||||
expect(await compare(evidence(partialMatch), evidence(known))).toMatchObject({
|
||||
changes: [{ state: "unknown" }],
|
||||
});
|
||||
expect(await compare(evidence(), evidence())).toMatchObject({
|
||||
coverage: "unknown",
|
||||
changes: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("authenticates semantic Evidence and binds display subject and selection identity", async () => {
|
||||
const left = JSON.parse(JSON.stringify(evidence(facts("f"))));
|
||||
left.normalized_result.interface.entries[0].name = "tampered";
|
||||
expect(
|
||||
await compareWasmInterfaces({
|
||||
left,
|
||||
right: evidence(facts("f")),
|
||||
scope: "both",
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
const rebound = JSON.parse(JSON.stringify(evidence(facts("f"))));
|
||||
rebound.subject.local_path = "/other.wasm";
|
||||
expect(
|
||||
await compareWasmInterfaces({
|
||||
left: rebound,
|
||||
right: evidence(facts("f")),
|
||||
scope: "both",
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
});
|
||||
|
||||
it("resolves exact retained references and permits cancellation between comparison batches", async () => {
|
||||
const left = evidence(facts("f"));
|
||||
const right = evidence(facts("f", "i64"));
|
||||
const references = {
|
||||
left: { kind: "retained-evidence", evidence_id: left.evidence_id },
|
||||
right: { kind: "retained-evidence", evidence_id: right.evidence_id },
|
||||
scope: "both",
|
||||
};
|
||||
expect(await compareWasmInterfaces(references)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
const result = await compareWasmInterfaces(references, {}, (id) =>
|
||||
id === left.evidence_id ? left : right,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.evidence_links).toEqual([
|
||||
left.evidence_id,
|
||||
right.evidence_id,
|
||||
]);
|
||||
const large = facts("f");
|
||||
large.entries.push(
|
||||
...Array.from({ length: 2000 }, (_, i) => facts(`f${i}`).entries[0]!),
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const pending = compareWasmInterfaces(
|
||||
{ left: evidence(large), right: evidence(large), scope: "both" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
setImmediate(() => controller.abort());
|
||||
expect(await pending).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"keeps a one-sided unsupported interface unknown with reverse=%s",
|
||||
async (reverse) => {
|
||||
const empty: WasmInterface = { state: "complete", issues: [], entries: [] };
|
||||
const unsupported = facts("exception");
|
||||
unsupported.entries[0]!.signature = null;
|
||||
unsupported.entries[0]!.issue = "Unsupported exnref global type";
|
||||
const sides = reverse ? [unsupported, empty] : [empty, unsupported];
|
||||
expect(await compare(evidence(sides[0]), evidence(sides[1]))).toMatchObject(
|
||||
{
|
||||
coverage: "partial",
|
||||
summary: { added: 0, removed: 0, unknown: 1 },
|
||||
changes: [{ state: "unknown" }],
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,250 @@
|
||||
import {
|
||||
WASM_INTERFACE_REPRESENTATION_BYTES,
|
||||
wasmInterfaceEntryRepresentationBytes,
|
||||
} from "../../domain/wasm/wasmInterface.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import {
|
||||
compareWasmInterfacesInputSchema,
|
||||
wasmInterfaceComparisonSchema,
|
||||
} from "../../contracts/wasm/wasmComparisonContracts.js";
|
||||
import {
|
||||
createEvidence,
|
||||
parseEvidence,
|
||||
type Evidence,
|
||||
} from "../../domain/evidence.js";
|
||||
import {
|
||||
wasmArtifactSchema,
|
||||
type WasmArtifact,
|
||||
} from "../../domain/wasm/wasmArtifact.js";
|
||||
import type { WasmInterfaceEntry } from "../../domain/wasm/wasmInterface.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { ARTIFACT_COMPARISON_PROVIDER } from "../InvestigationProviders.js";
|
||||
import {
|
||||
resolvePairedEvidenceRequest,
|
||||
type EvidenceLookup,
|
||||
} from "../EvidenceInputResolver.js";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { z } from "zod";
|
||||
|
||||
const OPERATION = "compare_wasm_interfaces";
|
||||
const parseInspection = (
|
||||
raw: unknown,
|
||||
): { evidence: Evidence; result: WasmArtifact } => {
|
||||
const evidence = parseEvidence(raw);
|
||||
if (evidence.operation !== "inspect_wasm_artifact")
|
||||
throw new TypeError("Expected complete inspect_wasm_artifact Evidence");
|
||||
const result = wasmArtifactSchema.parse(evidence.normalized_result);
|
||||
if (
|
||||
evidence.subject?.digest.sha256 !== result.artifact.sha256 ||
|
||||
evidence.subject.local_path !== result.artifact.path ||
|
||||
evidence.parameters.path !== result.artifact.path
|
||||
)
|
||||
throw new TypeError(
|
||||
"WASM Evidence subject/selection does not match normalized artifact identity",
|
||||
);
|
||||
return { evidence, result };
|
||||
};
|
||||
|
||||
/** Compare only producer-owned typed facts; no raw WAT or original file is reread. */
|
||||
export const compareWasmInterfaces = async (
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
lookup?: EvidenceLookup,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const parsed = compareWasmInterfacesInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput),
|
||||
);
|
||||
const resolved = resolvePairedEvidenceRequest(parsed.data, lookup);
|
||||
if (!resolved.ok) return resolved;
|
||||
try {
|
||||
await setImmediate();
|
||||
options?.signal?.throwIfAborted();
|
||||
const left = parseInspection(resolved.value.left);
|
||||
const right = parseInspection(resolved.value.right);
|
||||
const scope = parsed.data.scope;
|
||||
const selected = (entry: WasmInterfaceEntry): boolean =>
|
||||
scope === "both" ||
|
||||
entry.direction === (scope === "imports" ? "import" : "export");
|
||||
const groups = new Map<
|
||||
string,
|
||||
{
|
||||
left: WasmInterfaceEntry[];
|
||||
right: WasmInterfaceEntry[];
|
||||
entry: WasmInterfaceEntry;
|
||||
}
|
||||
>();
|
||||
let work = 0;
|
||||
for (const [side, inspection] of [
|
||||
["left", left],
|
||||
["right", right],
|
||||
] as const) {
|
||||
for (const entry of inspection.result.interface?.entries ?? []) {
|
||||
if (++work % 256 === 0) {
|
||||
await setImmediate();
|
||||
options?.signal?.throwIfAborted();
|
||||
}
|
||||
if (!selected(entry)) continue;
|
||||
const key = JSON.stringify([entry.direction, entry.module, entry.name]);
|
||||
let group = groups.get(key);
|
||||
if (group === undefined) {
|
||||
group = { left: [], right: [], entry };
|
||||
groups.set(key, group);
|
||||
}
|
||||
group[side].push(entry);
|
||||
}
|
||||
}
|
||||
const knownInventory = (inspection: typeof left): boolean =>
|
||||
inspection.result.interface?.state === "complete";
|
||||
const changes: z.infer<typeof wasmInterfaceComparisonSchema>["changes"] =
|
||||
[];
|
||||
const summary = {
|
||||
added: 0,
|
||||
removed: 0,
|
||||
changed: 0,
|
||||
unchanged: 0,
|
||||
unknown: 0,
|
||||
};
|
||||
let remaining = WASM_INTERFACE_REPRESENTATION_BYTES;
|
||||
for (const group of groups.values()) {
|
||||
remaining -=
|
||||
512 +
|
||||
group.left.reduce(
|
||||
(sum, entry) => sum + wasmInterfaceEntryRepresentationBytes(entry),
|
||||
0,
|
||||
) +
|
||||
group.right.reduce(
|
||||
(sum, entry) => sum + wasmInterfaceEntryRepresentationBytes(entry),
|
||||
0,
|
||||
);
|
||||
if (remaining < 0)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"capacity",
|
||||
"WASM comparison exceeds typed interface representation capacity",
|
||||
{ maximum_bytes: WASM_INTERFACE_REPRESENTATION_BYTES },
|
||||
);
|
||||
if (++work % 256 === 0) {
|
||||
await setImmediate();
|
||||
options?.signal?.throwIfAborted();
|
||||
}
|
||||
let state: keyof typeof summary;
|
||||
let reason: string | null = null;
|
||||
const l = group.left[0];
|
||||
const r = group.right[0];
|
||||
if (group.left.length > 1 || group.right.length > 1) {
|
||||
state = "unknown";
|
||||
reason =
|
||||
"Duplicate interface names are ambiguous; all occurrences retained";
|
||||
} else if (!knownInventory(left) || !knownInventory(right)) {
|
||||
state = "unknown";
|
||||
reason =
|
||||
"Incomplete interface inventories cannot establish per-key uniqueness or absence";
|
||||
} else if (
|
||||
[l, r].some(
|
||||
(entry) =>
|
||||
entry !== undefined &&
|
||||
(entry.signature === null ||
|
||||
entry.issue !== null ||
|
||||
entry.kind === "unknown"),
|
||||
)
|
||||
) {
|
||||
state = "unknown";
|
||||
reason =
|
||||
"Signature/type semantics were not admitted for every present entry";
|
||||
} else if (l === undefined) state = "added";
|
||||
else if (r === undefined) state = "removed";
|
||||
else if (l.kind !== r.kind) state = "changed";
|
||||
else
|
||||
state =
|
||||
JSON.stringify(l.signature) === JSON.stringify(r.signature)
|
||||
? "unchanged"
|
||||
: "changed";
|
||||
summary[state]++;
|
||||
changes.push({
|
||||
direction: group.entry.direction,
|
||||
module: group.entry.module,
|
||||
name: group.entry.name,
|
||||
state,
|
||||
left: group.left,
|
||||
right: group.right,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
const compareText = (a: string, b: string): number =>
|
||||
a < b ? -1 : a > b ? 1 : 0;
|
||||
changes.sort(
|
||||
(a, b) =>
|
||||
compareText(a.direction, b.direction) ||
|
||||
compareText(a.module ?? "", b.module ?? "") ||
|
||||
compareText(a.name, b.name),
|
||||
);
|
||||
const coverage =
|
||||
left.result.interface === undefined &&
|
||||
right.result.interface === undefined
|
||||
? "unknown"
|
||||
: !knownInventory(left) || !knownInventory(right) || summary.unknown > 0
|
||||
? "partial"
|
||||
: "complete-within-inputs";
|
||||
const limitations = [
|
||||
"Exact declared interface equality is not runtime/ABI compatibility, successful linking or original-source identity.",
|
||||
"Typed facts come from the selected validated WABT decoding; unsupported signature semantics and duplicate names remain unknown.",
|
||||
];
|
||||
const report = wasmInterfaceComparisonSchema.parse({
|
||||
left: {
|
||||
evidence_id: left.evidence.evidence_id,
|
||||
artifact: left.result.artifact,
|
||||
},
|
||||
right: {
|
||||
evidence_id: right.evidence.evidence_id,
|
||||
artifact: right.result.artifact,
|
||||
},
|
||||
scope,
|
||||
coverage,
|
||||
changes,
|
||||
summary,
|
||||
limitations,
|
||||
});
|
||||
await setImmediate();
|
||||
options?.signal?.throwIfAborted();
|
||||
return ok(
|
||||
createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
|
||||
operation: OPERATION,
|
||||
predicateType: "rea.wasm-interface-comparison",
|
||||
parameters: {
|
||||
left_evidence_id: left.evidence.evidence_id,
|
||||
right_evidence_id: right.evidence.evidence_id,
|
||||
scope,
|
||||
},
|
||||
result: report,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations,
|
||||
evidenceLinks: [left.evidence.evidence_id, right.evidence.evidence_id],
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
if (cause instanceof AnalysisError) return err(cause);
|
||||
return err(
|
||||
new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,3 +1,6 @@
|
||||
import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js";
|
||||
import { parseCliJsonInput } from "../cliJsonInput.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
@@ -13,6 +16,29 @@ export const registerWasmCommands = (
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.compareWasmInterfaces, {
|
||||
description:
|
||||
"Compare core WASM interfaces from two exact inspection Evidence records",
|
||||
args: z.object({
|
||||
input: z
|
||||
.string()
|
||||
.describe(
|
||||
"Inline JSON or input file containing left/right complete Evidence and required scope",
|
||||
),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
withCommandCancellation(async (signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.compareWasmInterfaces, async () => {
|
||||
const input = await parseCliJsonInput(
|
||||
args.input,
|
||||
"compare_wasm_interfaces",
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const result = await compareWasmInterfaces(input.value, { signal });
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
const service = wasmArtifactModule.create(environment);
|
||||
cli.command(wasmArtifactModule.cliCommand, {
|
||||
description: "Inspect an explicit local WASM artifact with WABT",
|
||||
|
||||
@@ -4,6 +4,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
inspectPacketCapture: "inspect-packet-capture",
|
||||
inspectSignalDecoders: "inspect-signal-decoders",
|
||||
decodeSignalRecording: "decode-signal-recording",
|
||||
compareWasmInterfaces: "compare-wasm-interfaces",
|
||||
inspectWasmArtifact: "inspect-wasm-artifact",
|
||||
inspectSqliteDatabase: "inspect-sqlite-database",
|
||||
inspectEvmInterface: "inspect-evm-interface",
|
||||
|
||||
@@ -30,6 +30,7 @@ const resolveReference = (
|
||||
root: Readonly<Record<string, unknown>>,
|
||||
reference: string,
|
||||
): unknown => {
|
||||
if (reference === "#") return root;
|
||||
if (!reference.startsWith("#/")) return undefined;
|
||||
let value: unknown = root;
|
||||
for (const token of reference.slice(2).split("/")) {
|
||||
@@ -229,3 +230,76 @@ export const presentInputJsonSchema = (
|
||||
const described = describeSchema(flattened, flattened, describeProperty);
|
||||
return isObject(described) ? described : flattened;
|
||||
};
|
||||
|
||||
/**
|
||||
* Clients that render advertised inputs into SDK declarations expand
|
||||
* schema-local references with a shared per-input budget: Pi 1.1.0 code-mode
|
||||
* allows 32 expansions and degrades every later reference to `unknown`
|
||||
* (morluto/rea#1632), hiding the fields those references describe. The budget
|
||||
* counts conservatively — every resolvable, non-cyclic reference occurrence
|
||||
* in every schema position — so any reference-resolving client stays within
|
||||
* its measured limit.
|
||||
*/
|
||||
export const advertisedReferenceExpansionBudget = 32;
|
||||
|
||||
const definitionKeys = new Set(["$defs", "definitions"]);
|
||||
|
||||
const countReferenceExpansions = (
|
||||
node: unknown,
|
||||
root: Readonly<Record<string, unknown>>,
|
||||
active: ReadonlySet<string>,
|
||||
count: { value: number },
|
||||
): void => {
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach((child) =>
|
||||
countReferenceExpansions(child, root, active, count),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!isObject(node)) return;
|
||||
if (typeof node.$ref === "string" && !active.has(node.$ref)) {
|
||||
const target = resolveReference(root, node.$ref);
|
||||
if (target !== undefined) {
|
||||
count.value += 1;
|
||||
countReferenceExpansions(
|
||||
target,
|
||||
root,
|
||||
new Set([...active, node.$ref]),
|
||||
count,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (definitionKeys.has(key)) continue;
|
||||
if (schemaMaps.has(key) && isObject(value)) {
|
||||
for (const child of Object.values(value))
|
||||
countReferenceExpansions(child, root, active, count);
|
||||
} else if (schemaArrays.has(key) || schemaChildren.has(key)) {
|
||||
countReferenceExpansions(value, root, active, count);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Conservative client expansion count over every schema position. */
|
||||
export const countLocalReferenceExpansions = (
|
||||
schema: Record<string, unknown>,
|
||||
): number => {
|
||||
const count = { value: 0 };
|
||||
countReferenceExpansions(schema, schema, new Set(), count);
|
||||
return count.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep the shared-definition form of an advertised input while clients can
|
||||
* still resolve it. Once rendering would exhaust the reference budget, fall
|
||||
* back to the inline projection, which carries no shared definitions for the
|
||||
* nonrecursive schemas this repository advertises, so every field renders
|
||||
* with complete structure in every reference-resolving client.
|
||||
*/
|
||||
export const inputSchemaWithinReferenceExpansionBudget = (
|
||||
shared: Record<string, unknown>,
|
||||
inline: () => Record<string, unknown>,
|
||||
budget: number,
|
||||
): Record<string, unknown> =>
|
||||
countLocalReferenceExpansions(shared) <= budget ? shared : inline();
|
||||
|
||||
@@ -67,7 +67,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
|
||||
...toolContractMetadata("inspect_recorded_crash"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Inspect a supplied Linux ELF64 amd64 little-endian core without launching its target or attaching to any live PID. Returns all recorded segments, raw note owners/descriptors and source ranges, every Linux CORE PRSTATUS thread/register and SIGINFO fields inline with SHA-256 Evidence. Historical PID is recorded metadata; current process/file identity, note coverage and signal-thread associations stay unknown. Optionally add derived core-only GDB/pwndbg mapping candidates through explicit BYO configuration; zero map flags mean unknown permissions. Uses the same stable snapshot for both stages, bounded complete output and owned cleanup. Initial Linux x64 profile: unchanged pwntools 4.15.0/pyelftools 0.33/Unicorn 2.1.2; optional unchanged pwndbg 2026.09.15. No implicit executable/library pairing, GDB command language, host configuration changes or dependency installation.",
|
||||
"Inspect a supplied Linux ELF64 amd64 or AArch64 little-endian core without launching its target or attaching to any live PID. Returns all recorded segments, raw note owners/descriptors and source ranges, every Linux CORE PRSTATUS thread/register and SIGINFO fields inline with SHA-256 Evidence. Historical PID is recorded metadata; current process/file identity, note coverage and signal-thread associations stay unknown. Optionally add derived core-only GDB/pwndbg mapping candidates through explicit BYO configuration; zero map flags mean unknown permissions. Uses the same stable snapshot for both stages, bounded complete output and owned cleanup. Linux x64 host profile: unchanged pwntools 4.15.0/pyelftools 0.33/Unicorn 2.1.2; optional unchanged pwndbg 2026.09.15. No implicit executable/library pairing, GDB command language, host configuration changes or dependency installation.",
|
||||
inputSchema: inspectRecordedCrashInputSchema,
|
||||
outputSchema: evidenceResultOf(recordedCrashSchema),
|
||||
examples: [
|
||||
|
||||
@@ -27,6 +27,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
|
||||
inspect_macho: "runs host Mach-O inspection tools, not the target",
|
||||
inspect_evm_interface:
|
||||
"decodes bytecode in REA's bundled worker without executing it",
|
||||
compare_wasm_interfaces:
|
||||
"compares retained inspection Evidence without executing modules",
|
||||
inspect_wasm_artifact:
|
||||
"WABT validates and decompiles the module without executing it",
|
||||
identify_flutter_build:
|
||||
|
||||
@@ -623,6 +623,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
}),
|
||||
compare_process_captures: sessionEvidence,
|
||||
compare_artifacts: sessionEvidence,
|
||||
compare_wasm_interfaces: sessionEvidence,
|
||||
compare_functions: sessionEvidence,
|
||||
compare_bundles: effects({ mutatesSession: true }),
|
||||
find_changed_behavior: sessionEvidence,
|
||||
|
||||
@@ -3,7 +3,12 @@ import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
|
||||
import {
|
||||
advertisedReferenceExpansionBudget,
|
||||
countLocalReferenceExpansions,
|
||||
inputSchemaWithinReferenceExpansionBudget,
|
||||
presentInputJsonSchema,
|
||||
} from "./inputSchemaPresentation.js";
|
||||
import { toolContract } from "./toolContracts.js";
|
||||
import { toolInputSchemaWithMetadata } from "./toolSchemaMetadata.js";
|
||||
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "./javascript/javascriptRuntimeReconciliationExample.js";
|
||||
@@ -166,6 +171,105 @@ describe("advertised input references", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("advertised reference expansion budget", () => {
|
||||
it("counts references in keyword-named fields, excluding literals", () => {
|
||||
const fields = ["default", "enum", "examples", "const", "$defs"];
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: Object.fromEntries(
|
||||
fields.map((name) => [name, { $ref: "#/$defs/value" }]),
|
||||
),
|
||||
$defs: { value: { type: "string" } },
|
||||
default: { $ref: "#/$defs/value" },
|
||||
examples: [{ $ref: "#/$defs/value" }],
|
||||
};
|
||||
expect(countLocalReferenceExpansions(schema)).toBe(fields.length);
|
||||
});
|
||||
const reusedComponent = z
|
||||
.object({ kind: z.literal("rec"), value: z.string() })
|
||||
.strict();
|
||||
const inputWithReusedFields = (count: number) =>
|
||||
z.strictObject(
|
||||
Object.fromEntries(
|
||||
Array.from({ length: count }, (_, index) => [
|
||||
`field_${String(index).padStart(2, "0")}`,
|
||||
reusedComponent,
|
||||
]),
|
||||
),
|
||||
);
|
||||
const advertisedInput = (
|
||||
canonical: z.ZodType<Readonly<Record<string, unknown>>>,
|
||||
) =>
|
||||
toolInputSchemaWithMetadata({
|
||||
...toolContract("open_binary"),
|
||||
inputSchema: canonical,
|
||||
})["~standard"].jsonSchema.input({ target: "draft-2020-12" });
|
||||
|
||||
it("keeps shared definitions while every client can resolve them", () => {
|
||||
const advertised = advertisedInput(inputWithReusedFields(8));
|
||||
expect(advertised.$defs).toBeDefined();
|
||||
expect(countLocalReferenceExpansions(advertised)).toBe(8);
|
||||
});
|
||||
|
||||
it("keeps shared definitions exactly at the budget", () => {
|
||||
const advertised = advertisedInput(
|
||||
inputWithReusedFields(advertisedReferenceExpansionBudget),
|
||||
);
|
||||
expect(advertised.$defs).toBeDefined();
|
||||
expect(countLocalReferenceExpansions(advertised)).toBe(
|
||||
advertisedReferenceExpansionBudget,
|
||||
);
|
||||
});
|
||||
|
||||
it("re-projects without shared definitions once the budget is exceeded", () => {
|
||||
const advertised = advertisedInput(
|
||||
inputWithReusedFields(advertisedReferenceExpansionBudget + 1),
|
||||
);
|
||||
expect(advertised.$defs).toBeUndefined();
|
||||
expect(countLocalReferenceExpansions(advertised)).toBe(0);
|
||||
const properties = advertised.properties as Record<string, unknown>;
|
||||
expect(properties.field_00).toMatchObject({
|
||||
type: "object",
|
||||
properties: { kind: { const: "rec" }, value: { type: "string" } },
|
||||
required: ["kind", "value"],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the shared form untouched when it fits and swaps it when not", () => {
|
||||
const shared = {
|
||||
type: "object",
|
||||
properties: { value: { $ref: "#/$defs/shared" } },
|
||||
$defs: { shared: { type: "string" } },
|
||||
};
|
||||
const inlined = {
|
||||
type: "object",
|
||||
properties: { value: { type: "string" } },
|
||||
};
|
||||
expect(
|
||||
inputSchemaWithinReferenceExpansionBudget(
|
||||
shared,
|
||||
() => inlined,
|
||||
advertisedReferenceExpansionBudget,
|
||||
),
|
||||
).toBe(shared);
|
||||
expect(
|
||||
inputSchemaWithinReferenceExpansionBudget(
|
||||
{
|
||||
...shared,
|
||||
properties: Object.fromEntries(
|
||||
Array.from({ length: 33 }, (_, index) => [
|
||||
`field_${index}`,
|
||||
{ $ref: "#/$defs/shared" },
|
||||
]),
|
||||
),
|
||||
},
|
||||
() => inlined,
|
||||
advertisedReferenceExpansionBudget,
|
||||
),
|
||||
).toBe(inlined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("root input presentation", () => {
|
||||
it("preserves prototype-named properties in object-root presentation", () => {
|
||||
const fields = Object.fromEntries([
|
||||
|
||||
@@ -2,7 +2,11 @@ import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
import { advertisedInputExamples } from "./advertisedInputExamples.js";
|
||||
import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
|
||||
import {
|
||||
advertisedReferenceExpansionBudget,
|
||||
inputSchemaWithinReferenceExpansionBudget,
|
||||
presentInputJsonSchema,
|
||||
} from "./inputSchemaPresentation.js";
|
||||
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
|
||||
|
||||
const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
|
||||
@@ -66,7 +70,25 @@ export const toolInputSchemaWithMetadata = <Contract extends ToolContract>(
|
||||
});
|
||||
const examples = advertisedInputExamples(contract);
|
||||
return {
|
||||
...presentInputJsonSchema(shared, fallbackPropertyDescription),
|
||||
// Sharing definitions only helps clients that resolve them. A client
|
||||
// rendering declarations from a shared expansion budget degrades
|
||||
// every reference past it to `unknown`, so an input whose shared form
|
||||
// exceeds the budget is re-projected without shared definitions.
|
||||
...inputSchemaWithinReferenceExpansionBudget(
|
||||
presentInputJsonSchema(shared, fallbackPropertyDescription),
|
||||
() =>
|
||||
presentInputJsonSchema(
|
||||
project({
|
||||
...options,
|
||||
libraryOptions: {
|
||||
...options.libraryOptions,
|
||||
reused: "inline",
|
||||
},
|
||||
}),
|
||||
fallbackPropertyDescription,
|
||||
),
|
||||
advertisedReferenceExpansionBudget,
|
||||
),
|
||||
...(examples.length === 0 ? {} : { examples }),
|
||||
};
|
||||
},
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
import { z } from "zod";
|
||||
import { evidenceInputSchema } from "../evidenceInputContracts.js";
|
||||
import { wasmInterfaceSchema } from "../../domain/wasm/wasmInterface.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
|
||||
export const compareWasmInterfacesInputSchema = z.strictObject({
|
||||
left: evidenceInputSchema.describe(
|
||||
"Exact complete inspect_wasm_artifact Evidence or retained session reference",
|
||||
),
|
||||
right: evidenceInputSchema.describe(
|
||||
"Exact complete inspect_wasm_artifact Evidence or retained session reference",
|
||||
),
|
||||
scope: z
|
||||
.enum(["imports", "exports", "both"])
|
||||
.describe(
|
||||
"Explicit interface selection; static equality does not establish runtime compatibility",
|
||||
),
|
||||
});
|
||||
const identity = z.object({
|
||||
evidence_id: z.string(),
|
||||
artifact: z.object({
|
||||
path: z.string(),
|
||||
sha256: z.string(),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
}),
|
||||
});
|
||||
export const wasmInterfaceComparisonSchema = z.object({
|
||||
left: identity,
|
||||
right: identity,
|
||||
scope: z.enum(["imports", "exports", "both"]),
|
||||
coverage: z.enum(["complete-within-inputs", "partial", "unknown"]),
|
||||
changes: z.array(
|
||||
z.object({
|
||||
direction: z.enum(["import", "export"]),
|
||||
module: z.string().nullable(),
|
||||
name: z.string(),
|
||||
state: z.enum(["added", "removed", "changed", "unchanged", "unknown"]),
|
||||
left: wasmInterfaceSchema.shape.entries,
|
||||
right: wasmInterfaceSchema.shape.entries,
|
||||
reason: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
summary: z.object({
|
||||
added: z.number(),
|
||||
removed: z.number(),
|
||||
changed: z.number(),
|
||||
unchanged: z.number(),
|
||||
unknown: z.number(),
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
export const COMPARE_WASM_INTERFACES_CONTRACT = {
|
||||
name: "compare_wasm_interfaces",
|
||||
...toolContractMetadata("compare_wasm_interfaces"),
|
||||
kind: "application",
|
||||
description:
|
||||
"Compare typed core WASM import/export names, kinds and exact signatures from two authenticated inspect_wasm_artifact Evidence records. Select imports, exports or both explicitly. Retained references resolve only in the current session; CLI accepts portable inline Evidence. Duplicate names, unsupported types and missing historical interface facets remain unknown. Preserve original module digests and every occurrence; no source acquisition, module execution or runtime-compatibility inference.",
|
||||
inputSchema: compareWasmInterfacesInputSchema,
|
||||
outputSchema: evidenceResultOf(wasmInterfaceComparisonSchema),
|
||||
examples: [],
|
||||
} as const satisfies ToolContract;
|
||||
@@ -1,3 +1,4 @@
|
||||
import { COMPARE_WASM_INTERFACES_CONTRACT } from "./wasmComparisonContracts.js";
|
||||
import {
|
||||
inspectWasmArtifactInputSchema,
|
||||
wasmArtifactSchema,
|
||||
@@ -40,4 +41,7 @@ export const INSPECT_WASM_ARTIFACT_CONTRACT = {
|
||||
} as const satisfies ToolContract;
|
||||
|
||||
/** Keep the public catalog in its existing order, using its named contract. */
|
||||
export const WASM_TOOL_CONTRACTS = [INSPECT_WASM_ARTIFACT_CONTRACT] as const;
|
||||
export const WASM_TOOL_CONTRACTS = [
|
||||
INSPECT_WASM_ARTIFACT_CONTRACT,
|
||||
COMPARE_WASM_INTERFACES_CONTRACT,
|
||||
] as const;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
inspectRecordedCrashInputSchema,
|
||||
recordedCrashSchema,
|
||||
type RecordedCrash,
|
||||
} from "./recordedCrash.js";
|
||||
import {
|
||||
recordedCrashFixture,
|
||||
@@ -282,3 +283,95 @@ it("keeps absent map flags unknown and validates reported permission bits", () =
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
describe("recorded AArch64 core profile", () => {
|
||||
it("accepts the complete AArch64 register window in ABI order", () => {
|
||||
const value = recordedCrashSchema.parse(
|
||||
recordedCrashFixture("/selected/aarch64.core", "aarch64-little-endian"),
|
||||
);
|
||||
expect(value.architecture).toBe("aarch64-little-endian");
|
||||
const registers = value.threads[0]?.registers ?? [];
|
||||
expect(registers.map(({ name }) => name)).toEqual([
|
||||
...Array.from({ length: 31 }, (_, index) => `x${String(index)}`),
|
||||
"sp",
|
||||
"pc",
|
||||
"pstate",
|
||||
]);
|
||||
expect(registers[14]?.value).toBe("0x1122334455667788");
|
||||
expect(registers.every(({ location }) => location.bytes === "0x8")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the AArch64 note ranges inside their recorded segment", () => {
|
||||
const value = recordedCrashSchema.parse(
|
||||
recordedCrashSignalFixture(undefined, "aarch64-little-endian"),
|
||||
);
|
||||
const note = value.notes[0];
|
||||
const segment = value.segments[0];
|
||||
if (note === undefined || segment === undefined)
|
||||
throw new Error("Expected recorded notes");
|
||||
expect(
|
||||
BigInt(note.location.offset) + BigInt(note.location.bytes),
|
||||
).toBeLessThanOrEqual(BigInt(segment.offset) + BigInt(segment.file_size));
|
||||
expect(value.signals[0]?.fault_address).toBe("0x1122334455667788");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"an amd64 register name inside an AArch64 window",
|
||||
(v: RecordedCrash) => ({
|
||||
...v,
|
||||
threads: v.threads.map((thread) => ({
|
||||
...thread,
|
||||
registers: thread.registers.map((register, index) =>
|
||||
index === 0 ? { ...register, name: "rax" } : register,
|
||||
),
|
||||
})),
|
||||
}),
|
||||
],
|
||||
[
|
||||
"the amd64 register count",
|
||||
(v: RecordedCrash) => ({
|
||||
...v,
|
||||
threads: v.threads.map((thread) => ({
|
||||
...thread,
|
||||
registers: thread.registers.slice(0, 27),
|
||||
})),
|
||||
}),
|
||||
],
|
||||
[
|
||||
"a 4-byte AArch64 register source",
|
||||
(v: RecordedCrash) => ({
|
||||
...v,
|
||||
threads: v.threads.map((thread) => ({
|
||||
...thread,
|
||||
registers: thread.registers.map((register, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...register,
|
||||
location: { ...register.location, bytes: "0x4" },
|
||||
}
|
||||
: register,
|
||||
),
|
||||
})),
|
||||
}),
|
||||
],
|
||||
] as const)("rejects %s", (_name, change) => {
|
||||
const value = recordedCrashFixture(
|
||||
"/selected/aarch64.core",
|
||||
"aarch64-little-endian",
|
||||
);
|
||||
expect(recordedCrashSchema.safeParse(change(value)).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an architecture outside the interpreted profiles", () => {
|
||||
const value = recordedCrashFixture();
|
||||
expect(
|
||||
recordedCrashSchema.safeParse({
|
||||
...value,
|
||||
architecture: "arm-little-endian",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { BinaryArchitecture } from "../binaryTargetTypes.js";
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
import { CANONICAL_BASE64_PATTERN } from "../stringPatterns.js";
|
||||
import { recordedNoteCoverageIssues } from "./recordedCrashNoteCoverage.js";
|
||||
@@ -18,7 +19,7 @@ const diagnostics = z.strictObject({
|
||||
const LINUX_CORE_OWNER_BASE64 = "Q09SRQA=";
|
||||
|
||||
/** Complete register identities in the supported Linux amd64 PRSTATUS ABI order. */
|
||||
export const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
|
||||
const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
|
||||
"r15",
|
||||
"r14",
|
||||
"r13",
|
||||
@@ -47,7 +48,95 @@ export const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
|
||||
"fs",
|
||||
"gs",
|
||||
];
|
||||
const supportedRegisters = new Set(RECORDED_LINUX_AMD64_REGISTERS);
|
||||
const RECORDED_LINUX_AARCH64_REGISTERS: readonly string[] = [
|
||||
"x0",
|
||||
"x1",
|
||||
"x2",
|
||||
"x3",
|
||||
"x4",
|
||||
"x5",
|
||||
"x6",
|
||||
"x7",
|
||||
"x8",
|
||||
"x9",
|
||||
"x10",
|
||||
"x11",
|
||||
"x12",
|
||||
"x13",
|
||||
"x14",
|
||||
"x15",
|
||||
"x16",
|
||||
"x17",
|
||||
"x18",
|
||||
"x19",
|
||||
"x20",
|
||||
"x21",
|
||||
"x22",
|
||||
"x23",
|
||||
"x24",
|
||||
"x25",
|
||||
"x26",
|
||||
"x27",
|
||||
"x28",
|
||||
"x29",
|
||||
"x30",
|
||||
"sp",
|
||||
"pc",
|
||||
"pstate",
|
||||
];
|
||||
|
||||
/** Recorded-core architectures whose Linux note ABI is interpreted. */
|
||||
export const RECORDED_LINUX_CORE_ARCHITECTURES = [
|
||||
"x86_64-little-endian",
|
||||
"aarch64-little-endian",
|
||||
] as const;
|
||||
|
||||
export type RecordedCrashArchitecture =
|
||||
(typeof RECORDED_LINUX_CORE_ARCHITECTURES)[number];
|
||||
|
||||
/**
|
||||
* ABI facts for one recorded-core architecture, measured from unchanged pwntools
|
||||
* 4.15.0 `elf_prstatus_*` and `user_regs_struct_*` structures and mirrored by
|
||||
* `bridge/pwntools/recorded_crash_impl.py`. Both profiles place `pr_cursig` at
|
||||
* 12, `pr_pid` at 32 and the register window at 112; the ELF machine, the window
|
||||
* contents and the Evidence CPU family differ per profile.
|
||||
*/
|
||||
export const RECORDED_LINUX_CORE_PROFILES: Record<
|
||||
RecordedCrashArchitecture,
|
||||
{
|
||||
readonly machine: number;
|
||||
readonly evidenceArchitecture: BinaryArchitecture;
|
||||
readonly registers: readonly string[];
|
||||
readonly registerBytes: number;
|
||||
readonly registerOffset: number;
|
||||
readonly prstatusBytes: number;
|
||||
}
|
||||
> = {
|
||||
"x86_64-little-endian": {
|
||||
machine: 62,
|
||||
evidenceArchitecture: "x86_64",
|
||||
registers: RECORDED_LINUX_AMD64_REGISTERS,
|
||||
registerBytes: 8,
|
||||
registerOffset: 112,
|
||||
prstatusBytes: 336,
|
||||
},
|
||||
"aarch64-little-endian": {
|
||||
machine: 183,
|
||||
evidenceArchitecture: "arm64",
|
||||
registers: RECORDED_LINUX_AARCH64_REGISTERS,
|
||||
registerBytes: 8,
|
||||
registerOffset: 112,
|
||||
prstatusBytes: 392,
|
||||
},
|
||||
};
|
||||
|
||||
const recordedCoreRegisterSets: Record<
|
||||
RecordedCrashArchitecture,
|
||||
ReadonlySet<string>
|
||||
> = {
|
||||
"x86_64-little-endian": new Set(RECORDED_LINUX_AMD64_REGISTERS),
|
||||
"aarch64-little-endian": new Set(RECORDED_LINUX_AARCH64_REGISTERS),
|
||||
};
|
||||
|
||||
/** Select an explicit recording and optionally request debugger-derived mapping context. */
|
||||
export const inspectRecordedCrashInputSchema = z.strictObject({
|
||||
@@ -108,7 +197,7 @@ const recordedCrashObjectSchema = z.strictObject({
|
||||
bytes: index,
|
||||
}),
|
||||
format: z.literal("elf-core"),
|
||||
architecture: z.literal("x86_64-little-endian"),
|
||||
architecture: z.enum(RECORDED_LINUX_CORE_ARCHITECTURES),
|
||||
target_execution: z.literal("not-performed"),
|
||||
live_process_identity: z.literal("unknown"),
|
||||
segments: z.array(
|
||||
@@ -284,6 +373,8 @@ export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
|
||||
"Each supported raw note requires exactly one corresponding interpretation.",
|
||||
);
|
||||
}
|
||||
const profile = RECORDED_LINUX_CORE_PROFILES[value.architecture];
|
||||
const profileRegisters = recordedCoreRegisterSets[value.architecture];
|
||||
for (const thread of value.threads) {
|
||||
const note = value.notes[thread.note_index];
|
||||
if (
|
||||
@@ -295,8 +386,8 @@ export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
thread.registers.length !== RECORDED_LINUX_AMD64_REGISTERS.length ||
|
||||
!thread.registers.every(({ name }) => supportedRegisters.has(name)) ||
|
||||
thread.registers.length !== profile.registers.length ||
|
||||
!thread.registers.every(({ name }) => profileRegisters.has(name)) ||
|
||||
new Set(thread.registers.map(({ name }) => name)).size !==
|
||||
thread.registers.length
|
||||
)
|
||||
@@ -305,7 +396,7 @@ export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
|
||||
);
|
||||
for (const register of thread.registers)
|
||||
if (
|
||||
BigInt(register.location.bytes) !== 8n ||
|
||||
BigInt(register.location.bytes) !== BigInt(profile.registerBytes) ||
|
||||
!within(
|
||||
register.location,
|
||||
BigInt(note.descriptor_location.offset),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { wasmInterfaceSchema } from "./wasmInterface.js";
|
||||
import { z } from "zod";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { EvidenceSubjectTarget } from "../evidence.js";
|
||||
@@ -32,6 +33,7 @@ export const wasmArtifactSchema = z
|
||||
description: z.string(),
|
||||
}),
|
||||
),
|
||||
interface: wasmInterfaceSchema.exactOptional(),
|
||||
imports: z.array(z.string()),
|
||||
exports: z.array(z.string()),
|
||||
headers: z.string(),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const kind = z.enum(["func", "table", "memory", "global", "tag", "unknown"]);
|
||||
const valueType = z.enum([
|
||||
"i32",
|
||||
"i64",
|
||||
"f32",
|
||||
"f64",
|
||||
"v128",
|
||||
"funcref",
|
||||
"externref",
|
||||
]);
|
||||
const limit = z.string().regex(/^(?:0|[1-9][0-9]*)$/u);
|
||||
const signature = z.discriminatedUnion("kind", [
|
||||
z.object({
|
||||
kind: z.literal("func"),
|
||||
params: z.array(valueType),
|
||||
results: z.array(valueType),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("tag"),
|
||||
params: z.array(valueType),
|
||||
results: z.array(valueType),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("table"),
|
||||
element: z.enum(["funcref", "externref"]),
|
||||
address_type: z.enum(["i32", "i64"]),
|
||||
minimum: limit,
|
||||
maximum: limit.nullable(),
|
||||
shared: z.boolean(),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("memory"),
|
||||
page_size: limit,
|
||||
address_type: z.enum(["i32", "i64"]),
|
||||
minimum: limit,
|
||||
maximum: limit.nullable(),
|
||||
shared: z.boolean(),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("global"),
|
||||
value_type: valueType,
|
||||
mutable: z.boolean(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Typed observations decoded once at the WABT producer boundary. */
|
||||
export const wasmInterfaceSchema = z.object({
|
||||
state: z.enum(["complete", "partial"]),
|
||||
entries: z.array(
|
||||
z
|
||||
.object({
|
||||
direction: z.enum(["import", "export"]),
|
||||
module: z.string().nullable(),
|
||||
name: z.string(),
|
||||
kind,
|
||||
index: z.number().int().nonnegative().max(0xffff_ffff).nullable(),
|
||||
signature: signature.nullable(),
|
||||
wat_form: z.string(),
|
||||
issue: z.string().nullable(),
|
||||
})
|
||||
.superRefine((entry, context) => {
|
||||
if (
|
||||
(entry.direction === "export" && entry.module !== null) ||
|
||||
(entry.direction === "import" && entry.module === null)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Interface direction does not match module-name presence",
|
||||
});
|
||||
if (entry.signature !== null && entry.signature.kind !== entry.kind)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Interface kind does not match its typed signature",
|
||||
});
|
||||
}),
|
||||
),
|
||||
issues: z.array(z.string()),
|
||||
});
|
||||
export type WasmInterface = z.infer<typeof wasmInterfaceSchema>;
|
||||
export type WasmInterfaceEntry = WasmInterface["entries"][number];
|
||||
export type WasmInterfaceSignature = NonNullable<
|
||||
WasmInterfaceEntry["signature"]
|
||||
>;
|
||||
|
||||
export type WasmInterfaceValueType = z.infer<typeof valueType>;
|
||||
|
||||
/** Bound eager typed output and repeated signature expansion independently of WAT bytes. */
|
||||
export const WASM_INTERFACE_REPRESENTATION_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/** Conservative JSON/retention charge; shared arrays still expand at every occurrence. */
|
||||
export const wasmInterfaceEntryRepresentationBytes = (
|
||||
entry: WasmInterfaceEntry,
|
||||
): number => {
|
||||
let bytes =
|
||||
1024 +
|
||||
[entry.module, entry.name, entry.wat_form, entry.issue].reduce<number>(
|
||||
(sum, value) => sum + (value?.length ?? 0) * 6,
|
||||
0,
|
||||
);
|
||||
const signature = entry.signature;
|
||||
if (signature?.kind === "func" || signature?.kind === "tag")
|
||||
bytes += (signature.params.length + signature.results.length) * 16;
|
||||
else if (signature !== null)
|
||||
for (const value of Object.values(signature))
|
||||
if (typeof value === "string") bytes += value.length * 6;
|
||||
return bytes;
|
||||
};
|
||||
@@ -63,6 +63,56 @@ const DYLIB_FIELDS = [
|
||||
const DYLIB_ENCODING_FIELDS = ["time stamp", "options"];
|
||||
const EMPTY_VALUE_FIELDS = new Set(["options", "segname", "sectname"]);
|
||||
|
||||
/**
|
||||
* Non-verbose otool prints LC_BUILD_VERSION platform and tool codes as
|
||||
* numbers. Name the codes declared in the SDK's <mach-o/loader.h>, without
|
||||
* the PLATFORM_/TOOL_ prefix, so build metadata uses the same symbolic style
|
||||
* as LC_VERSION_MIN_* platforms. Unknown codes keep their printed value.
|
||||
*/
|
||||
const BUILD_PLATFORM_NAMES: ReadonlyMap<string, string> = new Map([
|
||||
["1", "MACOS"],
|
||||
["2", "IOS"],
|
||||
["3", "TVOS"],
|
||||
["4", "WATCHOS"],
|
||||
["5", "BRIDGEOS"],
|
||||
["6", "MACCATALYST"],
|
||||
["7", "IOSSIMULATOR"],
|
||||
["8", "TVOSSIMULATOR"],
|
||||
["9", "WATCHOSSIMULATOR"],
|
||||
["10", "DRIVERKIT"],
|
||||
["11", "VISIONOS"],
|
||||
["12", "VISIONOSSIMULATOR"],
|
||||
["13", "FIRMWARE"],
|
||||
["14", "SEPOS"],
|
||||
["15", "MACOS_EXCLAVECORE"],
|
||||
["16", "MACOS_EXCLAVEKIT"],
|
||||
["17", "IOS_EXCLAVECORE"],
|
||||
["18", "IOS_EXCLAVEKIT"],
|
||||
["19", "TVOS_EXCLAVECORE"],
|
||||
["20", "TVOS_EXCLAVEKIT"],
|
||||
["21", "WATCHOS_EXCLAVECORE"],
|
||||
["22", "WATCHOS_EXCLAVEKIT"],
|
||||
["23", "VISIONOS_EXCLAVECORE"],
|
||||
["24", "VISIONOS_EXCLAVEKIT"],
|
||||
]);
|
||||
const BUILD_TOOL_NAMES: ReadonlyMap<string, string> = new Map([
|
||||
["1", "CLANG"],
|
||||
["2", "SWIFT"],
|
||||
["3", "LD"],
|
||||
["4", "LLD"],
|
||||
["1024", "METAL"],
|
||||
["1025", "AIRLLD"],
|
||||
["1026", "AIRNT"],
|
||||
["1027", "AIRNT_PLUGIN"],
|
||||
["1028", "AIRPACK"],
|
||||
["1031", "GPUARCHIVER"],
|
||||
["1032", "METAL_FRAMEWORK"],
|
||||
]);
|
||||
const buildCodeName = (
|
||||
names: ReadonlyMap<string, string>,
|
||||
value: string | null,
|
||||
): string | null => (value === null ? null : (names.get(value) ?? value));
|
||||
|
||||
/**
|
||||
* otool emits LF, but a capture replayed from another host or toolchain can
|
||||
* carry CRLF. The section/command boundaries below match a bare `\n`, so a
|
||||
@@ -295,7 +345,10 @@ const collectBuild = (
|
||||
if (numberField(fields, "ntools") !== tools.length)
|
||||
throw new TypeError("otool build-tool count does not match ntools");
|
||||
state.builds.push({
|
||||
platform: stringField(fields, "platform"),
|
||||
platform: buildCodeName(
|
||||
BUILD_PLATFORM_NAMES,
|
||||
stringField(fields, "platform"),
|
||||
),
|
||||
minimum_os: stringField(fields, "minos"),
|
||||
sdk: stringField(fields, "sdk"),
|
||||
tools,
|
||||
@@ -434,7 +487,7 @@ const parseBuildTools = (
|
||||
const tool = /^tool\s+(.+)$/u.exec(lines[index] ?? "")?.[1];
|
||||
const version = /^version\s+(.+)$/u.exec(lines[index + 1] ?? "")?.[1];
|
||||
if (tool !== undefined && version !== undefined)
|
||||
tools.push({ name: tool, version });
|
||||
tools.push({ name: BUILD_TOOL_NAMES.get(tool) ?? tool, version });
|
||||
}
|
||||
return tools;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
RECORDED_LINUX_CORE_ARCHITECTURES,
|
||||
RECORDED_LINUX_CORE_PROFILES,
|
||||
} from "../../domain/native/recordedCrash.js";
|
||||
import {
|
||||
recordedCrashFixture,
|
||||
recordedCrashFixtureBytes,
|
||||
} from "../../../tests/fixtures/binaryDiagnostics/recordedCrash.js";
|
||||
import { validateRecordedCrashSources } from "./RecordedCrashSourceBindings.js";
|
||||
|
||||
const diagnostics = { stdout: "", stderr: "", truncated: false } as const;
|
||||
|
||||
const bind = (
|
||||
architecture?: "x86_64-little-endian" | "aarch64-little-endian",
|
||||
) => {
|
||||
const report = recordedCrashFixture("/selected.core", architecture);
|
||||
return { report, bytes: recordedCrashFixtureBytes(report) };
|
||||
};
|
||||
|
||||
describe("recorded core source bindings", () => {
|
||||
it.each(RECORDED_LINUX_CORE_ARCHITECTURES)(
|
||||
"binds each %s register to its own source bytes",
|
||||
(architecture) => {
|
||||
const { report, bytes } = bind(architecture);
|
||||
expect(() =>
|
||||
validateRecordedCrashSources(report, bytes, diagnostics),
|
||||
).not.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("measures the AArch64 register window one slot wide per name", () => {
|
||||
const profile = RECORDED_LINUX_CORE_PROFILES["aarch64-little-endian"];
|
||||
expect(profile.registers.length).toBe(34);
|
||||
expect(profile.prstatusBytes).toBe(392);
|
||||
expect(profile.machine).toBe(183);
|
||||
// The fixtures and the bindings both read these numbers, so they are pinned
|
||||
// here against the ABI record rather than only used consistently.
|
||||
expect(profile.registerOffset).toBe(112);
|
||||
expect(profile.registerBytes).toBe(8);
|
||||
const amd64 = RECORDED_LINUX_CORE_PROFILES["x86_64-little-endian"];
|
||||
expect(amd64.registers.length).toBe(27);
|
||||
expect(amd64.prstatusBytes).toBe(336);
|
||||
expect(amd64.machine).toBe(62);
|
||||
expect(amd64.registerOffset).toBe(112);
|
||||
expect(amd64.registerBytes).toBe(8);
|
||||
});
|
||||
|
||||
it("stamps each crafted core with the machine its profile declares", () => {
|
||||
for (const architecture of RECORDED_LINUX_CORE_ARCHITECTURES) {
|
||||
const bytes = bind(architecture).bytes;
|
||||
expect(bytes.readUInt16LE(18)).toBe(
|
||||
RECORDED_LINUX_CORE_PROFILES[architecture].machine,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an AArch64 register bound to another slot", () => {
|
||||
const { report, bytes } = bind("aarch64-little-endian");
|
||||
const shifted = {
|
||||
...report,
|
||||
threads: report.threads.map((thread) => ({
|
||||
...thread,
|
||||
registers: thread.registers.map((register, index) =>
|
||||
index === 3
|
||||
? {
|
||||
...register,
|
||||
location: {
|
||||
...register.location,
|
||||
offset: `0x${(BigInt(register.location.offset) + 8n).toString(
|
||||
16,
|
||||
)}`,
|
||||
},
|
||||
}
|
||||
: register,
|
||||
),
|
||||
})),
|
||||
};
|
||||
expect(() =>
|
||||
validateRecordedCrashSources(shifted, bytes, diagnostics),
|
||||
).toThrow(/aarch64-little-endian register identity/);
|
||||
});
|
||||
|
||||
it("rejects an AArch64 note shorter than the profile descriptor", () => {
|
||||
const { report, bytes } = bind("aarch64-little-endian");
|
||||
const shortened = {
|
||||
...report,
|
||||
notes: report.notes.map((note, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...note,
|
||||
descriptor_location: {
|
||||
...note.descriptor_location,
|
||||
bytes: "0x150",
|
||||
},
|
||||
}
|
||||
: note,
|
||||
),
|
||||
};
|
||||
expect(() =>
|
||||
validateRecordedCrashSources(shortened, bytes, diagnostics),
|
||||
).toThrow(/aarch64-little-endian source bytes/);
|
||||
});
|
||||
|
||||
it("rejects an amd64 register name reported for AArch64", () => {
|
||||
const { report, bytes } = bind("aarch64-little-endian");
|
||||
const renamed = {
|
||||
...report,
|
||||
threads: report.threads.map((thread) => ({
|
||||
...thread,
|
||||
registers: thread.registers.map((register, index) =>
|
||||
index === 0 ? { ...register, name: "rax" } : register,
|
||||
),
|
||||
})),
|
||||
};
|
||||
expect(() =>
|
||||
validateRecordedCrashSources(renamed, bytes, diagnostics),
|
||||
).toThrow(/aarch64-little-endian register identity/);
|
||||
});
|
||||
|
||||
it("rejects a reported PID that differs from the recorded source bytes", () => {
|
||||
const { report, bytes } = bind("aarch64-little-endian");
|
||||
const wrongPid = {
|
||||
...report,
|
||||
threads: report.threads.map((thread) => ({
|
||||
...thread,
|
||||
historical_pid: thread.historical_pid + 1,
|
||||
})),
|
||||
};
|
||||
expect(() =>
|
||||
validateRecordedCrashSources(wrongPid, bytes, diagnostics),
|
||||
).toThrow(/aarch64-little-endian source bytes/);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +1,26 @@
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
RECORDED_LINUX_AMD64_REGISTERS,
|
||||
RECORDED_LINUX_CORE_PROFILES,
|
||||
type RecordedCrash,
|
||||
} from "../../domain/native/recordedCrash.js";
|
||||
|
||||
const registerOffsets = new Map<string, number>(
|
||||
RECORDED_LINUX_AMD64_REGISTERS.map((name, index) => [name, 112 + index * 8]),
|
||||
);
|
||||
|
||||
/** Bind interpreted values and register identities to Linux amd64 source bytes. */
|
||||
/** Bind interpreted values and register identities to recorded source bytes. */
|
||||
export function validateRecordedCrashSources(
|
||||
report: RecordedCrash,
|
||||
snapshot: Buffer,
|
||||
diagnostics: RecordedCrash["decoder_diagnostics"],
|
||||
): void {
|
||||
const profile = RECORDED_LINUX_CORE_PROFILES[report.architecture];
|
||||
const registerOffsets = new Map<string, number>(
|
||||
profile.registers.map((name, index) => [
|
||||
name,
|
||||
profile.registerOffset + index * profile.registerBytes,
|
||||
]),
|
||||
);
|
||||
const fail = () => {
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_recorded_crash",
|
||||
"Reported PID or signal value differs from its recorded Linux amd64 source bytes.",
|
||||
`Reported PID or signal value differs from its recorded ${report.architecture} source bytes.`,
|
||||
{ capturedOutput: diagnostics },
|
||||
);
|
||||
};
|
||||
@@ -29,10 +32,10 @@ export function validateRecordedCrashSources(
|
||||
if (length < minimumBytes) return fail();
|
||||
return snapshot.subarray(start, start + length);
|
||||
};
|
||||
// Fixed offsets independently checked against unchanged pwntools 4.15.0
|
||||
// elf_prstatus_amd64 / elf_siginfo_64; this is the sole supported note ABI.
|
||||
// Offsets come from unchanged pwntools 4.15.0 elf_prstatus_amd64 /
|
||||
// elf_prstatus_aarch64 and elf_siginfo_64 through the shared domain profile.
|
||||
for (const thread of report.threads) {
|
||||
const bytes = descriptor(thread.note_index, 336);
|
||||
const bytes = descriptor(thread.note_index, profile.prstatusBytes);
|
||||
if (
|
||||
thread.historical_pid !== bytes.readInt32LE(32) ||
|
||||
thread.recorded_current_signal !== bytes.readInt16LE(12)
|
||||
@@ -49,7 +52,7 @@ export function validateRecordedCrashSources(
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_recorded_crash",
|
||||
"Reported register source does not match its Linux amd64 register identity.",
|
||||
`Reported register source does not match its ${report.architecture} register identity.`,
|
||||
{ capturedOutput: diagnostics },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { RecordedCrash } from "../../domain/native/recordedCrash.js";
|
||||
import {
|
||||
RECORDED_LINUX_CORE_PROFILES,
|
||||
type RecordedCrash,
|
||||
} from "../../domain/native/recordedCrash.js";
|
||||
|
||||
// Exact amd64/core enum projections in the pinned pyelftools 0.33 profile.
|
||||
const segmentKinds = new Map([
|
||||
@@ -81,6 +84,8 @@ export function validateRecordedCrashStructure(
|
||||
return snapshot.subarray(Number(offset), Number(offset) + bytes);
|
||||
};
|
||||
const header = bytesAt(0n, 64);
|
||||
const expectedMachine =
|
||||
RECORDED_LINUX_CORE_PROFILES[report.architecture].machine;
|
||||
if (
|
||||
!header
|
||||
.subarray(0, 6)
|
||||
@@ -90,7 +95,7 @@ export function validateRecordedCrashStructure(
|
||||
![0, 3].includes(header[7] ?? -1) ||
|
||||
header[8] !== 0 ||
|
||||
header.readUInt16LE(16) !== 4 ||
|
||||
header.readUInt16LE(18) !== 62
|
||||
header.readUInt16LE(18) !== expectedMachine
|
||||
)
|
||||
fail();
|
||||
const table = header.readBigUInt64LE(32);
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js";
|
||||
import { COMPARE_WASM_INTERFACES_CONTRACT } from "../contracts/wasm/wasmComparisonContracts.js";
|
||||
import { resolvePairedEvidenceRequest } from "../application/EvidenceInputResolver.js";
|
||||
import { recordSessionEvidenceSources } from "./sessionEvidence.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
|
||||
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
|
||||
@@ -21,6 +25,38 @@ export const registerWasmTools = (
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
evidenceById?: EvidenceLookup,
|
||||
): void => {
|
||||
const comparison = COMPARE_WASM_INTERFACES_CONTRACT;
|
||||
const compareHandler = createEvidenceToolHandler(
|
||||
server,
|
||||
async (rawInput, options) => {
|
||||
const input = comparison.inputSchema.safeParse(rawInput);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(
|
||||
comparison.name,
|
||||
input.error.issues,
|
||||
rawInput,
|
||||
),
|
||||
);
|
||||
const sources = resolvePairedEvidenceRequest(input.data, evidenceById);
|
||||
if (!sources.ok) return sources;
|
||||
const result = await compareWasmInterfaces(sources.value, options);
|
||||
if (!result.ok) return result;
|
||||
const recorded = recordSessionEvidenceSources(recordEvidence, [
|
||||
sources.value.left,
|
||||
sources.value.right,
|
||||
]);
|
||||
return recorded.ok ? result : recorded;
|
||||
},
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
server.registerTool(
|
||||
comparison.name,
|
||||
toolRegistrationOptions(comparison),
|
||||
compareHandler(comparison),
|
||||
);
|
||||
const contract = wasmArtifactModule.contract;
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
|
||||
@@ -362,8 +362,13 @@ export class WabtArtifactProvider implements WasmArtifactPort {
|
||||
OPERATION,
|
||||
"Unexpected WABT decoding output.",
|
||||
);
|
||||
const { imports, exports, customSectionNames, debugModuleNames } =
|
||||
parseWabtWat(wat.stdout.text);
|
||||
const {
|
||||
imports,
|
||||
exports,
|
||||
customSectionNames,
|
||||
debugModuleNames,
|
||||
interface: interfaceFacts,
|
||||
} = parseWabtWat(wat.stdout.text);
|
||||
capturedOutput = {
|
||||
stdout: dump.stdout.text,
|
||||
stderr: dump.stderr.text,
|
||||
@@ -388,6 +393,7 @@ export class WabtArtifactProvider implements WasmArtifactPort {
|
||||
sections,
|
||||
imports,
|
||||
exports,
|
||||
interface: interfaceFacts,
|
||||
headers,
|
||||
details,
|
||||
wat: {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { parseWabtWat } from "./WabtWat.js";
|
||||
|
||||
it("resolves imported index spaces and decoded escaped names without depending on body/type numbering", () => {
|
||||
const report = parseWabtWat(`(module
|
||||
(type (;0;) (func (param i32) (result i64)))
|
||||
(import "a\\22b" "\\ef\\bb\\bf\\00" (func (;0;) (type 0)))
|
||||
(func (;1;) (type 0) (param i32) (result i64) local.get 0 i64.extend_i32_s)
|
||||
(export "" (func 1)))`).interface;
|
||||
expect(report.entries).toMatchObject([
|
||||
{
|
||||
direction: "import",
|
||||
module: 'a"b',
|
||||
name: "\ufeff\0",
|
||||
index: 0,
|
||||
signature: { kind: "func", params: ["i32"], results: ["i64"] },
|
||||
},
|
||||
{
|
||||
direction: "export",
|
||||
name: "",
|
||||
index: 1,
|
||||
signature: { kind: "func", params: ["i32"], results: ["i64"] },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains exact memory/table/global/tag declarations and keeps unsupported references unknown", () => {
|
||||
const report = parseWabtWat(`(module
|
||||
(type (func (param i32)))
|
||||
(type (struct (field i32)))
|
||||
(import "env" "table" (table 1 3 funcref))
|
||||
(memory i64 2 4 shared)
|
||||
(global (mut i64) (i64.const 1))
|
||||
(tag (type 0))
|
||||
(func (type 0))
|
||||
(func (param (ref null 1)))
|
||||
(export "memory" (memory 0)) (export "global" (global 0))
|
||||
(export "tag" (tag 0)) (export "gc" (func 1)))`).interface;
|
||||
expect(report.entries.map((e) => e.signature)).toEqual([
|
||||
{
|
||||
kind: "table",
|
||||
element: "funcref",
|
||||
address_type: "i32",
|
||||
minimum: "1",
|
||||
maximum: "3",
|
||||
shared: false,
|
||||
},
|
||||
{
|
||||
kind: "memory",
|
||||
page_size: "65536",
|
||||
address_type: "i64",
|
||||
minimum: "2",
|
||||
maximum: "4",
|
||||
shared: true,
|
||||
},
|
||||
{ kind: "global", value_type: "i64", mutable: true },
|
||||
{ kind: "tag", params: ["i32"], results: [] },
|
||||
null,
|
||||
]);
|
||||
expect(report.entries[4]?.issue).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not bind recursive-type index spaces by guessing their cardinality", () => {
|
||||
const report = parseWabtWat(
|
||||
`(module (rec (type (struct)) (type (func))) (func (type 1)) (export "f" (func 0)))`,
|
||||
).interface;
|
||||
expect(report.entries).toMatchObject([
|
||||
{ name: "f", signature: null, issue: expect.any(String) },
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves custom memory page sizes and treats unadmitted nested declarations as unknown", () => {
|
||||
const custom = parseWabtWat(
|
||||
'(module (memory 1 2 (pagesize 1)) (export "m" (memory 0)))',
|
||||
).interface;
|
||||
expect(custom.entries[0]?.signature).toMatchObject({
|
||||
kind: "memory",
|
||||
page_size: "1",
|
||||
});
|
||||
const unknown = parseWabtWat(
|
||||
'(module (memory 1 (future-proposal 0)) (export "m" (memory 0)))',
|
||||
).interface;
|
||||
expect(unknown.entries[0]?.signature).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses typed name expansion within the source WABT byte cap before retaining interface output", () => {
|
||||
const name = "x".repeat(6 * 1024 * 1024);
|
||||
expect(
|
||||
parseWabtWat(`(module (import "${name}" "f" (func)))`).interface,
|
||||
).toMatchObject({
|
||||
state: "partial",
|
||||
entries: [],
|
||||
issues: [expect.stringMatching(/representation budget/u)],
|
||||
});
|
||||
});
|
||||
|
||||
it("charges shared type signatures at every retained occurrence and preserves bounded partial facts", () => {
|
||||
const params = Array(1000).fill("i32").join(" ");
|
||||
const exports = Array.from(
|
||||
{ length: 10000 },
|
||||
(_, i) => `(export "f${i}" (func 0))`,
|
||||
).join(" ");
|
||||
const report = parseWabtWat(
|
||||
`(module (type (func (param ${params}))) (import "e" "f" (func (type 0))) ${exports})`,
|
||||
).interface;
|
||||
expect(report.state).toBe("partial");
|
||||
expect(report.entries.length).toBeGreaterThan(1);
|
||||
expect(report.entries.length).toBeLessThan(10001);
|
||||
expect(report.entries[0]?.signature).toMatchObject({
|
||||
kind: "func",
|
||||
params: expect.any(Array),
|
||||
});
|
||||
expect(Buffer.byteLength(JSON.stringify(report))).toBeLessThan(
|
||||
32 * 1024 * 1024,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
|
||||
import { wasmInterfaceEntryRepresentationBytes } from "../domain/wasm/wasmInterface.js";
|
||||
import { WasmInterfaceBudget } from "./WasmInterfaceBudget.js";
|
||||
import type {
|
||||
WasmInterface,
|
||||
WasmInterfaceEntry,
|
||||
WasmInterfaceSignature,
|
||||
WasmInterfaceValueType,
|
||||
} from "../domain/wasm/wasmInterface.js";
|
||||
import { watString } from "./WabtString.js";
|
||||
|
||||
/** Split direct WAT children only; function instruction bodies are never materialized. */
|
||||
const parts = (form: string): string[] => {
|
||||
const budget = new WasmInterfaceBudget();
|
||||
const items: string[] = [];
|
||||
let i = 1;
|
||||
while (i < form.length - 1) {
|
||||
if (/\s/u.test(form[i] ?? "")) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (form.startsWith("(;", i)) {
|
||||
let depth = 1;
|
||||
i += 2;
|
||||
while (i < form.length && depth > 0) {
|
||||
if (form.startsWith("(;", i)) {
|
||||
depth++;
|
||||
i += 2;
|
||||
} else if (form.startsWith(";)", i)) {
|
||||
depth--;
|
||||
i += 2;
|
||||
} else i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (form.startsWith(";;", i)) {
|
||||
const end = form.indexOf("\n", i);
|
||||
i = end < 0 ? form.length : end + 1;
|
||||
continue;
|
||||
}
|
||||
const start = i;
|
||||
if (form[i] === '"') {
|
||||
i = watString(form, i + 1).end;
|
||||
} else if (form[i] === "(") {
|
||||
let depth = 1;
|
||||
i++;
|
||||
while (i < form.length && depth > 0) {
|
||||
if (form[i] === '"') i = watString(form, i + 1).end;
|
||||
else {
|
||||
if (form[i] === "(") depth++;
|
||||
else if (form[i] === ")") depth--;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
while (i < form.length && !/[\s()]/u.test(form[i] ?? "")) i++;
|
||||
const atom = form.slice(start, i);
|
||||
if (items[0] === "func" && items.length > 1 && !atom.startsWith("$"))
|
||||
break;
|
||||
}
|
||||
if (i <= start) throw new Error("Malformed WABT form");
|
||||
budget.reserve(64 + (i - start) * 2);
|
||||
items.push(form.slice(start, i));
|
||||
}
|
||||
return items;
|
||||
};
|
||||
const head = (form: string): string | undefined => parts(form)[0];
|
||||
const admittedValues = new Set([
|
||||
"i32",
|
||||
"i64",
|
||||
"f32",
|
||||
"f64",
|
||||
"v128",
|
||||
"funcref",
|
||||
"externref",
|
||||
]);
|
||||
const isValueType = (type: string): type is WasmInterfaceValueType =>
|
||||
admittedValues.has(type);
|
||||
const values = (
|
||||
form: string,
|
||||
category: string,
|
||||
): WasmInterfaceValueType[] | null => {
|
||||
const result: WasmInterfaceValueType[] = [];
|
||||
for (const item of parts(form)) {
|
||||
if (!item.startsWith("(")) continue;
|
||||
const group = parts(item);
|
||||
if (group[0] !== category) continue;
|
||||
for (const type of group.slice(1).filter((t) => !t.startsWith("$"))) {
|
||||
if (!isValueType(type)) return null;
|
||||
result.push(type);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const functionType = (
|
||||
form: string,
|
||||
kind: "func" | "tag",
|
||||
): WasmInterfaceSignature | null => {
|
||||
const params = values(form, "param");
|
||||
const results = values(form, "result");
|
||||
return params === null || results === null ? null : { kind, params, results };
|
||||
};
|
||||
const name = (text: string | undefined): string => {
|
||||
if (text?.startsWith('"') !== true)
|
||||
throw new Error("WABT interface name is missing");
|
||||
return new TextDecoder("utf8", { fatal: true, ignoreBOM: true }).decode(
|
||||
watString(text, 1).bytes,
|
||||
);
|
||||
};
|
||||
const integer = (text: string): string | null => {
|
||||
if (!/^(?:\d+|0x[\da-f]+)$/iu.test(text)) return null;
|
||||
return BigInt(text).toString();
|
||||
};
|
||||
|
||||
/** Resolve index spaces at the producer, not from retained raw WAT in consumers. */
|
||||
const decodeWabtInterface = (
|
||||
forms: readonly string[],
|
||||
result: WasmInterface,
|
||||
): WasmInterface => {
|
||||
const budget = new WasmInterfaceBudget();
|
||||
const types: (WasmInterfaceSignature | null)[] = [];
|
||||
const typeNames = new Map<string, number>();
|
||||
const definitions = new Map<
|
||||
string,
|
||||
{ signature: WasmInterfaceSignature | null; label: string | undefined }[]
|
||||
>();
|
||||
const typeSpaceUnknown = forms.some((f) => head(f) === "rec");
|
||||
for (const form of forms) {
|
||||
const p = parts(form);
|
||||
if (p[0] !== "type") continue;
|
||||
if (p[1]?.startsWith("$") === true) typeNames.set(p[1], types.length);
|
||||
const body = p.find((item) => item.startsWith("("));
|
||||
budget.reserve(256 + (body?.length ?? 0) * 6);
|
||||
types.push(
|
||||
body !== undefined && head(body) === "func" && !typeSpaceUnknown
|
||||
? functionType(body, "func")
|
||||
: null,
|
||||
);
|
||||
}
|
||||
const signature = (form: string): WasmInterfaceSignature | null => {
|
||||
const p = parts(form);
|
||||
const kind = p[0];
|
||||
if (kind === "func" || kind === "tag") {
|
||||
const use = p.find((t) => t.startsWith("(type "));
|
||||
if (use === undefined) return functionType(form, kind);
|
||||
const reference = parts(use)[1];
|
||||
const index =
|
||||
reference === undefined
|
||||
? undefined
|
||||
: reference.startsWith("$")
|
||||
? typeNames.get(reference)
|
||||
: Number(reference);
|
||||
const type =
|
||||
index === undefined || typeSpaceUnknown ? undefined : types[index];
|
||||
return type?.kind === "func" ? { ...type, kind } : null;
|
||||
}
|
||||
if (kind === "memory" || kind === "table") {
|
||||
const groups = p.slice(1).filter((t) => t.startsWith("("));
|
||||
let pageSize = "65536";
|
||||
for (const group of groups) {
|
||||
const declaration = parts(group);
|
||||
if (
|
||||
kind !== "memory" ||
|
||||
declaration[0] !== "pagesize" ||
|
||||
declaration.length !== 2
|
||||
)
|
||||
return null;
|
||||
const parsedPageSize = integer(declaration[1] ?? "");
|
||||
if (parsedPageSize === null) return null;
|
||||
pageSize = parsedPageSize;
|
||||
}
|
||||
const tokens = p
|
||||
.slice(1)
|
||||
.filter((t) => !t.startsWith("$") && !t.startsWith("("));
|
||||
const address_type = tokens[0] === "i64" ? "i64" : "i32";
|
||||
if (tokens[0] === "i64" || tokens[0] === "i32") tokens.shift();
|
||||
const minimum = integer(tokens.shift() ?? "");
|
||||
const possibleMaximum =
|
||||
tokens[0] === undefined ? null : integer(tokens[0]);
|
||||
if (possibleMaximum !== null) tokens.shift();
|
||||
const shared = tokens[0] === "shared";
|
||||
if (shared) tokens.shift();
|
||||
if (minimum === null) return null;
|
||||
if (kind === "memory")
|
||||
return tokens.length === 0
|
||||
? {
|
||||
kind,
|
||||
page_size: pageSize,
|
||||
address_type,
|
||||
minimum,
|
||||
maximum: possibleMaximum,
|
||||
shared,
|
||||
}
|
||||
: null;
|
||||
const element = tokens.shift();
|
||||
return tokens.length === 0 &&
|
||||
element !== undefined &&
|
||||
(element === "funcref" || element === "externref")
|
||||
? {
|
||||
kind,
|
||||
address_type,
|
||||
minimum,
|
||||
maximum: possibleMaximum,
|
||||
shared,
|
||||
element,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
if (kind === "global") {
|
||||
const declaration = p[1]?.startsWith("$") === true ? p[2] : p[1];
|
||||
const mutable = declaration?.startsWith("(mut ") === true;
|
||||
const value_type =
|
||||
mutable && declaration !== undefined
|
||||
? parts(declaration)[1]
|
||||
: declaration;
|
||||
return value_type !== undefined && isValueType(value_type)
|
||||
? { kind, value_type, mutable }
|
||||
: null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const addDefinition = (
|
||||
form: string,
|
||||
): {
|
||||
index: number;
|
||||
kind: WasmInterfaceEntry["kind"];
|
||||
signature: WasmInterfaceSignature | null;
|
||||
} => {
|
||||
const p = parts(form);
|
||||
const rawKind = p[0] ?? "unknown";
|
||||
const kind = ["func", "table", "memory", "global", "tag"].includes(rawKind)
|
||||
? (rawKind as WasmInterfaceEntry["kind"])
|
||||
: "unknown";
|
||||
const space = definitions.get(kind) ?? [];
|
||||
const item = {
|
||||
signature: signature(form),
|
||||
label: p[1]?.startsWith("$") === true ? p[1] : undefined,
|
||||
};
|
||||
budget.reserve(256);
|
||||
const index = space.length;
|
||||
space.push(item);
|
||||
definitions.set(kind, space);
|
||||
return { index, kind, signature: item.signature };
|
||||
};
|
||||
for (const form of forms) {
|
||||
const p = parts(form);
|
||||
if (p[0] !== "import") continue;
|
||||
const body = p[3];
|
||||
if (body === undefined) throw new Error("Incomplete WABT import");
|
||||
const observed = addDefinition(body);
|
||||
const entry: WasmInterfaceEntry = {
|
||||
direction: "import",
|
||||
module: name(p[1]),
|
||||
name: name(p[2]),
|
||||
...observed,
|
||||
wat_form: form,
|
||||
issue:
|
||||
observed.signature === null
|
||||
? "Import type is outside admitted core signature semantics"
|
||||
: null,
|
||||
};
|
||||
budget.reserve(wasmInterfaceEntryRepresentationBytes(entry));
|
||||
result.entries.push(entry);
|
||||
}
|
||||
for (const form of forms) {
|
||||
const kind = head(form);
|
||||
if (
|
||||
kind !== undefined &&
|
||||
["func", "table", "memory", "global", "tag"].includes(kind)
|
||||
)
|
||||
addDefinition(form);
|
||||
}
|
||||
for (const form of forms) {
|
||||
const p = parts(form);
|
||||
if (p[0] !== "export") continue;
|
||||
const body = p[2];
|
||||
if (body === undefined) throw new Error("Incomplete WABT export");
|
||||
const descriptor = parts(body);
|
||||
const rawKind = descriptor[0] ?? "unknown";
|
||||
const kind = ["func", "table", "memory", "global", "tag"].includes(rawKind)
|
||||
? (rawKind as WasmInterfaceEntry["kind"])
|
||||
: "unknown";
|
||||
const reference = descriptor[1];
|
||||
const space = definitions.get(kind) ?? [];
|
||||
const index =
|
||||
reference === undefined
|
||||
? -1
|
||||
: reference.startsWith("$")
|
||||
? space.findIndex((d) => d.label === reference)
|
||||
: Number(reference);
|
||||
const observed =
|
||||
Number.isSafeInteger(index) && index >= 0 ? space[index] : undefined;
|
||||
const entry: WasmInterfaceEntry = {
|
||||
direction: "export",
|
||||
module: null,
|
||||
name: name(p[1]),
|
||||
kind,
|
||||
index: observed === undefined ? null : index,
|
||||
signature: observed?.signature ?? null,
|
||||
wat_form: form,
|
||||
issue:
|
||||
observed?.signature == null
|
||||
? "Export type/index is outside admitted core signature semantics"
|
||||
: null,
|
||||
};
|
||||
budget.reserve(wasmInterfaceEntryRepresentationBytes(entry));
|
||||
result.entries.push(entry);
|
||||
}
|
||||
// Unsupported signatures leave inventory completeness intact. A missing
|
||||
// signature is unknown per entry, not proof that a name is absent.
|
||||
return result;
|
||||
};
|
||||
|
||||
/** New typed coverage may be incomplete without discarding existing decoded WAT Evidence. */
|
||||
export const parseWabtInterface = (forms: readonly string[]): WasmInterface => {
|
||||
const result: WasmInterface = { state: "complete", entries: [], issues: [] };
|
||||
try {
|
||||
return decodeWabtInterface(forms, result);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof AnalysisResourceConstraintError)) throw cause;
|
||||
result.state = "partial";
|
||||
result.issues.push(cause.message);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
@@ -229,7 +229,7 @@ it("extracts escaped WAT import/export forms while retaining multiline producer
|
||||
new URL("../../tests/fixtures/wasm/decoded.wat", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
expect(parseWabtWat(text)).toEqual({
|
||||
expect(parseWabtWat(text)).toMatchObject({
|
||||
imports: ['(import "env" "foo" (func (;0;) (type 0)))'],
|
||||
exports: ['(export "memory" (memory 0))', '(export "run" (func 1))'],
|
||||
customSectionNames: ["test"],
|
||||
@@ -239,7 +239,7 @@ it("extracts escaped WAT import/export forms while retaining multiline producer
|
||||
parseWabtWat(
|
||||
'(module (import "a.b" "c\\0aline" (func)) (export "fake\\22Export[1]:" (func 0)))',
|
||||
),
|
||||
).toEqual({
|
||||
).toMatchObject({
|
||||
imports: ['(import "a.b" "c\\0aline" (func))'],
|
||||
exports: ['(export "fake\\22Export[1]:" (func 0))'],
|
||||
customSectionNames: [],
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/** Decode a producer WAT string to frame objdump's raw display text. */
|
||||
export const watString = (form: string, start: number) => {
|
||||
let end = start;
|
||||
while (end < form.length && form[end] !== '"') {
|
||||
if (form[end] === "\\") end++;
|
||||
end++;
|
||||
}
|
||||
if (end === form.length)
|
||||
throw new Error("Incomplete WABT custom-section name.");
|
||||
const name = form.slice(start, end);
|
||||
// Escapes shrink; literal UTF-8 has the same byte extent as its source.
|
||||
const bytes = Buffer.alloc(Buffer.byteLength(name, "utf8"));
|
||||
let length = 0;
|
||||
for (let index = 0; index < name.length;) {
|
||||
if (name[index] !== "\\") {
|
||||
const next = name.indexOf("\\", index);
|
||||
const end = next < 0 ? name.length : next;
|
||||
length += bytes.write(name.slice(index, end), length, "utf8");
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
const hex = name.slice(index + 1, index + 3);
|
||||
if (/^[\da-f]{2}$/iu.test(hex)) {
|
||||
bytes[length++] = Number.parseInt(hex, 16);
|
||||
index += 3;
|
||||
} else {
|
||||
const escape = name[index + 1];
|
||||
const value =
|
||||
escape === "t"
|
||||
? 9
|
||||
: escape === "n"
|
||||
? 10
|
||||
: escape === "r"
|
||||
? 13
|
||||
: escape === '"'
|
||||
? 34
|
||||
: escape === "\\"
|
||||
? 92
|
||||
: undefined;
|
||||
if (value === undefined) throw new Error("Unsupported WABT name escape.");
|
||||
bytes[length++] = value;
|
||||
index += 2;
|
||||
}
|
||||
}
|
||||
return { bytes: bytes.subarray(0, length), end: end + 1 };
|
||||
};
|
||||
+16
-47
@@ -1,49 +1,5 @@
|
||||
/** Decode a producer WAT string to frame objdump's raw display text. */
|
||||
const watString = (form: string, start: number) => {
|
||||
let end = start;
|
||||
while (end < form.length && form[end] !== '"') {
|
||||
if (form[end] === "\\") end++;
|
||||
end++;
|
||||
}
|
||||
if (end === form.length)
|
||||
throw new Error("Incomplete WABT custom-section name.");
|
||||
const name = form.slice(start, end);
|
||||
// Escapes shrink; literal UTF-8 has the same byte extent as its source.
|
||||
const bytes = Buffer.alloc(Buffer.byteLength(name, "utf8"));
|
||||
let length = 0;
|
||||
for (let index = 0; index < name.length;) {
|
||||
if (name[index] !== "\\") {
|
||||
const next = name.indexOf("\\", index);
|
||||
const end = next < 0 ? name.length : next;
|
||||
length += bytes.write(name.slice(index, end), length, "utf8");
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
const hex = name.slice(index + 1, index + 3);
|
||||
if (/^[\da-f]{2}$/iu.test(hex)) {
|
||||
bytes[length++] = Number.parseInt(hex, 16);
|
||||
index += 3;
|
||||
} else {
|
||||
const escape = name[index + 1];
|
||||
const value =
|
||||
escape === "t"
|
||||
? 9
|
||||
: escape === "n"
|
||||
? 10
|
||||
: escape === "r"
|
||||
? 13
|
||||
: escape === '"'
|
||||
? 34
|
||||
: escape === "\\"
|
||||
? 92
|
||||
: undefined;
|
||||
if (value === undefined) throw new Error("Unsupported WABT name escape.");
|
||||
bytes[length++] = value;
|
||||
index += 2;
|
||||
}
|
||||
}
|
||||
return { bytes: bytes.subarray(0, length), end: end + 1 };
|
||||
};
|
||||
import { parseWabtInterface } from "./WabtInterface.js";
|
||||
import { watString } from "./WabtString.js";
|
||||
|
||||
/** Read only module-name metadata from WABT's preserved name-section payload. */
|
||||
const moduleNames = (bytes: Uint8Array): string[] => {
|
||||
@@ -85,6 +41,7 @@ const moduleNames = (bytes: Uint8Array): string[] => {
|
||||
export const parseWabtWat = (text: string) => {
|
||||
if (!/^\(module(?:\s|\))/u.test(text))
|
||||
throw new Error("Unsupported WABT WAT module prefix.");
|
||||
const forms: string[] = [];
|
||||
const imports: string[] = [];
|
||||
const exports: string[] = [];
|
||||
const customSectionNames: string[] = [];
|
||||
@@ -140,6 +97,12 @@ export const parseWabtWat = (text: string) => {
|
||||
} else if (char === ")") {
|
||||
if (depth === 2) {
|
||||
const form = text.slice(start, index + 1);
|
||||
if (
|
||||
/^\((?:type|rec|import|export|func|table|memory|global|tag)\s/u.test(
|
||||
form,
|
||||
)
|
||||
)
|
||||
forms.push(form);
|
||||
if (/^\(import\s/u.test(form)) imports.push(form);
|
||||
else if (/^\(export\s/u.test(form)) exports.push(form);
|
||||
else if (/^\(@custom\s/u.test(form)) {
|
||||
@@ -172,5 +135,11 @@ export const parseWabtWat = (text: string) => {
|
||||
}
|
||||
if (depth !== 0 || quoted || commentDepth !== 0)
|
||||
throw new Error("Incomplete WABT WAT output.");
|
||||
return { imports, exports, customSectionNames, debugModuleNames };
|
||||
return {
|
||||
imports,
|
||||
exports,
|
||||
customSectionNames,
|
||||
debugModuleNames,
|
||||
interface: parseWabtInterface(forms),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
|
||||
import { WASM_INTERFACE_REPRESENTATION_BYTES } from "../domain/wasm/wasmInterface.js";
|
||||
|
||||
/** Eager typed observations share the existing WABT output capacity, not an agent token estimate. */
|
||||
export class WasmInterfaceBudget {
|
||||
#remaining = WASM_INTERFACE_REPRESENTATION_BYTES;
|
||||
reserve(bytes: number): void {
|
||||
if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.#remaining)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
"inspect_wasm_artifact",
|
||||
"capacity",
|
||||
"Typed WASM interface decoding exceeds the WABT output representation budget",
|
||||
{ maximum_bytes: WASM_INTERFACE_REPRESENTATION_BYTES },
|
||||
);
|
||||
this.#remaining -= bytes;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user