feat(wasm): inspect local artifacts with WABT (#1533)
* feat(wasm): inspect local artifacts with WABT * fix(wasm): preserve custom names and failed cleanup ownership --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
import { access, chmod, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { WabtArtifactProvider } from "./WabtArtifactProvider.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../process/ProviderProcess.js";
|
||||
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
|
||||
|
||||
const failureTags: Readonly<Record<string, string>> = {
|
||||
invalid: "AnalysisInputError",
|
||||
timeout: "AnalysisTimeoutError",
|
||||
cancelled: "AnalysisCancelledError",
|
||||
"changed-snapshot": "AnalysisArtifactChangedError",
|
||||
cleanup: "ProviderAdapterError",
|
||||
malformed: "AnalysisOutputError",
|
||||
"malformed-wat": "AnalysisOutputError",
|
||||
"wat-warning": "AnalysisOutputError",
|
||||
};
|
||||
|
||||
it("returns actionable unavailable without creating a workspace when tools are absent", async () => {
|
||||
const provider = new WabtArtifactProvider({}, undefined, () => {
|
||||
throw new Error("Must not allocate");
|
||||
});
|
||||
expect(
|
||||
await provider.inspect({
|
||||
path: "/module.wasm",
|
||||
glue_paths: [],
|
||||
candidate_paths: [],
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
userMessage: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
"success",
|
||||
"invalid",
|
||||
"malformed",
|
||||
"timeout",
|
||||
"cancelled",
|
||||
"cleanup",
|
||||
"changed-snapshot",
|
||||
"malformed-wat",
|
||||
"wat-warning",
|
||||
])("owns private artifact bytes and retains %s outcome", async (mode) => {
|
||||
const selectedRoot = await createTestTempDirectory("rea-wabt-seam-");
|
||||
const path = join(selectedRoot, "selected.wasm");
|
||||
const bytes = Buffer.alloc(76, 1);
|
||||
await writeFile(path, bytes);
|
||||
for (const tool of ["wasm-validate", "wasm-objdump", "wasm2wat"])
|
||||
await writeFile(
|
||||
join(selectedRoot, tool + (process.platform === "win32" ? ".exe" : "")),
|
||||
"source-owned executable seam",
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const dump = await readFile(
|
||||
new URL("../../tests/fixtures/wasm/objdump.txt", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
let runtimePath = "";
|
||||
let acquiredPid: number | undefined;
|
||||
let cleanupAttempts = 0;
|
||||
const controller = new AbortController();
|
||||
const provider = new WabtArtifactProvider(
|
||||
{ REA_WABT_BIN_DIRECTORY: selectedRoot },
|
||||
async (input) => {
|
||||
const version = input.arguments[0] === "--version";
|
||||
if (!version) {
|
||||
expect(await readFile(join(input.cwd ?? "", "module.wasm"))).toEqual(
|
||||
bytes,
|
||||
);
|
||||
if (mode === "changed-snapshot") {
|
||||
const snapshot = join(input.cwd ?? "", "module.wasm");
|
||||
await chmod(snapshot, 0o600);
|
||||
await writeFile(snapshot, Buffer.alloc(76, 2));
|
||||
}
|
||||
if (mode === "timeout")
|
||||
throw new OwnedCommandFailure(
|
||||
"timeout",
|
||||
"Source-owned deadline seam",
|
||||
);
|
||||
}
|
||||
const stdout = version
|
||||
? "1.0.42\n"
|
||||
: input.command.includes("objdump")
|
||||
? mode === "malformed"
|
||||
? "unexpected producer output"
|
||||
: dump
|
||||
: input.command.includes("wasm2wat")
|
||||
? mode === "malformed-wat"
|
||||
? "unexpected decoder output\n"
|
||||
: '(module (@custom "test" "payload"))\n'
|
||||
: "";
|
||||
const invalid = !version && mode === "invalid";
|
||||
const stderr = invalid
|
||||
? "module.wasm: invalid bytes\n"
|
||||
: !version &&
|
||||
input.command.includes("wasm2wat") &&
|
||||
mode === "wat-warning"
|
||||
? "decoder warning\n"
|
||||
: "";
|
||||
const script =
|
||||
!version && mode === "cancelled"
|
||||
? "setInterval(() => undefined, 1000)"
|
||||
: `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exit(${invalid ? 1 : 0});`;
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...input,
|
||||
command: process.execPath,
|
||||
arguments: ["-e", script],
|
||||
expectedCommand: null,
|
||||
});
|
||||
if (!version && mode === "cancelled") {
|
||||
acquiredPid = launched.process.pid;
|
||||
setImmediate(() => controller.abort());
|
||||
}
|
||||
return launched;
|
||||
},
|
||||
async () => {
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
prefix: "rea-wabt-owned-test-",
|
||||
});
|
||||
runtimePath = root.path;
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (mode === "cleanup" && ++cleanupAttempts <= 2)
|
||||
throw new Error("Source-owned cleanup uncertainty");
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
const result = await provider.inspect(
|
||||
{ path, glue_paths: [], candidate_paths: [] },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (mode === "success")
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
result: {
|
||||
artifact: { path, bytes: 76 },
|
||||
validation: "valid",
|
||||
runtime_execution: "not-performed",
|
||||
},
|
||||
},
|
||||
});
|
||||
else
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: failureTags[mode] },
|
||||
});
|
||||
if (mode === "invalid")
|
||||
expect(result).toMatchObject({
|
||||
error: { capturedOutput: { stderr: "module.wasm: invalid bytes\n" } },
|
||||
});
|
||||
if (mode === "cleanup") {
|
||||
expect(result).toMatchObject({
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: [runtimePath],
|
||||
partialObservation: { normalized_result: { validation: "valid" } },
|
||||
},
|
||||
});
|
||||
await expect(access(runtimePath)).resolves.toBeUndefined();
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
await expect(access(runtimePath)).resolves.toBeUndefined();
|
||||
await provider.close();
|
||||
}
|
||||
if (mode === "malformed-wat" || mode === "wat-warning")
|
||||
expect(result).toMatchObject({
|
||||
error: {
|
||||
capturedOutput: {
|
||||
stdout:
|
||||
mode === "malformed-wat"
|
||||
? "unexpected decoder output\n"
|
||||
: '(module (@custom "test" "payload"))\n',
|
||||
stderr: mode === "wat-warning" ? "decoder warning\n" : "",
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(access(runtimePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
if (acquiredPid !== undefined) {
|
||||
const pid = acquiredPid;
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,439 @@
|
||||
import { randomUUID, createHash } from "node:crypto";
|
||||
import { access, realpath, writeFile } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { createAnalysisExecution } from "../application/AnalysisProvider.js";
|
||||
import type { WasmArtifactPort } from "../application/wasm/WasmArtifactPort.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import type {
|
||||
AnalysisError,
|
||||
AnalysisCapturedOutput,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import {
|
||||
wasmArtifactSchema,
|
||||
type InspectWasmArtifactInput,
|
||||
} from "../domain/wasm/wasmArtifact.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { runOwnedCommand } from "../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { WABT_PROVIDER_IDENTITY, WABT_LIMITS } from "./WabtRelease.js";
|
||||
import { wabtFailure } from "./WabtFailures.js";
|
||||
import { parseWabtOutput } from "./WabtOutput.js";
|
||||
import { parseWabtWat } from "./WabtWat.js";
|
||||
import { associateWasmGlue } from "./WasmGlueAdapter.js";
|
||||
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
const OPERATION = "inspect_wasm_artifact";
|
||||
const digest = (text: string) =>
|
||||
createHash("sha256").update(text).digest("hex");
|
||||
/** Run caller-supplied WABT against private copies of exactly selected bytes. */
|
||||
export class WabtArtifactProvider implements WasmArtifactPort {
|
||||
readonly #pendingRoots = new Set<
|
||||
Pick<PrivateRuntimeRoot, "path" | "close">
|
||||
>();
|
||||
constructor(
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
readonly launcher?: Launcher,
|
||||
readonly createRuntime: () => Promise<
|
||||
Pick<PrivateRuntimeRoot, "path" | "close">
|
||||
> = () => PrivateRuntimeRoot.create({ prefix: "rea-wabt-" }),
|
||||
) {}
|
||||
/** Retry retained cleanup without discarding roots that still cannot be removed. */
|
||||
async close(): Promise<void> {
|
||||
const failures: { path: string; reason: string }[] = [];
|
||||
for (const root of this.#pendingRoots) {
|
||||
try {
|
||||
await root.close();
|
||||
this.#pendingRoots.delete(root);
|
||||
} catch (cause: unknown) {
|
||||
failures.push({
|
||||
path: root.path,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (failures.length > 0)
|
||||
throw new ProviderCleanupError(
|
||||
WABT_PROVIDER_IDENTITY.id,
|
||||
failures.map(({ path }) => path),
|
||||
{ failures },
|
||||
{ operation: OPERATION },
|
||||
);
|
||||
}
|
||||
async inspect(
|
||||
input: InspectWasmArtifactInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
|
||||
let phase: "configuration" | "artifact" | "producer" = "configuration";
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
let capturedOutput: AnalysisCapturedOutput | undefined;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
await this.close();
|
||||
const directory = this.environment.REA_WABT_BIN_DIRECTORY ?? "";
|
||||
if (!isAbsolute(directory))
|
||||
throw new Error(
|
||||
"REA_WABT_BIN_DIRECTORY must be an absolute tool directory.",
|
||||
);
|
||||
const commands: {
|
||||
tool: string;
|
||||
path: string;
|
||||
sha256: string;
|
||||
version_banner: string;
|
||||
arguments: string[];
|
||||
}[] = [];
|
||||
for (const tool of ["wasm-validate", "wasm-objdump", "wasm2wat"]) {
|
||||
const path = await realpath(
|
||||
join(
|
||||
directory,
|
||||
`${tool}${process.platform === "win32" ? ".exe" : ""}`,
|
||||
),
|
||||
);
|
||||
await access(path, constants.X_OK);
|
||||
const binary = await readStableArtifact(
|
||||
path,
|
||||
WABT_LIMITS.toolBytes,
|
||||
options?.signal,
|
||||
);
|
||||
commands.push({
|
||||
tool,
|
||||
path,
|
||||
sha256: binary.sha256,
|
||||
version_banner: "",
|
||||
arguments:
|
||||
tool === "wasm-objdump"
|
||||
? ["-h", "-x", "module.wasm"]
|
||||
: ["--enable-all", "module.wasm"],
|
||||
});
|
||||
}
|
||||
root = await this.createRuntime();
|
||||
const snapshotPath = join(root.path, "module.wasm");
|
||||
let snapshotHash: string | undefined;
|
||||
const verifySnapshot = async () => {
|
||||
if (snapshotHash === undefined) return;
|
||||
try {
|
||||
const bytes = await readStableArtifact(
|
||||
snapshotPath,
|
||||
WABT_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
if (bytes.sha256 !== snapshotHash)
|
||||
throw new Error("Private WASM snapshot bytes changed.");
|
||||
} catch (cause: unknown) {
|
||||
if (options?.signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION);
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
input.path,
|
||||
"Private WASM snapshot no longer matches selected byte identity.",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
const execute = async (
|
||||
command: (typeof commands)[number],
|
||||
args: readonly string[],
|
||||
acceptNonZeroExit = false,
|
||||
) => {
|
||||
await verifySnapshot();
|
||||
const snapshot = await runOwnedCommand(
|
||||
{
|
||||
command: command.path,
|
||||
arguments: args,
|
||||
...(root === undefined ? {} : { cwd: root.path }),
|
||||
expectedCommand: command.path,
|
||||
runId: `rea-wabt-${randomUUID()}`,
|
||||
hostEnvironment: this.environment,
|
||||
},
|
||||
{
|
||||
timeoutMs: WABT_LIMITS.timeoutMs,
|
||||
diagnosticBytes: WABT_LIMITS.outputBytes,
|
||||
acceptNonZeroExit,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined
|
||||
? {}
|
||||
: { signal: options.signal }),
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
},
|
||||
);
|
||||
const current = await readStableArtifact(
|
||||
command.path,
|
||||
WABT_LIMITS.toolBytes,
|
||||
options?.signal,
|
||||
);
|
||||
if (current.sha256 !== command.sha256)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Configured WABT executable changed during inspection.",
|
||||
);
|
||||
await verifySnapshot();
|
||||
return snapshot;
|
||||
};
|
||||
for (const command of commands) {
|
||||
const version = await execute(command, ["--version"]);
|
||||
if (
|
||||
version.stdout.text.trim() !== "1.0.42" ||
|
||||
version.stderr.text !== ""
|
||||
)
|
||||
throw new Error(
|
||||
`Unsupported ${command.tool} version banner; expected 1.0.42.`,
|
||||
);
|
||||
command.version_banner = version.stdout.text;
|
||||
}
|
||||
phase = "artifact";
|
||||
const selected = await readStableArtifact(
|
||||
input.path,
|
||||
WABT_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
const artifact = {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
bytes: selected.bytes.length,
|
||||
};
|
||||
const candidates = [];
|
||||
for (const path of new Set([input.path, ...input.candidate_paths])) {
|
||||
const bytes =
|
||||
path === input.path
|
||||
? selected
|
||||
: await readStableArtifact(
|
||||
path,
|
||||
WABT_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
candidates.push({
|
||||
path,
|
||||
sha256: bytes.sha256,
|
||||
bytes: bytes.bytes.length,
|
||||
});
|
||||
}
|
||||
const glue = [];
|
||||
for (const path of input.glue_paths) {
|
||||
const bytes = await readStableArtifact(
|
||||
path,
|
||||
WABT_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
const source = new TextDecoder("utf-8", { fatal: true }).decode(
|
||||
bytes.bytes,
|
||||
);
|
||||
glue.push({
|
||||
artifact: { path, sha256: bytes.sha256, bytes: bytes.bytes.length },
|
||||
...associateWasmGlue(
|
||||
source,
|
||||
path,
|
||||
candidates.map((candidate) => candidate.path),
|
||||
),
|
||||
});
|
||||
}
|
||||
await writeFile(snapshotPath, selected.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o400,
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
snapshotHash = selected.sha256;
|
||||
phase = "producer";
|
||||
const [validate, objdump, decode] = commands;
|
||||
if (
|
||||
validate === undefined ||
|
||||
objdump === undefined ||
|
||||
decode === undefined
|
||||
)
|
||||
throw new Error("Incomplete WABT tool profile.");
|
||||
const validation = await execute(validate, validate.arguments, true);
|
||||
if (validation.exitCode !== 0)
|
||||
throw new AnalysisInputError(
|
||||
OPERATION,
|
||||
{
|
||||
partialObservation: createEvidence(
|
||||
{ path: input.path, format: "file", sha256: selected.sha256 },
|
||||
WABT_PROVIDER_IDENTITY,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: input,
|
||||
result: {
|
||||
artifact,
|
||||
validation: "rejected-by-selected-profile",
|
||||
tool_profile: {
|
||||
source: "https://github.com/WebAssembly/wabt",
|
||||
release: "1.0.42",
|
||||
source_commit: "ff0ef7e0009402740c805a9744c09b05be063e48",
|
||||
commands,
|
||||
},
|
||||
exit_code: validation.exitCode ?? null,
|
||||
stdout: validation.stdout.text,
|
||||
stderr: validation.stderr.text,
|
||||
},
|
||||
confidence: "observed",
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations: [
|
||||
"WABT rejected these exact selected bytes with --enable-all; no complete inspection or target execution occurred.",
|
||||
],
|
||||
},
|
||||
),
|
||||
capturedOutput: {
|
||||
stdout: validation.stdout.text,
|
||||
stderr: validation.stderr.text,
|
||||
truncated: false,
|
||||
},
|
||||
},
|
||||
[
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message:
|
||||
"Selected bytes failed WABT validation with --enable-all; inspect retained upstream diagnostics.",
|
||||
},
|
||||
],
|
||||
);
|
||||
const dump = await execute(objdump, objdump.arguments);
|
||||
capturedOutput = {
|
||||
stdout: dump.stdout.text,
|
||||
stderr: dump.stderr.text,
|
||||
truncated: false,
|
||||
};
|
||||
if (dump.stderr.text !== "")
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Unexpected WABT section output.",
|
||||
);
|
||||
const wat = await execute(decode, decode.arguments);
|
||||
capturedOutput = {
|
||||
stdout: wat.stdout.text,
|
||||
stderr: wat.stderr.text,
|
||||
truncated: false,
|
||||
};
|
||||
if (!wat.stdout.text.startsWith("(module") || wat.stderr.text !== "")
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Unexpected WABT decoding output.",
|
||||
);
|
||||
const { imports, exports, customSectionNames } = parseWabtWat(
|
||||
wat.stdout.text,
|
||||
);
|
||||
capturedOutput = {
|
||||
stdout: dump.stdout.text,
|
||||
stderr: dump.stderr.text,
|
||||
truncated: false,
|
||||
};
|
||||
const { sections, headers, details } = parseWabtOutput(
|
||||
dump.stdout.text,
|
||||
artifact.bytes,
|
||||
customSectionNames,
|
||||
);
|
||||
const limitations = [
|
||||
"WAT is a decoded representation, not original source or proof of runtime behavior. Custom annotations may retain payloads, but WAT does not establish original binary layout or round-trip byte identity. Original bytes and objdump output remain authoritative.",
|
||||
"Imports and exports retain exact top-level WABT WAT forms. Names remain escaped producer text; unescaped objdump display names are not parsed as unambiguous identifiers.",
|
||||
"JavaScript references are AST-observed static literals only. Candidate matches are associations, not proven data flow, URL-to-file identity or runtime loading. Computed references and aliases are not resolved.",
|
||||
"No target execution or implicit fetch. WABT tools are trusted caller-supplied executables; SHA-256 identifies their bytes, not publisher authenticity. No OS memory sandbox is claimed.",
|
||||
"Each subprocess has a 30-second deadline and 32 MiB combined output budget. Oversized output fails instead of producing truncated success.",
|
||||
];
|
||||
const report = wasmArtifactSchema.parse({
|
||||
artifact,
|
||||
validation: "valid",
|
||||
sections,
|
||||
imports,
|
||||
exports,
|
||||
headers,
|
||||
details,
|
||||
wat: {
|
||||
text: wat.stdout.text,
|
||||
sha256: digest(wat.stdout.text),
|
||||
representation: "decoded-wat",
|
||||
},
|
||||
tool_profile: {
|
||||
source: "https://github.com/WebAssembly/wabt",
|
||||
release: "1.0.42",
|
||||
source_commit: "ff0ef7e0009402740c805a9744c09b05be063e48",
|
||||
commands,
|
||||
timeout_ms: WABT_LIMITS.timeoutMs,
|
||||
output_budget_bytes: WABT_LIMITS.outputBytes,
|
||||
},
|
||||
candidates,
|
||||
glue,
|
||||
runtime_execution: "not-performed",
|
||||
network_fetch: "not-performed",
|
||||
limitations,
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, WABT_PROVIDER_IDENTITY, {
|
||||
subject: {
|
||||
path: input.path,
|
||||
format: "file",
|
||||
sha256: selected.sha256,
|
||||
},
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations,
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
const failure = wabtFailure(cause, phase, input.path);
|
||||
result = err(
|
||||
failure instanceof AnalysisOutputError &&
|
||||
failure.capturedOutput === undefined &&
|
||||
capturedOutput !== undefined
|
||||
? new AnalysisOutputError(OPERATION, failure.reason, {
|
||||
cause,
|
||||
capturedOutput,
|
||||
})
|
||||
: failure,
|
||||
);
|
||||
}
|
||||
if (root !== undefined) {
|
||||
try {
|
||||
await root.close();
|
||||
} catch (cause: unknown) {
|
||||
this.#pendingRoots.add(root);
|
||||
const partialObservation = result.ok
|
||||
? createEvidence(
|
||||
result.value.subject ?? undefined,
|
||||
result.value.provider,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: input,
|
||||
result: result.value.result,
|
||||
confidence: "observed",
|
||||
locations: result.value.locations,
|
||||
limitations: result.value.limitations,
|
||||
},
|
||||
)
|
||||
: result.error.partialObservation;
|
||||
result = err(
|
||||
new ProviderCleanupError(
|
||||
WABT_PROVIDER_IDENTITY.id,
|
||||
[root.path],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
},
|
||||
{
|
||||
operation: OPERATION,
|
||||
cause,
|
||||
...(partialObservation === undefined
|
||||
? {}
|
||||
: { partialObservation }),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisTimeoutError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
|
||||
import { WABT_LIMITS, WABT_PROVIDER_IDENTITY } from "./WabtRelease.js";
|
||||
/** Preserve lifecycle failures and diagnostic bytes instead of returning partial success. */
|
||||
export const wabtFailure = (
|
||||
cause: unknown,
|
||||
phase: "configuration" | "artifact" | "producer",
|
||||
path: string,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
if (
|
||||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled") ||
|
||||
(cause instanceof Error && cause.name === "AbortError")
|
||||
)
|
||||
return new AnalysisCancelledError("inspect_wasm_artifact", { cause });
|
||||
if (cause instanceof OwnedCommandFailure) {
|
||||
const capturedOutput =
|
||||
cause.snapshot === null
|
||||
? undefined
|
||||
: {
|
||||
stdout: cause.snapshot.stdout.text,
|
||||
stderr: cause.snapshot.stderr.text,
|
||||
truncated: cause.snapshot.diagnosticTruncated ?? false,
|
||||
};
|
||||
const options =
|
||||
capturedOutput === undefined ? { cause } : { cause, capturedOutput };
|
||||
if (cause.cleanupFailure !== null)
|
||||
return new ProviderCleanupError(
|
||||
WABT_PROVIDER_IDENTITY.id,
|
||||
cause.resources,
|
||||
{
|
||||
reason: cause.cleanupFailure,
|
||||
previous_error: reason,
|
||||
...(capturedOutput === undefined
|
||||
? {}
|
||||
: { captured_output: capturedOutput }),
|
||||
},
|
||||
{ operation: "inspect_wasm_artifact", cause },
|
||||
);
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError("inspect_wasm_artifact", options);
|
||||
if (cause.reason === "timeout")
|
||||
return new AnalysisTimeoutError(
|
||||
"inspect_wasm_artifact",
|
||||
WABT_LIMITS.timeoutMs,
|
||||
options,
|
||||
);
|
||||
if (phase === "configuration" && cause.reason === "process")
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
WABT_PROVIDER_IDENTITY.id,
|
||||
"inspect_wasm_artifact",
|
||||
reason,
|
||||
{
|
||||
...options,
|
||||
userMessage:
|
||||
"Configured WABT could not start. Check executable/interpreter access and WABT 1.0.42 profile; inspect retained diagnostics.",
|
||||
},
|
||||
);
|
||||
return new AnalysisOutputError("inspect_wasm_artifact", reason, options);
|
||||
}
|
||||
if (phase === "configuration")
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
WABT_PROVIDER_IDENTITY.id,
|
||||
"inspect_wasm_artifact",
|
||||
reason,
|
||||
{
|
||||
cause,
|
||||
userMessage: `${reason} Supply WABT 1.0.42 via absolute REA_WABT_BIN_DIRECTORY; REA does not install tools.`,
|
||||
},
|
||||
);
|
||||
if (
|
||||
phase === "artifact" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "integrity"
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
"inspect_wasm_artifact",
|
||||
path,
|
||||
reason,
|
||||
{ cause },
|
||||
);
|
||||
if (
|
||||
phase === "artifact" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(
|
||||
"inspect_wasm_artifact",
|
||||
path,
|
||||
cause.code,
|
||||
{ cause },
|
||||
);
|
||||
if (phase === "artifact")
|
||||
return new AnalysisInputError("inspect_wasm_artifact", { cause }, [
|
||||
{ path: ["path"], reason: "invalid_value", message: reason },
|
||||
]);
|
||||
return new AnalysisOutputError("inspect_wasm_artifact", reason, { cause });
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { expect, it } from "vitest";
|
||||
import { parseWabtOutput } from "./WabtOutput.js";
|
||||
import { parseWabtWat } from "./WabtWat.js";
|
||||
import { associateWasmGlue } from "./WasmGlueAdapter.js";
|
||||
const golden = () =>
|
||||
readFile(
|
||||
new URL("../../tests/fixtures/wasm/objdump.txt", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
it("retains real WABT section ranges, custom section identity and original header output", async () => {
|
||||
const text = await golden();
|
||||
const headers = text.slice(0, text.indexOf("Section Details:\n"));
|
||||
expect(parseWabtOutput(text, 76, ["test"]).sections).toHaveLength(7);
|
||||
expect(parseWabtOutput(text, 76, ["test"]).headers).toBe(headers);
|
||||
expect(parseWabtOutput(text, 76, ["test"]).sections.at(-1)).toEqual({
|
||||
kind: "Custom",
|
||||
start: 64,
|
||||
end: 76,
|
||||
bytes: 12,
|
||||
description: '"test"',
|
||||
});
|
||||
expect(() => parseWabtOutput(text, 75, ["test"])).toThrow(/ranges/u);
|
||||
expect(() =>
|
||||
parseWabtOutput(text.replace("size=0x0000000c", "size=0x0000000d"), 76, [
|
||||
"test",
|
||||
]),
|
||||
).toThrow(/ranges/u);
|
||||
expect(() =>
|
||||
parseWabtOutput(
|
||||
text.replace("\nSection Details:\n", "unexpected\nSection Details:\n"),
|
||||
76,
|
||||
["test"],
|
||||
),
|
||||
).toThrow(/Unrecognized/u);
|
||||
});
|
||||
it("extracts escaped WAT import/export forms while retaining multiline producer text", async () => {
|
||||
const text = await readFile(
|
||||
new URL("../../tests/fixtures/wasm/decoded.wat", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
expect(parseWabtWat(text)).toEqual({
|
||||
imports: ['(import "env" "foo" (func (;0;) (type 0)))'],
|
||||
exports: ['(export "memory" (memory 0))', '(export "run" (func 1))'],
|
||||
customSectionNames: ["test"],
|
||||
});
|
||||
expect(
|
||||
parseWabtWat(
|
||||
'(module (import "a.b" "c\\0aline" (func)) (export "fake\\22Export[1]:" (func 0)))',
|
||||
),
|
||||
).toEqual({
|
||||
imports: ['(import "a.b" "c\\0aline" (func))'],
|
||||
exports: ['(export "fake\\22Export[1]:" (func 0))'],
|
||||
customSectionNames: [],
|
||||
});
|
||||
expect(
|
||||
parseWabtWat(
|
||||
'(module (; nested (; comment ;) ;) ;; comment\n (export "x" (func 0)))',
|
||||
).exports,
|
||||
).toEqual(['(export "x" (func 0))']);
|
||||
expect(() => parseWabtWat('(module (export "unfinished"')).toThrow(
|
||||
/Incomplete/u,
|
||||
);
|
||||
expect(() => parseWabtWat("(module) unexpected")).toThrow(/Unexpected/u);
|
||||
});
|
||||
it("keeps exact local, ambiguous URL, computed and unparseable glue distinct", () => {
|
||||
const candidates = ["/app/module.wasm", "/other/module.wasm"];
|
||||
const result = associateWasmGlue(
|
||||
'fetch("./module.wasm"); new URL("https://example.com/module.wasm?x=1", import.meta.url); fetch(`module.wasm`); fetch(name + ".wasm");',
|
||||
"/app/glue.js",
|
||||
candidates,
|
||||
);
|
||||
expect(result.parse_status).toBe("complete");
|
||||
expect(result.references).toMatchObject([
|
||||
{
|
||||
value: "./module.wasm",
|
||||
association: "local-path-candidate",
|
||||
candidate_paths: ["/app/module.wasm"],
|
||||
},
|
||||
{
|
||||
value: "https://example.com/module.wasm?x=1",
|
||||
association: "basename-candidates",
|
||||
candidate_paths: candidates,
|
||||
},
|
||||
{ value: "module.wasm", association: "local-path-candidate" },
|
||||
{ value: ".wasm", association: "unresolved" },
|
||||
]);
|
||||
expect(associateWasmGlue("function (", "/glue.js", candidates)).toEqual({
|
||||
parse_status: "failed",
|
||||
references: [],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/** Frame WABT's raw custom names using the ordered names from its escaped WAT output. */
|
||||
export const parseWabtOutput = (
|
||||
text: string,
|
||||
artifactBytes: number,
|
||||
customSectionNames: readonly string[],
|
||||
) => {
|
||||
const prefix =
|
||||
/^\nmodule\.wasm:\tfile format wasm 0x1\n\nSections:\n\n/u.exec(text);
|
||||
if (prefix === null)
|
||||
throw new Error("Unsupported WABT section header format.");
|
||||
let offset = prefix[0].length;
|
||||
let customIndex = 0;
|
||||
const sections = [];
|
||||
while (!text.startsWith("\nSection Details:\n", offset)) {
|
||||
const match =
|
||||
/^[ \t]+(\w+) start=0x([\da-f]+) end=0x([\da-f]+) \(size=0x([\da-f]+)\) /u.exec(
|
||||
text.slice(offset),
|
||||
);
|
||||
if (match === null) throw new Error("Unrecognized WABT section row.");
|
||||
offset += match[0].length;
|
||||
let description: string;
|
||||
if (match[1] === "Custom") {
|
||||
const name = customSectionNames[customIndex++];
|
||||
if (name === undefined || !text.startsWith(`"${name}"\n`, offset))
|
||||
throw new Error(
|
||||
"WABT custom-section header does not match decoded WAT.",
|
||||
);
|
||||
description = `"${name}"`;
|
||||
offset += description.length + 1;
|
||||
} else {
|
||||
const end = text.indexOf("\n", offset);
|
||||
if (end < 0) throw new Error("Incomplete WABT section row.");
|
||||
description = text.slice(offset, end).trim();
|
||||
offset = end + 1;
|
||||
}
|
||||
const section = {
|
||||
kind: match[1] ?? "",
|
||||
start: Number.parseInt(match[2] ?? "", 16),
|
||||
end: Number.parseInt(match[3] ?? "", 16),
|
||||
bytes: Number.parseInt(match[4] ?? "", 16),
|
||||
description,
|
||||
};
|
||||
if (
|
||||
section.end > artifactBytes ||
|
||||
section.end - section.start !== section.bytes ||
|
||||
section.start < 8 ||
|
||||
section.start < (sections.at(-1)?.end ?? 8)
|
||||
)
|
||||
throw new Error("WABT section ranges do not match selected artifact.");
|
||||
sections.push(section);
|
||||
}
|
||||
if (customIndex !== customSectionNames.length)
|
||||
throw new Error(
|
||||
"WABT custom-section inventory does not match decoded WAT.",
|
||||
);
|
||||
if ((sections.at(-1)?.end ?? 8) !== artifactBytes)
|
||||
throw new Error(
|
||||
"WABT section output does not cover the selected artifact.",
|
||||
);
|
||||
const separator = offset + 1;
|
||||
return {
|
||||
sections,
|
||||
headers: text.slice(0, separator),
|
||||
details: `module.wasm:\tfile format wasm 0x1\n\n${text.slice(separator)}`,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Exact upstream release whose producer output is admitted by this adapter. */
|
||||
export const WABT_PROVIDER_IDENTITY = {
|
||||
id: "wabt-artifact",
|
||||
name: "REA WABT artifact adapter",
|
||||
version: "wabt@1.0.42",
|
||||
} as const;
|
||||
export const WABT_LIMITS = {
|
||||
inputBytes: 8 * 1024 * 1024,
|
||||
toolBytes: 64 * 1024 * 1024,
|
||||
outputBytes: 32 * 1024 * 1024,
|
||||
timeoutMs: 30_000,
|
||||
} as const;
|
||||
@@ -0,0 +1,124 @@
|
||||
/** Decode only a producer custom-section name to frame objdump's raw display text. */
|
||||
const customSectionName = (form: string): string => {
|
||||
const prefix = /^\(@custom\s+"/u.exec(form);
|
||||
if (prefix === null) throw new Error("Unsupported WABT custom-section name.");
|
||||
const start = prefix[0].length;
|
||||
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 new TextDecoder("utf-8", { fatal: true }).decode(
|
||||
bytes.subarray(0, length),
|
||||
);
|
||||
};
|
||||
|
||||
/** Extract exact top-level WABT WAT forms; no binary decoding or import/export name unescaping. */
|
||||
export const parseWabtWat = (text: string) => {
|
||||
if (!/^\(module(?:\s|\))/u.test(text))
|
||||
throw new Error("Unsupported WABT WAT module prefix.");
|
||||
const imports: string[] = [];
|
||||
const exports: string[] = [];
|
||||
const customSectionNames: string[] = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
let quoted = false;
|
||||
let commentDepth = 0;
|
||||
let lineComment = false;
|
||||
let closed = false;
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
const char = text[index];
|
||||
const next = text[index + 1];
|
||||
if (lineComment) {
|
||||
if (char === "\n") lineComment = false;
|
||||
continue;
|
||||
}
|
||||
if (quoted) {
|
||||
if (char === "\\") index++;
|
||||
else if (char === '"') quoted = false;
|
||||
continue;
|
||||
}
|
||||
if (commentDepth > 0) {
|
||||
if (char === "(" && next === ";") {
|
||||
commentDepth++;
|
||||
index++;
|
||||
} else if (char === ";" && next === ")") {
|
||||
commentDepth--;
|
||||
index++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (char === ";" && next === ";") {
|
||||
lineComment = true;
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
if (char === "(" && next === ";") {
|
||||
commentDepth++;
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
if (char === '"') {
|
||||
if (depth === 0)
|
||||
throw new Error("Unexpected string outside WABT WAT module.");
|
||||
quoted = true;
|
||||
continue;
|
||||
}
|
||||
if (char === "(") {
|
||||
if (closed) throw new Error("Unexpected second WABT WAT module.");
|
||||
depth++;
|
||||
if (depth === 2) start = index;
|
||||
} else if (char === ")") {
|
||||
if (depth === 2) {
|
||||
const form = text.slice(start, index + 1);
|
||||
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))
|
||||
customSectionNames.push(customSectionName(form));
|
||||
}
|
||||
if (--depth < 0) throw new Error("Unbalanced WABT WAT output.");
|
||||
if (depth === 0) closed = true;
|
||||
} else if (depth === 0 && char !== undefined && !/\s/u.test(char))
|
||||
throw new Error("Unexpected text outside WABT WAT module.");
|
||||
}
|
||||
if (depth !== 0 || quoted || commentDepth !== 0)
|
||||
throw new Error("Incomplete WABT WAT output.");
|
||||
return { imports, exports, customSectionNames };
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { basename, dirname, resolve } from "node:path";
|
||||
import * as t from "@babel/types";
|
||||
import { parseJavaScriptSource } from "../domain/javascript/javascriptSourceParser.js";
|
||||
import { traverseJavaScriptAst } from "../domain/javascript/javascriptSemanticTraversal.js";
|
||||
/** Associate visible literals with selected candidates without asserting data flow or URL identity. */
|
||||
export const associateWasmGlue = (
|
||||
source: string,
|
||||
path: string,
|
||||
candidates: readonly string[],
|
||||
) => {
|
||||
const file = parseJavaScriptSource(source);
|
||||
const references: {
|
||||
value: string;
|
||||
line: number;
|
||||
column: number;
|
||||
candidate_paths: string[];
|
||||
association: "local-path-candidate" | "basename-candidates" | "unresolved";
|
||||
evidence_kind: "static-literal";
|
||||
}[] = [];
|
||||
if (file === null) return { parse_status: "failed" as const, references };
|
||||
traverseJavaScriptAst(file, {
|
||||
enter(node) {
|
||||
const value = t.isStringLiteral(node)
|
||||
? node.value
|
||||
: t.isTemplateLiteral(node) && node.expressions.length === 0
|
||||
? node.quasis[0]?.value.cooked
|
||||
: undefined;
|
||||
if (
|
||||
value === undefined ||
|
||||
value === null ||
|
||||
!/\.wasm(?:[?#].*)?$/iu.test(value) ||
|
||||
node.loc == null
|
||||
)
|
||||
return;
|
||||
const stripped = value.split(/[?#]/u)[0] ?? value;
|
||||
const local =
|
||||
!/^[a-z][a-z\d+.-]*:|^\/\//iu.test(value) &&
|
||||
!value.startsWith("/") &&
|
||||
!/[?#]/u.test(value);
|
||||
const exact = local
|
||||
? candidates.filter(
|
||||
(candidate) => candidate === resolve(dirname(path), value),
|
||||
)
|
||||
: [];
|
||||
const matches =
|
||||
exact.length > 0
|
||||
? exact
|
||||
: candidates.filter(
|
||||
(candidate) => basename(candidate) === basename(stripped),
|
||||
);
|
||||
references.push({
|
||||
value,
|
||||
line: node.loc.start.line,
|
||||
column: node.loc.start.column,
|
||||
candidate_paths: [...matches],
|
||||
association:
|
||||
exact.length > 0
|
||||
? "local-path-candidate"
|
||||
: matches.length > 0
|
||||
? "basename-candidates"
|
||||
: "unresolved",
|
||||
evidence_kind: "static-literal",
|
||||
});
|
||||
},
|
||||
});
|
||||
return {
|
||||
parse_status:
|
||||
file.errors.length === 0 ? ("complete" as const) : ("partial" as const),
|
||||
references,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user