chore: merge main into feat/dyld-shared-cache

This commit is contained in:
morluto
2026-10-08 17:02:53 +08:00
85 changed files with 5854 additions and 1121 deletions
+9
View File
@@ -35,6 +35,7 @@ export type AvailabilityPolicy = {
readonly processCaptureEnabled: boolean;
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
readonly binaryLayoutEnabled?: boolean;
readonly recordedCrashEnabled?: boolean;
readonly firmwareInspectionEnabled?: boolean;
readonly firmwareExtractionEnabled?: boolean;
readonly androidAnalysisEnabled?: boolean;
@@ -298,6 +299,14 @@ const workflowAvailabilityFor = ({
remediation:
"The bundled offline EVM interface profile is currently real-verified on Linux x64. No active binary target or chain endpoint is required.",
};
if (name === "inspect_recorded_crash")
return policy.recordedCrashEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
};
if (kind === "firmware-provider") {
const enabled =
name === "inspect_firmware_regions"
@@ -0,0 +1,19 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
InspectRecordedCrashInput,
RecordedCrash,
} from "../../domain/native/recordedCrash.js";
import type { Result } from "../../domain/result.js";
/** Replaceable decoder of supplied recordings; historical PID is never live authority. */
export interface RecordedCrashPort {
readonly identity: ProviderIdentity;
inspect(
input: InspectRecordedCrashInput,
options?: ExecutionOptions,
): Promise<Result<RecordedCrash, AnalysisError>>;
}
@@ -0,0 +1,148 @@
import { expect, it } from "vitest";
import { RecordedCrashService } from "./RecordedCrashService.js";
import {
recordedCrashFixture,
RECORDED_CRASH_TEST_PROVIDER,
recordedCrashDebuggerFixture,
} from "../../../tests/fixtures/binaryDiagnostics/recordedCrash.js";
import { parseEvidence } from "../../domain/evidence.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err, ok } from "../../domain/result.js";
it("binds original bytes, inline observations, unknowns and producing identity", async () => {
const fixture = recordedCrashFixture();
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
const result = await service.inspect({ path: fixture.artifact.path });
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(fixture);
expect(evidence.raw_result).toEqual(fixture);
expect(evidence.subject?.digest.sha256).toBe(fixture.artifact.sha256);
expect(evidence.provider).toEqual(RECORDED_CRASH_TEST_PROVIDER);
expect(evidence.confidence).toBe("observed");
});
it("labels an envelope containing debugger-derived maps as derived", async () => {
const fixture = recordedCrashFixture();
fixture.debugger = recordedCrashDebuggerFixture();
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
const result = await service.inspect({
path: fixture.artifact.path,
include_debugger_context: true,
});
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.confidence).toBe("derived");
expect(evidence.normalized_result).toEqual(fixture);
});
it.each([
{ path: "relative.elf" },
{ path: "/selected.core", approval: true },
{ path: 123 },
{},
])(
"rejects malformed selection before starting the provider: %j",
async (input) => {
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
},
});
expect(await service.inspect(input)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
},
);
it("preserves a provider's actionable unsupported reason", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"fixture-recorded-crash",
"inspect_recorded_crash",
"ELF core belongs to recorded-crash analysis.",
);
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(err(failure)),
});
expect(await service.inspect({ path: "/source.elf" })).toEqual(err(failure));
});
it("cancels before invocation and after an acquired observation", async () => {
const controller = new AbortController();
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => {
controller.abort();
return Promise.resolve(ok(recordedCrashFixture()));
},
});
expect(
await service.inspect(
{ path: "/artifacts/source-owned.core" },
{ signal: controller.signal },
),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
capturedOutput: recordedCrashFixture().diagnostics,
},
});
const untouched = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
},
});
expect(
await untouched.inspect(
{ path: "/source.elf" },
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
});
it.each(["different-path", "invalid-digest", "outside-range"])(
"rejects provider evidence at the next boundary: %s",
async (problem) => {
const fixture = recordedCrashFixture();
if (problem === "different-path") fixture.artifact.path = "/different.elf";
if (problem === "invalid-digest") fixture.artifact.sha256 = "unobserved";
if (problem === "outside-range")
fixture.segments.push({
index: 0,
type: "PT_LOAD",
offset: "0x200",
header_location: { offset: "0x0", bytes: "0x38" },
file_backing: "file",
file_size: "0x1",
memory_size: "0x1",
virtual_address: "0x20000000000001",
physical_address: "0x0",
alignment: "0x1",
flags: "0x5",
});
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
expect(
await service.inspect({ path: "/artifacts/source-owned.core" }),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
capturedOutput: fixture.diagnostics,
},
});
},
);
@@ -0,0 +1,97 @@
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { RecordedCrashPort } from "./RecordedCrashPort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
inspectRecordedCrashInputSchema,
recordedCrashSchema,
} from "../../domain/native/recordedCrash.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
const OPERATION = "inspect_recorded_crash";
/** Shared CLI/MCP validation and Evidence composition for recorded crash inspection. */
export class RecordedCrashService {
constructor(readonly provider: RecordedCrashPort) {}
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectRecordedCrashInputSchema.safeParse(rawInput);
if (!input.success)
return err(
new AnalysisInputError(
OPERATION,
{ cause: input.error },
projectInputIssues(input.error.issues, rawInput),
),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
const diagnostics = recordedCrashSchema.shape.diagnostics.safeParse(
inspected.value.diagnostics,
);
const outputOptions = diagnostics.success
? { capturedOutput: diagnostics.data }
: undefined;
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION, outputOptions));
const report = recordedCrashSchema.safeParse(inspected.value);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
(report.data.debugger.status === "available") !==
input.data.include_debugger_context
)
return err(
new AnalysisOutputError(
OPERATION,
"Recorded crash provider returned malformed evidence or changed the selected artifact identity.",
outputOptions,
),
);
const value = report.data;
return ok(
createEvidence(
{
path: value.artifact.path,
format: "elf",
architecture: "x86_64",
sha256: value.artifact.sha256,
},
this.provider.identity,
{
operation: OPERATION,
parameters: input.data,
result: value,
rawResult: value,
confidence:
value.debugger.status === "available" ? "derived" : "observed",
limitations: value.limitations,
locations: [{ kind: "artifact-path", path: value.artifact.path }],
},
),
);
}
}
@@ -1,7 +1,7 @@
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
import type { ElectronIpcFinding } from "../../domain/javascript/electronStaticAnalysisTypes.js";
import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
@@ -27,7 +27,7 @@ export interface ElectronIpcPairingState {
/** Flatten all per-file IPC facts into deterministic application records. */
export const collectElectronIpcRecords = (
analysis: JavaScriptArtifactAnalysis,
analysis: JavaScriptModuleArtifactAnalysis,
): readonly ElectronIpcRecord[] =>
analysis.files
.flatMap(({ file, javascript }) =>
@@ -79,7 +79,7 @@ export const unambiguousElectronIpcPairings = (
/** Summarize static Electron findings without treating gaps as absence. */
export const summarizeElectronBoundaries = (
analysis: JavaScriptArtifactAnalysis,
analysis: JavaScriptModuleArtifactAnalysis,
): ElectronBoundarySummary => {
const files = new Map(analysis.files.map(({ file }) => [file.path, file]));
const javascript = analysis.files.flatMap(({ javascript: value }) =>
@@ -7,7 +7,6 @@ import type {
AnalyzeJavaScriptApplicationInput,
JavaScriptApplicationAnalysisResult,
} from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { JAVASCRIPT_APPLICATION_PROVIDER } from "../InvestigationProviders.js";
/** Create Evidence for one deterministic local JavaScript application graph. */
@@ -26,7 +25,7 @@ export const createJavaScriptApplicationEvidence = (
predicateType: "rea.javascript-application-analysis",
operation: "analyze_javascript_application",
parameters: parameters(input),
result: jsonValueSchema.parse(result),
result,
rawResult: null,
confidence: "derived",
authority: "shipped-artifact",
@@ -1,7 +1,9 @@
import { createHash } from "node:crypto";
import { setImmediate } from "node:timers/promises";
import { analyzeParsedJavaScriptStaticSource } from "../../domain/javascript/javascriptStaticAnalysis.js";
import { analyzeParsedJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
import { hasValidSourceMapContents } from "../../domain/sourceMapContents.js";
import { flattenSourceMapLeaves } from "../../domain/sourceMapEnvelope.js";
@@ -18,6 +20,8 @@ import type {
import type {
AnalyzedJavaScriptArtifactFile,
JavaScriptArtifactAnalysis,
JavaScriptModuleArtifactAnalysis,
JavaScriptModuleSemanticIr,
JavaScriptHtmlScriptObservation,
JavaScriptJsonModuleObservation,
JavaScriptPackageObservation,
@@ -27,8 +31,10 @@ import type {
import { analyzeJavaScriptJsonModule } from "./JavaScriptJsonModules.js";
import { htmlArtifactReferences } from "../../domain/javascript/htmlArtifactReferences.js";
interface MutableArtifactAnalysis {
readonly files: AnalyzedJavaScriptArtifactFile[];
interface MutableArtifactAnalysis<
SemanticIr extends JavaScriptModuleSemanticIr,
> {
readonly files: AnalyzedJavaScriptArtifactFile<SemanticIr>[];
readonly packages: JavaScriptPackageObservation[];
readonly jsonModules: JavaScriptJsonModuleObservation[];
readonly htmlScripts: JavaScriptHtmlScriptObservation[];
@@ -40,23 +46,88 @@ interface MutableArtifactAnalysis {
truncatedScopes: number;
}
interface ArtifactAnalysisContext {
readonly state: MutableArtifactAnalysis;
interface ArtifactAnalysisContext<
SemanticIr extends JavaScriptModuleSemanticIr,
> {
readonly state: MutableArtifactAnalysis<SemanticIr>;
readonly projectSemantics: (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
) => SemanticIr;
}
/** Analyze every text source from the artifact without a result quota. */
export const analyzeJavaScriptArtifactFiles = (
fileSet: JavaScriptArtifactFileSet,
): JavaScriptArtifactAnalysis => {
const state = emptyArtifactAnalysis();
const context = { state };
): JavaScriptArtifactAnalysis =>
analyzeArtifactFiles(fileSet, (_file, ir) => ir);
/** Project each file's full IR immediately, retaining only later module facts. */
export const analyzeAndProjectJavaScriptArtifactFiles = async (
fileSet: JavaScriptArtifactFileSet,
projectSemantics: (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
) => void,
beforeFile?: (
file: JavaScriptArtifactFile,
completed: number,
total: number,
) => Promise<void>,
): Promise<JavaScriptModuleArtifactAnalysis> => {
const state = emptyArtifactAnalysis<JavaScriptModuleSemanticIr>();
const projectFileSemantics = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
): JavaScriptModuleSemanticIr => {
projectSemantics(file, ir);
const programScopes = ir.scopes.filter(({ kind }) => kind === "program");
const programScopeId = programScopes[0]?.scopeId;
const localNames = new Set(
ir.moduleLinks.map(({ localName }) => localName),
);
const callableIds = new Set(
ir.moduleLinks.map(({ callableId }) => callableId),
);
return {
scopes: programScopes,
bindings: ir.bindings.filter(
({ name, scopeId }) =>
scopeId === programScopeId && localNames.has(name),
),
callables: ir.callables.filter(({ callableId }) =>
callableIds.has(callableId),
),
moduleLinks: ir.moduleLinks,
coverage: ir.coverage,
limitations: ir.limitations,
};
};
const context = { state, projectSemantics: projectFileSemantics };
for (const [index, file] of fileSet.files.entries()) {
// Let progress, cancellation and garbage collection run between files.
await setImmediate();
await beforeFile?.(file, index, fileSet.files.length);
analyzeArtifactFile(file, context);
}
return finalizeArtifactAnalysis(state);
};
const analyzeArtifactFiles = <SemanticIr extends JavaScriptModuleSemanticIr>(
fileSet: JavaScriptArtifactFileSet,
projectSemantics: ArtifactAnalysisContext<SemanticIr>["projectSemantics"],
): JavaScriptArtifactAnalysis<SemanticIr> => {
const state = emptyArtifactAnalysis<SemanticIr>();
const context = { state, projectSemantics };
for (const file of fileSet.files) analyzeArtifactFile(file, context);
return finalizeArtifactAnalysis(state);
};
const finalizeArtifactAnalysis = (
state: MutableArtifactAnalysis,
): JavaScriptArtifactAnalysis => {
const finalizeArtifactAnalysis = <
SemanticIr extends JavaScriptModuleSemanticIr,
>(
state: MutableArtifactAnalysis<SemanticIr>,
): JavaScriptArtifactAnalysis<SemanticIr> => {
const truncatedScopes = state.truncatedScopes;
return {
files: state.files,
@@ -79,9 +150,9 @@ const finalizeArtifactAnalysis = (
};
};
const analyzeArtifactFile = (
const analyzeArtifactFile = <SemanticIr extends JavaScriptModuleSemanticIr>(
file: JavaScriptArtifactFile,
context: ArtifactAnalysisContext,
context: ArtifactAnalysisContext<SemanticIr>,
): void => {
const { state } = context;
addStructuredObservations(file, state);
@@ -108,7 +179,10 @@ const analyzeArtifactFile = (
state.files.push({
file,
javascript: analysis,
semantic: semantics === null ? null : { ir: semantics },
semantic:
semantics === null
? null
: { ir: context.projectSemantics(file, semantics) },
});
state.visitedNodes += analysis.visited_ast_nodes;
state.findings += staticFindings + (semantics?.moduleLinks.length ?? 0);
@@ -121,13 +195,15 @@ const analyzeArtifactFile = (
const addSourceMap = (
file: JavaScriptArtifactFile,
context: ArtifactAnalysisContext,
context: ArtifactAnalysisContext<JavaScriptModuleSemanticIr>,
): void => {
const sourceMap = parseSourceMap(file);
context.state.sourceMaps.push(sourceMap);
};
const emptyArtifactAnalysis = (): MutableArtifactAnalysis => ({
const emptyArtifactAnalysis = <
SemanticIr extends JavaScriptModuleSemanticIr,
>(): MutableArtifactAnalysis<SemanticIr> => ({
files: [],
packages: [],
jsonModules: [],
@@ -142,7 +218,7 @@ const emptyArtifactAnalysis = (): MutableArtifactAnalysis => ({
const addStructuredObservations = (
file: JavaScriptArtifactFile,
state: MutableArtifactAnalysis,
state: MutableArtifactAnalysis<JavaScriptModuleSemanticIr>,
): void => {
if (file.kind === "package-json") state.packages.push(parsePackage(file));
if (file.kind !== "json") return;
@@ -87,18 +87,33 @@ export type JavaScriptJsonModuleObservation = JavaScriptStructuredObservation &
}
);
/** Module facts needed after file-local semantic projection has finished. */
export type JavaScriptModuleSemanticIr = Pick<
JavaScriptSemanticIr,
| "scopes"
| "bindings"
| "callables"
| "moduleLinks"
| "coverage"
| "limitations"
>;
/** One relevant file plus optional AST-only JavaScript facts. */
export interface AnalyzedJavaScriptArtifactFile {
export interface AnalyzedJavaScriptArtifactFile<
SemanticIr extends JavaScriptModuleSemanticIr = JavaScriptSemanticIr,
> {
readonly file: JavaScriptArtifactFile;
readonly javascript: JavaScriptStaticAnalysis | null;
readonly semantic: {
readonly ir: JavaScriptSemanticIr;
readonly ir: SemanticIr;
} | null;
}
/** Complete static-analysis projection before graph construction. */
export interface JavaScriptArtifactAnalysis {
readonly files: readonly AnalyzedJavaScriptArtifactFile[];
export interface JavaScriptArtifactAnalysis<
SemanticIr extends JavaScriptModuleSemanticIr = JavaScriptSemanticIr,
> {
readonly files: readonly AnalyzedJavaScriptArtifactFile<SemanticIr>[];
readonly packages: readonly JavaScriptPackageObservation[];
readonly json_modules: readonly JavaScriptJsonModuleObservation[];
readonly html_scripts: readonly JavaScriptHtmlScriptObservation[];
@@ -110,3 +125,7 @@ export interface JavaScriptArtifactAnalysis {
readonly truncated_scopes: number;
readonly limitations: readonly string[];
}
/** Artifact facts retaining only semantics used by application relationships. */
export type JavaScriptModuleArtifactAnalysis =
JavaScriptArtifactAnalysis<JavaScriptModuleSemanticIr>;
@@ -3,7 +3,7 @@ import {
createJavaScriptApplicationGraph,
type JavaScriptApplicationGraph,
} from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFileSet } from "../../domain/javascript/javascriptArtifactFiles.js";
import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAccumulator.js";
import type { JavaScriptArtifactGraphContext } from "./JavaScriptArtifactGraphContext.js";
@@ -37,7 +37,7 @@ import {
export const buildJavaScriptArtifactGraph = (
snapshot: ArtifactInventorySnapshot,
fileSet: JavaScriptArtifactFileSet,
analysis: JavaScriptArtifactAnalysis,
analysis: JavaScriptModuleArtifactAnalysis,
): JavaScriptApplicationGraph => {
const accumulator = new JavaScriptArtifactGraphAccumulator();
const root = createJavaScriptArtifactRootNode(accumulator, snapshot);
@@ -6,7 +6,7 @@ import {
} from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type {
JavaScriptArtifactFile,
JavaScriptArtifactFileSet,
@@ -29,7 +29,7 @@ export interface JavaScriptArtifactGraphContext {
readonly accumulator: JavaScriptArtifactGraphAccumulator;
readonly snapshot: ArtifactInventorySnapshot;
readonly fileSet: JavaScriptArtifactFileSet;
readonly analysis: JavaScriptArtifactAnalysis;
readonly analysis: JavaScriptModuleArtifactAnalysis;
readonly root: ApplicationNode;
readonly filesByPath: ReadonlyMap<string, JavaScriptArtifactFile>;
readonly fileNodes: Map<string, ApplicationNode>;
@@ -209,7 +209,7 @@ export const addUnavailableStaticParseScope = (
/** Coverage for one bounded JavaScript AST analysis. */
export const javascriptAnalysisCoverage = (
analysis: NonNullable<
JavaScriptArtifactAnalysis["files"][number]["javascript"]
JavaScriptModuleArtifactAnalysis["files"][number]["javascript"]
>,
): JavaScriptArtifactGraphCoverage =>
analysis.parse_status === "complete"
@@ -1,7 +1,7 @@
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraph.js";
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type {
JavaScriptArtifactContainer,
JavaScriptArtifactFile,
@@ -270,7 +270,7 @@ export const addJavaScriptPackageNodes = (
const createFileTarget = (
context: JavaScriptArtifactGraphContext,
file: JavaScriptArtifactFile,
javascript: JavaScriptArtifactAnalysis["files"][number]["javascript"],
javascript: JavaScriptModuleArtifactAnalysis["files"][number]["javascript"],
): ApplicationNode => {
const kind = artifactFileNodeKind(file.kind);
const json = context.analysis.json_modules.find(
@@ -5,7 +5,7 @@ import { createJavaScriptArtifactReader as createReader } from "../../artifacts/
import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
import { analyzeAndProjectJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
import { readJavaScriptArtifactFiles } from "../../artifacts/javascript/JavaScriptArtifactFiles.js";
import { buildJavaScriptArtifactGraph } from "./JavaScriptArtifactGraphBuilder.js";
import {
@@ -14,7 +14,7 @@ import {
} from "./JavaScriptArtifactReconstructionInput.js";
import { scanCanonicalArtifactInventory } from "../../artifacts/inventory/ArtifactInventory.js";
import { summarizeElectronBoundaries } from "./ElectronBoundaryAnalysis.js";
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
import { createJavaScriptSemanticGraphProjection } from "./JavaScriptSemanticGraphBuilder.js";
import type { ProgressReporter } from "../ProgressReporter.js";
/** Application-layer result retaining local diagnostics outside the canonical graph. */
@@ -70,9 +70,23 @@ export const reconstructJavaScriptArtifact = async (
const files = await readJavaScriptArtifactFiles(reader, snapshot, signal);
await reportPhase(
"parse_javascript_sources",
`Parsing ${String(files.files.length)} application source files`,
`Parsing and projecting ${String(files.files.length)} application source files`,
);
const semanticProjection = createJavaScriptSemanticGraphProjection();
const analysis = await analyzeAndProjectJavaScriptArtifactFiles(
files,
semanticProjection.projectFile,
async (file, completed, total) => {
abortIfNeeded(signal);
await progress?.report({
phase: "parse_javascript_source",
completed: 0,
total: 1,
message: `Parsing and projecting ${file.path} (${String(completed + 1)}/${String(total)})`,
});
abortIfNeeded(signal);
},
);
const analysis = analyzeJavaScriptArtifactFiles(files);
abortIfNeeded(signal);
await reportPhase(
"build_javascript_application_graph",
@@ -81,13 +95,13 @@ export const reconstructJavaScriptArtifact = async (
const graph = buildJavaScriptArtifactGraph(snapshot, files, analysis);
await reportPhase(
"build_javascript_semantic_graph",
"Constructing static semantic relationships",
"Binding and validating static semantic relationships",
);
const semanticGraph = buildJavaScriptSemanticGraph({
rootArtifactSha256: snapshot.manifest.root_sha256,
applicationGraph: graph,
const semanticGraph = semanticProjection.finish(
snapshot.manifest.root_sha256,
graph,
analysis,
});
);
return {
input_path: path,
format,
@@ -8,7 +8,6 @@ import {
} from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type {
JavaScriptModuleOrigin,
JavaScriptSemanticIr,
JavaScriptSemanticModuleLink,
} from "../../domain/javascript/javascriptSemanticIr.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -28,8 +27,10 @@ import {
} from "./JavaScriptArtifactPathResolution.js";
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
import type { JavaScriptModuleSemanticIr } from "./JavaScriptArtifactAnalysisTypes.js";
interface SemanticAnalysis {
readonly ir: JavaScriptSemanticIr;
readonly ir: JavaScriptModuleSemanticIr;
}
interface RelationshipInput {
@@ -310,7 +311,7 @@ const unresolvedModuleNode = (
});
const moduleOriginForExport = (
ir: JavaScriptSemanticIr,
ir: JavaScriptModuleSemanticIr,
link: JavaScriptSemanticModuleLink,
): JavaScriptModuleOrigin | null => {
if (link.specifier !== null)
@@ -374,7 +375,7 @@ const semanticCoverage = (
const moduleFormat = (
path: string,
ir: JavaScriptSemanticIr,
ir: JavaScriptModuleSemanticIr,
): "commonjs" | "esm" | "mixed" | "unknown" => {
const extension = posix.extname(path).toLowerCase();
if (extension === ".mjs") return "esm";
@@ -4,13 +4,13 @@ import {
truncatedApplicationCoverage,
} from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type {
JavaScriptSemanticIr,
JavaScriptSemanticCallable,
JavaScriptSemanticModuleLink,
} from "../../domain/javascript/javascriptSemanticIr.js";
import { flattenSemanticReturnValue } from "../../domain/javascript/javascriptSemanticReturns.js";
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactGraphCoverage } from "./JavaScriptArtifactGraphContext.js";
import type { JavaScriptModuleSemanticIr } from "./JavaScriptArtifactAnalysisTypes.js";
export interface JavaScriptReturnShapeProjection {
readonly properties: ReturnType<typeof jsonObjectSchema.parse>;
@@ -21,7 +21,7 @@ export interface JavaScriptReturnShapeProjection {
/** Project one exact export/callable link into shallow bounded graph values. */
export const projectJavaScriptExportReturnShapes = (input: {
readonly ir: JavaScriptSemanticIr;
readonly ir: JavaScriptModuleSemanticIr;
readonly link: JavaScriptSemanticModuleLink;
readonly modulePath: string;
readonly baseCoverage: JavaScriptArtifactGraphCoverage;
@@ -5,10 +5,9 @@ import type {
JavaScriptSemanticTimerOperation,
} from "../../domain/javascript/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
@@ -59,55 +58,41 @@ const addEventNode = (
operation: JavaScriptSemanticEventOperation,
eventKey: string,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "event",
roleKey: `event:${eventKey}`,
location: operation.eventName === null ? operation.location : null,
label: operation.eventName,
functionNodeId: null,
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "event",
roleKey: `event:${eventKey}`,
location: operation.eventName === null ? operation.location : null,
label: operation.eventName,
functionNodeId: null,
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
},
});
const addListenerNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "listener",
roleKey: `listener:${operation.eventId}`,
location: operation.listenerLocation ?? operation.location,
label:
operation.eventName === null
? operation.method
: `${operation.method}:${operation.eventName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
method: operation.method,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "listener",
roleKey: `listener:${operation.eventId}`,
location: operation.listenerLocation ?? operation.location,
label:
operation.eventName === null
? operation.method
: `${operation.method}:${operation.eventName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
method: operation.method,
},
});
const eventEmitterNode = (
context: SemanticFlowProjectionContext,
@@ -164,24 +149,17 @@ export const projectSemanticTimers = (
operation.ownerCallableId === null
? undefined
: context.callableNodes.get(operation.ownerCallableId);
const timer = addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "timer",
roleKey: operation.timerId,
location: operation.location,
label: operation.method,
functionNodeId: owner?.node_id ?? null,
properties: {
delay_milliseconds: operation.delayMilliseconds,
method: operation.method,
},
},
context.state,
),
);
const timer = retainSemanticGraphNode(context.state, context.file, {
kind: "timer",
roleKey: operation.timerId,
location: operation.location,
label: operation.method,
functionNodeId: owner?.node_id ?? null,
properties: {
delay_milliseconds: operation.delayMilliseconds,
method: operation.method,
},
});
return timer === null ? [] : [[operation.timerId, timer] as const];
}),
);
@@ -38,16 +38,17 @@ import {
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
import {
owningSemanticCallableNode,
createSemanticCallableOwnerLookup,
createSemanticCallSiteLookup,
createSemanticNodeRangeLookup,
semanticFamilyStatus,
semanticNodesWithinRange,
} from "./JavaScriptSemanticGraphProjection.js";
import {
addSemanticFallbackRoot as addFallbackRoot,
addSemanticGraphNode as addNode,
retainSemanticGraphNode as retainNode,
addSemanticGraphRelation as addRelation,
constructSemanticGraphNode as semanticNode,
createSemanticGraphProjectionState as emptyState,
bindSemanticGraphApplicationNodes,
type SemanticGraphProjectionState as BuilderState,
} from "./JavaScriptSemanticGraphConstruction.js";
@@ -72,6 +73,9 @@ interface FileContext extends SemanticFlowProjectionContext {
readonly argumentNodes: Map<string, JavaScriptSemanticGraphNode>;
readonly referenceNodes: JavaScriptSemanticGraphNode[];
readonly callResolutions: ReadonlyMap<string, "candidate" | "resolved">;
readonly callableOwnerAt: ReturnType<
typeof createSemanticCallableOwnerLookup
>;
}
/**
@@ -108,152 +112,170 @@ export const buildJavaScriptSemanticGraph = ({
applicationGraph,
analysis,
}: BuilderInput): JavaScriptSemanticGraph => {
const state = emptyState(applicationGraph);
const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
let truncatedFiles = 0;
const projection = createJavaScriptSemanticGraphProjection();
for (const analyzed of analysis.files) {
if (analyzed.semantic === null) continue;
if (state.nodes.size >= SEMANTIC_GRAPH_NODE_CEILING) {
truncatedFiles += 1;
continue;
}
const remainingTreeBudget = SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size;
state.fileNodeBudget = Math.min(
SEMANTIC_GRAPH_FILE_NODE_CEILING,
remainingTreeBudget,
);
state.fileNodesDropped = false;
fingerprints.push(
...projectFile(analyzed.file, analyzed.semantic.ir, state),
);
// Nodes were dropped only if the budget actually blocked creation. A file
// that exactly fills its share ends with a zero budget without dropping
// anything, so the remaining budget alone cannot decide truncation.
if (state.fileNodesDropped) truncatedFiles += 1;
state.fileNodeBudget = null;
if (analyzed.semantic !== null)
projection.projectFile(analyzed.file, analyzed.semantic.ir);
}
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const unknowns = [...state.unknowns.values()];
return createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
root_artifact_sha256: rootArtifactSha256,
application_graph_id: applicationGraph.graph_id,
root_node_ids: [...state.roots],
nodes: [...state.nodes.values()],
relations: [...state.relations.values()],
fingerprints,
unknowns,
coverage: {
status: truncatedFiles > 0 ? "partial" : "unknown",
truncated: truncatedFiles > 0,
omitted_nodes: truncatedFiles > 0 ? null : 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
limits:
truncatedFiles > 0
? [
{
name: "semantic_graph_node_ceiling",
value: SEMANTIC_GRAPH_NODE_CEILING,
unit: "items" as const,
},
]
: [],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: semanticFamilyStatus(family, analysis),
retained_relations: [...state.relations.values()].filter(
(relation) =>
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] === family,
).length,
omitted_relations: truncatedFiles > 0 ? null : 0,
unknown_ids: unknowns
.filter((unknown) => unknown.family === family)
.map(({ unknown_id: identifier }) => identifier),
})),
},
limitations: [
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
"Local data flow does not claim control-flow-sensitive reaching definitions or arbitrary dynamic property resolution.",
"Promise ownership covers explicit unshadowed Promise construction, static factories, aggregation, chaining, and await syntax only.",
"Function fingerprints are static candidates; equal digests can remain ambiguous and do not prove behavioral equivalence.",
"Event extraction covers EventEmitter-style literal registrations, removals, and dispatch candidates; dynamic names remain unknown.",
"Timer extraction covers global or node:timers scheduling and exact local-handle cancellation.",
"Child-process extraction covers asynchronous node:child_process creation, literal argv/env/stdio options, exit/error listeners, and kill signals.",
"Configuration extraction covers process.env, process.argv, node:fs reads, and direct logical defaults.",
"Request extraction covers fetch, WebSocket, node:http/node:https construction, direct option fields, and exact local response consumers.",
"Boundary extraction covers unshadowed JSON/global coercions plus parse and validation method candidates.",
"Resource extraction covers built-in filesystem/network acquisition and exact local close/destroy/end handles.",
],
});
return projection.finish(rootArtifactSha256, applicationGraph, analysis);
};
/** File-local semantic projection that does not retain consumed source IR. */
export interface JavaScriptSemanticGraphProjection {
readonly projectFile: (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
) => void;
readonly finish: (
rootArtifactSha256: string,
applicationGraph: BuilderInput["applicationGraph"],
analysis: Pick<JavaScriptArtifactAnalysis, "truncated_scopes">,
) => JavaScriptSemanticGraph;
}
/** Accumulate semantic nodes while each source IR is still file-local. */
export const createJavaScriptSemanticGraphProjection =
(): JavaScriptSemanticGraphProjection => {
const state = emptyState({ nodes: [] });
const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
let truncatedFiles = 0;
const projectSource = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
): void => {
if (state.nodes.size >= SEMANTIC_GRAPH_NODE_CEILING) {
truncatedFiles += 1;
return;
}
const remainingTreeBudget =
SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size;
state.fileNodeBudget = Math.min(
SEMANTIC_GRAPH_FILE_NODE_CEILING,
remainingTreeBudget,
);
state.fileNodesDropped = false;
fingerprints.push(...projectFile(file, ir, state));
// Nodes were dropped only if the budget actually blocked creation. A file
// that exactly fills its share ends with a zero budget without dropping
// anything, so the remaining budget alone cannot decide truncation.
if (state.fileNodesDropped) truncatedFiles += 1;
state.fileNodeBudget = null;
};
return {
projectFile: projectSource,
finish: (rootArtifactSha256, applicationGraph, analysis) => {
bindSemanticGraphApplicationNodes(state, applicationGraph);
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const unknowns = [...state.unknowns.values()];
const graph = createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
root_artifact_sha256: rootArtifactSha256,
application_graph_id: applicationGraph.graph_id,
root_node_ids: [...state.roots],
nodes: [...state.nodes.values()],
relations: [...state.relations.values()],
fingerprints,
unknowns,
coverage: {
status: truncatedFiles > 0 ? "partial" : "unknown",
truncated: truncatedFiles > 0,
omitted_nodes: truncatedFiles > 0 ? null : 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
limits:
truncatedFiles > 0
? [
{
name: "semantic_graph_node_ceiling",
value: SEMANTIC_GRAPH_NODE_CEILING,
unit: "items" as const,
},
]
: [],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: semanticFamilyStatus(family, analysis),
retained_relations: [...state.relations.values()].filter(
(relation) =>
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] ===
family,
).length,
omitted_relations: truncatedFiles > 0 ? null : 0,
unknown_ids: unknowns
.filter((unknown) => unknown.family === family)
.map(({ unknown_id: identifier }) => identifier),
})),
},
limitations: [
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
"Local data flow does not claim control-flow-sensitive reaching definitions or arbitrary dynamic property resolution.",
"Promise ownership covers explicit unshadowed Promise construction, static factories, aggregation, chaining, and await syntax only.",
"Function fingerprints are static candidates; equal digests can remain ambiguous and do not prove behavioral equivalence.",
"Event extraction covers EventEmitter-style literal registrations, removals, and dispatch candidates; dynamic names remain unknown.",
"Timer extraction covers global or node:timers scheduling and exact local-handle cancellation.",
"Child-process extraction covers asynchronous node:child_process creation, literal argv/env/stdio options, exit/error listeners, and kill signals.",
"Configuration extraction covers process.env, process.argv, node:fs reads, and direct logical defaults.",
"Request extraction covers fetch, WebSocket, node:http/node:https construction, direct option fields, and exact local response consumers.",
"Boundary extraction covers unshadowed JSON/global coercions plus parse and validation method candidates.",
"Resource extraction covers built-in filesystem/network acquisition and exact local close/destroy/end handles.",
],
});
state.nodes.clear();
state.relations.clear();
state.unknowns.clear();
state.roots.clear();
fingerprints.length = 0;
return graph;
},
};
};
const projectFile = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
state: BuilderState,
): JavaScriptSemanticGraph["fingerprints"][number][] => {
const moduleNode = addNode(
state,
semanticNode(
file,
{
kind: "module",
roleKey: "module",
location: null,
label: file.path,
functionNodeId: null,
},
state,
),
);
const moduleNode = retainNode(state, file, {
kind: "module",
roleKey: "module",
location: null,
label: file.path,
functionNodeId: null,
});
if (moduleNode === null) return [];
state.roots.add(moduleNode.node_id);
const callableNodes = new Map(
ir.callables.flatMap((callable) => {
const node = addNode(
state,
semanticNode(
file,
{
kind: "function",
roleKey: `callable:${callable.callableId}`,
location: callable.location,
label: callable.name,
functionNodeId: null,
// The label is display text; keep the exact name, which may be "".
properties: { name: callable.name },
},
state,
),
);
const node = retainNode(state, file, {
kind: "function",
roleKey: `callable:${callable.callableId}`,
location: callable.location,
label: callable.name,
functionNodeId: null,
// The label is display text; keep the exact name, which may be "".
properties: { name: callable.name },
});
return node === null ? [] : [[callable.callableId, node] as const];
}),
);
const callableOwnerAt = createSemanticCallableOwnerLookup(ir, callableNodes);
const bindingNodes = new Map(
ir.bindings.flatMap((binding) => {
const location = binding.definitions[0]?.location ?? null;
const kind = binding.kind === "parameter" ? "parameter" : "binding";
const owner = owningSemanticCallableNode(location, ir, callableNodes);
const node = addNode(
state,
semanticNode(
file,
{
kind,
roleKey: `binding:${binding.bindingId}`,
location,
label: binding.name,
functionNodeId: owner?.node_id ?? null,
},
state,
),
);
const owner = callableOwnerAt(location);
const node = retainNode(state, file, {
kind,
roleKey: `binding:${binding.bindingId}`,
location,
label: binding.name,
functionNodeId: owner?.node_id ?? null,
});
return node === null ? [] : [[binding.bindingId, node] as const];
}),
);
const returnSiteNodes = createReturnSiteNodes(file, ir, callableNodes, state);
const callSiteNodes = createCallSiteNodes(file, ir, callableNodes, state);
const context: FileContext = {
const definitions: Omit<FileContext, "referenceNodesWithin"> = {
file,
ir,
state,
@@ -270,8 +292,16 @@ const projectFile = (
call.resolution === "exact" ? "resolved" : "candidate",
]),
),
callableOwnerAt,
callSiteAt: createSemanticCallSiteLookup(ir, callSiteNodes),
};
projectDefinitionsAndReferences(definitions);
const context: FileContext = {
...definitions,
referenceNodesWithin: createSemanticNodeRangeLookup(
definitions.referenceNodes,
),
};
projectDefinitionsAndReferences(context);
projectSemanticValues(context);
projectSemanticObjects(context);
projectCalls(context);
@@ -300,20 +330,13 @@ const createReturnSiteNodes = (
if (owner === undefined) continue;
for (const site of callable.returnSites) {
const identifier = site.returnSiteId;
const node = addNode(
state,
semanticNode(
file,
{
kind: "return-site",
roleKey: identifier,
location: site.location,
label: "return",
functionNodeId: owner.node_id,
},
state,
),
);
const node = retainNode(state, file, {
kind: "return-site",
roleKey: identifier,
location: site.location,
label: "return",
functionNodeId: owner.node_id,
});
if (node !== null) result.set(identifier, node);
}
}
@@ -332,44 +355,32 @@ const createCallSiteNodes = (
call.callerCallableId === null
? null
: (callables.get(call.callerCallableId)?.node_id ?? null);
const node = addNode(
state,
semanticNode(
file,
{
kind: "call-site",
roleKey: `call:${call.callSiteId}`,
location: call.location,
label: call.kind,
functionNodeId: owner,
},
state,
),
);
const node = retainNode(state, file, {
kind: "call-site",
roleKey: `call:${call.callSiteId}`,
location: call.location,
label: call.kind,
functionNodeId: owner,
});
if (node !== null) result.set(call.callSiteId, node);
}
return result;
};
const projectDefinitionsAndReferences = (context: FileContext): void => {
const projectDefinitionsAndReferences = (
context: Omit<FileContext, "referenceNodesWithin">,
): void => {
for (const binding of context.ir.bindings) {
const bindingNode = context.bindingNodes.get(binding.bindingId);
if (bindingNode === undefined) continue;
for (const [index, definition] of binding.definitions.entries()) {
const definitionNode = addNode(
context.state,
semanticNode(
context.file,
{
kind: "expression",
roleKey: `definition:${binding.bindingId}:${String(index)}`,
location: definition.location,
label: definition.kind,
functionNodeId: bindingNode.function_node_id,
},
context.state,
),
);
const definitionNode = retainNode(context.state, context.file, {
kind: "expression",
roleKey: `definition:${binding.bindingId}:${String(index)}`,
location: definition.location,
label: definition.kind,
functionNodeId: bindingNode.function_node_id,
});
addRelation(context.state, {
source: definitionNode,
target: bindingNode,
@@ -379,25 +390,14 @@ const projectDefinitionsAndReferences = (context: FileContext): void => {
}
}
for (const [index, reference] of context.ir.references.entries()) {
const expression = addNode(
context.state,
semanticNode(
context.file,
{
kind: "expression",
roleKey: `reference:${String(index)}:${reference.role}:${reference.name}`,
location: reference.location,
label: reference.name,
functionNodeId:
owningSemanticCallableNode(
reference.location,
context.ir,
context.callableNodes,
)?.node_id ?? null,
},
context.state,
),
);
const expression = retainNode(context.state, context.file, {
kind: "expression",
roleKey: `reference:${String(index)}:${reference.role}:${reference.name}`,
location: reference.location,
label: reference.name,
functionNodeId:
context.callableOwnerAt(reference.location)?.node_id ?? null,
});
const binding =
reference.bindingId === null
? undefined
@@ -447,10 +447,7 @@ const projectCalls = (context: FileContext): void => {
`${call.callSiteId}\u0000${String(argument.index)}`,
argumentNode,
);
const references = semanticNodesWithinRange(
context.referenceNodes,
argument.location,
);
const references = context.referenceNodesWithin(argument.location);
for (const reference of references)
addRelation(context.state, {
source: reference,
@@ -499,19 +496,12 @@ const createArgumentNode = (
callSiteId: string,
argument: JavaScriptSemanticCallArgument,
): JavaScriptSemanticGraphNode | null =>
addNode(
context.state,
semanticNode(
context.file,
{
kind: "expression",
roleKey: `argument:${callSiteId}:${String(argument.index)}`,
location: argument.location,
label: argument.spread
? "spread argument"
: `argument ${String(argument.index)}`,
functionNodeId: callNode.function_node_id,
},
context.state,
),
);
retainNode(context.state, context.file, {
kind: "expression",
roleKey: `argument:${callSiteId}:${String(argument.index)}`,
location: argument.location,
label: argument.spread
? "spread argument"
: `argument ${String(argument.index)}`,
functionNodeId: callNode.function_node_id,
});
@@ -5,10 +5,9 @@ import type {
JavaScriptSemanticChildProcessSpawn,
} from "../../domain/javascript/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
@@ -53,31 +52,23 @@ const addChildProcessNode = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "child-process",
roleKey: spawn.processId,
location: spawn.location,
label: spawn.command ?? spawn.method,
functionNodeId:
spawn.ownerCallableId === null
? null
: (context.callableNodes.get(spawn.ownerCallableId)?.node_id ??
null),
properties: {
argv_count: spawn.argvCount,
command: spawn.command,
environment_supplied: spawn.environmentSupplied,
method: spawn.method,
stdio_mode: spawn.stdioMode,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "child-process",
roleKey: spawn.processId,
location: spawn.location,
label: spawn.command ?? spawn.method,
functionNodeId:
spawn.ownerCallableId === null
? null
: (context.callableNodes.get(spawn.ownerCallableId)?.node_id ?? null),
properties: {
argv_count: spawn.argvCount,
command: spawn.command,
environment_supplied: spawn.environmentSupplied,
method: spawn.method,
stdio_mode: spawn.stdioMode,
},
});
const projectSpawn = (
context: SemanticFlowProjectionContext,
@@ -141,21 +132,14 @@ const addStdioNode = (
spawn: JavaScriptSemanticChildProcessSpawn,
child: JavaScriptSemanticGraphNode,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "stdio",
roleKey: `stdio:${spawn.processId}`,
location: spawn.location,
label: spawn.stdioMode,
functionNodeId: child.function_node_id,
properties: { mode: spawn.stdioMode },
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "stdio",
roleKey: `stdio:${spawn.processId}`,
location: spawn.location,
label: spawn.stdioMode,
functionNodeId: child.function_node_id,
properties: { mode: spawn.stdioMode },
});
const projectInteraction = (
context: SemanticFlowProjectionContext,
@@ -204,52 +188,38 @@ const addChildListenerNode = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "listener",
roleKey: interaction.interactionId,
location: interaction.listenerLocation ?? interaction.location,
label: interaction.eventName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)
?.node_id ?? null),
properties: {
event_name: interaction.eventName,
method: interaction.method,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "listener",
roleKey: interaction.interactionId,
location: interaction.listenerLocation ?? interaction.location,
label: interaction.eventName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)?.node_id ??
null),
properties: {
event_name: interaction.eventName,
method: interaction.method,
},
});
const addSignalNode = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "signal",
roleKey: interaction.interactionId,
location: interaction.location,
label: interaction.signalName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)
?.node_id ?? null),
properties: { signal_name: interaction.signalName },
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "signal",
roleKey: interaction.interactionId,
location: interaction.location,
label: interaction.signalName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)?.node_id ??
null),
properties: { signal_name: interaction.signalName },
});
const addChildUnknown = (input: ChildUnknownInput): void => {
const { context, node, location, relationKinds, detail, candidateNodeIds } =
@@ -4,6 +4,7 @@ import { javascriptDisplayText } from "../../domain/javascript/javascriptAstValu
import {
createJavaScriptSemanticGraphNode,
createJavaScriptSemanticGraphRelation,
javaScriptSemanticNodeId,
type JavaScriptSemanticGraphNode,
} from "../../domain/javascript/javascriptSemanticGraph.js";
import type { ApplicationGraphEvidence } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
@@ -80,6 +81,28 @@ export const createSemanticGraphProjectionState = (
};
};
/** Bind retained semantic identities after all application observations exist. */
export const bindSemanticGraphApplicationNodes = (
state: SemanticGraphProjectionState,
applicationGraph: Pick<JavaScriptApplicationGraph, "nodes">,
): void => {
const index = indexApplicationNodes(applicationGraph.nodes).identifiers;
for (const [identifier, node] of state.nodes) {
state.nodes.set(identifier, {
...node,
application_node_ids: [
...(index.get(
applicationLocationKey(
node.identity.artifact_sha256,
node.identity.module_path,
node.identity.source_range,
),
) ?? []),
],
});
}
};
/** Construct one canonical semantic node backed by an exact artifact file. */
export const constructSemanticGraphNode = (
file: JavaScriptArtifactFile,
@@ -101,6 +124,33 @@ export const constructSemanticGraphNode = (
evidence: observedSemanticEvidence(file, input.location),
});
/** Reuse retained identities and reject exhausted budgets before allocation. */
export const retainSemanticGraphNode = (
state: SemanticGraphProjectionState,
file: JavaScriptArtifactFile,
input: SemanticNodeConstructionInput,
): JavaScriptSemanticGraphNode | null => {
const identifier = javaScriptSemanticNodeId({
kind: input.kind,
identity: {
artifact_sha256: file.sha256,
module_path: file.path,
source_range: input.location,
role_key: input.roleKey,
},
});
const existing = state.nodes.get(identifier);
if (existing !== undefined) return existing;
if (typeof state.fileNodeBudget === "number" && state.fileNodeBudget <= 0) {
state.fileNodesDropped = true;
return null;
}
return addSemanticGraphNode(
state,
constructSemanticGraphNode(file, input, state),
);
};
/** Retain one canonical semantic node. */
export const addSemanticGraphNode = (
state: SemanticGraphProjectionState,
@@ -6,10 +6,9 @@ import type {
JavaScriptSemanticRequestOperation,
} from "../../domain/javascript/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
@@ -70,29 +69,22 @@ const addConfigurationNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticConfigurationOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "config-source",
roleKey: operation.configId,
location: operation.location,
label: operation.key ?? operation.kind,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
key: operation.key,
source_kind: operation.kind,
value: operation.value,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "config-source",
roleKey: operation.configId,
location: operation.location,
label: operation.key ?? operation.kind,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
key: operation.key,
source_kind: operation.kind,
value: operation.value,
},
});
const configurationRelation = (
operation: JavaScriptSemanticConfigurationOperation,
@@ -144,29 +136,22 @@ const addRequestNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: operation.kind === "request" ? "request" : "response",
roleKey: operation.requestId,
location: operation.location,
label: operation.endpoint ?? operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
endpoint: operation.endpoint,
method: operation.method,
operation_kind: operation.kind,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: operation.kind === "request" ? "request" : "response",
roleKey: operation.requestId,
location: operation.location,
label: operation.endpoint ?? operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
endpoint: operation.endpoint,
method: operation.method,
operation_kind: operation.kind,
},
});
const projectRequestConstruction = (
context: SemanticFlowProjectionContext,
@@ -265,28 +250,21 @@ const addBoundaryNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticBoundaryOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "boundary",
roleKey: operation.boundaryId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
boundary_kind: operation.kind,
method: operation.method,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "boundary",
roleKey: operation.boundaryId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
boundary_kind: operation.kind,
method: operation.method,
},
});
const bindingOrOwner = (
context: SemanticFlowProjectionContext,
@@ -5,17 +5,15 @@ import { sourceRangesEqual } from "../../domain/javascript/javascriptStaticAnaly
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
type SemanticGraphProjectionState,
} from "./JavaScriptSemanticGraphConstruction.js";
import {
inferredSemanticEvidenceAt,
unknownSemanticEvidence,
} from "./JavaScriptSemanticGraphEvidence.js";
import { semanticNodesWithinRange } from "./JavaScriptSemanticGraphProjection.js";
/** File-local graph state needed by return, capture, and frontier projection. */
export interface SemanticFlowProjectionContext {
@@ -28,6 +26,12 @@ export interface SemanticFlowProjectionContext {
readonly callSiteNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly returnSiteNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly referenceNodes: readonly JavaScriptSemanticGraphNode[];
readonly referenceNodesWithin: (
range: JavaScriptSourceRange,
) => JavaScriptSemanticGraphNode[];
readonly callSiteAt: (
range: JavaScriptSourceRange,
) => JavaScriptSemanticGraphNode | undefined;
}
/** Find the retained call-site node at one exact semantic source range. */
@@ -35,12 +39,7 @@ export const semanticCallSiteAt = (
context: SemanticFlowProjectionContext,
location: JavaScriptSourceRange,
): JavaScriptSemanticGraphNode | undefined => {
const call = context.ir.callSites.find(({ location: candidate }) =>
sourceRangesEqual(candidate, location),
);
return call === undefined
? undefined
: context.callSiteNodes.get(call.callSiteId);
return context.callSiteAt(location);
};
/** Project explicit static Promise/task ownership without runtime claims. */
@@ -53,26 +52,19 @@ export const projectSemanticPromises = (
operation.ownerCallableId === null
? undefined
: context.callableNodes.get(operation.ownerCallableId);
const node = addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: operation.kind === "awaited-expression" ? "task" : "promise",
roleKey: operation.promiseId,
location: operation.location,
label: promiseLabel(operation),
functionNodeId: owner?.node_id ?? null,
properties: {
method: operation.method,
operation_kind: operation.kind,
ownership: operation.ownership,
source_resolution: operation.sourceResolution,
},
},
context.state,
),
);
const node = retainSemanticGraphNode(context.state, context.file, {
kind: operation.kind === "awaited-expression" ? "task" : "promise",
roleKey: operation.promiseId,
location: operation.location,
label: promiseLabel(operation),
functionNodeId: owner?.node_id ?? null,
properties: {
method: operation.method,
operation_kind: operation.kind,
ownership: operation.ownership,
source_resolution: operation.sourceResolution,
},
});
return node === null ? [] : [[operation.promiseId, node] as const];
}),
);
@@ -217,10 +209,7 @@ export const projectSemanticReturnValues = (
for (const callable of context.ir.callables)
for (const site of callable.returnSites) {
const returnNode = context.returnSiteNodes.get(site.returnSiteId);
const references = semanticNodesWithinRange(
context.referenceNodes,
site.location,
);
const references = context.referenceNodesWithin(site.location);
for (const reference of references)
addSemanticGraphRelation(context.state, {
source: reference,
@@ -2,10 +2,9 @@ import { createJavaScriptSemanticGraphUnknown } from "../../domain/javascript/ja
import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { JavaScriptSemanticObjectOperation } from "../../domain/javascript/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
@@ -72,31 +71,24 @@ const addObjectOccurrence = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticObjectOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "expression",
roleKey: operation.objectOperationId,
location: operation.location,
label:
operation.propertyName === null
? operation.kind
: `${operation.kind}:${operation.propertyName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
operation_kind: operation.kind,
property_name: operation.propertyName,
},
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "expression",
roleKey: operation.objectOperationId,
location: operation.location,
label:
operation.propertyName === null
? operation.kind
: `${operation.kind}:${operation.propertyName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
operation_kind: operation.kind,
property_name: operation.propertyName,
},
});
const addObjectUnknown = (
context: SemanticFlowProjectionContext,
@@ -0,0 +1,259 @@
import { expect, it } from "vitest";
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import {
constructSemanticGraphNode,
createSemanticGraphProjectionState,
} from "./JavaScriptSemanticGraphConstruction.js";
import {
createSemanticCallableOwnerLookup,
createSemanticNodeRangeLookup,
createSemanticCallSiteLookup,
} from "./JavaScriptSemanticGraphProjection.js";
import { sourceRangesEqual } from "../../domain/javascript/javascriptStaticAnalysisHelpers.js";
const fixtureFile: JavaScriptArtifactFile = {
path: "app.js",
container_sha256: "a".repeat(64),
sha256: "b".repeat(64),
bytes: 0,
inventory_artifact_id: "fixture-app",
kind: "javascript",
unpacked: false,
text: { included: true, value: "" },
};
const nodesFor = (ir: JavaScriptSemanticIr) => {
const state = createSemanticGraphProjectionState({ nodes: [] });
return new Map(
ir.callables.map((callable) => [
callable.callableId,
constructSemanticGraphNode(
fixtureFile,
{
kind: "function",
roleKey: callable.callableId,
label: callable.name,
location: callable.location,
functionNodeId: null,
},
state,
),
]),
);
};
// Reference behavior before the optimization, including stable ties and
// fallback when the most deeply nested callable has no retained graph node.
const previousOwner = (
location: JavaScriptSourceRange | null,
ir: JavaScriptSemanticIr,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
) => {
if (location === null) return undefined;
const compare = (
left: JavaScriptSourceRange["start"],
right: JavaScriptSourceRange["start"],
) => left.line - right.line || left.column - right.column;
const key = (range: JavaScriptSourceRange) =>
`${String(range.start.line).padStart(12, "0")}:${String(range.start.column).padStart(12, "0")}`;
return ir.callables
.filter(
(callable) =>
compare(callable.location.start, location.start) <= 0 &&
compare(callable.location.end, location.end) >= 0,
)
.sort((left, right) =>
compareCodePoints(key(right.location), key(left.location)),
)
.map((callable) => nodes.get(callable.callableId))
.find((node) => node !== undefined);
};
const rangesFor = (ir: JavaScriptSemanticIr) => [
null,
...ir.callables.map((callable) => callable.location),
...ir.bindings.flatMap((binding) =>
binding.definitions.map((definition) => definition.location),
),
...ir.references.map((reference) => reference.location),
{ start: { line: 999, column: 0 }, end: { line: 999, column: 1 } },
];
it("matches the prior owner selection across nested functions, arrows and methods", () => {
const ir = analyzeJavaScriptSemantics(`
const outside = 1;
function outer(parameter) {
function inner(value) { return value + parameter; }
const callback = argument => inner(argument);
return callback(outside);
}
class Example { method(value) { return () => outer(value); } }
`);
const nodes = nodesFor(ir);
const lookup = createSemanticCallableOwnerLookup(ir, nodes);
for (const range of rangesFor(ir))
expect(lookup(range)).toBe(previousOwner(range, ir, nodes));
});
it("reads retained node membership at query time and keeps file indexes independent", () => {
const ir = analyzeJavaScriptSemantics(
"function outer() { function inner() { return 1; } return inner(); }",
);
const inner = ir.callables.find((callable) => callable.name === "inner");
if (inner === undefined) throw new Error("Missing inner fixture callable");
const nodes = nodesFor(ir);
const otherNodes = nodesFor(ir);
const lookup = createSemanticCallableOwnerLookup(ir, nodes);
const otherLookup = createSemanticCallableOwnerLookup(ir, otherNodes);
const before = lookup(inner.location);
expect(before?.label).toBe("inner");
nodes.delete(inner.callableId);
expect(lookup(inner.location)?.label).toBe("outer");
expect(otherLookup(inner.location)?.label).toBe("inner");
if (before === undefined) throw new Error("Missing retained fixture node");
nodes.set(inner.callableId, before);
expect(lookup(inner.location)).toBe(before);
});
it("preserves stable ties and non-nested overlapping ranges", () => {
const original = analyzeJavaScriptSemantics(
"function first() { return 1; } function second() { return 2; } function third() { return 3; }",
);
const range = (start: number, end: number): JavaScriptSourceRange => ({
start: { line: 1, column: start },
end: { line: 1, column: end },
});
const ir = {
...original,
callables: original.callables.map((callable, index) => ({
...callable,
location: index === 0 ? range(0, 90) : range(20, index === 1 ? 60 : 80),
})),
};
const nodes = nodesFor(ir);
const lookup = createSemanticCallableOwnerLookup(ir, nodes);
for (const query of [
range(25, 30),
range(25, 70),
range(0, 80),
range(80, 90),
range(91, 92),
])
expect(lookup(query)).toBe(previousOwner(query, ir, nodes));
});
it("matches the prior result across a compiled-style collection of sibling callables", () => {
const ir = analyzeJavaScriptSemantics(
Array.from(
{ length: 300 },
(_, index) =>
`function f${String(index)}(value) { return value + ${String(index)}; }`,
).join(""),
);
const nodes = nodesFor(ir);
const lookup = createSemanticCallableOwnerLookup(ir, nodes);
for (const range of rangesFor(ir))
expect(lookup(range)).toBe(previousOwner(range, ir, nodes));
});
it("returns contained nodes in original order, including repeated and overlapping entries", () => {
const ir = analyzeJavaScriptSemantics(`
function outer(value) { function inner() { return value; } return inner(); }
const sibling = () => outer(1);
`);
const nodes = [...nodesFor(ir).values()].reverse();
const repeated = nodes[0];
if (repeated === undefined) throw new Error("Missing range fixture node");
nodes.push(
repeated,
constructSemanticGraphNode(
fixtureFile,
{
kind: "module",
roleKey: "module",
location: null,
label: "module",
functionNodeId: null,
},
createSemanticGraphProjectionState({ nodes: [] }),
),
);
const lookup = createSemanticNodeRangeLookup(nodes);
const compare = (
left: JavaScriptSourceRange["start"],
right: JavaScriptSourceRange["start"],
) => left.line - right.line || left.column - right.column;
for (const range of rangesFor(ir)) {
if (range === null) continue;
const expected = nodes.filter(
({ identity }) =>
identity.source_range !== null &&
compare(range.start, identity.source_range.start) <= 0 &&
compare(range.end, identity.source_range.end) >= 0,
);
expect(lookup(range)).toEqual(expected);
}
expect(
createSemanticNodeRangeLookup([])(
repeated.identity.source_range ?? {
start: { line: 1, column: 0 },
end: { line: 1, column: 1 },
},
),
).toEqual([]);
});
it("keeps first-call matching and current retained membership for exact locations", () => {
const original = analyzeJavaScriptSemantics(
"function target(value) { return value; } target(1); target(2);",
);
const first = original.callSites[0];
const node = [...nodesFor(original).values()][0];
if (first === undefined || node === undefined)
throw new Error("Missing call fixture");
const duplicate = { ...first, callSiteId: `${first.callSiteId}:duplicate` };
const ir = {
...original,
callSites: [first, duplicate, ...original.callSites.slice(1)],
};
const nodes = new Map(
ir.callSites.map((call) => [
call.callSiteId,
constructSemanticGraphNode(
fixtureFile,
{
kind: "call-site",
roleKey: call.callSiteId,
location: call.location,
label: call.callSiteId,
functionNodeId: null,
},
createSemanticGraphProjectionState({ nodes: [] }),
),
]),
);
const lookup = createSemanticCallSiteLookup(ir, nodes);
const previous = (range: JavaScriptSourceRange) => {
const call = ir.callSites.find((candidate) =>
sourceRangesEqual(candidate.location, range),
);
return call === undefined ? undefined : nodes.get(call.callSiteId);
};
for (const call of ir.callSites)
expect(lookup(call.location)).toBe(previous(call.location));
nodes.delete(first.callSiteId);
expect(lookup(first.location)).toBeUndefined();
expect(nodes.has(duplicate.callSiteId)).toBe(true);
nodes.set(first.callSiteId, node);
expect(lookup(first.location)).toBe(node);
expect(
lookup({ start: { line: 99, column: 0 }, end: { line: 99, column: 1 } }),
).toBeUndefined();
});
@@ -5,40 +5,173 @@ import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSem
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
/** Find the innermost callable that contains one exact source range. */
export const owningSemanticCallableNode = (
location: JavaScriptSourceRange | null,
interface SourceInterval {
readonly range: JavaScriptSourceRange;
readonly order: number;
}
interface CallableInterval extends SourceInterval {
readonly callableId: string;
readonly priority: string;
}
interface SourceIntervalTree<Interval extends SourceInterval> {
readonly entry: Interval;
readonly minimumStart: JavaScriptSourceRange["start"];
readonly maximumStart: JavaScriptSourceRange["start"];
readonly minimumEnd: JavaScriptSourceRange["end"];
readonly maximumEnd: JavaScriptSourceRange["end"];
readonly left: SourceIntervalTree<Interval> | null;
readonly right: SourceIntervalTree<Interval> | null;
}
/** Index one immutable file IR; read retained callable membership at query time. */
export const createSemanticCallableOwnerLookup = (
ir: JavaScriptSemanticIr,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): JavaScriptSemanticGraphNode | undefined => {
if (location === null) return undefined;
return ir.callables
.filter((callable) => contains(callable.location, location))
.sort((left, right) =>
compareCodePoints(
positionKey(right.location),
positionKey(left.location),
),
)
.map(({ callableId }) => nodes.get(callableId))
.find((node) => node !== undefined);
): ((
location: JavaScriptSourceRange | null,
) => JavaScriptSemanticGraphNode | undefined) => {
const entries = ir.callables
.map((callable, order): CallableInterval => ({
callableId: callable.callableId,
range: callable.location,
order,
priority: positionKey(callable.location),
}))
.sort(
(left, right) =>
pointCompare(left.range.start, right.range.start) ||
left.order - right.order,
);
const tree = buildSourceIntervalTree(entries, 0, entries.length);
return (location) => {
if (location === null || tree === null || nodes.size === 0)
return undefined;
const pending = [tree];
let best: CallableInterval | undefined;
let result: JavaScriptSemanticGraphNode | undefined;
while (pending.length > 0) {
const current = pending.pop();
if (
current === undefined ||
pointCompare(current.minimumStart, location.start) > 0 ||
pointCompare(current.maximumEnd, location.end) < 0
)
continue;
const candidate = current.entry;
if (contains(candidate.range, location)) {
const node = nodes.get(candidate.callableId);
const rank =
best === undefined
? 1
: compareCodePoints(candidate.priority, best.priority) ||
best.order - candidate.order;
if (node !== undefined && rank > 0) {
best = candidate;
result = node;
}
}
if (current.left !== null) pending.push(current.left);
if (current.right !== null) pending.push(current.right);
}
return result;
};
};
/** Find retained semantic nodes whose exact ranges are within one expression. */
export const semanticNodesWithinRange = (
const buildSourceIntervalTree = <Interval extends SourceInterval>(
entries: readonly Interval[],
start: number,
end: number,
): SourceIntervalTree<Interval> | null => {
if (start >= end) return null;
const middle = Math.floor((start + end) / 2);
const entry = entries[middle];
if (entry === undefined) return null;
// This recursion follows a balanced index, not the producer's nesting depth.
const left = buildSourceIntervalTree(entries, start, middle);
const right = buildSourceIntervalTree(entries, middle + 1, end);
let minimumEnd = entry.range.end;
let maximumEnd = entry.range.end;
for (const child of [left, right]) {
if (child !== null && pointCompare(child.minimumEnd, minimumEnd) < 0)
minimumEnd = child.minimumEnd;
if (child !== null && pointCompare(child.maximumEnd, maximumEnd) > 0)
maximumEnd = child.maximumEnd;
}
return {
entry,
minimumStart: left?.minimumStart ?? entry.range.start,
maximumStart: right?.maximumStart ?? entry.range.start,
minimumEnd,
maximumEnd,
left,
right,
};
};
/** Index an immutable node list; return contained ranges in producer order. */
export const createSemanticNodeRangeLookup = (
nodes: readonly JavaScriptSemanticGraphNode[],
): ((range: JavaScriptSourceRange) => JavaScriptSemanticGraphNode[]) => {
const entries = nodes
.flatMap((node, order) => {
const range = node.identity.source_range;
return range === null ? [] : [{ node, range, order }];
})
.sort(
(left, right) =>
pointCompare(left.range.start, right.range.start) ||
left.order - right.order,
);
const tree = buildSourceIntervalTree(entries, 0, entries.length);
return (range) => {
if (tree === null) return [];
const pending = [tree];
const matches: (typeof entries)[number][] = [];
while (pending.length > 0) {
const current = pending.pop();
if (
current === undefined ||
pointCompare(current.maximumStart, range.start) < 0 ||
pointCompare(current.minimumEnd, range.end) > 0
)
continue;
if (contains(range, current.entry.range)) matches.push(current.entry);
if (current.left !== null) pending.push(current.left);
if (current.right !== null) pending.push(current.right);
}
return matches
.sort((left, right) => left.order - right.order)
.map(({ node }) => node);
};
};
/** Index exact call ranges, preserving the first producer occurrence. */
export const createSemanticCallSiteLookup = (
ir: JavaScriptSemanticIr,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): ((
range: JavaScriptSourceRange,
): JavaScriptSemanticGraphNode[] =>
nodes.filter(
(node) =>
node.identity.source_range !== null &&
contains(range, node.identity.source_range),
);
) => JavaScriptSemanticGraphNode | undefined) => {
const identifiers = new Map<string, string>();
for (const call of ir.callSites) {
const key = rangeKey(call.location);
if (!identifiers.has(key)) identifiers.set(key, call.callSiteId);
}
return (range) => {
const identifier = identifiers.get(rangeKey(range));
return identifier === undefined ? undefined : nodes.get(identifier);
};
};
const rangeKey = (range: JavaScriptSourceRange): string =>
`${range.start.line}:${range.start.column}-${range.end.line}:${range.end.column}`;
/** Report extractor support without treating missing families as absence. */
export const semanticFamilyStatus = (
family: (typeof JAVASCRIPT_SEMANTIC_RELATION_FAMILIES)[number],
analysis: JavaScriptArtifactAnalysis,
analysis: Pick<JavaScriptArtifactAnalysis, "truncated_scopes">,
): "complete" | "partial" | "unknown" | "unsupported" => {
if (
![
@@ -2,10 +2,9 @@ import { createJavaScriptSemanticGraphUnknown } from "../../domain/javascript/ja
import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { JavaScriptSemanticResourceOperation } from "../../domain/javascript/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
@@ -39,25 +38,18 @@ const addResourceNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticResourceOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "resource",
roleKey: operation.resourceId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: { method: operation.method },
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "resource",
roleKey: operation.resourceId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: { method: operation.method },
});
const projectRelease = (
context: SemanticFlowProjectionContext,
@@ -4,9 +4,8 @@ import type {
JavaScriptSemanticValue,
} from "../../domain/javascript/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
retainSemanticGraphNode,
addSemanticGraphRelation,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
@@ -85,22 +84,15 @@ const addLiteralNode = (
value: string | number | boolean | null,
role: string,
) =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "literal",
roleKey: `literal:${binding.bindingId}:${role}:${JSON.stringify(value)}`,
location: binding.definitions[0]?.location ?? null,
label: JSON.stringify(value),
functionNodeId:
context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null,
properties: { value },
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "literal",
roleKey: `literal:${binding.bindingId}:${role}:${JSON.stringify(value)}`,
location: binding.definitions[0]?.location ?? null,
label: JSON.stringify(value),
functionNodeId:
context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null,
properties: { value },
});
/** Create one canonical property slot for a binding/property identity. */
export const semanticPropertySlot = (
@@ -108,22 +100,15 @@ export const semanticPropertySlot = (
objectBindingId: string,
name: string,
) =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "property-slot",
roleKey: `property:${objectBindingId}:${name}`,
location: null,
label: name,
functionNodeId:
context.bindingNodes.get(objectBindingId)?.function_node_id ?? null,
properties: {
name,
object_binding_id: objectBindingId,
} satisfies Readonly<Record<string, JsonValue>>,
},
context.state,
),
);
retainSemanticGraphNode(context.state, context.file, {
kind: "property-slot",
roleKey: `property:${objectBindingId}:${name}`,
location: null,
label: name,
functionNodeId:
context.bindingNodes.get(objectBindingId)?.function_node_id ?? null,
properties: {
name,
object_binding_id: objectBindingId,
} satisfies Readonly<Record<string, JsonValue>>,
});
+29 -1
View File
@@ -1,6 +1,9 @@
import { z } from "incur";
import { resolve } from "node:path";
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
import {
createRecordedCrashService,
createBinaryLayoutService,
} from "../composition/binaryDiagnostics.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
@@ -32,4 +35,29 @@ export const registerBinaryDiagnosticsCommands = (
}),
),
});
const recorded = createRecordedCrashService(environment);
cli.command(CLI_COMMANDS.inspectRecordedCrash, {
description:
"Inspect supplied core registers/signals and optional debugger mapping evidence",
args: z.object({ path: z.string().describe("Local Linux amd64 ELF core") }),
options: z.object({
debuggerContext: z
.boolean()
.default(false)
.describe("Add BYO core-only GDB/pwndbg mapping candidates"),
}),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectRecordedCrash, async () => {
const result = await recorded.inspect(
{
path: resolve(args.path),
include_debugger_context: options.debuggerContext,
},
{ signal },
);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
+4
View File
@@ -61,6 +61,10 @@ function* bufferedParts(parts: Iterable<string>): Generator<string> {
}
function* encodeString(value: string): Generator<string> {
if (value.length <= 8192) {
yield JSON.stringify(value);
return;
}
yield '"';
for (let start = 0; start < value.length;) {
let end = Math.min(start + 8192, value.length);
+1
View File
@@ -40,6 +40,7 @@ export const CLI_COMMANDS = Object.freeze({
resolveNativeCallTargets: "resolve-native-call-targets",
inspectAssetCatalog: "inspect-asset-catalog",
inspectManagedArtifact: "inspect-managed-artifact",
inspectRecordedCrash: "inspect-recorded-crash",
inspectBinaryLayout: "inspect-binary-layout",
inspectFirmwareRegions: "inspect-firmware-regions",
extractFirmware: "extract-firmware",
+8
View File
@@ -1,3 +1,5 @@
import { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
import { PwntoolsRecordedCrashProvider } from "../native/pwntools/PwntoolsRecordedCrashProvider.js";
import { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import { PwntoolsLayoutProvider } from "../native/pwntools/PwntoolsLayoutProvider.js";
@@ -6,3 +8,9 @@ export const createBinaryLayoutService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): BinaryLayoutService =>
new BinaryLayoutService(new PwntoolsLayoutProvider(environment));
/** Compose recorded-core inspection without acquiring a debugger or toolchain. */
export const createRecordedCrashService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): RecordedCrashService =>
new RecordedCrashService(new PwntoolsRecordedCrashProvider(environment));
@@ -1,3 +1,7 @@
import {
inspectRecordedCrashInputSchema,
recordedCrashSchema,
} from "../../domain/native/recordedCrash.js";
import {
inspectBinaryLayoutInputSchema,
binaryLayoutSchema,
@@ -23,4 +27,26 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
},
],
},
{
name: "inspect_recorded_crash",
...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.",
inputSchema: inspectRecordedCrashInputSchema,
outputSchema: evidenceResultOf(recordedCrashSchema),
examples: [
{
title: "Inspect recorded registers and signal evidence",
input: { path: "/artifacts/crash.core" },
},
{
title: "Add core-only debugger mapping candidates",
input: {
path: "/artifacts/crash.core",
include_debugger_context: true,
},
},
],
},
] as const satisfies readonly ToolContract[];
+5
View File
@@ -70,6 +70,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
launchesProcess: true,
accessesNetwork: true,
}),
inspect_recorded_crash: effects({
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
}),
inspect_binary_layout: effects({
mutatesSession: true,
writesFilesystem: true,
+25
View File
@@ -17,6 +17,31 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
it("snapshots caller-owned payloads before deriving their identity", () => {
const result = { nested: { values: ["observed"] } };
const rawResult = { entries: [{ value: "raw" }] };
const parameters = { selected: ["target"] };
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "inspect",
parameters,
result,
rawResult,
});
result.nested.values.push("later");
const rawEntry = rawResult.entries[0];
if (rawEntry !== undefined) rawEntry.value = "changed";
parameters.selected.push("other");
expect(evidence.normalized_result).toEqual({
nested: { values: ["observed"] },
});
expect(evidence.raw_result).toEqual({ entries: [{ value: "raw" }] });
expect(evidence.parameters).toEqual({ selected: ["target"] });
expect(parseEvidence(evidence)).toEqual(evidence);
expect(() =>
parseEvidence({ ...evidence, normalized_result: result }),
).toThrow(/semantic identifier/u);
});
describe("analysis evidence identity", () => {
it("normalizes prototype-named parameter keys", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
+13 -3
View File
@@ -274,13 +274,23 @@ export const createEvidence = (
locations: [...(observation.locations ?? [])],
evidence_links: [...(observation.evidenceLinks ?? [])],
} satisfies JsonValue;
const normalized = evidenceRecordSchema.parse({
// Select the known envelope before parsing. A union otherwise traverses and
// clones a legacy result for the profiled branch before rejecting its absent
// profile and trying the legacy branch.
const schema =
observation.analysisProfile === undefined
? evidenceBaseSchema
: profiledEvidenceSchema;
const normalized = schema.parse({
...semantic,
evidence_id: `ev_${"0".repeat(64)}`,
subject,
});
return parseEvidence({
// The envelope has already been parsed into an independent snapshot. Only
// its derived identifier changes here; parsing again clones the full payload
// and recomputes the same digest while the previous snapshot is still live.
return {
...normalized,
evidence_id: computeEvidenceId(normalized),
});
};
};
@@ -38,7 +38,8 @@ const normalizeEvidence = (
evidence_ids: uniqueSorted(evidence.evidence_ids),
});
const nodeId = (
/** Derive a semantic node ID from its kind and exact artifact identity. */
export const javaScriptSemanticNodeId = (
node: Pick<JavaScriptSemanticGraphNode, "kind" | "identity">,
): string =>
`jsrg_node_${canonicalDigest({ kind: node.kind, identity: node.identity }, "JavaScript semantic graph")}`;
@@ -59,7 +60,7 @@ export const createJavaScriptSemanticGraphNode = (
};
return javaScriptSemanticNodeSchema.parse({
...semantic,
node_id: nodeId(semantic),
node_id: javaScriptSemanticNodeId(semantic),
});
};
@@ -129,11 +130,21 @@ export const createJavaScriptSemanticFingerprint = (input: unknown) => {
type GraphRecord = z.infer<typeof javaScriptSemanticGraphRecordSchema>;
type SemanticGraphIssue = {
readonly code: "custom";
readonly path: PropertyKey[];
readonly message: string;
};
interface GraphIssueReporter {
readonly addIssue: (issue: SemanticGraphIssue) => void;
}
const sortedUniqueIssue = (
values: readonly string[],
path: PropertyKey[],
label: string,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (let index = 1; index < values.length; index += 1) {
if (compareCodePoints(values[index - 1] ?? "", values[index] ?? "") < 0)
@@ -147,7 +158,10 @@ const sortedUniqueIssue = (
}
};
const checkCoverage = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkCoverage = (
graph: GraphRecord,
context: GraphIssueReporter,
): void => {
const families = graph.coverage.families.map(({ family }) => family);
if (
canonicalJson(families, "JavaScript semantic graph") !==
@@ -221,7 +235,7 @@ const checkCoverage = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkCanonicalOrder = (
graph: GraphRecord,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
sortedUniqueIssue(
graph.root_node_ids,
@@ -259,10 +273,10 @@ const checkCanonicalOrder = (
const checkNodes = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, node] of graph.nodes.entries()) {
if (node.node_id !== nodeId(node))
if (node.node_id !== javaScriptSemanticNodeId(node))
context.addIssue({
code: "custom",
path: ["nodes", index, "node_id"],
@@ -283,7 +297,7 @@ const checkNodes = (
const checkRoots = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const root of graph.root_node_ids)
if (!nodes.has(root))
@@ -297,7 +311,7 @@ const checkRoots = (
const checkRelations = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, relation] of graph.relations.entries()) {
const { relation_id: identifier, ...semantic } = relation;
@@ -340,7 +354,7 @@ const checkRelations = (
const checkUnknowns = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, unknown] of graph.unknowns.entries()) {
const { unknown_id: identifier, ...semantic } = unknown;
@@ -386,7 +400,7 @@ const checkUnknowns = (
const checkUnknownReferences = (
graph: GraphRecord,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
const unknownIds = new Set(
graph.unknowns.map(({ unknown_id }) => unknown_id),
@@ -403,7 +417,7 @@ const checkUnknownReferences = (
const checkFingerprints = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, fingerprint] of graph.fingerprints.entries()) {
if (nodes.get(fingerprint.function_node_id)?.kind !== "function")
@@ -449,7 +463,10 @@ const checkFingerprints = (
}
};
const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkGraphContent = (
graph: GraphRecord,
context: GraphIssueReporter,
): void => {
checkCanonicalOrder(graph, context);
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
checkNodes(graph, nodes, context);
@@ -465,6 +482,10 @@ const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
path: ["limitations"],
message: "Non-complete graph coverage requires a limitation",
});
};
const checkGraph = (graph: GraphRecord, context: GraphIssueReporter): void => {
checkGraphContent(graph, context);
const { graph_id: identifier, ...semantic } = graph;
if (
identifier !==
@@ -523,10 +544,21 @@ export const createJavaScriptSemanticGraph = (
},
limitations: uniqueSorted(parsed.limitations),
};
return javaScriptSemanticGraphSchema.parse({
// The input schema already cloned and validated every field. Validate the
// normalized relationships in place, then derive the only added field. The
// public schema still verifies arbitrary records and their commitments.
const record: GraphRecord = {
...semantic,
graph_id: `jsrg_${canonicalDigest(semantic, "JavaScript semantic graph")}`,
};
const issues: SemanticGraphIssue[] = [];
checkGraphContent(record, {
addIssue: (issue) => {
issues.push(issue);
},
});
if (issues.length > 0) throw new z.ZodError(issues);
return record;
};
export type { JavaScriptSemanticGraphNode, JavaScriptSemanticGraphRelation };
+284
View File
@@ -0,0 +1,284 @@
import { expect, it } from "vitest";
import {
inspectRecordedCrashInputSchema,
recordedCrashSchema,
} from "./recordedCrash.js";
import {
recordedCrashFixture,
recordedCrashSignalFixture,
} from "../../../tests/fixtures/binaryDiagnostics/recordedCrash.js";
it("preserves high uint64 registers and historical thread identity", () => {
const value = recordedCrashSchema.parse(recordedCrashFixture());
expect(
value.threads[0]?.registers.find(({ name }) => name === "rdi")?.value,
).toBe("0x1122334455667788");
expect(value.live_process_identity).toBe("unknown");
expect(
inspectRecordedCrashInputSchema.parse({ path: "/selected.core" })
.include_debugger_context,
).toBe(false);
});
it("preserves a short zero-filled note-segment tail", () => {
const value = recordedCrashSignalFixture();
value.segments = value.segments.map((segment) => ({
...segment,
file_size: "0x19b",
}));
value.note_padding.push({
segment_index: 0,
location: { offset: "0x218", bytes: "0x3" },
bytes_base64: "AAAA",
});
expect(recordedCrashSchema.safeParse(value).success).toBe(true);
});
it.each([
"missing-thread",
"duplicate-thread",
"missing-signal",
"duplicate-signal",
"missing-register",
"unknown-register",
"duplicated-physical-thread",
"duplicated-physical-signal",
"omitted-physical-note",
"expanded-note-span",
"forged-padding",
])("rejects an incomplete or duplicate interpretation: %s", (scenario) => {
const value = recordedCrashSignalFixture();
if (
scenario === "duplicated-physical-thread" ||
scenario === "duplicated-physical-signal"
) {
const noteIndex = scenario === "duplicated-physical-thread" ? 0 : 1;
const note = value.notes[noteIndex];
if (note === undefined) throw new Error("missing fixture note");
value.notes.push({ ...note, index: 2 });
if (noteIndex === 0)
value.threads.push(
...value.threads.map((thread) => ({ ...thread, note_index: 2 })),
);
else
value.signals.push(
...value.signals.map((signal) => ({ ...signal, note_index: 2 })),
);
}
if (
["omitted-physical-note", "expanded-note-span", "forged-padding"].includes(
scenario,
)
) {
value.notes = value.notes.filter((note) => note.index === 0);
value.signals = [];
}
if (scenario === "expanded-note-span")
value.notes = value.notes.map((note) => ({
...note,
location: { ...note.location, bytes: "0x198" },
}));
if (scenario === "forged-padding")
value.note_padding.push({
segment_index: 0,
location: { offset: "0x1e4", bytes: "0x34" },
bytes_base64: Buffer.alloc(52).toString("base64"),
});
if (scenario === "missing-thread") value.threads = [];
if (scenario === "duplicate-thread")
value.threads = [...value.threads, ...value.threads];
if (scenario === "missing-signal") value.signals = [];
if (scenario === "duplicate-signal")
value.signals = [...value.signals, ...value.signals];
if (scenario === "missing-register")
value.threads = value.threads.map((thread) => ({
...thread,
registers: thread.registers.slice(1),
}));
if (scenario === "unknown-register")
value.threads = value.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register) =>
register.name === "rdi"
? { ...register, name: "unrecognized" }
: register,
),
}));
expect(recordedCrashSchema.safeParse(value).success).toBe(false);
});
it.each([
[
"unsafe register number",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [
{
...v.threads[0],
registers: [
{
name: "rdi",
value: 9007199254740992,
location: { offset: "0x104", bytes: "0x8" },
},
],
},
],
}),
],
[
"source outside artifact",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
artifact: { ...v.artifact, bytes: 120 },
}),
],
[
"invalid note reference",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [{ ...v.threads[0], note_index: 1 }],
}),
],
[
"register outside descriptor",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [
{
...v.threads[0],
registers: [
{
name: "rdi",
value: "0x0",
location: { offset: "0x1e4", bytes: "0x8" },
},
],
},
],
}),
],
[
"raw descriptor length",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({ ...n, descriptor_bytes_base64: "AA==" })),
}),
],
[
"different owner ABI",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({ ...n, owner_display: "OTHER" })),
}),
],
[
"raw owner ABI hidden by a CORE display label",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({
...n,
owner_bytes_base64: Buffer.from("EVIL\0").toString("base64"),
})),
}),
],
[
"duplicate register",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: v.threads.map((t) => ({
...t,
registers: [...t.registers, ...t.registers],
})),
}),
],
] as const)("rejects %s before Evidence serialization", (_name, change) =>
expect(
recordedCrashSchema.safeParse(change(recordedCrashFixture())).success,
).toBe(false),
);
it("does not interpret a signal through a mislabeled raw owner ABI", () => {
const value = recordedCrashFixture();
expect(
recordedCrashSchema.safeParse({
...value,
threads: [],
notes: value.notes.map((note) => ({
...note,
type: "NT_SIGINFO",
owner_bytes_base64: Buffer.from("EVIL\0").toString("base64"),
})),
signals: [
{
note_index: 0,
number: 11,
code: 1,
errno: 0,
fault_address: "0x123",
fault_address_meaning: "recorded-sigsegv-address",
thread_association: "unknown",
},
],
}).success,
).toBe(false);
});
it("keeps absent map flags unknown and validates reported permission bits", () => {
const value = recordedCrashFixture();
const context = {
status: "available",
gdb_version: "fixture",
pwndbg_version: "fixture",
connection: "core",
executable: null,
historical_pid: 123,
reported_limits: {
address_space_bytes: 3221225472,
cpu_seconds: 30,
file_size_bytes: 67108864,
},
maps: [
{
start: "0x1000",
end: "0x2000",
offset: "0x0",
reported_flags: 0,
permissions: null,
pathname_display: "recorded pathname",
current_file_identity: "unknown",
},
],
confidence: "derived",
completeness: "unknown",
diagnostics: value.diagnostics,
} as const;
expect(
recordedCrashSchema.safeParse({ ...value, debugger: context }).success,
).toBe(true);
expect(
recordedCrashSchema.safeParse({
...value,
debugger: {
...context,
maps: context.maps.map((m) => ({
...m,
permissions: { read: false, write: false, execute: false },
})),
},
}).success,
).toBe(false);
expect(
recordedCrashSchema.safeParse({
...value,
debugger: {
...context,
maps: context.maps.map((m) => ({
...m,
reported_flags: 4,
permissions: { read: false, write: false, execute: false },
})),
},
}).success,
).toBe(false);
});
+362
View File
@@ -0,0 +1,362 @@
import { z } from "zod";
import { recordedNoteCoverageIssues } from "./recordedCrashNoteCoverage.js";
const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/);
const index = z.number().int().nonnegative();
const signed32 = z.number().int().min(-2147483648).max(2147483647);
const base64 = z
.string()
.regex(
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/,
);
const range = z.strictObject({ offset: hex, bytes: hex });
const diagnostics = z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
});
// Exact b"CORE\0"; a lossy display label cannot establish the Linux note ABI.
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[] = [
"r15",
"r14",
"r13",
"r12",
"rbp",
"rbx",
"r11",
"r10",
"r9",
"r8",
"rax",
"rcx",
"rdx",
"rsi",
"rdi",
"orig_rax",
"rip",
"cs",
"eflags",
"rsp",
"ss",
"fs_base",
"gs_base",
"ds",
"es",
"fs",
"gs",
];
const supportedRegisters = new Set(RECORDED_LINUX_AMD64_REGISTERS);
/** Select an explicit recording and optionally request debugger-derived mapping context. */
export const inspectRecordedCrashInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute filesystem path to a supplied Linux ELF core"),
include_debugger_context: z
.boolean()
.default(false)
.describe(
"Add core-only mapping candidates through caller-supplied GDB/pwndbg",
),
});
/** Debugger map candidates preserve reported flags; zero does not establish absent permissions. */
export const recordedCrashDebuggerSchema = z.discriminatedUnion("status", [
z.strictObject({ status: z.literal("not-requested") }),
z.strictObject({
status: z.literal("available"),
gdb_version: z.string().min(1),
pwndbg_version: z.string().min(1),
connection: z.literal("core"),
executable: z.null(),
historical_pid: signed32,
reported_limits: z.strictObject({
address_space_bytes: index,
cpu_seconds: index,
file_size_bytes: index,
}),
maps: z.array(
z.strictObject({
start: hex,
end: hex,
offset: hex,
reported_flags: index,
permissions: z
.strictObject({
read: z.boolean(),
write: z.boolean(),
execute: z.boolean(),
})
.nullable(),
pathname_display: z.string(),
current_file_identity: z.literal("unknown"),
}),
),
confidence: z.literal("derived"),
completeness: z.literal("unknown"),
diagnostics,
}),
]);
/** Portable recorded observations; registers and source coordinates remain lossless. */
const recordedCrashObjectSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: index,
}),
format: z.literal("elf-core"),
architecture: z.literal("x86_64-little-endian"),
target_execution: z.literal("not-performed"),
live_process_identity: z.literal("unknown"),
segments: z.array(
z.strictObject({
index,
type: z.union([z.string(), index]),
header_location: range,
offset: hex,
file_size: hex,
memory_size: hex,
virtual_address: hex,
physical_address: hex,
alignment: hex,
flags: hex,
file_backing: z.enum(["file", "none"]),
}),
),
notes: z.array(
z.strictObject({
index,
segment_index: index,
type: z.union([z.string(), index]),
location: range,
owner_location: range,
owner_bytes_base64: base64,
owner_display: z.string().nullable(),
descriptor_location: range,
descriptor_bytes_base64: base64,
}),
),
note_padding: z.array(
z.strictObject({
segment_index: index,
location: range,
bytes_base64: base64,
}),
),
threads: z.array(
z.strictObject({
note_index: index,
historical_pid: signed32,
recorded_current_signal: z.number().int().min(-32768).max(32767),
registers: z.array(
z.strictObject({
name: z.string().min(1),
value: hex,
location: range,
}),
),
}),
),
signals: z.array(
z.strictObject({
note_index: index,
number: signed32,
code: signed32,
errno: signed32,
fault_address: hex.nullable(),
fault_address_meaning: z.enum(["recorded-sigsegv-address", "unknown"]),
thread_association: z.literal("unknown"),
}),
),
debugger: recordedCrashDebuggerSchema,
note_interpretation_completeness: z.literal("unknown"),
decoder_diagnostics: diagnostics,
diagnostics,
limitations: z.array(z.string()),
});
/** Provider payload excludes identity and diagnostics bound by the owned snapshot boundary. */
export const recordedCrashPayloadSchema = recordedCrashObjectSchema.omit({
artifact: true,
diagnostics: true,
debugger: true,
decoder_diagnostics: true,
});
/** Validate the next consumer's file ranges, note links and register representations. */
export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
(value, context) => {
const fail = (message: string) =>
context.addIssue({ code: "custom", message });
const within = (
item: z.output<typeof range>,
start = 0n,
end = BigInt(value.artifact.bytes),
) => {
const offset = BigInt(item.offset);
const bytes = BigInt(item.bytes);
return offset >= start && offset <= end && bytes <= end - offset;
};
for (const issue of recordedNoteCoverageIssues(
value.segments,
value.notes,
value.note_padding,
))
fail(issue);
for (const [position, segment] of value.segments.entries()) {
if (position !== segment.index || !within(segment.header_location))
fail("Invalid original segment identity or header range.");
if (
segment.file_backing === "file" &&
!within({ offset: segment.offset, bytes: segment.file_size })
)
fail("Recorded segment exceeds artifact bytes.");
if (
segment.type === "PT_LOAD" &&
BigInt(segment.file_size) > BigInt(segment.memory_size)
)
fail("Recorded PT_LOAD file size exceeds memory size.");
}
for (const [position, note] of value.notes.entries()) {
const segment = value.segments[note.segment_index];
if (position !== note.index || segment?.type !== "PT_NOTE") {
fail("Invalid original note identity or segment reference.");
continue;
}
const decodedLength = (raw: string) =>
BigInt(
(raw.length / 4) * 3 -
(raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0),
);
if (
decodedLength(note.owner_bytes_base64) !==
BigInt(note.owner_location.bytes) ||
decodedLength(note.descriptor_bytes_base64) !==
BigInt(note.descriptor_location.bytes)
)
fail("Raw note lengths differ from their source ranges.");
const start = BigInt(segment.offset);
const end = start + BigInt(segment.file_size);
if (
!within(note.location, start, end) ||
!within(
note.owner_location,
BigInt(note.location.offset),
BigInt(note.location.offset) + BigInt(note.location.bytes),
) ||
!within(
note.descriptor_location,
BigInt(note.location.offset),
BigInt(note.location.offset) + BigInt(note.location.bytes),
)
)
fail("Note source ranges exceed their recorded segment.");
}
for (const padding of value.note_padding) {
const segment = value.segments[padding.segment_index];
if (
segment?.type !== "PT_NOTE" ||
!within(
padding.location,
BigInt(segment.offset),
BigInt(segment.offset) + BigInt(segment.file_size),
)
)
fail("Invalid recorded note padding range.");
}
for (const [kind, rows] of [
["NT_PRSTATUS", value.threads],
["NT_SIGINFO", value.signals],
] as const) {
const matchingNotes = value.notes.filter(
(note) =>
note.type === kind &&
note.owner_bytes_base64 === LINUX_CORE_OWNER_BASE64,
);
if (
rows.length !== matchingNotes.length ||
new Set(rows.map(({ note_index }) => note_index)).size !== rows.length
)
fail(
"Each supported raw note requires exactly one corresponding interpretation.",
);
}
for (const thread of value.threads) {
const note = value.notes[thread.note_index];
if (
note?.type !== "NT_PRSTATUS" ||
note.owner_display !== "CORE" ||
note.owner_bytes_base64 !== LINUX_CORE_OWNER_BASE64
) {
fail("Thread references a different note kind.");
continue;
}
if (
thread.registers.length !== RECORDED_LINUX_AMD64_REGISTERS.length ||
!thread.registers.every(({ name }) => supportedRegisters.has(name)) ||
new Set(thread.registers.map(({ name }) => name)).size !==
thread.registers.length
)
fail(
"Each recorded thread requires every supported register exactly once.",
);
for (const register of thread.registers)
if (
BigInt(register.location.bytes) !== 8n ||
!within(
register.location,
BigInt(note.descriptor_location.offset),
BigInt(note.descriptor_location.offset) +
BigInt(note.descriptor_location.bytes),
)
)
fail("Register source exceeds its descriptor.");
}
for (const signal of value.signals) {
if (
value.notes[signal.note_index]?.type !== "NT_SIGINFO" ||
value.notes[signal.note_index]?.owner_display !== "CORE" ||
value.notes[signal.note_index]?.owner_bytes_base64 !==
LINUX_CORE_OWNER_BASE64
)
fail("Signal references a different note kind.");
const known =
signal.number === 11 && (signal.code === 1 || signal.code === 2);
if (
known !== (signal.fault_address !== null) ||
(signal.fault_address !== null) !==
(signal.fault_address_meaning === "recorded-sigsegv-address")
)
fail("Signal union meaning does not match recorded SIGSEGV code.");
}
if (value.debugger.status === "available")
for (const map of value.debugger.maps) {
if (BigInt(map.end) < BigInt(map.start))
fail("Debugger mapping end precedes its start.");
if (
map.permissions !== null &&
(map.permissions.read !== Boolean(map.reported_flags & 4) ||
map.permissions.write !== Boolean(map.reported_flags & 2) ||
map.permissions.execute !== Boolean(map.reported_flags & 1))
)
fail("Mapping permissions differ from reported flags.");
if (
(map.reported_flags === 0 || map.reported_flags > 7) !==
(map.permissions === null)
)
fail(
"Unreported or unfamiliar map flags require unknown permissions.",
);
}
},
);
export type InspectRecordedCrashInput = z.output<
typeof inspectRecordedCrashInputSchema
>;
export type RecordedCrash = z.output<typeof recordedCrashSchema>;
@@ -0,0 +1,111 @@
type Range = { readonly offset: string; readonly bytes: string };
type Segment = {
readonly index: number;
readonly type: string | number;
readonly offset: string;
readonly file_size: string;
};
type Note = {
readonly segment_index: number;
readonly location: Range;
readonly owner_location: Range;
readonly descriptor_location: Range;
};
type Padding = {
readonly segment_index: number;
readonly location: Range;
readonly bytes_base64: string;
};
const align = (size: bigint) => ((size + 3n) / 4n) * 4n;
const layoutMatches = (note: Note): boolean => {
const start = BigInt(note.location.offset);
const owner = BigInt(note.owner_location.bytes);
const descriptor = BigInt(note.descriptor_location.bytes);
return (
BigInt(note.owner_location.offset) === start + 12n &&
BigInt(note.descriptor_location.offset) === start + 12n + align(owner) &&
BigInt(note.location.bytes) === 12n + align(owner) + align(descriptor)
);
};
const paddingMatches = (
item: Padding,
segment: Segment | undefined,
): boolean => {
const bytes = BigInt(item.location.bytes);
const decodedLength =
(item.bytes_base64.length / 4) * 3 -
(item.bytes_base64.endsWith("==")
? 2
: item.bytes_base64.endsWith("=")
? 1
: 0);
return (
bytes > 0n &&
bytes < 12n &&
BigInt(decodedLength) === bytes &&
/^A*={0,2}$/.test(item.bytes_base64) &&
segment !== undefined &&
BigInt(item.location.offset) + bytes ===
BigInt(segment.offset) + BigInt(segment.file_size)
);
};
/** Require exact aligned note layouts and one complete, nonoverlapping physical coverage. */
export function recordedNoteCoverageIssues(
segments: readonly Segment[],
notes: readonly Note[],
padding: readonly Padding[],
): readonly string[] {
const issues: string[] = [];
const bySegment = new Map<number, Range[]>();
const all: Range[] = [];
const add = (segment: number, range: Range) => {
const ranges = bySegment.get(segment) ?? [];
ranges.push(range);
bySegment.set(segment, ranges);
all.push(range);
};
for (const note of notes) {
if (!layoutMatches(note))
issues.push(
"Recorded note layout differs from its aligned header/owner/descriptor ranges.",
);
add(note.segment_index, note.location);
}
for (const item of padding) {
if (!paddingMatches(item, segments[item.segment_index]))
issues.push(
"Recorded note padding must be a short zero-filled segment tail.",
);
add(item.segment_index, item.location);
}
const compare = (left: Range, right: Range) =>
BigInt(left.offset) < BigInt(right.offset)
? -1
: BigInt(left.offset) > BigInt(right.offset)
? 1
: 0;
let end = 0n;
for (const range of all.sort(compare)) {
const start = BigInt(range.offset);
if (start < end)
issues.push("Physical recorded note/padding ranges overlap or repeat.");
if (start + BigInt(range.bytes) > end) end = start + BigInt(range.bytes);
}
for (const segment of segments) {
if (segment.type !== "PT_NOTE") continue;
let cursor = BigInt(segment.offset);
for (const range of (bySegment.get(segment.index) ?? []).sort(compare)) {
if (BigInt(range.offset) !== cursor)
issues.push(
"Recorded note/padding ranges leave a gap or overlap in their segment.",
);
cursor = BigInt(range.offset) + BigInt(range.bytes);
}
if (cursor !== BigInt(segment.offset) + BigInt(segment.file_size))
issues.push(
"Recorded note/padding ranges do not completely cover their segment.",
);
}
return issues;
}
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "32",
skillVersion: "33",
} as const;
+232
View File
@@ -0,0 +1,232 @@
import { access, mkdir, stat, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { randomUUID } from "node:crypto";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { AnalysisCapturedOutput } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import {
recordedCrashDebuggerSchema,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { runOwnedCommand } from "../../process/OwnedCommand.js";
import {
capturedPwntoolsOutput,
pwntoolsDecoderFailure,
} from "../pwntools/PwntoolsFailures.js";
import { PWNTOOLS_LIMITS } from "../pwntools/PwntoolsRelease.js";
import { readPwntoolsFailureEvidence } from "../pwntools/PwntoolsResourceLimits.js";
import type { PwntoolsLauncher } from "../pwntools/PwntoolsDecoder.js";
const OPERATION = "inspect_recorded_crash";
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({ ok: z.literal(true), value: recordedCrashDebuggerSchema }),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"unavailable",
"unsupported",
"decoder",
"format",
"output-limit",
]),
message: z.string(),
}),
]);
/** Add mapping candidates from an owned core-only debugger, using the existing snapshot. */
export const inspectPwndbgCore = async ({
environment,
rootPath,
diagnostics,
options,
launcher,
}: {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly rootPath: string;
readonly diagnostics: AnalysisCapturedOutput;
readonly options: ExecutionOptions | undefined;
readonly launcher?: PwntoolsLauncher;
}): Promise<RecordedCrash["debugger"]> => {
const gdb = environment.REA_PWNDBG_GDB ?? "/usr/bin/gdb";
const entry = environment.REA_PWNDBG_GDBINIT ?? "";
const venv = environment.REA_PWNDBG_VENV_PATH ?? "";
const unavailable = (message: string, cause?: unknown) =>
new AnalysisCapabilityUnavailableError("pwndbg-core", OPERATION, message, {
...(cause === undefined ? {} : { cause }),
userMessage: message,
capturedOutput: diagnostics,
});
for (const [key, path, kind] of [
["REA_PWNDBG_GDB", gdb, "file"],
["REA_PWNDBG_GDBINIT", entry, "file"],
["REA_PWNDBG_VENV_PATH", venv, "directory"],
] as const) {
try {
if (!isAbsolute(path))
throw new Error("Expected an absolute caller-supplied path.");
await access(
path,
key === "REA_PWNDBG_GDB" ? constants.X_OK : constants.R_OK,
);
const information = await stat(path);
if (kind === "file" ? !information.isFile() : !information.isDirectory())
throw new Error(`Expected a ${kind}.`);
} catch (cause: unknown) {
throw unavailable(
`${key} is unavailable at ${path}: ${cause instanceof Error ? cause.message : String(cause)}. Configure the requested core-only context, or omit include_debugger_context for basic recorded evidence.`,
cause,
);
}
}
const stage = join(rootPath, "debugger");
await mkdir(stage, { mode: 0o700 });
const requestPath = join(stage, "request.json");
const replyPath = join(stage, "reply.json");
await writeFile(
requestPath,
JSON.stringify({
snapshot_path: join(rootPath, "object.snapshot"),
reply_path: replyPath,
gdb,
gdbinit: entry,
venv,
}),
{ flag: "wx", mode: 0o600 },
);
let output: AnalysisCapturedOutput | undefined;
try {
options?.signal?.throwIfAborted();
const execution = await runOwnedCommand(
{
command: environment.REA_PWNTOOLS_PYTHON ?? "",
arguments: [
"-I",
fileURLToPath(
new URL("../../../bridge/pwndbg/launch.py", import.meta.url),
),
join(stage, "resource.failure"),
requestPath,
],
cwd: stage,
runId: `rea-recorded-core-debugger-${randomUUID()}`,
hostEnvironment: {
...environment,
PWNDBG_NO_AUTOUPDATE: "1",
PWNDBG_VENV_PATH: venv,
PWNLIB_NOTERM: "1",
TERM: "dumb",
HOME: stage,
XDG_CACHE_HOME: join(stage, "cache"),
XDG_CONFIG_HOME: join(stage, "config"),
PYTHONNOUSERSITE: "1",
OPENBLAS_NUM_THREADS: "1",
OMP_NUM_THREADS: "1",
},
},
{
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
...(launcher === undefined ? {} : { launcher }),
},
);
output = capturedPwntoolsOutput(execution);
let reply: z.output<typeof replySchema>;
try {
const raw = await readStableArtifact(
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
);
reply = replySchema.parse(JSON.parse(raw.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw new AnalysisOutputError(
OPERATION,
`Core-only debugger reply failed: ${cause instanceof Error ? cause.message : String(cause)}`,
{
cause,
capturedOutput: recordedCrashStageOutput(diagnostics, output),
},
);
}
if (!reply.ok) {
if (reply.reason === "unavailable" || reply.reason === "unsupported")
throw new AnalysisCapabilityUnavailableError(
"pwndbg-core",
OPERATION,
reply.message,
{
userMessage: reply.message,
capturedOutput: recordedCrashStageOutput(diagnostics, output),
},
);
if (reply.reason === "format" || reply.reason === "output-limit")
throw new AnalysisOutputError(OPERATION, reply.message, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw new ProviderAdapterError("pwndbg-core", OPERATION, {
diagnostics: {
stage: "debugger",
reason: reply.message,
captured_output: { ...recordedCrashStageOutput(diagnostics, output) },
},
});
}
if (reply.value.status !== "available")
throw new AnalysisOutputError(
OPERATION,
"Requested debugger context returned no core evidence.",
{ capturedOutput: recordedCrashStageOutput(diagnostics, output) },
);
return { ...reply.value, diagnostics: output };
} catch (cause: unknown) {
if (
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
)
throw new AnalysisCancelledError(OPERATION, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw pwntoolsDecoderFailure(
cause,
"debugger",
gdb,
environment.REA_PWNTOOLS_PYTHON ?? "",
await readPwntoolsFailureEvidence(cause, stage),
{
operation: OPERATION,
providerId: "pwndbg-core",
precedingOutput: diagnostics,
},
);
}
};
/** Preserve both stages' exact text and their independently observed truncation state. */
export const recordedCrashStageOutput = (
basic: AnalysisCapturedOutput,
debuggerOutput?: AnalysisCapturedOutput,
): AnalysisCapturedOutput =>
debuggerOutput === undefined
? basic
: {
stdout: `[core decoder]\n${basic.stdout}\n[debugger]\n${debuggerOutput.stdout}`,
stderr: `[core decoder]\n${basic.stderr}\n[debugger]\n${debuggerOutput.stderr}`,
truncated: basic.truncated || debuggerOutput.truncated,
};
+333
View File
@@ -0,0 +1,333 @@
import {
pwntoolsDecoderFailure,
pwntoolsUnavailable,
capturedPwntoolsOutput,
} from "./PwntoolsFailures.js";
import { randomUUID } from "node:crypto";
import { access, stat, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { ProviderIdentity } from "../../application/AnalysisProvider.js";
import type { AnalysisCapturedOutput } from "../../domain/analysisErrorBase.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err, ok, type Result } from "../../domain/result.js";
import { runOwnedCommand } from "../../process/OwnedCommand.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
pwntoolsResourceLimitsSchema,
readPwntoolsFailureEvidence,
} from "./PwntoolsResourceLimits.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
PWNTOOLS_PROVIDER_IDENTITY,
PWNTOOLS_LIMITS,
} from "./PwntoolsRelease.js";
/** Owned launcher seam shared by the offline pwntools artifact adapters. */
export type PwntoolsLauncher = NonNullable<
Parameters<typeof runOwnedCommand>[2]
>["launcher"];
interface DecoderReport {
readonly diagnostics: AnalysisCapturedOutput;
}
/** Adapter-selected semantics around a shared owned pwntools process boundary. */
export interface PwntoolsDecoderProfile<
Input extends { readonly path: string },
Payload,
Report extends DecoderReport,
> {
readonly identity: ProviderIdentity;
readonly operation: string;
readonly bridge: URL;
readonly payloadSchema: z.ZodType<Payload>;
readonly project: (context: {
readonly input: Input;
readonly payload: Payload;
readonly snapshot: { readonly bytes: Buffer; readonly sha256: string };
readonly rootPath: string;
readonly diagnostics: AnalysisCapturedOutput;
readonly options: ExecutionOptions | undefined;
}) => Report | Promise<Report>;
}
/** Thin owned-process adapter; all ELF parsing and heuristics come from unchanged upstream code. */
export class PwntoolsDecoder<
Input extends { readonly path: string },
Payload,
Report extends DecoderReport,
> {
readonly identity: ProviderIdentity;
constructor(
readonly profile: PwntoolsDecoderProfile<Input, Payload, Report>,
readonly environment: Readonly<NodeJS.ProcessEnv>,
readonly launcher?: PwntoolsLauncher,
readonly createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-artifact-decoder-" }),
) {
this.identity = profile.identity;
}
/** Snapshot one explicit artifact and return complete static observations without launching the selected object as a host process. */
async inspect(
input: Input,
options?: ExecutionOptions,
): Promise<Result<Report, AnalysisError>> {
const OPERATION = this.profile.operation;
const context = { operation: OPERATION, providerId: this.identity.id };
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({
ok: z.literal(true),
profile: z.literal(PWNTOOLS_PROVIDER_IDENTITY.version),
value: this.profile.payloadSchema,
}),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"format",
"unsupported",
"unsupported-target",
"unavailable",
"resource-limit",
"output-limit",
"decoder",
]),
message: z.string(),
reported_limits: pwntoolsResourceLimitsSchema.nullable().optional(),
}),
]);
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let result: Result<Report, AnalysisError>;
let phase: "configuration" | "artifact-read" | "decoder" = "configuration";
const executablePath = this.environment.REA_PWNTOOLS_PYTHON ?? "";
let selectedPath = executablePath;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
if (process.platform !== "linux" || process.arch !== "x64")
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
OPERATION,
"The initial real-verified pwntools artifact profile supports Linux x64 only.",
);
if (!isAbsolute(selectedPath))
throw pwntoolsUnavailable(
"Set REA_PWNTOOLS_PYTHON to an absolute caller-supplied Python executable with pwntools 4.15.0, pyelftools 0.33 and Unicorn 2.1.2; REA never installs Python or packages.",
selectedPath,
undefined,
undefined,
context,
);
await access(selectedPath, constants.X_OK);
if (!(await stat(selectedPath)).isFile())
throw pwntoolsUnavailable(
"Selected Python executable must be a regular executable file, not a directory: " +
selectedPath,
selectedPath,
undefined,
undefined,
context,
);
phase = "artifact-read";
selectedPath = input.path;
const snapshot = await readStableArtifact(
input.path,
PWNTOOLS_LIMITS.inputBytes,
options?.signal,
);
phase = "decoder";
root = await this.createRuntime();
const requestPath = join(root.path, "request.json");
const snapshotPath = join(root.path, "object.snapshot");
const replyPath = join(root.path, "reply.json");
await writeFile(snapshotPath, snapshot.bytes, {
flag: "wx",
mode: 0o600,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
await writeFile(
requestPath,
JSON.stringify({ snapshot_path: snapshotPath, reply_path: replyPath }),
{ flag: "wx", mode: 0o600 },
);
const execution = await runOwnedCommand(
{
command: this.environment.REA_PWNTOOLS_PYTHON ?? "",
arguments: [
"-I",
fileURLToPath(this.profile.bridge),
join(root.path, "resource.failure"),
requestPath,
],
cwd: root.path,
runId: `rea-artifact-decoder-${randomUUID()}`,
hostEnvironment: {
...this.environment,
PWNLIB_NOTERM: "1",
OPENBLAS_NUM_THREADS: "1",
OMP_NUM_THREADS: "1",
},
},
{
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
},
);
const capturedOutput = capturedPwntoolsOutput(execution);
let reply: z.output<typeof replySchema>;
try {
const file = await readStableArtifact(
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
);
reply = replySchema.parse(JSON.parse(file.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { capturedOutput });
throw new AnalysisOutputError(
OPERATION,
`Owned pwntools decoder reply failed for ${input.path}: ${cause instanceof z.ZodError ? cause.issues[0]?.message + " at " + (cause.issues[0]?.path.map(String).join(".") ?? "root") : cause instanceof Error ? cause.message : String(cause)}`,
{ cause, capturedOutput },
);
}
if (!reply.ok) {
if (reply.reason === "unsupported-target")
throw new AnalysisUnsupportedTargetError(
OPERATION,
input.path,
reply.message,
{ capturedOutput },
);
if (reply.reason === "resource-limit")
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
reply.message,
reply.reported_limits ?? null,
{ capturedOutput },
);
if (reply.reason === "format")
throw new AnalysisInputError(OPERATION, { capturedOutput }, [
{
path: ["path"],
reason: "invalid_format",
message: reply.message,
},
]);
if (reply.reason === "unavailable")
throw pwntoolsUnavailable(
reply.message,
this.environment.REA_PWNTOOLS_PYTHON ?? "",
undefined,
capturedOutput,
context,
);
if (reply.reason === "unsupported")
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
OPERATION,
reply.message,
{ userMessage: reply.message, capturedOutput },
);
if (reply.reason === "output-limit")
throw new AnalysisOutputError(OPERATION, reply.message, {
capturedOutput,
});
throw new ProviderAdapterError(this.identity.id, OPERATION, {
diagnostics: {
phase,
failure_kind: reply.reason,
reason: reply.message,
stdout: execution.stdout.text,
stderr: execution.stderr.text,
captured_output: { ...capturedOutput },
},
});
}
result = ok(
await this.profile.project({
input,
payload: reply.value,
snapshot,
rootPath: root.path,
diagnostics: capturedOutput,
options,
}),
);
} catch (cause: unknown) {
const evidence = await readPwntoolsFailureEvidence(cause, root?.path);
result = err(
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
? new AnalysisCancelledError(OPERATION)
: pwntoolsDecoderFailure(
cause,
phase,
selectedPath,
executablePath,
evidence,
context,
),
);
}
if (root !== undefined) {
try {
await root.close();
} catch (cause: unknown) {
return err(
new ProviderCleanupError(
this.identity.id,
[root.path],
{
reason: cause instanceof Error ? cause.message : String(cause),
previous_error: result.ok
? null
: projectAnalysisError(result.error),
...(result.ok
? {
captured_output: {
stdout: result.value.diagnostics.stdout,
stderr: result.value.diagnostics.stderr,
truncated: result.value.diagnostics.truncated,
},
}
: {}),
},
{ operation: OPERATION },
),
);
}
}
return result.ok && options?.signal?.aborted
? err(
new AnalysisCancelledError(OPERATION, {
capturedOutput: {
stdout: result.value.diagnostics.stdout,
stderr: result.value.diagnostics.stderr,
truncated: result.value.diagnostics.truncated,
},
}),
)
: result;
}
}
+75 -28
View File
@@ -25,33 +25,58 @@ import {
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
const OPERATION = "inspect_binary_layout";
/** Operation identity supplied by each adapter sharing the pwntools boundary. */
export interface PwntoolsFailureContext {
readonly operation: string;
readonly providerId: string;
readonly precedingOutput?: AnalysisCapturedOutput;
}
const DEFAULT_CONTEXT = {
operation: "inspect_binary_layout",
providerId: PWNTOOLS_PROVIDER_IDENTITY.id,
};
/** Keep read, engine, output and owned-lifecycle failure reasons distinct. */
export const pwntoolsLayoutFailure = (
export const pwntoolsDecoderFailure = (
cause: unknown,
phase: string,
path: string,
executablePath = path,
failureEvidence: PwntoolsFailureEvidence = {},
context: PwntoolsFailureContext = DEFAULT_CONTEXT,
): AnalysisError => {
const limitReport = failureEvidence.limits;
if (cause instanceof AnalysisError) return cause;
if (cause instanceof OwnedCommandFailure) {
const outputOptions =
const currentOutput =
cause.snapshot === null
? undefined
: { capturedOutput: capturedPwntoolsOutput(cause.snapshot) };
: capturedPwntoolsOutput(cause.snapshot);
const combinedOutput =
context.precedingOutput === undefined
? currentOutput
: currentOutput === undefined
? context.precedingOutput
: {
stdout: `[core decoder]\n${context.precedingOutput.stdout}\n[debugger]\n${currentOutput.stdout}`,
stderr: `[core decoder]\n${context.precedingOutput.stderr}\n[debugger]\n${currentOutput.stderr}`,
truncated:
context.precedingOutput.truncated || currentOutput.truncated,
};
const outputOptions =
combinedOutput === undefined
? undefined
: { capturedOutput: combinedOutput };
if (cause.cleanupFailure !== null)
return new ProviderCleanupError(
PWNTOOLS_PROVIDER_IDENTITY.id,
context.providerId,
cause.resources,
{
reason: cause.cleanupFailure,
...(cause.snapshot === null
...(combinedOutput === undefined
? {}
: {
captured_output: { ...capturedPwntoolsOutput(cause.snapshot) },
captured_output: { ...combinedOutput },
}),
previous_error: {
failure_kind: cause.reason,
@@ -62,18 +87,22 @@ export const pwntoolsLayoutFailure = (
stderr: cause.snapshot?.stderr.text ?? null,
},
},
{ operation: OPERATION, cause },
{ operation: context.operation, cause },
);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION, outputOptions);
return new AnalysisCancelledError(context.operation, outputOptions);
if (cause.reason === "timeout")
return new AnalysisTimeoutError(
OPERATION,
context.operation,
PWNTOOLS_LIMITS.timeoutMs,
outputOptions,
);
if (cause.reason === "output-limit")
return new AnalysisOutputError(OPERATION, cause.message, outputOptions);
return new AnalysisOutputError(
context.operation,
cause.message,
outputOptions,
);
if (
cause.reason === "process" &&
(cause.snapshot?.signal === "SIGXFSZ" ||
@@ -82,7 +111,7 @@ export const pwntoolsLayoutFailure = (
cause.snapshot.signal === null))
)
return new AnalysisResourceConstraintError(
OPERATION,
context.operation,
"file-size",
(cause.snapshot.signal === "SIGXFSZ"
? "Owned Python terminated with SIGXFSZ; the exact signal cause is unknown."
@@ -95,7 +124,7 @@ export const pwntoolsLayoutFailure = (
);
if (cause.reason === "process" && cause.snapshot?.signal === "SIGXCPU")
return new AnalysisResourceConstraintError(
OPERATION,
context.operation,
"cpu",
"Owned Python terminated with SIGXCPU; the exact signal cause is unknown." +
(limitReport?.failure === null || limitReport === undefined
@@ -111,7 +140,7 @@ export const pwntoolsLayoutFailure = (
cause.snapshot.signal === null
)
return new AnalysisResourceConstraintError(
OPERATION,
context.operation,
"memory",
"The owned Python bridge reported a memory allocation failure without a structured reply; the exact allocation cause is unknown." +
(limitReport?.failure === null || limitReport === undefined
@@ -132,20 +161,27 @@ export const pwntoolsLayoutFailure = (
`Selected Python could not launch (${String(cause.code)}): ${executablePath}. Check the configured executable, its interpreter and host execute access.`,
executablePath,
String(cause.code),
undefined,
context,
);
if (cause instanceof ArtifactReaderFailure) {
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, cause.message, {
cause,
});
return new AnalysisArtifactChangedError(
context.operation,
path,
cause.message,
{
cause,
},
);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION);
return new AnalysisCancelledError(context.operation);
if (
cause.reason === "limit" ||
cause.reason === "path" ||
cause.reason === "format"
)
return new AnalysisInputError(OPERATION, { cause }, [
return new AnalysisInputError(context.operation, { cause }, [
{
path: ["path"],
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
@@ -159,19 +195,26 @@ export const pwntoolsLayoutFailure = (
`Selected Python executable is unavailable (${String(cause.code)}): ${path}. Check the caller-selected path and execute access.`,
path,
String(cause.code),
undefined,
context,
);
if (
phase === "artifact-read" &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
return new AnalysisAccessDeniedError(
context.operation,
path,
cause.code,
{
cause,
},
);
if (
phase === "artifact-read" &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
return new AnalysisInputError(OPERATION, { cause }, [
return new AnalysisInputError(context.operation, { cause }, [
{
path: ["path"],
reason: "invalid_value",
@@ -179,11 +222,14 @@ export const pwntoolsLayoutFailure = (
},
]);
}
return new ProviderAdapterError(PWNTOOLS_PROVIDER_IDENTITY.id, OPERATION, {
return new ProviderAdapterError(context.providerId, context.operation, {
cause,
diagnostics: {
phase,
path,
...(context.precedingOutput === undefined
? {}
: { preceding_output: { ...context.precedingOutput } }),
reason: cause instanceof Error ? cause.message : String(cause),
...(failureEvidence.marker === undefined
? {}
@@ -214,16 +260,17 @@ export const pwntoolsUnavailable = (
path: string,
systemCode?: string,
capturedOutput?: AnalysisCapturedOutput,
context: PwntoolsFailureContext = DEFAULT_CONTEXT,
): ProviderSelectionError =>
new ProviderSelectionError({
...(capturedOutput === undefined ? {} : { capturedOutput }),
operation: OPERATION,
operation: context.operation,
reason: "provider_unavailable",
requestedProviderId: PWNTOOLS_PROVIDER_IDENTITY.id,
candidateIds: [PWNTOOLS_PROVIDER_IDENTITY.id],
requestedProviderId: context.providerId,
candidateIds: [context.providerId],
rejections: [
{
providerId: PWNTOOLS_PROVIDER_IDENTITY.id,
providerId: context.providerId,
code: "provider_unavailable",
reason,
diagnostics: {
+58 -365
View File
@@ -1,381 +1,74 @@
import {
pwntoolsLayoutFailure,
pwntoolsUnavailable,
capturedPwntoolsOutput,
} from "./PwntoolsFailures.js";
import { randomUUID } from "node:crypto";
import { access, stat, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { BinaryLayoutPort } from "../../application/binaryDiagnostics/BinaryLayoutPort.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
binaryLayoutPayloadSchema,
binaryLayoutSchema,
type BinaryLayout,
type InspectBinaryLayoutInput,
} from "../../domain/native/binaryLayout.js";
import { runOwnedCommand } from "../../process/OwnedCommand.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
pwntoolsResourceLimitsSchema,
type PwntoolsLimitReport,
type PwntoolsFailureEvidence,
} from "./PwntoolsResourceLimits.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { PwntoolsDecoder, type PwntoolsLauncher } from "./PwntoolsDecoder.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "./PwntoolsRelease.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
PWNTOOLS_PROVIDER_IDENTITY,
PWNTOOLS_LIMITS,
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
PWNTOOLS_MEMORY_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
import type { BinaryLayoutPort } from "../../application/binaryDiagnostics/BinaryLayoutPort.js";
import type { z } from "zod";
const OPERATION = "inspect_binary_layout";
const decoded = binaryLayoutPayloadSchema;
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({
ok: z.literal(true),
profile: z.literal(PWNTOOLS_PROVIDER_IDENTITY.version),
value: decoded,
}),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"format",
"unsupported",
"unavailable",
"resource-limit",
"output-limit",
"decoder",
]),
message: z.string(),
reported_limits: pwntoolsResourceLimitsSchema.nullable().optional(),
}),
]);
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
/** Thin owned-process adapter; all ELF parsing and heuristics come from unchanged upstream code. */
export class PwntoolsLayoutProvider implements BinaryLayoutPort {
readonly identity = PWNTOOLS_PROVIDER_IDENTITY;
/** ELF-specific projection around the shared owned pwntools decoder boundary. */
export class PwntoolsLayoutProvider
extends PwntoolsDecoder<
InspectBinaryLayoutInput,
z.output<typeof binaryLayoutPayloadSchema>,
BinaryLayout
>
implements BinaryLayoutPort
{
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv>,
readonly launcher?: Launcher,
readonly createRuntime: () => Promise<
environment: Readonly<NodeJS.ProcessEnv>,
launcher?: PwntoolsLauncher,
createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-elf-layout-" }),
) {}
/** Snapshot one explicit artifact and return complete static observations without launching the selected object as a host process. */
async inspect(
input: InspectBinaryLayoutInput,
options?: ExecutionOptions,
): Promise<Result<BinaryLayout, AnalysisError>> {
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let result: Result<BinaryLayout, AnalysisError>;
let phase: "configuration" | "artifact-read" | "decoder" = "configuration";
const executablePath = this.environment.REA_PWNTOOLS_PYTHON ?? "";
let selectedPath = executablePath;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
if (process.platform !== "linux" || process.arch !== "x64")
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
OPERATION,
"The real-verified pwntools layout profile currently supports Linux x64 only.",
);
if (!isAbsolute(selectedPath))
throw pwntoolsUnavailable(
"Set REA_PWNTOOLS_PYTHON to an absolute caller-supplied Python executable with pwntools 4.15.0, pyelftools 0.33 and Unicorn 2.1.2; REA never installs Python or packages.",
selectedPath,
);
await access(selectedPath, constants.X_OK);
if (!(await stat(selectedPath)).isFile())
throw pwntoolsUnavailable(
"Selected Python executable must be a regular executable file, not a directory: " +
selectedPath,
selectedPath,
);
phase = "artifact-read";
selectedPath = input.path;
const snapshot = await readStableArtifact(
input.path,
PWNTOOLS_LIMITS.inputBytes,
options?.signal,
);
phase = "decoder";
root = await this.createRuntime();
const requestPath = join(root.path, "request.json");
const snapshotPath = join(root.path, "object.snapshot");
const replyPath = join(root.path, "reply.json");
await writeFile(snapshotPath, snapshot.bytes, {
flag: "wx",
mode: 0o600,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
await writeFile(
requestPath,
JSON.stringify({ snapshot_path: snapshotPath, reply_path: replyPath }),
{ flag: "wx", mode: 0o600 },
);
const execution = await runOwnedCommand(
{
command: this.environment.REA_PWNTOOLS_PYTHON ?? "",
arguments: [
"-I",
fileURLToPath(
new URL("../../../bridge/pwntools/layout.py", import.meta.url),
),
join(root.path, "resource.failure"),
requestPath,
],
cwd: root.path,
runId: `rea-elf-layout-${randomUUID()}`,
hostEnvironment: {
...this.environment,
PWNLIB_NOTERM: "1",
OPENBLAS_NUM_THREADS: "1",
OMP_NUM_THREADS: "1",
},
},
{
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
},
);
const capturedOutput = capturedPwntoolsOutput(execution);
let reply: z.output<typeof replySchema>;
try {
const file = await readStableArtifact(
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
);
reply = replySchema.parse(JSON.parse(file.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { capturedOutput });
throw new AnalysisOutputError(
OPERATION,
`Owned ELF decoder reply failed for ${input.path}: ${cause instanceof z.ZodError ? cause.issues[0]?.message + " at " + (cause.issues[0]?.path.map(String).join(".") ?? "root") : cause instanceof Error ? cause.message : String(cause)}`,
{ cause, capturedOutput },
);
}
if (!reply.ok) {
if (reply.reason === "resource-limit")
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
reply.message,
reply.reported_limits ?? null,
{ capturedOutput },
);
if (reply.reason === "format")
throw new AnalysisInputError(OPERATION, { capturedOutput }, [
{
path: ["path"],
reason: "invalid_format",
message: reply.message,
) {
super(
{
identity: PWNTOOLS_PROVIDER_IDENTITY,
operation: "inspect_binary_layout",
bridge: new URL("../../../bridge/pwntools/layout.py", import.meta.url),
payloadSchema: binaryLayoutPayloadSchema,
project: ({ input, payload, snapshot, diagnostics }) => {
const value = binaryLayoutSchema.safeParse({
...payload,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
]);
if (reply.reason === "unavailable")
throw pwntoolsUnavailable(
reply.message,
this.environment.REA_PWNTOOLS_PYTHON ?? "",
undefined,
capturedOutput,
);
if (reply.reason === "unsupported")
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
OPERATION,
reply.message,
{ userMessage: reply.message, capturedOutput },
);
if (reply.reason === "output-limit")
throw new AnalysisOutputError(OPERATION, reply.message, {
capturedOutput,
diagnostics,
});
throw new ProviderAdapterError(this.identity.id, OPERATION, {
diagnostics: {
phase,
failure_kind: reply.reason,
reason: reply.message,
stdout: execution.stdout.text,
stderr: execution.stderr.text,
captured_output: { ...capturedOutput },
},
});
}
const validated = binaryLayoutSchema.safeParse({
...reply.value,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
diagnostics: {
stdout: execution.stdout.text,
stderr: execution.stderr.text,
truncated: capturedOutput.truncated,
},
});
if (!validated.success)
throw new AnalysisOutputError(
OPERATION,
`ELF reply contains invalid source ranges or value meanings: ${validated.error.issues[0]?.message ?? "schema mismatch"}`,
{ capturedOutput },
);
for (const table of validated.data.packed_relative_relocations) {
const start = Number(BigInt(table.location.offset));
const length = Number(BigInt(table.location.bytes));
if (
!Buffer.from(table.encoded_bytes_base64, "base64").equals(
snapshot.bytes.subarray(start, start + length),
)
)
throw new AnalysisOutputError(
OPERATION,
"Reported packed relocation bytes differ from the selected snapshot at their original file range.",
{ capturedOutput },
);
}
result = ok(validated.data);
} catch (cause: unknown) {
let limitReport: PwntoolsLimitReport | undefined;
let marker: PwntoolsFailureEvidence["marker"];
if (
cause instanceof OwnedCommandFailure &&
cause.snapshot?.signal === null &&
(cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT ||
cause.snapshot.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT) &&
root !== undefined
) {
try {
const reported = await readStableArtifact(
join(root.path, "resource.failure"),
1,
);
const expected =
cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT
? "M"
: "F";
if (!reported.bytes.equals(Buffer.from(expected, "ascii")))
throw new Error(
"Private bridge failure marker does not match the observed exit status.",
if (!value.success)
throw new AnalysisOutputError(
"inspect_binary_layout",
`ELF reply contains invalid source ranges or value meanings: ${value.error.issues[0]?.message ?? "schema mismatch"}`,
{ capturedOutput: diagnostics },
);
marker = {
resource: expected === "M" ? "memory" : "file-size",
failure: null,
};
} catch (markerFailure: unknown) {
marker = {
resource: null,
failure:
markerFailure instanceof Error
? markerFailure.message
: String(markerFailure),
};
}
}
if (
cause instanceof OwnedCommandFailure &&
(cause.snapshot?.signal === "SIGXCPU" ||
cause.snapshot?.signal === "SIGXFSZ" ||
((cause.snapshot?.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT ||
cause.snapshot?.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT) &&
cause.snapshot.signal === null)) &&
root !== undefined
) {
try {
const reported = await readStableArtifact(
join(root.path, "limits.json"),
4096,
);
limitReport = {
limits: pwntoolsResourceLimitsSchema.parse(
JSON.parse(reported.bytes.toString("utf8")),
),
failure: null,
};
} catch (reportFailure: unknown) {
limitReport = {
limits: null,
failure:
reportFailure instanceof Error
? reportFailure.message
: String(reportFailure),
};
}
}
result = err(
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
? new AnalysisCancelledError(OPERATION)
: pwntoolsLayoutFailure(cause, phase, selectedPath, executablePath, {
...(limitReport === undefined ? {} : { limits: limitReport }),
...(marker === undefined ? {} : { marker }),
}),
);
}
if (root !== undefined) {
try {
await root.close();
} catch (cause: unknown) {
return err(
new ProviderCleanupError(
this.identity.id,
[root.path],
{
reason: cause instanceof Error ? cause.message : String(cause),
previous_error: result.ok
? null
: projectAnalysisError(result.error),
...(result.ok
? {
captured_output: {
stdout: result.value.diagnostics.stdout,
stderr: result.value.diagnostics.stderr,
truncated: result.value.diagnostics.truncated,
},
}
: {}),
},
{ operation: OPERATION },
),
);
}
}
return result.ok && options?.signal?.aborted
? err(
new AnalysisCancelledError(OPERATION, {
capturedOutput: {
stdout: result.value.diagnostics.stdout,
stderr: result.value.diagnostics.stderr,
truncated: result.value.diagnostics.truncated,
},
}),
)
: result;
for (const table of value.data.packed_relative_relocations) {
const start = Number(BigInt(table.location.offset));
const length = Number(BigInt(table.location.bytes));
if (
!Buffer.from(table.encoded_bytes_base64, "base64").equals(
snapshot.bytes.subarray(start, start + length),
)
)
throw new AnalysisOutputError(
"inspect_binary_layout",
"Reported packed relocation bytes differ from the selected snapshot at their original file range.",
{ capturedOutput: diagnostics },
);
}
return value.data;
},
},
environment,
launcher,
createRuntime,
);
}
}
@@ -0,0 +1,144 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import {
recordedCrashPayloadSchema,
recordedCrashSchema,
type InspectRecordedCrashInput,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
import type { RecordedCrashPort } from "../../application/binaryDiagnostics/RecordedCrashPort.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import { PwntoolsDecoder, type PwntoolsLauncher } from "./PwntoolsDecoder.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "./PwntoolsRelease.js";
import { validateRecordedCrashSources } from "./RecordedCrashSourceBindings.js";
import { validateRecordedCrashStructure } from "./RecordedCrashStructureBindings.js";
import {
inspectPwndbgCore,
recordedCrashStageOutput,
} from "../pwndbg/PwndbgCoreContext.js";
import type { z } from "zod";
/** Preserve every recorded thread while optionally enriching the same owned snapshot. */
export class PwntoolsRecordedCrashProvider
extends PwntoolsDecoder<
InspectRecordedCrashInput,
z.output<typeof recordedCrashPayloadSchema>,
RecordedCrash
>
implements RecordedCrashPort
{
constructor(
environment: Readonly<NodeJS.ProcessEnv>,
launcher?: PwntoolsLauncher,
createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-recorded-crash-" }),
) {
super(
{
identity: PWNTOOLS_PROVIDER_IDENTITY,
operation: "inspect_recorded_crash",
bridge: new URL(
"../../../bridge/pwntools/recorded_crash.py",
import.meta.url,
),
payloadSchema: recordedCrashPayloadSchema,
project: async ({
input,
payload,
snapshot,
rootPath,
diagnostics,
options,
}) => {
const validate = (debuggerContext: RecordedCrash["debugger"]) =>
recordedCrashSchema.safeParse({
...payload,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
debugger: debuggerContext,
decoder_diagnostics: diagnostics,
diagnostics:
debuggerContext.status === "available"
? recordedCrashStageOutput(
diagnostics,
debuggerContext.diagnostics,
)
: diagnostics,
});
const checked = validate({ status: "not-requested" });
if (!checked.success)
throw new AnalysisOutputError(
"inspect_recorded_crash",
`Recorded core reply is invalid: ${checked.error.issues[0]?.message ?? "schema mismatch"}`,
{ capturedOutput: diagnostics },
);
const value = checked.data;
validateRecordedCrashStructure(value, snapshot.bytes, diagnostics);
const checkBytes = (
raw: string,
range: { readonly offset: string; readonly bytes: string },
) => {
const start = Number(BigInt(range.offset));
const length = Number(BigInt(range.bytes));
if (
!Buffer.from(raw, "base64").equals(
snapshot.bytes.subarray(start, start + length),
)
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported raw note bytes differ from the selected snapshot.",
{ capturedOutput: diagnostics },
);
};
for (const note of value.notes) {
checkBytes(note.owner_bytes_base64, note.owner_location);
checkBytes(note.descriptor_bytes_base64, note.descriptor_location);
}
for (const padding of value.note_padding)
checkBytes(padding.bytes_base64, padding.location);
validateRecordedCrashSources(value, snapshot.bytes, diagnostics);
for (const thread of value.threads)
for (const register of thread.registers) {
const start = Number(BigInt(register.location.offset));
if (
snapshot.bytes.readBigUInt64LE(start) !== BigInt(register.value)
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported register value differs from its recorded source bytes.",
{ capturedOutput: diagnostics },
);
}
if (!input.include_debugger_context) return value;
const context = await inspectPwndbgCore({
environment,
rootPath,
diagnostics,
options,
...(launcher === undefined ? {} : { launcher }),
});
const enriched = validate(context);
if (!enriched.success)
throw new AnalysisOutputError(
"inspect_recorded_crash",
`Recorded debugger context is invalid: ${enriched.error.issues[0]?.message ?? "schema mismatch"}`,
{
capturedOutput:
context.status === "available"
? recordedCrashStageOutput(diagnostics, context.diagnostics)
: diagnostics,
},
);
return enriched.data;
},
},
environment,
launcher,
createRuntime,
);
}
}
@@ -1,3 +1,10 @@
import { join } from "node:path";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
PWNTOOLS_MEMORY_FAILURE_EXIT,
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
import { z } from "zod";
import { PWNTOOLS_LIMITS } from "./PwntoolsRelease.js";
@@ -30,3 +37,78 @@ export interface PwntoolsFailureEvidence {
readonly failure: string | null;
};
}
/** Read only bounded owned reports; unverified reserved statuses stay unclassified. */
export const readPwntoolsFailureEvidence = async (
cause: unknown,
rootPath?: string,
): Promise<PwntoolsFailureEvidence> => {
let limitReport: PwntoolsLimitReport | undefined;
let marker: PwntoolsFailureEvidence["marker"];
if (
cause instanceof OwnedCommandFailure &&
cause.snapshot?.signal === null &&
(cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT ||
cause.snapshot.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT) &&
rootPath !== undefined
) {
try {
const reported = await readStableArtifact(
join(rootPath, "resource.failure"),
1,
);
const expected =
cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT ? "M" : "F";
if (!reported.bytes.equals(Buffer.from(expected, "ascii")))
throw new Error(
"Private bridge failure marker does not match the observed exit status.",
);
marker = {
resource: expected === "M" ? "memory" : "file-size",
failure: null,
};
} catch (markerFailure: unknown) {
marker = {
resource: null,
failure:
markerFailure instanceof Error
? markerFailure.message
: String(markerFailure),
};
}
}
if (
cause instanceof OwnedCommandFailure &&
(cause.snapshot?.signal === "SIGXCPU" ||
cause.snapshot?.signal === "SIGXFSZ" ||
((cause.snapshot?.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT ||
cause.snapshot?.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT) &&
cause.snapshot.signal === null)) &&
rootPath !== undefined
) {
try {
const reported = await readStableArtifact(
join(rootPath, "limits.json"),
4096,
);
limitReport = {
limits: pwntoolsResourceLimitsSchema.parse(
JSON.parse(reported.bytes.toString("utf8")),
),
failure: null,
};
} catch (reportFailure: unknown) {
limitReport = {
limits: null,
failure:
reportFailure instanceof Error
? reportFailure.message
: String(reportFailure),
};
}
}
return {
...(limitReport === undefined ? {} : { limits: limitReport }),
...(marker === undefined ? {} : { marker }),
};
};
@@ -0,0 +1,68 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import {
RECORDED_LINUX_AMD64_REGISTERS,
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. */
export function validateRecordedCrashSources(
report: RecordedCrash,
snapshot: Buffer,
diagnostics: RecordedCrash["decoder_diagnostics"],
): void {
const fail = () => {
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported PID or signal value differs from its recorded Linux amd64 source bytes.",
{ capturedOutput: diagnostics },
);
};
const descriptor = (noteIndex: number, minimumBytes: number): Buffer => {
const note = report.notes[noteIndex];
if (note === undefined) return fail();
const start = Number(BigInt(note.descriptor_location.offset));
const length = Number(BigInt(note.descriptor_location.bytes));
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.
for (const thread of report.threads) {
const bytes = descriptor(thread.note_index, 336);
if (
thread.historical_pid !== bytes.readInt32LE(32) ||
thread.recorded_current_signal !== bytes.readInt16LE(12)
)
fail();
const note = report.notes[thread.note_index];
if (note === undefined) return fail();
for (const register of thread.registers) {
const offset = registerOffsets.get(register.name);
if (
offset === undefined ||
BigInt(register.location.offset) !==
BigInt(note.descriptor_location.offset) + BigInt(offset)
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported register source does not match its Linux amd64 register identity.",
{ capturedOutput: diagnostics },
);
}
}
for (const signal of report.signals) {
const bytes = descriptor(signal.note_index, 32);
if (
signal.number !== bytes.readInt32LE(0) ||
signal.errno !== bytes.readInt32LE(4) ||
signal.code !== bytes.readInt32LE(8) ||
(signal.fault_address !== null &&
BigInt(signal.fault_address) !== bytes.readBigUInt64LE(16))
)
fail();
}
}
@@ -0,0 +1,133 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { RecordedCrash } from "../../domain/native/recordedCrash.js";
// Exact amd64/core enum projections in the pinned pyelftools 0.33 profile.
const segmentKinds = new Map([
[0, "PT_NULL"],
[1, "PT_LOAD"],
[2, "PT_DYNAMIC"],
[3, "PT_INTERP"],
[4, "PT_NOTE"],
[5, "PT_SHLIB"],
[6, "PT_PHDR"],
[7, "PT_TLS"],
[0x60000000, "PT_LOOS"],
[0x6fffffff, "PT_HIOS"],
[0x6474e550, "PT_GNU_EH_FRAME"],
[0x6474e551, "PT_GNU_STACK"],
[0x6474e552, "PT_GNU_RELRO"],
[0x6474e553, "PT_GNU_PROPERTY"],
]);
const noteKinds = new Map([
[1, "NT_PRSTATUS"],
[2, "NT_FPREGSET"],
[3, "NT_PRPSINFO"],
[4, "NT_TASKSTRUCT"],
[6, "NT_AUXV"],
[0x53494749, "NT_SIGINFO"],
[0x46494c45, "NT_FILE"],
]);
const matchesKind = (
raw: number,
reported: string | number,
kinds: ReadonlyMap<number, string>,
): boolean => {
const known = kinds.get(raw);
return typeof reported === "string"
? reported === known
: known === undefined && reported === raw;
};
const segmentMatches = (
segment: RecordedCrash["segments"][number],
raw: Buffer,
): boolean => {
const type = raw.readUInt32LE(0);
return (
matchesKind(type, segment.type, segmentKinds) &&
BigInt(segment.flags) === BigInt(raw.readUInt32LE(4)) &&
segment.file_backing ===
(type === 0 || raw.readBigUInt64LE(32) === 0n ? "none" : "file") &&
(
[
[segment.offset, 8],
[segment.virtual_address, 16],
[segment.physical_address, 24],
[segment.file_size, 32],
[segment.memory_size, 40],
[segment.alignment, 48],
] as const
).every(
([field, relative]) => BigInt(field) === raw.readBigUInt64LE(relative),
)
);
};
/** Bind coverage-bearing ELF and note headers to the same snapshot as their payloads. */
export function validateRecordedCrashStructure(
report: RecordedCrash,
snapshot: Buffer,
diagnostics: RecordedCrash["decoder_diagnostics"],
): void {
const fail = () => {
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported core structure differs from its original ELF/note headers.",
{ capturedOutput: diagnostics },
);
};
const bytesAt = (offset: bigint, bytes: number): Buffer => {
if (offset < 0n || offset > BigInt(snapshot.length - bytes)) return fail();
return snapshot.subarray(Number(offset), Number(offset) + bytes);
};
const header = bytesAt(0n, 64);
if (
!header
.subarray(0, 6)
.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1])) ||
![0, 3].includes(header[7] ?? -1) ||
header[8] !== 0 ||
header.readUInt16LE(16) !== 4 ||
header.readUInt16LE(18) !== 62
)
fail();
const table = header.readBigUInt64LE(32);
const entryBytes = header.readUInt16LE(54);
let count = header.readUInt16LE(56);
if (count === 0xffff) {
if (header.readUInt16LE(58) < 64) return fail();
count = bytesAt(header.readBigUInt64LE(40), 64).readUInt32LE(44);
}
if (count !== report.segments.length || (count > 0 && entryBytes < 56))
fail();
for (const segment of report.segments) {
const offset = table + BigInt(segment.index) * BigInt(entryBytes);
if (
BigInt(segment.header_location.offset) !== offset ||
BigInt(segment.header_location.bytes) !== BigInt(entryBytes)
)
fail();
const raw = bytesAt(offset, entryBytes);
if (!segmentMatches(segment, raw)) fail();
}
for (const note of report.notes) {
const raw = bytesAt(BigInt(note.location.offset), 12);
if (
BigInt(note.owner_location.bytes) !== BigInt(raw.readUInt32LE(0)) ||
BigInt(note.descriptor_location.bytes) !== BigInt(raw.readUInt32LE(4)) ||
!matchesKind(raw.readUInt32LE(8), note.type, noteKinds)
)
fail();
const owner = bytesAt(
BigInt(note.owner_location.offset),
raw.readUInt32LE(0),
);
const terminator = owner.indexOf(0);
const display =
owner.length === 0
? null
: owner.subarray(0, terminator).toString("utf8");
if ((owner.length > 0 && terminator < 0) || note.owner_display !== display)
fail();
}
}
+15
View File
@@ -1,6 +1,9 @@
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import { createEvmInterfaceService } from "../composition/evm.js";
import { registerEvmTools } from "./registerEvmTools.js";
import { registerRecordedCrashTools } from "./registerRecordedCrashTools.js";
import { createRecordedCrashService } from "../composition/binaryDiagnostics.js";
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
import { registerBinaryDiagnosticsTools } from "./registerBinaryDiagnosticsTools.js";
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
@@ -68,6 +71,7 @@ export interface CreateServerOptions {
readonly evmInterface?: EvmInterfaceService;
readonly logger?: Logger;
readonly binaryLayout?: BinaryLayoutService;
readonly recordedCrash?: RecordedCrashService;
readonly firmwareAnalysis?: FirmwareAnalysisPort;
readonly javascriptRecovery?: JavaScriptRecoveryPort;
readonly webModuleTrace?: WebModuleTraceService;
@@ -99,6 +103,11 @@ const installSessionToolAvailability = (
webModuleResolutionEnabled:
options.webModuleTrace !== undefined ||
isAbsolute(process.env.REA_BROWSER_EXECUTABLE ?? ""),
recordedCrashEnabled:
options.recordedCrash !== undefined ||
(process.platform === "linux" &&
process.arch === "x64" &&
isAbsolute(process.env.REA_PWNTOOLS_PYTHON ?? "")),
binaryLayoutEnabled:
options.binaryLayout !== undefined ||
(process.platform === "linux" &&
@@ -218,6 +227,12 @@ export const createServer = (
toolLogger,
recordEvidence,
);
registerRecordedCrashTools(
server,
options.recordedCrash ?? createRecordedCrashService(),
toolLogger,
recordEvidence,
);
registerFirmwareTools(
server,
new FirmwareAnalysisService(
+32
View File
@@ -0,0 +1,32 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { toCallToolResult } from "./toolResult.js";
/** Bind recorded crash inspection to its named contract and session Evidence owner. */
export const registerRecordedCrashTools = (
server: McpServer,
service: RecordedCrashService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
): void => {
const contract = toolContract("inspect_recorded_crash");
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input, context) => {
const result = await logToolExecution(logger, contract.name, () =>
service.inspect(input, { signal: context.mcpReq.signal }),
);
if (!result.ok) return toCallToolResult(result, contract);
const recorded = recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult(result, contract);
},
);
};
+3
View File
@@ -20,6 +20,7 @@ export interface SessionAvailabilityDefaults {
| "javascriptRecoveryEnabled"
| "webModuleResolutionEnabled"
| "binaryLayoutEnabled"
| "recordedCrashEnabled"
| "firmwareInspectionEnabled"
| "firmwareExtractionEnabled"
>;
@@ -36,6 +37,8 @@ export const sessionAvailabilityPolicy = (
evmInterfaceEnabled:
defaults.optionalFeatures?.evmInterfaceEnabled ?? false,
processCaptureEnabled: platform !== "win32",
recordedCrashEnabled:
defaults.optionalFeatures?.recordedCrashEnabled ?? false,
binaryLayoutEnabled:
defaults.optionalFeatures?.binaryLayoutEnabled ?? false,
firmwareInspectionEnabled: