chore: merge captured main into iNES container support

This commit is contained in:
morluto
2026-10-13 21:45:12 +08:00
252 changed files with 12483 additions and 1405 deletions
+65 -2
View File
@@ -52,7 +52,7 @@ const snapshotWithHistoricalEvidence = () => {
};
return {
current,
snapshot: {
snapshot: analysisSnapshotSchema.parse({
target,
binding,
entries: [entry],
@@ -66,11 +66,32 @@ const snapshotWithHistoricalEvidence = () => {
result: { summary: "unprofiled" },
}),
]),
} satisfies AnalysisSnapshot,
}),
};
};
describe("analysis snapshot target identity", () => {
it("keeps 6502 confined to executable raw snapshots", () => {
const target = {
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable",
architecture: "6502",
};
expect(
analysisSnapshotSchema.shape.target.safeParse({
...target,
format: "pe",
}).success,
).toBe(false);
expect(
analysisSnapshotSchema.shape.target.safeParse({
...target,
format: "raw-binary",
entry_point: "0x8001",
}).success,
).toBe(true);
});
it("partitions raw snapshots and query identities by the canonical entry", () => {
const target: BinaryTarget = {
path: "/fixture/image.bin",
@@ -120,6 +141,48 @@ describe("analysis snapshot target identity", () => {
});
});
describe("analysis snapshot nested subject contract", () => {
it("rejects raw-only 6502 in nested detected execution subjects", () => {
const { snapshot } = snapshotWithHistoricalEvidence();
const entry = snapshot.entries[0];
if (entry === undefined) throw new Error("Fixture has no snapshot entry");
const malformedSubject = {
...entry.execution.subject,
format: "pe",
architecture: "6502",
};
expect(
analysisSnapshotSchema.safeParse({
...snapshot,
entries: [
{
...entry,
execution: {
...entry.execution,
subject: malformedSubject,
},
},
],
}).success,
).toBe(false);
expect(
analysisSnapshotSchema.safeParse({
...snapshot,
workflow_entries: [
{
...entry,
execution: {
...entry.execution,
analysis_profile: snapshot.binding.analysis_profile,
subject: malformedSubject,
},
},
],
}).success,
).toBe(false);
});
});
describe("analysis snapshot contract", () => {
it.each([
["dos-mz", "x86"],
+47 -28
View File
@@ -41,7 +41,10 @@ import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
import { rawBinaryEntryPointSchema } from "./rawBinary.js";
import {
binaryArchitectureSchema,
rawBinaryEntryPointSchema,
} from "./rawBinary.js";
import {
relationshipCoverageSchema,
type RelationshipCoverage,
@@ -74,20 +77,30 @@ const formatSchema = z.enum([
"source-map",
]);
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
const subjectSchema = z.object({
const subjectBaseSchema = z.object({
path: localPathStringSchema,
sha256: digestSchema,
format: z.enum([
...formatSchema.options,
"hopper",
"directory",
"file",
"unknown",
"javascript-bundle",
"entitlements",
]),
architecture: architectureSchema.nullable(),
});
const subjectFormatSchema = z.enum([
...formatSchema.options,
"hopper",
"directory",
"file",
"unknown",
"javascript-bundle",
"entitlements",
]);
// Snapshot entries retain the same raw-only architecture boundary as targets.
const subjectSchema = z.discriminatedUnion("format", [
subjectBaseSchema.extend({
format: subjectFormatSchema.exclude(["raw-binary"]),
architecture: architectureSchema.exclude(["6502"]).nullable(),
}),
subjectBaseSchema.extend({
format: z.literal("raw-binary"),
architecture: architectureSchema.nullable(),
}),
]);
const targetIdentitySchema = z.object({
sha256: digestSchema,
kind: kindSchema,
@@ -98,9 +111,12 @@ const targetSchema = z.discriminatedUnion("format", [
format: z.enum(
formatSchema.options.filter((format) => format !== "raw-binary"),
),
architecture: architectureSchema.exclude(["6502"]).nullable(),
}),
targetIdentitySchema.extend({
format: z.literal("raw-binary"),
kind: z.literal("executable"),
architecture: binaryArchitectureSchema,
entry_point: rawBinaryEntryPointSchema,
}),
]);
@@ -333,18 +349,21 @@ const canonicalJson = (value: unknown): string => {
};
/** Project a binary into the path-free identity used for cache invalidation. */
export const snapshotTarget = (
target: BinaryTarget,
): AnalysisSnapshotTarget => {
const identity = {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture ?? null,
};
return target.format === "raw-binary"
? { ...identity, format: target.format, entry_point: target.entryPoint }
: { ...identity, format: target.format };
};
export const snapshotTarget = (target: BinaryTarget): AnalysisSnapshotTarget =>
target.format === "raw-binary"
? {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture,
format: target.format,
entry_point: target.entryPoint,
}
: {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture ?? null,
format: target.format,
};
/** Build the immutable provider/profile binding used by a cached snapshot. */
export const snapshotBinding = (
@@ -476,10 +495,10 @@ export const createAnalysisSnapshotWorkflowEntry = (input: {
subject:
execution.subject === null
? null
: {
: subjectSchema.parse({
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
}),
},
};
};
@@ -539,10 +558,10 @@ export const createAnalysisSnapshotEntry = (input: {
subject:
execution.subject === null
? null
: {
: subjectSchema.parse({
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
}),
},
};
};
+19 -1
View File
@@ -169,7 +169,8 @@ it("pages every retained dossier collection and the native API record", () => {
| "comments"
| "unresolved_calls"
| "referenced_strings"
| "referenced_names",
| "referenced_names"
| "swift_string_literals",
result: unknown = original,
) => {
const view = projectAnalysisView(nativeParent(result), {
@@ -195,6 +196,23 @@ it("pages every retained dossier collection and the native API record", () => {
}),
).toMatchObject({ item: [{ text: "entry" }] });
expect(page("referenced_names")).toMatchObject({ coverage: { total: 0 } });
const literal = {
source_address: "0x401004",
value: "SleepDisabled",
representation: "small",
address: null,
registers: ["x0", "x1"],
words: ["0x7369447065656c53", "0xed000064656c6261"],
};
expect(
page("swift_string_literals", {
...original,
swift_string_literals: [literal],
}),
).toMatchObject({ item: [literal], coverage: { total: 1 } });
expect(page("swift_string_literals")).toMatchObject({
item: { available: false, reason: "not recorded" },
});
const { unresolved_calls: _omitted, ...withoutUnresolved } = original;
expect(
page("unresolved_calls", {
+2
View File
@@ -160,6 +160,8 @@ const nativeViewSchema = z.strictObject({
"unresolved_calls",
"referenced_strings",
"referenced_names",
"swift_string_literals",
"swift_string_literal_omissions",
"native_api",
"value_flow_summary",
"value_flow_operations",
@@ -79,6 +79,8 @@ const nativeRows = (
unresolved_calls: dossier.unresolved_calls,
referenced_strings: dossier.referenced_strings,
referenced_names: dossier.referenced_names,
swift_string_literals: dossier.swift_string_literals,
swift_string_literal_omissions: dossier.swift_string_literal_omissions,
value_flow_operations: flow?.operations,
value_flow_def_use: flow?.def_use,
value_flow_effects: flow?.effects,
@@ -163,7 +165,8 @@ export const projectNativeFunctionView = (
singleton({
available: false,
// Only value-flow facets inherit the value-flow failure reason; an
// older dossier simply has no unresolved_calls record.
// older dossier simply has no unresolved_calls record, and a target
// whose provider does not decode Swift literals has no such record.
reason:
view.facet.startsWith("value_flow_") && flow?.available === false
? flow.reason
@@ -510,6 +510,106 @@ describe("AppKit keyed archive connectors", () => {
});
});
describe("keyed archive unresolved connectors", () => {
// A rooted UIKit archive whose only connector is UID 3, with UID 1 as the
// owner, UID 2 as the destination and UID 7 as the "view" label.
const rootedOutletArchive = (connection: Record<string, unknown>) => ({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{ $class: { CF$UID: 4 } },
{ $class: { CF$UID: 5 } },
{ $class: { CF$UID: 6 }, ...connection },
{
$classname: "UIViewController",
$classes: ["UIViewController", "UIResponder", "NSObject"],
},
{ $classname: "UIView", $classes: ["UIView", "UIResponder", "NSObject"] },
{
$classname: "UIRuntimeOutletConnection",
$classes: [
"UIRuntimeOutletConnection",
"UIRuntimeConnection",
"NSObject",
],
},
"view",
{
$class: { CF$UID: 11 },
"NS.objects": [{ CF$UID: 1 }, { CF$UID: 2 }, { CF$UID: 3 }],
},
{ $class: { CF$UID: 11 }, "NS.objects": [{ CF$UID: 3 }] },
{
$class: { CF$UID: 11 },
"NS.objects": [{ CF$UID: 1 }, { CF$UID: 2 }],
},
{ $classname: "NSArray", $classes: ["NSArray", "NSObject"] },
],
$top: {
root: { CF$UID: 8 },
UINibConnectionsKey: { CF$UID: 9 },
UINibObjectsKey: { CF$UID: 10 },
UINibTopLevelObjectsKey: { CF$UID: 10 },
},
});
const project = (raw: unknown) =>
buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Main.nib",
archiveSha256: hash,
documentKind: "nib",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
it("covers a resolvable connector as a complete examined connection", () => {
const raw = rootedOutletArchive({
UISource: { CF$UID: 1 },
UIDestination: { CF$UID: 2 },
UILabel: { CF$UID: 7 },
});
expect(parseInterfaceBuilderRecords(raw).unresolvedConnections).toBe(0);
expect(project(raw).graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Main.nib",
status: "complete",
examined: 1,
omitted: 0,
}),
);
});
it("reports a recognized connector with no resolvable owner as unresolved", () => {
const raw = rootedOutletArchive({
UIDestination: { CF$UID: 2 },
UILabel: { CF$UID: 7 },
});
expect(parseInterfaceBuilderRecords(raw).unresolvedConnections).toBe(1);
const analysis = project(raw);
expect(analysis.graph.nodes.some(({ kind }) => kind === "outlet")).toBe(
false,
);
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Main.nib",
status: "partial",
reason: "connection_unresolved",
examined: 0,
omitted: 1,
}),
);
expect(analysis.graph.truncated).toBe(true);
});
});
it("names the archive once per evidence record", () => {
const relativePath = "Views/Main.storyboardc/scene.nib/objects.nib";
const result = buildInterfaceBuilderAnalysis({
+18 -5
View File
@@ -410,18 +410,26 @@ export const buildInterfaceBuilderAnalysis = (input: {
const connectionsTruncated =
parserOmittedConnections > 0 ||
parsed.connections.length > input.limits.max_connections;
// A recognized connector the parser could not attach to an owner produces
// no connection record, so its coverage is partial with its own reason
// rather than absent or truncated.
const connectionsUnresolved = parsed.unresolvedConnections > 0;
omittedObjects +=
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount);
omittedConnections +=
Math.max(0, parsed.connections.length - input.limits.max_connections) +
parserOmittedConnections;
parserOmittedConnections +
parsed.unresolvedConnections;
summaries.push({
relative_path: document.relativePath,
archive_sha256: document.archiveSha256,
document_kind: document.documentKind,
object_count: parsed.objectCount,
connection_count: parsed.connections.length + parserOmittedConnections,
connection_count:
parsed.connections.length +
parserOmittedConnections +
parsed.unresolvedConnections,
hierarchy_complete:
parsed.hierarchy.length > 0 &&
!truncated &&
@@ -440,13 +448,17 @@ export const buildInterfaceBuilderAnalysis = (input: {
{
facet: `connections:${document.relativePath}`,
status:
connectionsTruncated || documentOmittedConnections > 0
connectionsTruncated ||
documentOmittedConnections > 0 ||
connectionsUnresolved
? "partial"
: "complete",
reason:
connectionsTruncated || documentOmittedConnections > 0
? "connection_limit_reached"
: null,
: connectionsUnresolved
? "connection_unresolved"
: null,
examined: Math.min(
parsed.connections.length,
input.limits.max_connections,
@@ -457,7 +469,8 @@ export const buildInterfaceBuilderAnalysis = (input: {
parsed.connections.length - input.limits.max_connections,
) +
documentOmittedConnections +
parserOmittedConnections,
parserOmittedConnections +
parsed.unresolvedConnections,
},
{
facet: `hierarchy:${document.relativePath}`,
@@ -55,6 +55,7 @@ export const parseInterfaceBuilderRecords = (
readonly objectCount: number;
readonly omittedObjects: number;
readonly omittedConnections: number;
readonly unresolvedConnections: number;
readonly omittedHierarchyReferences: number;
} => {
const root = record(value);
@@ -135,6 +136,7 @@ export const parseInterfaceBuilderRecords = (
objectCount: objectEntries.length,
omittedObjects: Math.max(0, objectEntries.length - 20_000),
omittedConnections,
unresolvedConnections: 0,
omittedHierarchyReferences: 0,
};
};
@@ -320,6 +322,7 @@ const parseKeyedArchive = (
const connections: InterfaceBuilderConnection[] = [];
let objectCount = 0;
let omittedConnections = 0;
let unresolvedConnections = 0;
for (const [index, raw] of objectTable.entries()) {
if (index === 0) continue;
const resolved = record(resolve(raw));
@@ -371,7 +374,13 @@ const parseKeyedArchive = (
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
if (source === null) continue;
if (source === null) {
// A recognized connector that cannot name its owner is an unresolved
// connection, not an absent one, and cannot be represented as a
// connection because connection identity requires a source.
unresolvedConnections += 1;
continue;
}
const kind = controlAction ? "action" : classifyConnection(className);
const parsedConnection = connection.parse({
id: `archive:${objectId}`,
@@ -426,6 +435,7 @@ const parseKeyedArchive = (
objectCount,
omittedObjects: Math.max(0, objectCount - 20_000),
omittedConnections,
unresolvedConnections,
omittedHierarchyReferences: hierarchy.omittedReferences,
};
};
+5
View File
@@ -63,6 +63,11 @@ export const readFatContainerHeader = (
const magic = view.getUint32(0, false);
if (![FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic))
return { state: "not-fat" };
if (!Number.isSafeInteger(fileSize) || fileSize < bytes.byteLength)
return {
state: "malformed",
reason: "FAT file size is invalid or contradicts retained bytes",
};
if (bytes.byteLength < 8) {
return fileSize < 8
? { state: "malformed", reason: "FAT header is truncated" }
+9 -3
View File
@@ -278,8 +278,12 @@ export const parsePeRecord = (
record.toString("binary", 0, 4) !== "PE\u0000\u0000"
)
return err("invalid or truncated PE header");
const machine = decodePeMachine(record.readUInt16LE(4));
if (machine === undefined) return err("unsupported PE architecture");
const machineType = record.readUInt16LE(4);
const machine = decodePeMachine(machineType);
if (machine === undefined)
return err(
`unsupported PE architecture (COFF machine 0x${machineType.toString(16).padStart(4, "0")})`,
);
const { architecture } = machine;
const optionalHeaderSize = record.readUInt16LE(20);
if (optionalHeaderSize > 4096 || record.length < 24 + optionalHeaderSize)
@@ -347,7 +351,9 @@ const machArchitecture = (cpu: number): HeaderArchitecture | undefined => {
return undefined;
};
const elfArchitecture = (machine: number): BinaryArchitecture | undefined => {
const elfArchitecture = (
machine: number,
): Exclude<BinaryArchitecture, "6502"> | undefined => {
switch (machine) {
case 3:
return "x86";
+13 -3
View File
@@ -1,12 +1,13 @@
import type { ZipPackageFormat } from "./zipPackageFormat.js";
/** Provider-neutral CPU families detected from supported executable headers. */
/** Provider-neutral CPU families detected from headers or explicitly selected raw loads. */
export const BINARY_ARCHITECTURES = [
"x86",
"x86_64",
"arm",
"arm64",
"mips",
"6502",
"riscv",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
@@ -40,7 +41,7 @@ export const isElfMetadataArchitecture = (
/** Recognized family with no ELF metadata member; the header alone is the fact. */
export type HeaderArchitecture = Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
ElfMetadataArchitecture | "6502"
>;
/** Raw ELF facts; family recognition does not establish ISA or ABI support. */
@@ -144,8 +145,17 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "raw-binary";
readonly architecture: Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>[];
readonly entryPoint: string;
readonly entryPointSource: string;
readonly executableRole?: never;
+83
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { buildCallPath } from "./callPath.js";
import { combineFunctionRelationshipCoverage } from "./functionCallCoverage.js";
import { callPathResultSchema, type CallPathInput } from "./callPathSchemas.js";
import { createEvidence, type Evidence } from "./evidence.js";
import type { JsonValue } from "./jsonValue.js";
@@ -396,6 +397,60 @@ describe("explicit call relationship coverage", () => {
expect(result.limitations).toEqual([reason]);
});
it("establishes not_found when only caller coverage is unknown", () => {
const reason =
"Callers: Upstream xrefs do not establish direct caller relationships.";
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
observe("0x2000", [], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
]);
expect(result).toMatchObject({
status: "not_found",
search_scope: { exhaustive: true },
});
expect(result.limitations).toContain(reason);
});
it("stays unknown when callee coverage is unknown", () => {
const reason =
"Callees: Upstream callees capped results at 500; additional callees remain unknown.";
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
observe("0x2000", [], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
]);
expect(result).toMatchObject({
status: "unknown",
search_scope: { exhaustive: false },
});
expect(result.limitations).toContain(reason);
});
it("stays unknown when both caller and callee coverage are unknown", () => {
const reason =
"Callers: Upstream xrefs do not establish direct caller relationships. Callees: Upstream callees are not observed.";
const result = run([
observe("0x1000", ["0x2000"], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
observe("0x2000", [], "rea-workflow", {
relationshipCoverage: { status: "unknown", reason },
}),
]);
expect(result).toMatchObject({
status: "unknown",
search_scope: { exhaustive: false },
});
expect(result.limitations).toContain(reason);
});
it("ignores incomplete relationship coverage outside the reachable search closure", () => {
const reason = "An unrelated function's callees were not observed.";
const result = run([
@@ -415,6 +470,34 @@ describe("explicit call relationship coverage", () => {
});
});
describe("IDA-capped callee coverage beside unknown callers", () => {
it("keeps the search non-exhaustive for the combined coverage value", () => {
const combined = combineFunctionRelationshipCoverage(
{
status: "unknown",
reason: "Upstream xrefs do not establish direct caller relationships.",
},
{
status: "partial",
limitations: [
"Upstream callees capped results at 500; additional callees remain unknown.",
],
},
);
expect(combined.status).toBe("unknown");
const result = run([
observe("0x1000", [], "rea-workflow", { relationshipCoverage: combined }),
observe("0x4000", []),
]);
expect(result).toMatchObject({
status: "unknown",
search_scope: { exhaustive: false },
shortest_hops: null,
paths: [],
});
});
});
describe("call path evidence admission", () => {
it("normalizes hex addresses and rejects duplicates and mixed providers", () => {
expect(
+6 -1
View File
@@ -10,6 +10,7 @@ import {
parseFunctionEvidence,
type FunctionSnapshot,
} from "./functionDossierEvidence.js";
import { isCallerOnlyUnknownCoverage } from "./functionCallCoverage.js";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
/** Minimal directed caller-to-callee adjacency for call-path search. */
@@ -255,10 +256,14 @@ const inspectSearch = ({
// Explicit, Evidence-bound relationship coverage owns completeness;
// generic provider/dossier limitations remain contextual. Legacy Evidence
// without that metadata retains its conservative limitation-based rule.
// The search only expands callee edges, so coverage that is unknown
// solely because callers are unobservable does not make the searched
// callee closure incomplete; the caller caveat stays in limitations.
if (
coverage === null
? snapshot.limitations.length > 0
: coverage.status !== "complete"
: coverage.status !== "complete" &&
!isCallerOnlyUnknownCoverage(coverage)
)
incompleteExpandedCoverage = true;
} else if (node === goal) {
+27
View File
@@ -19,6 +19,33 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
it("rejects a detected Evidence subject with the raw-only 6502 architecture", () => {
const selected = {
path: TARGET.path,
sha256: TARGET.sha256,
format: "raw-binary" as const,
architecture: "6502" as const,
};
expect(
createEvidence(selected, PROVIDER, {
operation: "inspect",
parameters: {},
result: null,
}).subject,
).toMatchObject({ format: "raw-binary", architecture: "6502" });
const malformed = {
...selected,
format: "pe" as const,
};
expect(() =>
createEvidence(malformed, PROVIDER, {
operation: "inspect",
parameters: {},
result: null,
}),
).toThrow();
});
it("preserves omitted relationship diagnostics and authenticates reported diagnostics", () => {
const observation = {
operation: "procedure_callees",
+44 -34
View File
@@ -38,43 +38,53 @@ export const providerSchema = z.strictObject({
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.strictObject({
const subjectFormatSchema = z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"ines",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]);
const subjectBaseSchema = z.strictObject({
name: z.string().min(1),
digest: z.strictObject({ sha256: digestSchema }),
format: z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"ines",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
local_path: nulFreeStringSchema,
});
// The format owns the architecture claim, including nested Evidence subjects.
const subjectSchema = z.discriminatedUnion("format", [
subjectBaseSchema.extend({
format: subjectFormatSchema.exclude(["raw-binary"]),
architecture: z.enum(BINARY_ARCHITECTURES).exclude(["6502"]).nullable(),
}),
subjectBaseSchema.extend({
format: z.literal("raw-binary"),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
}),
]);
/** Source location attached to an evidence observation. */
/** Source-location schema shared by evidence-bearing persistence formats. */
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
@@ -187,7 +197,7 @@ const immutableResultSchema = z
});
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
/** Minimal immutable local artifact identity accepted by Evidence. */
/** Candidate local artifact identity validated by the Evidence subject schema. */
export interface EvidenceSubjectTarget {
readonly path: string;
readonly sha256: string;
+13 -10
View File
@@ -16,14 +16,17 @@ import {
} from "./residualUnknown.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
const artifactManifestSchema = evidenceSchema.shape.subject
.unwrap()
.pick({
digest: true,
format: true,
architecture: true,
})
.strict();
const [detectedSubjectSchema, rawSubjectSchema] =
evidenceSchema.shape.subject.unwrap().options;
const manifestFields = {
digest: true,
format: true,
architecture: true,
} as const;
const artifactManifestSchema = z.discriminatedUnion("format", [
detectedSubjectSchema.pick(manifestFields),
rawSubjectSchema.pick(manifestFields),
]);
const providerManifestSchema = providerSchema;
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
const scenarioManifestSchema = z.strictObject({
@@ -85,11 +88,11 @@ export const createEvidenceBundle = (
subject === null
? []
: [
{
artifactManifestSchema.parse({
digest: subject.digest,
format: subject.format,
architecture: subject.architecture,
},
}),
],
),
),
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import {
combineFunctionRelationshipCoverage,
isCallerOnlyUnknownCoverage,
} from "./functionCallCoverage.js";
import type { RelationshipCoverage } from "./relationshipCoverage.js";
const unknownCallers: RelationshipCoverage = {
status: "unknown",
reason: "Upstream xrefs do not establish direct caller relationships.",
};
const unknownCallees: RelationshipCoverage = {
status: "unknown",
reason: "Upstream callees are not observed in this profile.",
};
const cappedCallees: RelationshipCoverage = {
status: "partial",
limitations: [
"Upstream callees capped results at 500; additional callees remain unknown.",
],
};
const complete: RelationshipCoverage = { status: "complete" };
describe("isCallerOnlyUnknownCoverage", () => {
it("detects unknown callers beside complete callees", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
complete,
);
expect(combined.status).toBe("unknown");
expect(isCallerOnlyUnknownCoverage(combined)).toBe(true);
});
it("rejects unknown callees beside complete callers", () => {
const combined = combineFunctionRelationshipCoverage(
complete,
unknownCallees,
);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
it("rejects unknown coverage on both sides", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
unknownCallees,
);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
it("rejects unknown callers beside IDA-capped callees", () => {
const combined = combineFunctionRelationshipCoverage(
unknownCallers,
cappedCallees,
);
expect(combined.status).toBe("unknown");
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
it("rejects complete coverage", () => {
const combined = combineFunctionRelationshipCoverage(complete, complete);
expect(isCallerOnlyUnknownCoverage(combined)).toBe(false);
});
});
+20 -2
View File
@@ -2,6 +2,9 @@ import type { RelationshipCoverage } from "./relationshipCoverage.js";
import type { FunctionDossier } from "./hopperValues.js";
import { uniqueSorted } from "./canonicalOrdering.js";
const callerCoveragePrefix = "Callers: ";
const calleeCoveragePrefix = "Callees: ";
/** Combine caller and callee read outcomes without losing either explanation. */
export const combineFunctionRelationshipCoverage = (
callers: RelationshipCoverage | undefined,
@@ -20,7 +23,8 @@ export const combineFunctionRelationshipCoverage = (
);
const details = diagnostics.length > 0 ? { diagnostics } : {};
const reasons = reads.flatMap(({ direction, coverage }) => {
const label = direction === "callers" ? "Callers" : "Callees";
const label =
direction === "callers" ? callerCoveragePrefix : calleeCoveragePrefix;
const limitations =
coverage === undefined
? ["Provider did not report relationship coverage."]
@@ -29,7 +33,7 @@ export const combineFunctionRelationshipCoverage = (
: coverage.status === "partial"
? coverage.limitations
: [];
return limitations.map((reason) => `${label}: ${reason}`);
return limitations.map((reason) => `${label}${reason}`);
});
if (
reads.some(
@@ -50,6 +54,20 @@ export const combineFunctionRelationshipCoverage = (
return { status: "complete", ...details };
};
/**
* Whether combined relationship coverage is unknown only on the caller side.
* The combine helper above prefixes each direction's reasons, so a reason
* that carries the caller prefix and no callee prefix records observed
* callees with unobservable callers. Forward (callee-edge) searches stay
* exhaustive under that caveat; the caller reason remains a limitation.
*/
export const isCallerOnlyUnknownCoverage = (
coverage: RelationshipCoverage,
): boolean =>
coverage.status === "unknown" &&
coverage.reason.startsWith(callerCoveragePrefix) &&
!coverage.reason.includes(calleeCoveragePrefix);
/** Explain why two resolved call sets cannot establish call-set equality. */
export const functionCallCoverageLimitations = (
coverage: RelationshipCoverage | null,
+230
View File
@@ -716,6 +716,236 @@ describe("function comparison identity and malformed CFG", () => {
});
});
const withLiterals = (base: "0x1000" | "0x2000", values: readonly string[]) =>
functionDossierSchema.parse({
...dossier("return 0;", base),
swift_string_literals: values.map((value) => ({
source_address: base,
value,
representation: "small" as const,
address: null,
registers: ["x0", "x1"] as const,
words: ["0x0", "0xe"] as const,
})),
});
const stringsDimension = (
leftDigit: string,
left: ReturnType<typeof withLiterals> | ReturnType<typeof dossier>,
rightDigit: string,
right: ReturnType<typeof withLiterals> | ReturnType<typeof dossier>,
) =>
compareFunctions(
observe(leftDigit, left),
observe(rightDigit, right),
).dimensions.find(({ dimension }) => dimension === "strings_names");
describe("function comparison Swift string literals", () => {
it("treats differing decoded literals as a strings and names change", () => {
expect(
stringsDimension(
"1",
withLiterals("0x1000", ["SleepDisabled"]),
"2",
withLiterals("0x2000", ["Holding awake"]),
),
).toMatchObject({ status: "changed" });
});
it("matches the same decoded literal after the function is relocated", () => {
expect(
stringsDimension(
"3",
withLiterals("0x1000", ["SleepDisabled"]),
"4",
withLiterals("0x2000", ["SleepDisabled"]),
),
).toMatchObject({ status: "unchanged" });
});
it("keeps strings and names unknown when only one dossier recorded Swift literals", () => {
expect(
stringsDimension(
"5",
withLiterals("0x1000", []),
"6",
dossier("return 0;", "0x2000"),
),
).toMatchObject({
status: "unknown",
limitations: [
"Swift String literal coverage differs or is partial; referenced strings and names match, and complete coverage does not establish a differing literal.",
],
});
});
it("reports a referenced name change even when Swift literal coverage differs", () => {
const named = functionDossierSchema.parse({
...dossier("return 0;", "0x2000"),
referenced_names: [
{ address: "0x3000", value: "helper", source_address: "0x2000" },
],
});
expect(
stringsDimension("7", withLiterals("0x1000", []), "8", named),
).toMatchObject({ status: "changed" });
});
});
describe("function comparison partial Swift literal coverage", () => {
it("does not equate a partial literal record with a complete one", () => {
const partial = functionDossierSchema.parse({
...withLiterals("0x2000", ["SleepDisabled"]),
swift_string_literal_omissions: [
{
source_address: "0x2000",
representation: "large",
address: "0x3000",
byte_length: 64,
reason: "capacity",
registers: ["x0", "x1"],
words: ["0xd000000000000040", "0x8000000000002fe0"],
},
],
});
expect(
stringsDimension(
"9",
withLiterals("0x1000", ["SleepDisabled"]),
"a",
partial,
),
).toMatchObject({ status: "unknown" });
});
it("reports a literal that a complete dossier shows absent at a site the partial one decoded", () => {
const partial = functionDossierSchema.parse({
...withLiterals("0x2000", ["SleepDisabled"]),
swift_string_literal_omissions: [
{
source_address: "0x2004",
representation: "small",
address: null,
byte_length: 4,
reason: "capacity",
registers: ["x0", "x1"],
words: ["0x732f4220", "0xe400000000000000"],
},
],
});
expect(
stringsDimension("d", withLiterals("0x1000", []), "e", partial),
).toMatchObject({ status: "changed" });
});
it("does not interpret an unexamined path as a missing literal at a retained site", () => {
const partial = functionDossierSchema.parse({
...withLiterals("0x2000", ["A"]),
swift_string_literal_omissions: [
{
source_address: "0x2004",
representation: "small",
address: null,
byte_length: 0,
reason: "capacity",
registers: ["x0", "x1"],
words: ["0x0", "0xe000000000000000"],
},
],
});
const complete = withLiterals("0x1000", ["A", "B"]);
expect(stringsDimension("1", complete, "2", partial)).toMatchObject({
status: "unknown",
});
expect(stringsDimension("3", partial, "4", complete)).toMatchObject({
status: "unknown",
});
expect(
stringsDimension("5", withLiterals("0x1000", []), "6", partial),
).toMatchObject({ status: "changed" });
});
it("treats an omission record without decoded literals as partial coverage", () => {
const omissionOnly = functionDossierSchema.parse({
...dossier("return 0;", "0x2000"),
swift_string_literal_omissions: [
{
source_address: "0x2004",
representation: "small",
address: null,
byte_length: 4,
reason: "capacity",
registers: ["x0", "x1"],
words: ["0x732f4220", "0xe400000000000000"],
},
],
});
expect(
stringsDimension("f", dossier("return 0;", "0x1000"), "0", omissionOnly),
).toMatchObject({ status: "unknown" });
});
it("keeps different retained representations unknown when both dossiers are partial", () => {
const omission = {
source_address: "0x1004",
representation: "small",
address: null,
byte_length: 4,
reason: "capacity",
registers: ["x0", "x1"],
words: ["0x732f4220", "0xe400000000000000"],
} as const;
const small = functionDossierSchema.parse({
...withLiterals("0x1000", ["SleepDisabled"]),
swift_string_literal_omissions: [omission],
});
const large = functionDossierSchema.parse({
...dossier("return 0;", "0x2000"),
swift_string_literals: [
{
source_address: "0x2000",
value: "SleepDisabled",
representation: "large",
address: "0x3000",
registers: ["x0", "x1"],
words: ["0xd00000000000000d", "0x8000000000002fe0"],
},
],
swift_string_literal_omissions: [
{ ...omission, source_address: "0x2004" },
],
});
expect(stringsDimension("1", small, "2", large)).toMatchObject({
status: "unknown",
});
});
it("keeps different retained literals unknown when both dossiers are partial", () => {
const partial = (base: "0x1000" | "0x2000", value: string) =>
functionDossierSchema.parse({
...withLiterals(base, [value]),
swift_string_literal_omissions: [
{
source_address: base === "0x1000" ? "0x1004" : "0x2004",
representation: "large",
address: "0x3000",
byte_length: 64,
reason: "capacity",
registers: ["x0", "x1"],
words: ["0xd000000000000040", "0x8000000000002fe0"],
},
],
});
expect(
stringsDimension(
"b",
partial("0x1000", "SleepDisabled"),
"c",
partial("0x2000", "Holding awake"),
),
).toMatchObject({ status: "unknown" });
});
});
const expectInlineComparisonEvidence = (
result: ReturnType<typeof compareFunctions>,
): void => {
+39 -3
View File
@@ -11,6 +11,7 @@ import {
referenceProjection,
sorted,
stringAndNameProjection,
swiftLiteralSitesConflict,
} from "./functionComparisonNormalization.js";
import type {
DimensionName,
@@ -139,8 +140,12 @@ const compareStringsAndNames = (
right: FunctionSnapshot,
context: ComparisonContext,
): FunctionDimension => {
const leftValues = stringAndNameProjection(left);
const rightValues = stringAndNameProjection(right);
const complete =
swiftLiteralCoverage(left) === swiftLiteralCoverage(right) &&
swiftLiteralCoverage(left) !== "partial";
// Facts both dossiers record decide a change before Swift literal coverage can.
const leftValues = stringAndNameProjection(left, complete);
const rightValues = stringAndNameProjection(right, complete);
if (leftValues === null || rightValues === null)
return unresolvedDimension({
dimension: "strings_names",
@@ -151,9 +156,40 @@ const compareStringsAndNames = (
"Reference source locations could not be normalized to function offsets.",
],
});
return compareValues("strings_names", leftValues, rightValues, context);
const compared = compareValues(
"strings_names",
leftValues,
rightValues,
context,
);
if (complete || compared.status === "changed") return compared;
// A retained literal differs only when the opposite dossier establishes its absence.
if (swiftLiteralSitesConflict(left, right)) {
const leftAll = stringAndNameProjection(left);
const rightAll = stringAndNameProjection(right);
if (leftAll !== null && rightAll !== null)
return compareValues("strings_names", leftAll, rightAll, context);
}
return unresolvedDimension({
dimension: "strings_names",
links: context.links,
leftCount: null,
rightCount: null,
limitations: [
"Swift String literal coverage differs or is partial; referenced strings and names match, and complete coverage does not establish a differing literal.",
],
});
};
const swiftLiteralCoverage = (
snapshot: FunctionSnapshot,
): "absent" | "complete" | "partial" =>
(snapshot.dossier.swift_string_literal_omissions ?? []).length > 0
? "partial"
: snapshot.dossier.swift_string_literals === undefined
? "absent"
: "complete";
const compareReferences = (
left: FunctionSnapshot,
right: FunctionSnapshot,
@@ -142,6 +142,7 @@ export const commentProjection = (
export const stringAndNameProjection = (
snapshot: FunctionSnapshot,
includeSwiftLiterals = true,
): readonly unknown[] | null => {
const values = [
...snapshot.dossier.referenced_strings.map(
@@ -164,12 +165,90 @@ export const stringAndNameProjection = (
value,
}),
),
...(includeSwiftLiterals
? (snapshot.dossier.swift_string_literals ?? [])
: []
).map(
({
source_address: sourceAddress,
value,
representation,
registers,
}) => ({
kind: "swift_string",
source_offset: relativeAddress(
sourceAddress,
snapshot.dossier.procedure.address,
),
value,
representation,
registers,
}),
),
];
return values.some(({ source_offset: offset }) => offset === null)
? null
: sorted(values);
};
/**
* A retained literal proves presence, not that every path through its site was examined.
* A differing retained fact proves a change only when the opposite dossier is complete
* and therefore establishes its absence.
*/
export const swiftLiteralSitesConflict = (
left: FunctionSnapshot,
right: FunctionSnapshot,
): boolean => {
const leftSites = swiftLiteralSites(left);
const rightSites = swiftLiteralSites(right);
for (const site of new Set([
...leftSites.values.keys(),
...rightSites.values.keys(),
])) {
const leftValues =
leftSites.values.get(site) ?? (leftSites.complete ? [] : undefined);
const rightValues =
rightSites.values.get(site) ?? (rightSites.complete ? [] : undefined);
if (leftValues === undefined || rightValues === undefined) continue;
const leftFacts = new Set(leftValues);
const rightFacts = new Set(rightValues);
if (
(rightSites.complete &&
leftValues.some((value) => !rightFacts.has(value))) ||
(leftSites.complete && rightValues.some((value) => !leftFacts.has(value)))
)
return true;
}
return false;
};
const swiftLiteralSites = (snapshot: FunctionSnapshot) => {
const base = snapshot.dossier.procedure.address;
const omissions = snapshot.dossier.swift_string_literal_omissions ?? [];
const site = (sourceAddress: string, registers: readonly string[]) => {
const offset = relativeAddress(sourceAddress, base);
return offset === null ? null : canonicalJson([offset, registers]);
};
// Keep the same literal facts the full strings_names projection compares.
const values = new Map<string, string[]>();
for (const literal of snapshot.dossier.swift_string_literals ?? []) {
const key = site(literal.source_address, literal.registers);
if (key === null) continue;
values.set(
key,
[
...(values.get(key) ?? []),
canonicalJson([literal.value, literal.representation]),
].sort(compareUnicodeCodePoints),
);
}
const complete =
snapshot.dossier.swift_string_literals !== undefined &&
omissions.length === 0;
return { values, complete };
};
export const sorted = (values: readonly unknown[]): readonly unknown[] =>
values
.map((value) => ({
+76
View File
@@ -290,6 +290,70 @@ export const unresolvedCallSchema = z.strictObject({
reason: z.string(),
});
const swiftStringLiteralFields = {
source_address: z
.string()
.describe(
"Instruction that consumes both words: a call, tail call, return, or paired store.",
),
value: z
.string()
.describe("Decoded UTF-8 text, including the canonical empty string."),
registers: z.tuple([z.string(), z.string()]),
words: z
.tuple([z.string(), z.string()])
.describe("Observed constant register values, in register order."),
};
/** A Swift String literal decoded from the two words of its ABI value, not a data reference. */
export const swiftStringLiteralSchema = z.discriminatedUnion("representation", [
z.strictObject({
...swiftStringLiteralFields,
representation: z
.literal("small")
.describe("The UTF-8 bytes are inside the two words."),
address: z.null().describe("A small literal has no storage of its own."),
}),
z.strictObject({
...swiftStringLiteralFields,
representation: z
.literal("large")
.describe(
"An immortal literal whose words hold its count and a pointer to its bytes.",
),
address: z.string().describe("Address of a large literal's bytes."),
}),
]);
const swiftStringLiteralOmissionFields = {
source_address: swiftStringLiteralFields.source_address,
byte_length: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
reason: z
.literal("capacity")
.describe(
"The record did not fit the provider's memory budget for this dossier; decoding stopped here, so later use sites were not examined.",
),
registers: swiftStringLiteralFields.registers,
words: swiftStringLiteralFields.words,
};
/** A Swift literal whose layout matched but whose record did not fit; decoding stopped there. */
export const swiftStringLiteralOmissionSchema = z.discriminatedUnion(
"representation",
[
z.strictObject({
...swiftStringLiteralOmissionFields,
representation: z.literal("small"),
address: z.null(),
}),
z.strictObject({
...swiftStringLiteralOmissionFields,
representation: z.literal("large"),
address: z.string().describe("Address of the literal's bytes."),
}),
],
);
/** Observed endpoints with complete or partial reference classification evidence. */
export const referenceEdgeSchema = z
.object({
@@ -341,6 +405,18 @@ export const functionDossierSchema = z
})
.strict(),
),
swift_string_literals: z
.array(swiftStringLiteralSchema)
.exactOptional()
.describe(
"Swift String literals decoded from constant register values. Absent when the provider does not decode them for this target.",
),
swift_string_literal_omissions: z
.array(swiftStringLiteralOmissionSchema)
.exactOptional()
.describe(
"The literal at which decoding stopped for capacity. Present exactly when swift_string_literals is present; empty when decoding examined every use site.",
),
basic_blocks: z.array(
z
.object({
@@ -0,0 +1,351 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
import { onlyCallable } from "./javascriptSemanticAnalysis.fixture.js";
const returnedValue = (getter: string, write = "box.v.x = 2;") =>
onlyCallable(
analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1, y: 1 };
const box = { s: shared, get v() { ${getter} } };
${write}
return shared.x;
}`),
"result",
).returnSites[0]?.value;
describe("projected private getter receivers", () => {
it.each([
[
"destructured self field",
"shared",
"peer = this;",
"const { peer: self } = this; return self.#s;",
true,
"unknown",
],
[
"unrelated private child",
"{ peer: shared }",
"peer = this;",
"const { peer: self } = this; return self.#s;",
true,
"literal",
],
[
"read without write",
"shared",
"peer = this;",
"const { peer: self } = this; return self.#s;",
false,
"literal",
],
[
"two self fields",
"shared",
"peer = this; next = this.peer;",
"const { next: self } = this; return self.#s;",
true,
"unknown",
],
[
"nested receiver projection",
"shared",
"peer = this;",
"const { peer: { peer: self } } = this; return self.#s;",
true,
"unknown",
],
[
"member receiver alias",
"shared",
"peer = this;",
"const self = this.peer.peer; return self.#s;",
true,
"unknown",
],
[
"projected result suffix",
"{ child: shared }",
"peer = this;",
"const { peer: self } = this; return self.#s.child;",
true,
"unknown",
],
[
"external receiver",
"shared",
"peer = external;",
"const { peer: self } = this; return self.#s;",
true,
"literal",
],
[
"field receiver cycle",
"shared",
"peer = this.other; other = this.peer;",
"const { peer: self } = this; return self.#s;",
true,
"literal",
],
] as const)(
"keeps receiver and result paths separate for %s",
(_name, value, fields, getter, write, status) => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
class Box {
#s = ${value}; ${fields}
get v() { ${getter} }
}
const box = new Box();
${write ? "box.v.x = 2;" : "const saved = box.v;"}
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject(
status === "literal" ? { status, value: 1 } : { status },
);
},
);
});
describe("private receiver field ownership", () => {
it("bounds growing receiver projections under cyclic class inheritance", () => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
class A extends B {
#s = shared;
peer = this.other.other;
get v() { const { peer: self } = this; return self.#s; }
}
class B extends A { other = this.peer.peer; }
new A().v.x = 2;
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject({
status: "literal",
value: 1,
});
}, 1000);
it.each([
[
"own static receiver",
"class Box { static #s=shared; static peer=this; static get v(){const {peer:self}=this;return self.#s;} } Box.v.x=2;",
"unknown",
],
[
"inherited instance receiver",
"class Base {peer=this;} class Box extends Base {#s=shared;get v(){const {peer:self}=this;return self.#s;}} new Box().v.x=2;",
"unknown",
],
[
"inherited static field retains its declaring class",
"class Base {static peer=this;} class Box extends Base {static #s=shared;static get v(){const {peer:self}=this;return self.#s;}} Box.v.x=2;",
"literal",
],
[
"inherited static getter's own private field",
"class Base {static #s=shared;static peer=this;static get v(){const {peer:self}=this;return self.#s;}} class Box extends Base {} Box.v.x=2;",
"unknown",
],
[
"a field that is not initialized yet",
"class Box {#s=shared;peer=this.later;later=this;get v(){const {peer:self}=this;return self.#s;}} new Box().v.x=2;",
"literal",
],
[
"remaining getter projection after a captured field",
"class Box {#s=shared;peer=this;next=this.peer;later=this;get v(){const {next:{later:self}}=this;return self.#s;}} new Box().v.x=2;",
"unknown",
],
[
"a replaced self field",
"class Box {#s=shared;peer=this;peer=external;get v(){const {peer:self}=this;return self.#s;}} new Box().v.x=2;",
"literal",
],
] as const)("respects %s", (_name, body, status) => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
${body}
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject(
status === "literal" ? { status, value: 1 } : { status },
);
});
});
describe("getter-local receiver aliases (#2653)", () => {
it.each([
["initialized alias", "const self = this; return self.s;"],
["assigned alias", "let self; self = this; return self.s;"],
[
"chained assignment",
"let self; let alias; self = alias = this; return self.s;",
],
["destructured receiver", "const { s: value } = this; return value;"],
["alias chain", "const self = this; const saved = self; return saved.s;"],
[
"capture before reassignment",
"let self = this; const saved = self; self = { s: { x: 1 } }; return saved.s;",
],
[
"conditional receiver alias",
"const self = flag ? this : { s: { x: 1 } }; return self.s;",
],
])("invalidates shared values through %s", (_name, getter) => {
expect(returnedValue(getter)?.status).toBe("unknown");
});
it.each([
["no write", "const self = this; return self.s;", "const saved = box.v;"],
[
"an unrelated property write",
"const self = this; return self.s;",
"box.v.y = 2;",
],
[
"a cycle that does not grow the selected path",
"let self = this; while (flag) self = self; return self.s;",
"box.v.y = 2;",
],
[
"an alias replaced before return",
"let self = this; self = { s: { x: 1 } }; return self.s;",
"box.v.x = 2;",
],
[
"a shadowing block binding",
"const self = this; { const self = { s: { x: 1 } }; return self.s; }",
"box.v.x = 2;",
],
[
"a nested function's receiver",
"function other() { const self = this; return self.s; } return other();",
"box.v.x = 2;",
],
[
"an alias assigned in a different receiver scope",
"let self; function assign() { self = this; } assign(); return self.s;",
"box.v.x = 2;",
],
[
"an excluded destructuring default",
"const { value = shared } = { value: { x: 1 } }; return value;",
"box.v.x = 2;",
],
])("preserves known values with %s", (_name, getter, write) => {
expect(returnedValue(getter, write)).toMatchObject({
status: "literal",
value: 1,
});
});
});
describe("getter receiver alias boundaries", () => {
it("does not reinterpret an outer this binding as the getter receiver", () => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
const outside = this;
const box = { s: shared, get v() { return outside.s; } };
box.v.x = 2;
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject({
status: "literal",
value: 1,
});
});
it("retains a private field's lexical owner through a receiver alias", () => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
class Box {
#s = shared;
get v() { const self = this; return self.#s; }
}
new Box().v.x = 2;
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value.status).toBe(
"unknown",
);
});
it("does not append a receiver projection to a private field's result path", () => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
class Box {
#s = { peer: shared };
peer = this;
get v() { const { peer: self } = this; return self.#s; }
}
new Box().v.x = 2;
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject({
status: "literal",
value: 1,
});
});
it("resolves a long local alias chain without recursive expansion", () => {
const aliases = ["const a0 = this;"];
for (let index = 1; index <= 2000; index++)
aliases.push(`const a${String(index)} = a${String(index - 1)};`);
expect(returnedValue(`${aliases.join("\n")} return a2000.s;`)?.status).toBe(
"unknown",
);
});
it("bounds a growing alias cycle without losing the original receiver", () => {
expect(
returnedValue(
"let self = this; while (flag) self = self.s; return self.s;",
)?.status,
).toBe("unknown");
});
it.each([true, false])(
"retains deeper shared references through an alias cycle (write=%s)",
(write) => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
const box = {
start: { child: { child: shared } },
get v() {
let self = this.start;
while (flag) self = self.child;
return self;
}
};
${write ? "box.v.x = 2;" : "const saved = box.v;"}
return shared.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject(
write ? { status: "unknown" } : { status: "literal", value: 1 },
);
},
);
it("does not widen a growing cycle to unrelated receiver properties", () => {
const ir = analyzeJavaScriptSemantics(`export function result() {
const shared = { x: 1 };
const unrelated = { x: 1 };
const box = {
start: { child: { child: shared } },
unrelated,
get v() {
let self = this.start;
while (flag) self = self.child;
return self;
}
};
box.v.x = 2;
return unrelated.x;
}`);
expect(onlyCallable(ir, "result").returnSites[0]?.value).toMatchObject({
status: "literal",
value: 1,
});
});
});
@@ -33,6 +33,38 @@ const getterReceivers = [
"nested owner",
"const outer = { box: { x: 1, get self() { return this; } } }; outer.box.self.x = 2; return outer.box.x;",
],
[
"array element",
"const arr = [{ x: 1, get self() { return this; } }]; arr[0].self.x = 2; return arr[0].x;",
],
[
"array element after a hole",
"const arr = [, { x: 1, get self() { return this; } }]; arr[1].self.x = 2; return arr[1].x;",
],
[
"mixed object and array owners",
"const outer = { rows: [{ box: { x: 1, get self() { return this; } } }] }; outer.rows[0].box.self.x = 2; return outer.rows[0].box.x;",
],
[
"assigned owner",
"let box; box = { x: 1, get self() { return this; } }; box.self.x = 2; return box.x;",
],
[
"saved array receiver alias",
"const arr = [{ x: 1, get self() { return this; } }]; const saved = arr[0].self; saved.x = 2; return arr[0].x;",
],
[
"old receiver captured inside its replacement initializer",
"const old = { x: 1 }; let box = old; box = { old: box, get self() { return this; } }; box.self.old.x = 2; return old.x;",
],
[
"array receiver after an unknown spread",
"const arr = [...items, { x: 1, get self() { return this; } }]; arr[index].self.x = 2; return arr[index].x;",
],
[
"saved receiver before its array alias is reassigned",
"const original = [{ x: 1, get self() { return this; } }]; let arr = original; const saved = arr[0].self; arr = [{ x: 1 }]; saved.x = 2; return original[0].x;",
],
[
"inherited receiver field",
"const shared = { x: 1 }; class A { get v() { return this.s; } } class B extends A { s = shared; } new B().v.x = 2; return shared.x;",
@@ -75,7 +107,7 @@ const getterReceivers = [
],
] as const;
describe("getter receiver mutation aliases (#1665)", () => {
describe("getter receiver mutation aliases (#1665, #2654)", () => {
it.each(getterReceivers)(
"does not report a stale literal through %s",
(_shape, body) => {
@@ -103,6 +135,42 @@ describe("getter receiver mutation aliases (#1665)", () => {
"unrelated sibling",
"const box = { x: 1, y: 1, get self() { return this; } }; box.self.y = 2; return box.x;",
],
[
"array receiver read without write",
"const arr = [{ x: 1, get self() { return this; } }]; const saved = arr[0].self; return arr[0].x;",
],
[
"assigned receiver read without write",
"let box; box = { x: 1, get self() { return this; } }; const saved = box.self; return box.x;",
],
[
"unrelated array receiver property",
"const arr = [{ x: 1, y: 1, get self() { return this; } }]; arr[0].self.y = 2; return arr[0].x;",
],
[
"unrelated array element",
"const arr = [{ x: 1, get self() { return this; } }, { x: 1 }]; arr[0].self.x = 2; return arr[1].x;",
],
[
"array replacement after a receiver was captured",
"const original = [{ x: 1, get self() { return this; } }]; const replacement = [{ x: 1 }]; let arr = original; const saved = arr[0].self; arr = replacement; saved.x = 2; return replacement[0].x;",
],
[
"known array prefix before a spread receiver",
"const arr = [{ x: 1 }, ...items, { x: 1, get self() { return this; } }]; arr[1].self.x = 2; return arr[0].x;",
],
[
"outer binding shadowed by an assigned receiver",
"let box; box = { x: 1 }; { let box; box = { x: 1, get self() { return this; } }; box.self.x = 2; } return box.x;",
],
[
"old object before an unconditional receiver assignment",
"const old = { x: 1 }; let box = old; box = { x: 1, get self() { return this; } }; box.self.x = 2; return old.x;",
],
[
"unmodified old receiver captured inside its replacement initializer",
"const old = { x: 1 }; let box = old; box = { x: 1, old: box, get self() { return this; } }; box.self.x = 2; return old.x;",
],
[
"replace getter",
"const shared = { x: 1 }; const box = { s: shared, get v() { return this.s; } }; box.v = {}; return shared.x;",
@@ -10,19 +10,21 @@ import {
evaluateSemanticBinding,
evaluateSemanticExpression,
} from "./javascriptSemanticValues.js";
import {
semanticContainer,
semanticSlotAtPath,
} from "./javascriptSemanticSlots.js";
import { semanticContainer } from "./javascriptSemanticSlots.js";
import {
semanticClassCandidates,
semanticClassPropertyReferences,
semanticObjectPropertyReferences,
type JavaScriptSemanticObjectReference,
} from "./javascriptSemanticObjectReferences.js";
import { semanticIterationSources } from "./javascriptSemanticIterationSources.js";
import { semanticCallableResultExpressions } from "./javascriptSemanticCallableResults.js";
import { createSemanticReturnedReferences } from "./javascriptSemanticReturnedReferences.js";
import { semanticMutationInitializers } from "./javascriptSemanticMutationInitializers.js";
import {
semanticReferenceSourcesInactive,
semanticSelectedReferenceSlot,
} from "./javascriptSemanticReferenceSources.js";
import {
semanticArrayIndex,
SemanticPropertyPathCoverage,
@@ -98,8 +100,20 @@ export function* collectSemanticMemberMutationsSteps(
effect: ValueEffect = "write",
mutation?: t.Node,
originAt: t.Node | undefined = mutation,
ownerInitializer?: t.Node,
): void => {
const pending = [{ node, path, bindings, originAt }];
const pending: (ReferencedValue & {
readonly bindings: ReadonlySet<string>;
readonly originAt: t.Node | undefined;
})[] = [
{
node,
path,
bindings,
originAt,
...(ownerInitializer === undefined ? {} : { ownerInitializer }),
},
];
// Visit shallower alias traversals first so their exact prefixes suppress
// longer loop paths before those paths enumerate every assignment order.
for (let cursor = 0; cursor < pending.length; cursor++) {
@@ -132,6 +146,8 @@ export function* collectSemanticMemberMutationsSteps(
binding.bindingId,
current.originAt?.start,
current.originAt?.end,
current.ownerInitializer?.start,
current.ownerInitializer?.end,
];
const lifetime = JSON.stringify([...capture, current.path]);
if (current.bindings.has(lifetime)) continue;
@@ -165,6 +181,7 @@ export function* collectSemanticMemberMutationsSteps(
"escape",
mutation,
current.originAt,
current.ownerInitializer,
);
continue;
}
@@ -195,6 +212,8 @@ export function* collectSemanticMemberMutationsSteps(
mutation?.end,
current.originAt?.start,
current.originAt?.end,
current.ownerInitializer?.start,
current.ownerInitializer?.end,
]);
const previous = selections.get(selectionIdentity);
const excludedKeys =
@@ -220,6 +239,8 @@ export function* collectSemanticMemberMutationsSteps(
mutation?.end,
current.originAt?.start,
current.originAt?.end,
current.ownerInitializer?.start,
current.ownerInitializer?.end,
]);
let covering = coveringPaths.get(pathState);
if (covering === undefined) {
@@ -235,6 +256,8 @@ export function* collectSemanticMemberMutationsSteps(
mutation?.end,
current.originAt?.start,
current.originAt?.end,
current.ownerInitializer?.start,
current.ownerInitializer?.end,
]);
if (recordedEffects.has(identity)) continue;
// A recorded write invalidates the binding to a non-primitive value, so
@@ -248,10 +271,23 @@ export function* collectSemanticMemberMutationsSteps(
value?.status === "literal" || value?.status === "union";
recordedEffects.add(identity);
const nested = new Set([...current.bindings, lifetime, captureKey]);
// Returning a literal's receiver reaches that allocation, not the
// binding's older values read while evaluating its initializer.
const origins =
current.originAt === undefined
? binding
: semanticMutationInitializers(binding, current.originAt, parents);
current.ownerInitializer !== undefined
? {
initializers: binding.initializers.filter(
({ node }) => node === current.ownerInitializer,
),
referenceInitializers: [],
}
: current.originAt === undefined
? binding
: semanticMutationInitializers(
binding,
current.originAt,
parents,
);
if (!primitiveWrite) {
if (effect === "escape")
binding.escapedPaths.push({ path, node: mutation });
@@ -294,7 +330,17 @@ export function* collectSemanticMemberMutationsSteps(
for (const value of effect === "escape"
? escapedReferenceLeaves(expression, current.path)
: expandedValues(expression, current.path, effect)) {
if (value.iterableFallbackPath !== undefined)
if (value.escapes && effect !== "escape")
markValue(
value.node,
value.path,
new Set(),
"escape",
mutation,
current.originAt,
value.ownerInitializer,
);
else if (value.iterableFallbackPath !== undefined)
deferIterable({
node: value.node,
projection: [],
@@ -367,6 +413,8 @@ export function* collectSemanticMemberMutationsSteps(
binding === undefined ? null : binding.bindingId,
binding === undefined ? node.name : null,
pathKey,
value.ownerInitializer?.start,
value.ownerInitializer?.end,
]);
if (leafIdentities.has(identity)) continue;
leafIdentities.add(identity);
@@ -467,7 +515,7 @@ export function* collectSemanticMemberMutationsSteps(
for (const [index, reference] of pendingReferences.splice(0).entries()) {
if (index % 64 === 0) yield;
const { initializer } = reference;
if (referenceSourcesInactive(initializer, state))
if (semanticReferenceSourcesInactive(initializer, state))
pendingReferences.push(reference);
else if (t.isForOfStatement(initializer.node))
deferIterable({
@@ -512,7 +560,7 @@ export function* collectSemanticMemberMutationsSteps(
}
for (const [index, reference] of [...iterableReferences].entries()) {
if (index % 64 === 0) yield;
if (referenceSourcesInactive(reference, state)) continue;
if (semanticReferenceSourcesInactive(reference, state)) continue;
if (reference.iterationOnly) {
const expanded = expandedIterationReferences(reference, state);
if (expanded !== null) {
@@ -520,7 +568,7 @@ export function* collectSemanticMemberMutationsSteps(
continue;
}
}
const slot = selectedReferenceSlot(reference, state);
const slot = semanticSelectedReferenceSlot(reference, state);
// Custom iteration can yield the iterable itself as well as any child.
// Treat its root as escaped, including writes through yielded references.
const knownArray =
@@ -551,9 +599,7 @@ export function* collectSemanticMemberMutationsSteps(
clearSemanticValueCaches(state);
}
interface ReferencedValue {
readonly node: t.Node;
readonly path: PropertyPath;
interface ReferencedValue extends JavaScriptSemanticObjectReference {
readonly iterableFallbackPath?: PropertyPath;
}
@@ -575,27 +621,6 @@ interface IterableReference extends ReferencedValue {
}[];
}
const referenceSourcesInactive = (
reference: Pick<IterableReference, "requiredSources" | "fallbackSources">,
state: JavaScriptSemanticAnalysisState,
): boolean =>
reference.requiredSources?.some(
(source) =>
selectedReferenceSlot(source, state, source.node)?.presence === "absent",
) === true ||
reference.fallbackSources?.some((source) => {
// Selection precedes effects through the chosen reference. A later escape
// cannot make a fallback that was excluded at destructuring reachable.
const slot = selectedReferenceSlot(source, state, source.node);
return (
slot?.presence === "present" &&
(slot.value.status === "literal" ||
slot.value.status === "union" ||
slot.value.status === "object" ||
slot.value.status === "array")
);
}) === true;
const expandedIterationReferences = (
reference: IterableReference,
state: JavaScriptSemanticAnalysisState,
@@ -610,7 +635,10 @@ const expandedIterationReferences = (
...(reference.fallbackSources ?? []),
].find((source) => source.node === iterable && source.projection[0] === null);
if (source === undefined) return null;
const slot = selectedReferenceSlot({ node: iterable, projection: [] }, state);
const slot = semanticSelectedReferenceSlot(
{ node: iterable, projection: [] },
state,
);
const container = slot === undefined ? null : semanticContainer(slot.value);
if (container?.coverage.status !== "complete") return null;
const select = (
@@ -1106,19 +1134,3 @@ const copiedReferencePath = (
}
return [...initializer.projection.slice(0, offset), key, ...remaining];
};
const selectedReferenceSlot = (
source: { readonly node: t.Node; readonly projection: PropertyPath },
state: JavaScriptSemanticAnalysisState,
capturePoint?: t.Node,
) => {
const path: string[] = [];
for (const key of source.projection) {
if (key === null || typeof key === "object") return undefined;
path.push(String(key));
}
return semanticSlotAtPath(
evaluateSemanticExpression(source.node, state, capturePoint),
path,
);
};
@@ -149,7 +149,50 @@ export const semanticMutationInitializers = (
const mutationPosition =
directMutationPosition(mutation, parents) ??
referenceInitializerPosition(mutation, parents);
if (mutationPosition === null) return binding;
return selectInitializers(binding, mutationPosition, parents);
};
/** Select a local alias at its read, before any later straight-line reassignment. */
export const semanticReadInitializers = (
binding: JavaScriptSemanticBindingState,
read: t.Node,
parents: WeakMap<t.Node, t.Node>,
): Pick<
JavaScriptSemanticBindingState,
"initializers" | "referenceInitializers"
> => {
let position: StatementPosition | null = null;
let current = read;
for (
let parent = parents.get(current);
parent;
parent = parents.get(current)
) {
if (t.isLoop(parent)) return binding;
if (t.isFunction(parent)) break;
if (position === null) {
if (t.isVariableDeclarator(parent)) {
const declaration = parents.get(parent);
if (t.isVariableDeclaration(declaration))
position = statementPosition(declaration, parents, parent);
} else if (t.isStatement(parent))
position = statementPosition(parent, parents);
}
current = parent;
}
return selectInitializers(binding, position, parents, true);
};
const selectInitializers = (
binding: JavaScriptSemanticBindingState,
position: StatementPosition | null,
parents: WeakMap<t.Node, t.Node>,
atRead = false,
): Pick<
JavaScriptSemanticBindingState,
"initializers" | "referenceInitializers"
> => {
if (position === null) return binding;
const origins = [
...binding.initializers.map((initializer) => ({
initializer,
@@ -169,12 +212,20 @@ export const semanticMutationInitializers = (
];
if (
origins.some(
({ position }) =>
position === null || !positionPrecedes(position, mutationPosition),
({ position: origin }) =>
origin === null ||
origin.body !== position.body ||
(!atRead && !positionPrecedes(origin, position)),
)
)
return binding;
const latest = origins.reduce<StatementPosition | null>(
const preceding = atRead
? origins.filter(
({ position: origin }) =>
origin !== null && positionPrecedes(origin, position),
)
: origins;
const latest = preceding.reduce<StatementPosition | null>(
(latest, { position }) =>
position !== null &&
(latest === null || positionPrecedes(latest, position))
@@ -183,7 +234,7 @@ export const semanticMutationInitializers = (
null,
);
const retained = new Set(
origins
preceding
.filter(
({ position }) =>
position?.index === latest?.index &&
@@ -4,6 +4,8 @@ import {
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
import { semanticCallableResultExpressions } from "./javascriptSemanticCallableResults.js";
import { semanticReadInitializers } from "./javascriptSemanticMutationInitializers.js";
import { semanticReferenceSourcesInactive } from "./javascriptSemanticReferenceSources.js";
import {
semanticStaticPropertyKey,
unwrapJavaScriptExpression,
@@ -14,9 +16,12 @@ import {
} from "./javascriptSemanticPropertyPaths.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
interface ReferencedValue {
export interface JavaScriptSemanticObjectReference {
readonly node: t.Node;
readonly path: PropertyPath;
readonly escapes?: true;
/** The allocation owned by this binding, rather than a read of its prior value. */
readonly ownerInitializer?: t.Node;
}
export const semanticClassCandidates = (
@@ -71,11 +76,12 @@ const instanceFieldReferences = (
propertyName: string | null,
path: PropertyPath,
state: JavaScriptSemanticAnalysisState,
initializedBefore?: t.ClassProperty,
): {
readonly references: readonly ReferencedValue[];
readonly references: readonly JavaScriptSemanticObjectReference[];
readonly definiteNames: ReadonlySet<string>;
} => {
const references: ReferencedValue[] = [];
const references: JavaScriptSemanticObjectReference[] = [];
const pending = [{ klass: root, excluded: new Set<string>() }];
const selections = new Map<t.Node, ReadonlySet<string>>();
let definiteNames: ReadonlySet<string> | undefined;
@@ -92,7 +98,15 @@ const instanceFieldReferences = (
if (previous !== undefined && previous.size === excluded.size) continue;
selections.set(current.klass, excluded);
const shadowed = new Set(excluded);
for (const member of [...current.klass.body.body].reverse()) {
const before =
initializedBefore === undefined
? -1
: current.klass.body.body.indexOf(initializedBefore);
const members =
before < 0
? current.klass.body.body
: current.klass.body.body.slice(0, before);
for (const member of [...members].reverse()) {
if (!t.isClassProperty(member) || member.static) continue;
const key = semanticStaticPropertyKey(member.key, member.computed);
if (key !== null && shadowed.has(key)) continue;
@@ -121,12 +135,15 @@ interface ClassPropertyLookup {
readonly owner: t.ClassDeclaration | t.ClassExpression;
readonly receiver?: t.ClassDeclaration | t.ClassExpression;
readonly kind: "instance" | "static" | "prototype";
readonly fieldsOnly?: true;
readonly initializedBefore?: t.ClassProperty;
}
const classPropertyDescriptors = (
klass: t.ClassDeclaration | t.ClassExpression,
propertyName: string | null,
kind: ClassPropertyLookup["kind"],
initializedBefore?: t.ClassProperty,
) => {
const isStatic = kind === "static";
const selectedGetters: t.ClassMethod[] = [];
@@ -136,7 +153,12 @@ const classPropertyDescriptors = (
readonly index: number;
readonly key: string | null;
}[] = [];
const before =
initializedBefore === undefined
? -1
: klass.body.body.indexOf(initializedBefore);
klass.body.body.forEach((member, index) => {
if (before >= 0 && index >= before && t.isClassProperty(member)) return;
if (
(t.isClassMethod(member) ||
(kind === "static" && t.isClassProperty(member))) &&
@@ -208,7 +230,7 @@ export const semanticClassPropertyReferences = (
selection: PropertyPath,
state: JavaScriptSemanticAnalysisState,
activeGetters: ReadonlyMap<t.Node, number> = new Map(),
): readonly ReferencedValue[] => {
): readonly JavaScriptSemanticObjectReference[] => {
const root = lookup.owner;
const receiver = lookup.receiver ?? root;
const [key, ...path] = selection;
@@ -216,12 +238,18 @@ export const semanticClassPropertyReferences = (
key == null || typeof key === "object" ? null : String(key);
const pending: (t.ClassDeclaration | t.ClassExpression)[] = [root];
const seen = new Set<t.Node>();
const possibleResults: ReferencedValue[] = [];
const possibleResults: JavaScriptSemanticObjectReference[] = [];
// Instance fields are own properties, including fields initialized by base
// constructors. They take precedence over every prototype descriptor.
let instanceFields: ReadonlySet<string> = new Set();
if (lookup.kind === "instance") {
const fields = instanceFieldReferences(root, propertyName, path, state);
const fields = instanceFieldReferences(
root,
propertyName,
path,
state,
lookup.initializedBefore,
);
possibleResults.push(...fields.references);
instanceFields = fields.definiteNames;
if (propertyName !== null && instanceFields.has(propertyName))
@@ -235,11 +263,12 @@ export const semanticClassPropertyReferences = (
klass,
propertyName,
lookup.kind,
lookup.initializedBefore,
);
for (const field of descriptors.fields)
if (field.value != null)
possibleResults.push({ node: field.value, path });
for (const getter of descriptors.getters) {
for (const getter of lookup.fieldsOnly ? [] : descriptors.getters) {
const key = semanticStaticPropertyKey(getter.key, getter.computed);
if (key !== null && instanceFields.has(key)) continue;
possibleResults.push(
@@ -267,11 +296,11 @@ const objectReceiverReference = (
object: t.ObjectExpression,
path: PropertyPath,
state: JavaScriptSemanticAnalysisState,
): readonly ReferencedValue[] => {
): readonly JavaScriptSemanticObjectReference[] => {
// A literal's enclosing binding owns its slots. Returning the literal
// itself would bypass invalidation of that binding's observed properties.
let current: t.Node = object;
const projection: (string | number | null)[] = [];
const projection: PropertyPath[number][] = [];
while (true) {
const parent = state.parentsByNode.get(current);
if (
@@ -279,7 +308,43 @@ const objectReceiverReference = (
parent.init === current &&
t.isIdentifier(parent.id)
)
return [{ node: parent.id, path: [...projection, ...path] }];
return [
{
node: parent.id,
path: [...projection, ...path],
ownerInitializer: current,
},
];
if (
t.isAssignmentExpression(parent, { operator: "=" }) &&
parent.right === current &&
t.isIdentifier(parent.left)
)
return [
{
node: parent.left,
path: [...projection, ...path],
ownerInitializer: current,
},
];
if (t.isArrayExpression(parent)) {
let minimumIndex = 0;
let uncertainIndex = false;
for (const element of parent.elements) {
if (element === current) break;
if (t.isSpreadElement(element)) uncertainIndex = true;
else minimumIndex++;
}
// A spread contributes an unknown number of slots. Retain the known
// prefix without treating the element's syntax position as its index.
projection.unshift(
uncertainIndex
? { excludedKeys: [], startIndex: minimumIndex }
: minimumIndex,
);
current = parent;
continue;
}
if (t.isObjectProperty(parent) && parent.value === current) {
projection.unshift(
semanticStaticPropertyKey(parent.key, parent.computed),
@@ -307,12 +372,108 @@ interface GetterInvocation {
| t.ClassExpression;
}
/** Follow only data fields whose initializers retain a class receiver. */
const privateReceiverProjection = (
receiver: t.ClassDeclaration | t.ClassExpression,
owner: t.ClassDeclaration | t.ClassExpression,
path: PropertyPath,
isStatic: boolean,
state: JavaScriptSemanticAnalysisState,
): boolean => {
if (path.some((key) => key === null || typeof key === "object")) return false;
type Selection = { readonly key: string; readonly before?: t.ClassProperty };
const pending: {
receiver: typeof receiver;
path: readonly Selection[];
visits: ReadonlyMap<string, number>;
}[] = [
{
receiver,
path: path.map((key) => ({ key: String(key) })),
visits: new Map(),
},
];
const seen = new Set<string>();
const declaringClass = (field: t.ClassProperty) => {
const body = state.parentsByNode.get(field);
return body === undefined ? undefined : state.parentsByNode.get(body);
};
for (let cursor = 0; cursor < pending.length; cursor++) {
const current = pending[cursor];
if (current === undefined) break;
const [selection, ...remaining] = current.path;
if (selection === undefined) {
if (!isStatic || current.receiver === owner) return true;
continue;
}
const origin = JSON.stringify([
current.receiver.start,
selection.key,
selection.before?.start,
]);
const previous = current.visits.get(origin);
// Repeated fields may consume a finite getter path. An initializer cycle
// that preserves or grows it cannot establish another receiver identity.
if (previous !== undefined && previous <= current.path.length) continue;
const visits = new Map(current.visits).set(origin, current.path.length);
const identity = JSON.stringify([
current.receiver.start,
current.path.map(({ key, before }) => [key, before?.start]),
]);
if (seen.has(identity)) continue;
seen.add(identity);
const lookupOwner =
selection.before === undefined
? current.receiver
: declaringClass(selection.before);
if (!t.isClass(lookupOwner)) continue;
for (const reference of semanticClassPropertyReferences(
{
owner: lookupOwner,
receiver: current.receiver,
kind: isStatic ? "static" : "instance",
fieldsOnly: true,
...(selection.before === undefined
? {}
: { initializedBefore: selection.before }),
},
[selection.key],
state,
)) {
const field = state.parentsByNode.get(reference.node);
if (!t.isClassProperty(field)) continue;
const fieldOwner = declaringClass(field);
if (!t.isClass(fieldOwner)) continue;
const projection: Selection[] = [];
let value = unwrapJavaScriptExpression(reference.node).node;
while (
t.isMemberExpression(value) ||
t.isOptionalMemberExpression(value)
) {
const key = semanticStaticPropertyKey(value.property, value.computed);
if (key === null || t.isPrivateName(value.property)) break;
projection.unshift({ key, before: field });
value = unwrapJavaScriptExpression(value.object).node;
}
if (!t.isThisExpression(value)) continue;
// Instance fields retain the actual instance. Static field `this` belongs
// to its declaring class, even when a subclass inherits the field.
pending.push({
receiver: isStatic ? fieldOwner : current.receiver,
path: [...projection, ...remaining],
visits,
});
}
}
return false;
};
const getterResultReferences = (
invocation: GetterInvocation,
path: PropertyPath,
state: JavaScriptSemanticAnalysisState,
activeGetters: ReadonlyMap<t.Node, number> = new Map(),
): readonly ReferencedValue[] => {
): readonly JavaScriptSemanticObjectReference[] => {
const { getter, owner, receiver = owner } = invocation;
const previousLength = activeGetters.get(getter);
if (previousLength !== undefined && previousLength <= path.length) return [];
@@ -320,40 +481,206 @@ const getterResultReferences = (
// path; recursive getters that preserve or grow that path cannot progress.
const active = new Map(activeGetters).set(getter, path.length);
const isStatic = t.isClassMethod(getter) && getter.static;
const resolve = (
node: t.Node,
remaining: PropertyPath,
): readonly ReferencedValue[] => {
const expression = unwrapJavaScriptExpression(node).node;
if (t.isThisExpression(expression)) {
if (t.isClass(receiver)) {
return semanticClassPropertyReferences(
{ owner: receiver, kind: isStatic ? "static" : "instance" },
remaining,
state,
active,
);
interface AliasVisit {
readonly identity: string;
readonly pathLength: number;
readonly parent: AliasVisit | undefined;
}
const pending: {
readonly node: t.Node;
readonly path: PropertyPath;
readonly aliases: AliasVisit | undefined;
readonly escapes?: true;
readonly privateRead?: {
readonly node: t.MemberExpression | t.OptionalMemberExpression;
readonly name: string;
readonly path: PropertyPath;
};
}[] = semanticCallableResultExpressions(getter).flatMap(({ node }) =>
node === null ? [] : [{ node, path, aliases: undefined }],
);
const references: JavaScriptSemanticObjectReference[] = [];
const expandedAliases = new Map<string, Set<string>>();
const getterScope = state.scopeByNode.get(getter)?.scopeId;
for (let cursor = 0; cursor < pending.length; cursor++) {
const current = pending[cursor];
if (current === undefined) break;
const { path: remaining } = current;
const expression = unwrapJavaScriptExpression(current.node).node;
const retain = (reference: JavaScriptSemanticObjectReference): void => {
references.push(
current.escapes ? { ...reference, escapes: true } : reference,
);
};
const retainPrivateRead = (): void => {
if (current.privateRead !== undefined)
retain({
node: current.privateRead.node,
path: current.escapes ? [] : current.privateRead.path,
});
};
if (t.isIdentifier(expression)) {
const binding = resolveSemanticBindingState(
state,
expression,
expression.name,
);
let scope =
binding === undefined
? undefined
: state.scopesById.get(binding.scopeId);
while (scope !== undefined && scope.scopeId !== getterScope) {
if (scope.kind === "function" || scope.parentScopeId === null) {
scope = undefined;
break;
}
scope = state.scopesById.get(scope.parentScopeId);
}
return objectReceiverReference(receiver, remaining, state);
if (
binding !== undefined &&
scope !== undefined &&
binding.referenceInitializers.every(
(initializer) => initializer.copyKind === undefined,
)
) {
const identity = JSON.stringify([
binding.bindingId,
expression.start,
expression.end,
]);
const known = expandedAliases.get(identity);
const key = JSON.stringify([
remaining,
current.privateRead?.name,
current.privateRead?.path,
current.escapes,
]);
let cyclic = false;
let growing = false;
if (known !== undefined)
for (
let visit = current.aliases;
visit !== undefined;
visit = visit.parent
)
if (visit.identity === identity) {
cyclic = true;
growing = remaining.length > visit.pathLength;
break;
}
if (cyclic) {
// A repeated alias can select arbitrarily deep children. Revisit its
// roots as escapes rather than enumerating iterations or dropping them.
if (growing && !current.escapes)
pending.push({
...current,
path: [],
aliases: undefined,
escapes: true,
});
continue;
}
if (known?.has(key)) continue;
const selections = known ?? new Set<string>();
selections.add(key);
expandedAliases.set(identity, selections);
const aliases = {
identity,
pathLength: remaining.length,
parent: current.aliases,
};
const origins = semanticReadInitializers(
binding,
expression,
state.parentsByNode,
);
for (const initializer of [
...origins.initializers,
...origins.referenceInitializers.filter(
(initializer) =>
!semanticReferenceSourcesInactive(initializer, state),
),
])
pending.push({
...current,
node: initializer.node,
path: [...initializer.projection, ...remaining],
aliases,
});
continue;
}
}
if (t.isThisExpression(expression)) {
// An outer binding or a nested ordinary function has a different receiver.
let ownerNode = state.parentsByNode.get(expression);
while (
ownerNode !== undefined &&
!t.isClass(ownerNode) &&
!(t.isFunction(ownerNode) && !t.isArrowFunctionExpression(ownerNode))
)
ownerNode = state.parentsByNode.get(ownerNode);
if (ownerNode !== getter) continue;
if (current.privateRead !== undefined && t.isClass(owner)) {
if (
!t.isClass(receiver) ||
!privateReceiverProjection(
receiver,
owner,
remaining,
isStatic,
state,
)
) {
retainPrivateRead();
continue;
}
for (const member of owner.body.body)
if (
t.isClassPrivateProperty(member) &&
member.static === isStatic &&
member.key.id.name === current.privateRead.name &&
member.value != null
)
retain({
node: member.value,
path: current.escapes ? [] : current.privateRead.path,
});
continue;
}
for (const reference of t.isClass(receiver)
? semanticClassPropertyReferences(
{ owner: receiver, kind: isStatic ? "static" : "instance" },
remaining,
state,
active,
)
: objectReceiverReference(receiver, remaining, state))
retain(reference);
continue;
}
if (
t.isMemberExpression(expression) ||
t.isOptionalMemberExpression(expression)
) {
if (
t.isPrivateName(expression.property) &&
t.isThisExpression(expression.object) &&
t.isClass(owner)
current.privateRead !== undefined &&
t.isPrivateName(expression.property)
) {
const privateName = expression.property.id.name;
return owner.body.body.flatMap((member) =>
t.isClassPrivateProperty(member) &&
member.static === isStatic &&
member.key.id.name === privateName &&
member.value != null
? [{ node: member.value, path: remaining }]
: [],
);
retainPrivateRead();
continue;
}
if (t.isPrivateName(expression.property) && t.isClass(owner)) {
pending.push({
...current,
node: expression.object,
path: [],
privateRead: {
node: expression,
name: expression.property.id.name,
path: remaining,
},
});
continue;
}
const key = semanticStaticPropertyKey(
expression.property,
@@ -364,50 +691,61 @@ const getterResultReferences = (
t.isClass(owner) &&
owner.superClass != null
) {
return semanticClassCandidates(owner.superClass, state).flatMap(
(base) =>
semanticClassPropertyReferences(
{
owner: base,
receiver: t.isClass(receiver) ? receiver : owner,
kind: isStatic ? "static" : "prototype",
},
[key, ...remaining],
state,
active,
),
);
for (const base of semanticClassCandidates(owner.superClass, state))
for (const reference of semanticClassPropertyReferences(
{
owner: base,
receiver: t.isClass(receiver) ? receiver : owner,
kind: isStatic ? "static" : "prototype",
},
[key, ...remaining],
state,
active,
))
retain(reference);
continue;
}
return resolve(expression.object, [key, ...remaining]);
}
if (t.isConditionalExpression(expression))
return [
...resolve(expression.consequent, remaining),
...resolve(expression.alternate, remaining),
];
if (t.isLogicalExpression(expression))
return [
...resolve(expression.left, remaining),
...resolve(expression.right, remaining),
];
if (t.isSequenceExpression(expression)) {
pending.push({
...current,
node: expression.object,
path: [key, ...remaining],
});
} else if (t.isConditionalExpression(expression))
pending.push(
{ ...current, node: expression.consequent },
{ ...current, node: expression.alternate },
);
else if (t.isLogicalExpression(expression))
pending.push(
{ ...current, node: expression.left },
{ ...current, node: expression.right },
);
else if (t.isSequenceExpression(expression)) {
const last = expression.expressions.at(-1);
return last === undefined ? [] : resolve(last, remaining);
}
return [{ node: expression, path: remaining }];
};
return semanticCallableResultExpressions(getter).flatMap(({ node }) =>
node === null ? [] : resolve(node, path),
);
if (last !== undefined) pending.push({ ...current, node: last });
} else if (t.isAssignmentExpression(expression, { operator: "=" }))
pending.push({ ...current, node: expression.right });
else if (
t.isAssignmentExpression(expression) &&
["&&=", "||=", "??="].includes(expression.operator)
)
pending.push(
{ ...current, node: expression.left },
{ ...current, node: expression.right },
);
else if (current.privateRead !== undefined) retainPrivateRead();
else retain({ node: expression, path: remaining });
}
return references;
};
export const semanticObjectPropertyReferences = (
node: t.ObjectExpression,
path: PropertyPath,
state: JavaScriptSemanticAnalysisState,
): readonly ReferencedValue[] => {
): readonly JavaScriptSemanticObjectReference[] => {
const [key, ...remaining] = path;
const references: ReferencedValue[] = [];
const references: JavaScriptSemanticObjectReference[] = [];
const overwritten = new Set<string>();
const dataOverwritten = new Set<string>();
const accessorNames = new Set<string>();
@@ -0,0 +1,53 @@
import type * as t from "@babel/types";
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
import type { JavaScriptSemanticPropertyPath as PropertyPath } from "./javascriptSemanticPropertyPaths.js";
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
import { semanticSlotAtPath } from "./javascriptSemanticSlots.js";
interface ReferenceSource {
readonly node: t.Node;
readonly projection: PropertyPath;
}
/** Exclude references whose source slot or destructuring fallback is absent. */
export const semanticReferenceSourcesInactive = (
reference: {
readonly requiredSources?: readonly ReferenceSource[];
readonly fallbackSources?: readonly ReferenceSource[];
},
state: JavaScriptSemanticAnalysisState,
): boolean =>
reference.requiredSources?.some(
(source) =>
semanticSelectedReferenceSlot(source, state, source.node)?.presence ===
"absent",
) === true ||
reference.fallbackSources?.some((source) => {
// Selection precedes effects through the chosen reference. A later escape
// cannot make a fallback that was excluded at destructuring reachable.
const slot = semanticSelectedReferenceSlot(source, state, source.node);
return (
slot?.presence === "present" &&
(slot.value.status === "literal" ||
slot.value.status === "union" ||
slot.value.status === "object" ||
slot.value.status === "array")
);
}) === true;
/** Select a retained source slot at its capture, before later effects. */
export const semanticSelectedReferenceSlot = (
source: ReferenceSource,
state: JavaScriptSemanticAnalysisState,
capturePoint?: t.Node,
) => {
const path: string[] = [];
for (const key of source.projection) {
if (key === null || typeof key === "object") return undefined;
path.push(String(key));
}
return semanticSlotAtPath(
evaluateSemanticExpression(source.node, state, capturePoint),
path,
);
};
@@ -181,18 +181,37 @@ export const staticPath = (node: t.Node): string | undefined => {
if (t.isStringLiteral(node)) return node.value;
if (t.isTemplateLiteral(node) && node.expressions.length === 0)
return stringValue(node);
if (t.isBinaryExpression(node, { operator: "+" })) {
const left = staticPath(node.left);
const right = staticPath(node.right);
return left === undefined || right === undefined
? undefined
: `${left}${right}`;
}
if (t.isBinaryExpression(node, { operator: "+" }))
return staticConcatenation(node);
if (t.isCallExpression(node) || t.isNewExpression(node))
return staticCallPath(node);
return undefined;
};
/**
* Concatenate inert text. A leading source directory contributes no text:
* `__dirname + "/preload.js"` names a file inside it, while text without a
* leading separator extends the directory's own name and stays unknown.
*/
const staticConcatenation = (node: t.BinaryExpression): string | undefined => {
const operands: t.Node[] = [];
let current: t.Node = node;
while (t.isBinaryExpression(current, { operator: "+" })) {
operands.push(current.right);
current = current.left;
}
const anchored = isDirectoryPath(current);
if (!anchored) operands.push(current);
let text = "";
for (const operand of operands.reverse()) {
const value = staticPath(operand);
if (value === undefined) return undefined;
text += value;
}
if (!anchored) return text;
return text.startsWith("/") ? posix.join(".", text) : undefined;
};
const staticCallPath = (
node: t.CallExpression | t.NewExpression,
): string | undefined => {
@@ -204,11 +223,6 @@ const staticCallPath = (
if (name === "fileURLToPath" || name.endsWith(".fileURLToPath")) {
return staticFileUrlPath(argumentNode(node.arguments[0]));
}
if (
(name === "dirname" || name.endsWith(".dirname")) &&
isFileIdentity(argumentNode(node.arguments[0]))
)
return "";
if (name.endsWith(".resolve"))
return name === "win32.resolve" || name.endsWith(".win32.resolve")
? undefined
@@ -216,7 +230,12 @@ const staticCallPath = (
if (!name.endsWith(".join") && name !== "join") return undefined;
const parts: string[] = [];
for (const argument of node.arguments) {
if (isDirectoryIdentity(argumentNode(argument))) continue;
if (isDirectoryIdentity(argumentNode(argument))) {
// join never resets at an absolute segment, so `/preload.js` after the
// source directory stays inside it.
parts.push(".");
continue;
}
const value = t.isNode(argument) ? staticPath(argument) : undefined;
if (value === undefined) return undefined;
parts.push(value);
@@ -331,11 +350,20 @@ const isFilesystemPathExpression = (node: t.Node): boolean => {
};
const isDirectoryIdentity = (node: t.Node | undefined): boolean => {
if (t.isIdentifier(node, { name: "__dirname" })) return true;
if (isDirectoryPath(node)) return true;
if (!t.isCallExpression(node) && !t.isNewExpression(node)) return false;
const name = calleeName(node.callee);
if (name === "URL" || name.endsWith(".URL"))
return isFileIdentity(argumentNode(node.arguments[1]));
return (
(name === "URL" || name.endsWith(".URL")) &&
isFileIdentity(argumentNode(node.arguments[1]))
);
};
/** `__dirname` or the dirname of the source file, as a string. */
const isDirectoryPath = (node: t.Node | undefined): boolean => {
if (t.isIdentifier(node, { name: "__dirname" })) return true;
if (!t.isCallExpression(node)) return false;
const name = calleeName(node.callee);
return (
(name === "dirname" || name.endsWith(".dirname")) &&
isFileIdentity(argumentNode(node.arguments[0]))
@@ -38,6 +38,9 @@ const anchoredExpressions = [
["path.resolve(__dirname)", "."],
['path.posix.resolve(`/app`, `/shared`, "preload.js")', "/shared/preload.js"],
['path.posix.resolve("" + "/app", "preload.js")', "/app/preload.js"],
['__dirname + "/preload.js"', "preload.js"],
['__dirname + "/" + "preload.js"', "preload.js"],
['path.dirname(__filename) + "/lib" + "/preload.js"', "lib/preload.js"],
] as const;
const unknownExpressions = [
@@ -58,6 +61,8 @@ const unknownExpressions = [
'path.win32.resolve(__dirname, "preload.js")',
'win32.resolve("/app", "preload.js")',
'resolve("/app", "preload.js")',
'__dirname + "preload.js"',
'path.dirname(__filename) + "preload.js"',
];
describe("inert JavaScript path resolution", () => {
@@ -100,6 +105,16 @@ describe("inert JavaScript path resolution", () => {
"preload.js",
"filesystem-expression",
],
[
'path.join(__dirname, "/preload.js")',
"preload.js",
"filesystem-expression",
],
[
'path.join(dirname(fileURLToPath(import.meta.url)), "/lib", "/preload.js")',
"lib/preload.js",
"filesystem-expression",
],
[
'path.join("ignored", __dirname, "preload.js")',
"ignored/preload.js",
@@ -111,6 +126,7 @@ describe("inert JavaScript path resolution", () => {
"filesystem-expression",
],
['join("sub", "preload.js")', "sub/preload.js", "module-specifier"],
["path.join(__dirname)", ".", "filesystem-expression"],
] as const)("preserves join behavior in %s", (expression, path, context) => {
assertPathProjection(expression, path, context);
});
@@ -182,7 +198,6 @@ describe("inert JavaScript path resolution", () => {
it.each([
"path.join()",
"path.join(__dirname)",
'path.join("/app", runtimeFile)',
"path.join(...parts)",
])("preserves unresolved join syntax in %s", (expression) =>
+18 -1
View File
@@ -203,10 +203,18 @@ const managedMethodSchema = z.object({
body: managedMethodBodySchema,
});
// Declaring types are namespace-qualified like TypeDef `full_name`, nested
// types keep bare names, and a generic instantiation names its generic type.
// Evidence recorded before declaring types were named reads them as null.
const declaringTypeNameSchema = z.string().nullable().default(null);
const managedMemberReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
parent_token: tokenSchema.nullable(),
parent_name: declaringTypeNameSchema.describe(
"Name of a TypeDef, TypeRef, or generic-instantiation TypeSpec parent; null for other parents or when unknown",
),
name: z.string(),
signature: managedSignatureSchema,
});
@@ -281,7 +289,13 @@ const managedCallEdgeSchema = z.object({
opcode: z.string(),
target_token: tokenSchema,
target_kind: z.enum(["method-def", "member-ref", "method-spec", "unknown"]),
target_name: z.string().nullable(),
target_name: z
.string()
.nullable()
.describe("Method name; a method-spec target reports its generic method"),
target_declaring_type: declaringTypeNameSchema.describe(
"Declaring type of the called method; null when unknown",
),
});
const managedFieldAccessSchema = z.object({
@@ -290,6 +304,9 @@ const managedFieldAccessSchema = z.object({
opcode: z.string(),
field_token: tokenSchema,
field_name: z.string().nullable(),
field_declaring_type: declaringTypeNameSchema.describe(
"Declaring type of the accessed field; null when unknown",
),
});
const managedParseIssueSchema = z.object({
+19
View File
@@ -159,3 +159,22 @@ describe("read-only NativeAOT PE parser", () => {
});
});
});
describe("NativeAOT PE signature admission", () => {
it.each([
["MZ", "Not a PE image"],
["PE", "Invalid PE signature"],
])(
"rejects a high-bit lookalike of the %s signature",
(signature, reason) => {
const bytes = nativeAotPeFixture();
const offset = signature === "MZ" ? 0 : bytes.readUInt32LE(0x3c);
for (const position of [offset, offset + 1])
bytes.writeUInt8(bytes.readUInt8(position) | 0x80, position);
expect(
parseNativeAotPe(bytes, nativeAotPeDigest(bytes), SUMMARY_BUDGET)
.summary,
).toMatchObject({ status: "not_applicable", reason });
},
);
});
+2 -2
View File
@@ -384,11 +384,11 @@ class PeImage {
constructor(bytes: Buffer) {
this.#bytes = bytes;
if (bytes.length < 0x40 || bytes.toString("ascii", 0, 2) !== "MZ")
if (bytes.length < 0x40 || bytes.toString("latin1", 0, 2) !== "MZ")
throw new Error("Not a PE image");
const peOffset = this.#u32(0x3c);
this.#range(peOffset, 24);
if (bytes.toString("ascii", peOffset, peOffset + 4) !== "PE\0\0")
if (bytes.toString("latin1", peOffset, peOffset + 4) !== "PE\0\0")
throw new Error("Invalid PE signature");
this.#machine = this.#u16(peOffset + 4);
const count = this.#u16(peOffset + 6);
@@ -83,6 +83,61 @@ const graph = nativeInvestigationGraphSchema.parse({
});
describe("native investigation graph traces", () => {
it.each(["forward", "backward"] as const)(
"keeps both endpoints of retained edges within the %s node budget",
(direction) => {
const trace = traceNativeInvestigationGraph(graph, {
start: direction === "forward" ? "a" : "c",
direction,
limits: { max_nodes: 1 },
});
expect(trace.nodes).toHaveLength(1);
expect(trace.edges).toEqual([]);
expect(trace).toMatchObject({
truncated: true,
reason: "max_nodes_reached",
reached_depth: 0,
});
},
);
it.each([{ max_nodes: 2 }, { max_edges: 1 }])(
"reports retained node depth when a sibling hits the budget %j",
(limits) => {
const branching = {
...graph,
edges: graph.edges
.filter((edge) => edge.resolution !== "unresolved")
.map((edge) => ({ ...edge, from: "a" })),
};
const trace = traceNativeInvestigationGraph(branching, {
start: "a",
limits,
});
expect(trace.nodes.map(({ id }) => id)).toEqual(["a", "b"]);
expect(trace.edges.map(({ id }) => id)).toEqual(["1"]);
expect(trace.reached_depth).toBe(1);
expect(trace.truncated).toBe(true);
},
);
it("retains cycle edges to admitted nodes when the node budget is full", () => {
const cycle = {
...graph,
nodes: graph.nodes.slice(0, 2),
edges: [
graph.edges[0],
{ ...graph.edges[0], id: "back", from: "b", to: "a" },
],
};
const trace = traceNativeInvestigationGraph(
nativeInvestigationGraphSchema.parse(cycle),
{ start: "a", limits: { max_nodes: 2 } },
);
expect(trace.edges.map(({ id }) => id)).toEqual(["1", "back"]);
expect(trace).toMatchObject({ reached_depth: 1, truncated: false });
});
it("retains observed and inferred route edges plus unresolved dispatch", () => {
const trace = traceNativeInvestigationGraph(graph, { start: "a" });
expect(trace.nodes.map(({ id }) => id)).toEqual(["a", "b", "c"]);
@@ -207,7 +207,6 @@ export const traceNativeInvestigationGraph = (
while (queue.length > 0) {
const current = queue.shift();
if (current === undefined) break;
reachedDepth = Math.max(reachedDepth, current.depth);
const adjacent = adjacency.get(current.id) ?? [];
for (const edge of adjacent) {
@@ -227,19 +226,24 @@ export const traceNativeInvestigationGraph = (
reason ??= "max_depth_reached";
continue;
}
selectedEdges.set(edge.id, edge);
if (alreadyVisited) continue;
if (visited.size >= limits.max_nodes) {
// Check destination capacity before retaining its edge. Otherwise the node
// bound leaves a resolved edge pointing outside the returned trace.
if (!alreadyVisited && visited.size >= limits.max_nodes) {
truncated = true;
reason = "max_nodes_reached";
break;
}
selectedEdges.set(edge.id, edge);
if (alreadyVisited) continue;
if (!nodeById.has(nextId)) {
truncated = true;
reason ??= "edge_target_missing_from_graph";
continue;
}
visited.add(nextId);
// A retained node has already been reached even if a later sibling
// exhausts a budget before this node is dequeued for expansion.
reachedDepth = Math.max(reachedDepth, current.depth + 1);
queue.push({ id: nextId, depth: current.depth + 1 });
}
if (reason === "max_edges_reached" || reason === "max_nodes_reached") break;
+2 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { nativeMetadataRecoverySummarySchema } from "./nativeMetadataRecovery.js";
import { jsonValueSchema } from "../jsonValue.js";
import { binaryArchitectureSchema } from "../rawBinary.js";
const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -112,7 +113,7 @@ export const nativeLoadImageSchema = z.union([
status: z.enum(["verified", "mismatch"]),
format: z.literal("raw-binary"),
target_sha256: digest,
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
architecture: binaryArchitectureSchema,
language_id: z.string().min(1),
compiler_spec_id: z.string().min(1),
base_address: address,
+38
View File
@@ -39,6 +39,44 @@ describe("raw-binary entry addresses", () => {
});
describe("raw-binary admission", () => {
it("admits byte-aligned 6502 images up to the 16-bit address boundary", () => {
for (const [entryPoint, fileBytes] of [
["0x8001", 8],
["0xffff", 1],
["0x0", 65536],
] as const) {
const result = admitRawBinary({
architecture: "6502",
entryPoint,
fileBytes,
});
if (!result.ok) throw new Error(result.error.reason);
expect(result.value).toEqual({
architecture: "6502",
entryPoint,
entryPointSource: entryPoint,
});
}
});
it.each([
["0x10000", 1],
["0xffff", 2],
["0x0", 65537],
])(
"rejects a 6502 mapping at %s with %i bytes that exceeds 16 bits",
(entryPoint, fileBytes) => {
const result = admitRawBinary({
architecture: "6502",
entryPoint,
fileBytes,
});
if (result.ok) throw new Error("expected 16-bit overflow rejection");
expect(result.error).toEqual({
reason: `raw-binary mapping from ${entryPoint} must fit in the 6502 address width`,
constraint: "load_selection_rejected",
});
},
);
it("admits a little-endian ARM image mapped at the caller entry", () => {
expect(
admitRawBinary({
+8 -5
View File
@@ -13,6 +13,7 @@ export const BINARY_ARCHITECTURES = [
"x86_64",
"arm",
"arm64",
"6502",
] as const satisfies readonly BinaryArchitecture[];
/** Provider-neutral CPU family for a caller-supplied raw-binary load. */
@@ -58,7 +59,7 @@ export const validateRawBinaryLength = (
/** Admitted headerless load identity used by target resolution and profiles. */
export interface RawBinaryAdmission {
readonly architecture: HeaderArchitecture;
readonly architecture: HeaderArchitecture | "6502";
readonly entryPoint: string;
readonly entryPointSource: string;
}
@@ -74,9 +75,11 @@ export interface RawBinaryAdmissionRejection {
}
const addressWidth = (architecture: BinaryArchitecture): bigint =>
architecture === "x86" || architecture === "arm"
? 0xffffffffn
: 0xffffffffffffffffn;
architecture === "6502"
? 0xffffn
: architecture === "x86" || architecture === "arm"
? 0xffffffffn
: 0xffffffffffffffffn;
/** Validate architecture, entry, and that the mapped image fits the CPU width. */
export const admitRawBinary = (input: {
@@ -88,7 +91,7 @@ export const admitRawBinary = (input: {
if (!architecture.success)
return err({
reason:
"raw-binary format requires architecture (x86, x86_64, arm, or arm64)",
"raw-binary format requires architecture (x86, x86_64, arm, arm64, or 6502)",
constraint: "load_selection_rejected",
});
if (typeof input.entryPoint !== "string")