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

This commit is contained in:
morluto
2026-10-08 17:02:53 +08:00
85 changed files with 5854 additions and 1121 deletions
+25
View File
@@ -17,6 +17,31 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
it("snapshots caller-owned payloads before deriving their identity", () => {
const result = { nested: { values: ["observed"] } };
const rawResult = { entries: [{ value: "raw" }] };
const parameters = { selected: ["target"] };
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "inspect",
parameters,
result,
rawResult,
});
result.nested.values.push("later");
const rawEntry = rawResult.entries[0];
if (rawEntry !== undefined) rawEntry.value = "changed";
parameters.selected.push("other");
expect(evidence.normalized_result).toEqual({
nested: { values: ["observed"] },
});
expect(evidence.raw_result).toEqual({ entries: [{ value: "raw" }] });
expect(evidence.parameters).toEqual({ selected: ["target"] });
expect(parseEvidence(evidence)).toEqual(evidence);
expect(() =>
parseEvidence({ ...evidence, normalized_result: result }),
).toThrow(/semantic identifier/u);
});
describe("analysis evidence identity", () => {
it("normalizes prototype-named parameter keys", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
+13 -3
View File
@@ -274,13 +274,23 @@ export const createEvidence = (
locations: [...(observation.locations ?? [])],
evidence_links: [...(observation.evidenceLinks ?? [])],
} satisfies JsonValue;
const normalized = evidenceRecordSchema.parse({
// Select the known envelope before parsing. A union otherwise traverses and
// clones a legacy result for the profiled branch before rejecting its absent
// profile and trying the legacy branch.
const schema =
observation.analysisProfile === undefined
? evidenceBaseSchema
: profiledEvidenceSchema;
const normalized = schema.parse({
...semantic,
evidence_id: `ev_${"0".repeat(64)}`,
subject,
});
return parseEvidence({
// The envelope has already been parsed into an independent snapshot. Only
// its derived identifier changes here; parsing again clones the full payload
// and recomputes the same digest while the previous snapshot is still live.
return {
...normalized,
evidence_id: computeEvidenceId(normalized),
});
};
};
@@ -38,7 +38,8 @@ const normalizeEvidence = (
evidence_ids: uniqueSorted(evidence.evidence_ids),
});
const nodeId = (
/** Derive a semantic node ID from its kind and exact artifact identity. */
export const javaScriptSemanticNodeId = (
node: Pick<JavaScriptSemanticGraphNode, "kind" | "identity">,
): string =>
`jsrg_node_${canonicalDigest({ kind: node.kind, identity: node.identity }, "JavaScript semantic graph")}`;
@@ -59,7 +60,7 @@ export const createJavaScriptSemanticGraphNode = (
};
return javaScriptSemanticNodeSchema.parse({
...semantic,
node_id: nodeId(semantic),
node_id: javaScriptSemanticNodeId(semantic),
});
};
@@ -129,11 +130,21 @@ export const createJavaScriptSemanticFingerprint = (input: unknown) => {
type GraphRecord = z.infer<typeof javaScriptSemanticGraphRecordSchema>;
type SemanticGraphIssue = {
readonly code: "custom";
readonly path: PropertyKey[];
readonly message: string;
};
interface GraphIssueReporter {
readonly addIssue: (issue: SemanticGraphIssue) => void;
}
const sortedUniqueIssue = (
values: readonly string[],
path: PropertyKey[],
label: string,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (let index = 1; index < values.length; index += 1) {
if (compareCodePoints(values[index - 1] ?? "", values[index] ?? "") < 0)
@@ -147,7 +158,10 @@ const sortedUniqueIssue = (
}
};
const checkCoverage = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkCoverage = (
graph: GraphRecord,
context: GraphIssueReporter,
): void => {
const families = graph.coverage.families.map(({ family }) => family);
if (
canonicalJson(families, "JavaScript semantic graph") !==
@@ -221,7 +235,7 @@ const checkCoverage = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkCanonicalOrder = (
graph: GraphRecord,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
sortedUniqueIssue(
graph.root_node_ids,
@@ -259,10 +273,10 @@ const checkCanonicalOrder = (
const checkNodes = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, node] of graph.nodes.entries()) {
if (node.node_id !== nodeId(node))
if (node.node_id !== javaScriptSemanticNodeId(node))
context.addIssue({
code: "custom",
path: ["nodes", index, "node_id"],
@@ -283,7 +297,7 @@ const checkNodes = (
const checkRoots = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const root of graph.root_node_ids)
if (!nodes.has(root))
@@ -297,7 +311,7 @@ const checkRoots = (
const checkRelations = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, relation] of graph.relations.entries()) {
const { relation_id: identifier, ...semantic } = relation;
@@ -340,7 +354,7 @@ const checkRelations = (
const checkUnknowns = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, unknown] of graph.unknowns.entries()) {
const { unknown_id: identifier, ...semantic } = unknown;
@@ -386,7 +400,7 @@ const checkUnknowns = (
const checkUnknownReferences = (
graph: GraphRecord,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
const unknownIds = new Set(
graph.unknowns.map(({ unknown_id }) => unknown_id),
@@ -403,7 +417,7 @@ const checkUnknownReferences = (
const checkFingerprints = (
graph: GraphRecord,
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
context: z.RefinementCtx,
context: GraphIssueReporter,
): void => {
for (const [index, fingerprint] of graph.fingerprints.entries()) {
if (nodes.get(fingerprint.function_node_id)?.kind !== "function")
@@ -449,7 +463,10 @@ const checkFingerprints = (
}
};
const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
const checkGraphContent = (
graph: GraphRecord,
context: GraphIssueReporter,
): void => {
checkCanonicalOrder(graph, context);
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
checkNodes(graph, nodes, context);
@@ -465,6 +482,10 @@ const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
path: ["limitations"],
message: "Non-complete graph coverage requires a limitation",
});
};
const checkGraph = (graph: GraphRecord, context: GraphIssueReporter): void => {
checkGraphContent(graph, context);
const { graph_id: identifier, ...semantic } = graph;
if (
identifier !==
@@ -523,10 +544,21 @@ export const createJavaScriptSemanticGraph = (
},
limitations: uniqueSorted(parsed.limitations),
};
return javaScriptSemanticGraphSchema.parse({
// The input schema already cloned and validated every field. Validate the
// normalized relationships in place, then derive the only added field. The
// public schema still verifies arbitrary records and their commitments.
const record: GraphRecord = {
...semantic,
graph_id: `jsrg_${canonicalDigest(semantic, "JavaScript semantic graph")}`,
};
const issues: SemanticGraphIssue[] = [];
checkGraphContent(record, {
addIssue: (issue) => {
issues.push(issue);
},
});
if (issues.length > 0) throw new z.ZodError(issues);
return record;
};
export type { JavaScriptSemanticGraphNode, JavaScriptSemanticGraphRelation };
+284
View File
@@ -0,0 +1,284 @@
import { expect, it } from "vitest";
import {
inspectRecordedCrashInputSchema,
recordedCrashSchema,
} from "./recordedCrash.js";
import {
recordedCrashFixture,
recordedCrashSignalFixture,
} from "../../../tests/fixtures/binaryDiagnostics/recordedCrash.js";
it("preserves high uint64 registers and historical thread identity", () => {
const value = recordedCrashSchema.parse(recordedCrashFixture());
expect(
value.threads[0]?.registers.find(({ name }) => name === "rdi")?.value,
).toBe("0x1122334455667788");
expect(value.live_process_identity).toBe("unknown");
expect(
inspectRecordedCrashInputSchema.parse({ path: "/selected.core" })
.include_debugger_context,
).toBe(false);
});
it("preserves a short zero-filled note-segment tail", () => {
const value = recordedCrashSignalFixture();
value.segments = value.segments.map((segment) => ({
...segment,
file_size: "0x19b",
}));
value.note_padding.push({
segment_index: 0,
location: { offset: "0x218", bytes: "0x3" },
bytes_base64: "AAAA",
});
expect(recordedCrashSchema.safeParse(value).success).toBe(true);
});
it.each([
"missing-thread",
"duplicate-thread",
"missing-signal",
"duplicate-signal",
"missing-register",
"unknown-register",
"duplicated-physical-thread",
"duplicated-physical-signal",
"omitted-physical-note",
"expanded-note-span",
"forged-padding",
])("rejects an incomplete or duplicate interpretation: %s", (scenario) => {
const value = recordedCrashSignalFixture();
if (
scenario === "duplicated-physical-thread" ||
scenario === "duplicated-physical-signal"
) {
const noteIndex = scenario === "duplicated-physical-thread" ? 0 : 1;
const note = value.notes[noteIndex];
if (note === undefined) throw new Error("missing fixture note");
value.notes.push({ ...note, index: 2 });
if (noteIndex === 0)
value.threads.push(
...value.threads.map((thread) => ({ ...thread, note_index: 2 })),
);
else
value.signals.push(
...value.signals.map((signal) => ({ ...signal, note_index: 2 })),
);
}
if (
["omitted-physical-note", "expanded-note-span", "forged-padding"].includes(
scenario,
)
) {
value.notes = value.notes.filter((note) => note.index === 0);
value.signals = [];
}
if (scenario === "expanded-note-span")
value.notes = value.notes.map((note) => ({
...note,
location: { ...note.location, bytes: "0x198" },
}));
if (scenario === "forged-padding")
value.note_padding.push({
segment_index: 0,
location: { offset: "0x1e4", bytes: "0x34" },
bytes_base64: Buffer.alloc(52).toString("base64"),
});
if (scenario === "missing-thread") value.threads = [];
if (scenario === "duplicate-thread")
value.threads = [...value.threads, ...value.threads];
if (scenario === "missing-signal") value.signals = [];
if (scenario === "duplicate-signal")
value.signals = [...value.signals, ...value.signals];
if (scenario === "missing-register")
value.threads = value.threads.map((thread) => ({
...thread,
registers: thread.registers.slice(1),
}));
if (scenario === "unknown-register")
value.threads = value.threads.map((thread) => ({
...thread,
registers: thread.registers.map((register) =>
register.name === "rdi"
? { ...register, name: "unrecognized" }
: register,
),
}));
expect(recordedCrashSchema.safeParse(value).success).toBe(false);
});
it.each([
[
"unsafe register number",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [
{
...v.threads[0],
registers: [
{
name: "rdi",
value: 9007199254740992,
location: { offset: "0x104", bytes: "0x8" },
},
],
},
],
}),
],
[
"source outside artifact",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
artifact: { ...v.artifact, bytes: 120 },
}),
],
[
"invalid note reference",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [{ ...v.threads[0], note_index: 1 }],
}),
],
[
"register outside descriptor",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: [
{
...v.threads[0],
registers: [
{
name: "rdi",
value: "0x0",
location: { offset: "0x1e4", bytes: "0x8" },
},
],
},
],
}),
],
[
"raw descriptor length",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({ ...n, descriptor_bytes_base64: "AA==" })),
}),
],
[
"different owner ABI",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({ ...n, owner_display: "OTHER" })),
}),
],
[
"raw owner ABI hidden by a CORE display label",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
notes: v.notes.map((n) => ({
...n,
owner_bytes_base64: Buffer.from("EVIL\0").toString("base64"),
})),
}),
],
[
"duplicate register",
(v: ReturnType<typeof recordedCrashFixture>) => ({
...v,
threads: v.threads.map((t) => ({
...t,
registers: [...t.registers, ...t.registers],
})),
}),
],
] as const)("rejects %s before Evidence serialization", (_name, change) =>
expect(
recordedCrashSchema.safeParse(change(recordedCrashFixture())).success,
).toBe(false),
);
it("does not interpret a signal through a mislabeled raw owner ABI", () => {
const value = recordedCrashFixture();
expect(
recordedCrashSchema.safeParse({
...value,
threads: [],
notes: value.notes.map((note) => ({
...note,
type: "NT_SIGINFO",
owner_bytes_base64: Buffer.from("EVIL\0").toString("base64"),
})),
signals: [
{
note_index: 0,
number: 11,
code: 1,
errno: 0,
fault_address: "0x123",
fault_address_meaning: "recorded-sigsegv-address",
thread_association: "unknown",
},
],
}).success,
).toBe(false);
});
it("keeps absent map flags unknown and validates reported permission bits", () => {
const value = recordedCrashFixture();
const context = {
status: "available",
gdb_version: "fixture",
pwndbg_version: "fixture",
connection: "core",
executable: null,
historical_pid: 123,
reported_limits: {
address_space_bytes: 3221225472,
cpu_seconds: 30,
file_size_bytes: 67108864,
},
maps: [
{
start: "0x1000",
end: "0x2000",
offset: "0x0",
reported_flags: 0,
permissions: null,
pathname_display: "recorded pathname",
current_file_identity: "unknown",
},
],
confidence: "derived",
completeness: "unknown",
diagnostics: value.diagnostics,
} as const;
expect(
recordedCrashSchema.safeParse({ ...value, debugger: context }).success,
).toBe(true);
expect(
recordedCrashSchema.safeParse({
...value,
debugger: {
...context,
maps: context.maps.map((m) => ({
...m,
permissions: { read: false, write: false, execute: false },
})),
},
}).success,
).toBe(false);
expect(
recordedCrashSchema.safeParse({
...value,
debugger: {
...context,
maps: context.maps.map((m) => ({
...m,
reported_flags: 4,
permissions: { read: false, write: false, execute: false },
})),
},
}).success,
).toBe(false);
});
+362
View File
@@ -0,0 +1,362 @@
import { z } from "zod";
import { recordedNoteCoverageIssues } from "./recordedCrashNoteCoverage.js";
const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/);
const index = z.number().int().nonnegative();
const signed32 = z.number().int().min(-2147483648).max(2147483647);
const base64 = z
.string()
.regex(
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/,
);
const range = z.strictObject({ offset: hex, bytes: hex });
const diagnostics = z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
});
// Exact b"CORE\0"; a lossy display label cannot establish the Linux note ABI.
const LINUX_CORE_OWNER_BASE64 = "Q09SRQA=";
/** Complete register identities in the supported Linux amd64 PRSTATUS ABI order. */
export const RECORDED_LINUX_AMD64_REGISTERS: readonly string[] = [
"r15",
"r14",
"r13",
"r12",
"rbp",
"rbx",
"r11",
"r10",
"r9",
"r8",
"rax",
"rcx",
"rdx",
"rsi",
"rdi",
"orig_rax",
"rip",
"cs",
"eflags",
"rsp",
"ss",
"fs_base",
"gs_base",
"ds",
"es",
"fs",
"gs",
];
const supportedRegisters = new Set(RECORDED_LINUX_AMD64_REGISTERS);
/** Select an explicit recording and optionally request debugger-derived mapping context. */
export const inspectRecordedCrashInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute filesystem path to a supplied Linux ELF core"),
include_debugger_context: z
.boolean()
.default(false)
.describe(
"Add core-only mapping candidates through caller-supplied GDB/pwndbg",
),
});
/** Debugger map candidates preserve reported flags; zero does not establish absent permissions. */
export const recordedCrashDebuggerSchema = z.discriminatedUnion("status", [
z.strictObject({ status: z.literal("not-requested") }),
z.strictObject({
status: z.literal("available"),
gdb_version: z.string().min(1),
pwndbg_version: z.string().min(1),
connection: z.literal("core"),
executable: z.null(),
historical_pid: signed32,
reported_limits: z.strictObject({
address_space_bytes: index,
cpu_seconds: index,
file_size_bytes: index,
}),
maps: z.array(
z.strictObject({
start: hex,
end: hex,
offset: hex,
reported_flags: index,
permissions: z
.strictObject({
read: z.boolean(),
write: z.boolean(),
execute: z.boolean(),
})
.nullable(),
pathname_display: z.string(),
current_file_identity: z.literal("unknown"),
}),
),
confidence: z.literal("derived"),
completeness: z.literal("unknown"),
diagnostics,
}),
]);
/** Portable recorded observations; registers and source coordinates remain lossless. */
const recordedCrashObjectSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: index,
}),
format: z.literal("elf-core"),
architecture: z.literal("x86_64-little-endian"),
target_execution: z.literal("not-performed"),
live_process_identity: z.literal("unknown"),
segments: z.array(
z.strictObject({
index,
type: z.union([z.string(), index]),
header_location: range,
offset: hex,
file_size: hex,
memory_size: hex,
virtual_address: hex,
physical_address: hex,
alignment: hex,
flags: hex,
file_backing: z.enum(["file", "none"]),
}),
),
notes: z.array(
z.strictObject({
index,
segment_index: index,
type: z.union([z.string(), index]),
location: range,
owner_location: range,
owner_bytes_base64: base64,
owner_display: z.string().nullable(),
descriptor_location: range,
descriptor_bytes_base64: base64,
}),
),
note_padding: z.array(
z.strictObject({
segment_index: index,
location: range,
bytes_base64: base64,
}),
),
threads: z.array(
z.strictObject({
note_index: index,
historical_pid: signed32,
recorded_current_signal: z.number().int().min(-32768).max(32767),
registers: z.array(
z.strictObject({
name: z.string().min(1),
value: hex,
location: range,
}),
),
}),
),
signals: z.array(
z.strictObject({
note_index: index,
number: signed32,
code: signed32,
errno: signed32,
fault_address: hex.nullable(),
fault_address_meaning: z.enum(["recorded-sigsegv-address", "unknown"]),
thread_association: z.literal("unknown"),
}),
),
debugger: recordedCrashDebuggerSchema,
note_interpretation_completeness: z.literal("unknown"),
decoder_diagnostics: diagnostics,
diagnostics,
limitations: z.array(z.string()),
});
/** Provider payload excludes identity and diagnostics bound by the owned snapshot boundary. */
export const recordedCrashPayloadSchema = recordedCrashObjectSchema.omit({
artifact: true,
diagnostics: true,
debugger: true,
decoder_diagnostics: true,
});
/** Validate the next consumer's file ranges, note links and register representations. */
export const recordedCrashSchema = recordedCrashObjectSchema.superRefine(
(value, context) => {
const fail = (message: string) =>
context.addIssue({ code: "custom", message });
const within = (
item: z.output<typeof range>,
start = 0n,
end = BigInt(value.artifact.bytes),
) => {
const offset = BigInt(item.offset);
const bytes = BigInt(item.bytes);
return offset >= start && offset <= end && bytes <= end - offset;
};
for (const issue of recordedNoteCoverageIssues(
value.segments,
value.notes,
value.note_padding,
))
fail(issue);
for (const [position, segment] of value.segments.entries()) {
if (position !== segment.index || !within(segment.header_location))
fail("Invalid original segment identity or header range.");
if (
segment.file_backing === "file" &&
!within({ offset: segment.offset, bytes: segment.file_size })
)
fail("Recorded segment exceeds artifact bytes.");
if (
segment.type === "PT_LOAD" &&
BigInt(segment.file_size) > BigInt(segment.memory_size)
)
fail("Recorded PT_LOAD file size exceeds memory size.");
}
for (const [position, note] of value.notes.entries()) {
const segment = value.segments[note.segment_index];
if (position !== note.index || segment?.type !== "PT_NOTE") {
fail("Invalid original note identity or segment reference.");
continue;
}
const decodedLength = (raw: string) =>
BigInt(
(raw.length / 4) * 3 -
(raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0),
);
if (
decodedLength(note.owner_bytes_base64) !==
BigInt(note.owner_location.bytes) ||
decodedLength(note.descriptor_bytes_base64) !==
BigInt(note.descriptor_location.bytes)
)
fail("Raw note lengths differ from their source ranges.");
const start = BigInt(segment.offset);
const end = start + BigInt(segment.file_size);
if (
!within(note.location, start, end) ||
!within(
note.owner_location,
BigInt(note.location.offset),
BigInt(note.location.offset) + BigInt(note.location.bytes),
) ||
!within(
note.descriptor_location,
BigInt(note.location.offset),
BigInt(note.location.offset) + BigInt(note.location.bytes),
)
)
fail("Note source ranges exceed their recorded segment.");
}
for (const padding of value.note_padding) {
const segment = value.segments[padding.segment_index];
if (
segment?.type !== "PT_NOTE" ||
!within(
padding.location,
BigInt(segment.offset),
BigInt(segment.offset) + BigInt(segment.file_size),
)
)
fail("Invalid recorded note padding range.");
}
for (const [kind, rows] of [
["NT_PRSTATUS", value.threads],
["NT_SIGINFO", value.signals],
] as const) {
const matchingNotes = value.notes.filter(
(note) =>
note.type === kind &&
note.owner_bytes_base64 === LINUX_CORE_OWNER_BASE64,
);
if (
rows.length !== matchingNotes.length ||
new Set(rows.map(({ note_index }) => note_index)).size !== rows.length
)
fail(
"Each supported raw note requires exactly one corresponding interpretation.",
);
}
for (const thread of value.threads) {
const note = value.notes[thread.note_index];
if (
note?.type !== "NT_PRSTATUS" ||
note.owner_display !== "CORE" ||
note.owner_bytes_base64 !== LINUX_CORE_OWNER_BASE64
) {
fail("Thread references a different note kind.");
continue;
}
if (
thread.registers.length !== RECORDED_LINUX_AMD64_REGISTERS.length ||
!thread.registers.every(({ name }) => supportedRegisters.has(name)) ||
new Set(thread.registers.map(({ name }) => name)).size !==
thread.registers.length
)
fail(
"Each recorded thread requires every supported register exactly once.",
);
for (const register of thread.registers)
if (
BigInt(register.location.bytes) !== 8n ||
!within(
register.location,
BigInt(note.descriptor_location.offset),
BigInt(note.descriptor_location.offset) +
BigInt(note.descriptor_location.bytes),
)
)
fail("Register source exceeds its descriptor.");
}
for (const signal of value.signals) {
if (
value.notes[signal.note_index]?.type !== "NT_SIGINFO" ||
value.notes[signal.note_index]?.owner_display !== "CORE" ||
value.notes[signal.note_index]?.owner_bytes_base64 !==
LINUX_CORE_OWNER_BASE64
)
fail("Signal references a different note kind.");
const known =
signal.number === 11 && (signal.code === 1 || signal.code === 2);
if (
known !== (signal.fault_address !== null) ||
(signal.fault_address !== null) !==
(signal.fault_address_meaning === "recorded-sigsegv-address")
)
fail("Signal union meaning does not match recorded SIGSEGV code.");
}
if (value.debugger.status === "available")
for (const map of value.debugger.maps) {
if (BigInt(map.end) < BigInt(map.start))
fail("Debugger mapping end precedes its start.");
if (
map.permissions !== null &&
(map.permissions.read !== Boolean(map.reported_flags & 4) ||
map.permissions.write !== Boolean(map.reported_flags & 2) ||
map.permissions.execute !== Boolean(map.reported_flags & 1))
)
fail("Mapping permissions differ from reported flags.");
if (
(map.reported_flags === 0 || map.reported_flags > 7) !==
(map.permissions === null)
)
fail(
"Unreported or unfamiliar map flags require unknown permissions.",
);
}
},
);
export type InspectRecordedCrashInput = z.output<
typeof inspectRecordedCrashInputSchema
>;
export type RecordedCrash = z.output<typeof recordedCrashSchema>;
@@ -0,0 +1,111 @@
type Range = { readonly offset: string; readonly bytes: string };
type Segment = {
readonly index: number;
readonly type: string | number;
readonly offset: string;
readonly file_size: string;
};
type Note = {
readonly segment_index: number;
readonly location: Range;
readonly owner_location: Range;
readonly descriptor_location: Range;
};
type Padding = {
readonly segment_index: number;
readonly location: Range;
readonly bytes_base64: string;
};
const align = (size: bigint) => ((size + 3n) / 4n) * 4n;
const layoutMatches = (note: Note): boolean => {
const start = BigInt(note.location.offset);
const owner = BigInt(note.owner_location.bytes);
const descriptor = BigInt(note.descriptor_location.bytes);
return (
BigInt(note.owner_location.offset) === start + 12n &&
BigInt(note.descriptor_location.offset) === start + 12n + align(owner) &&
BigInt(note.location.bytes) === 12n + align(owner) + align(descriptor)
);
};
const paddingMatches = (
item: Padding,
segment: Segment | undefined,
): boolean => {
const bytes = BigInt(item.location.bytes);
const decodedLength =
(item.bytes_base64.length / 4) * 3 -
(item.bytes_base64.endsWith("==")
? 2
: item.bytes_base64.endsWith("=")
? 1
: 0);
return (
bytes > 0n &&
bytes < 12n &&
BigInt(decodedLength) === bytes &&
/^A*={0,2}$/.test(item.bytes_base64) &&
segment !== undefined &&
BigInt(item.location.offset) + bytes ===
BigInt(segment.offset) + BigInt(segment.file_size)
);
};
/** Require exact aligned note layouts and one complete, nonoverlapping physical coverage. */
export function recordedNoteCoverageIssues(
segments: readonly Segment[],
notes: readonly Note[],
padding: readonly Padding[],
): readonly string[] {
const issues: string[] = [];
const bySegment = new Map<number, Range[]>();
const all: Range[] = [];
const add = (segment: number, range: Range) => {
const ranges = bySegment.get(segment) ?? [];
ranges.push(range);
bySegment.set(segment, ranges);
all.push(range);
};
for (const note of notes) {
if (!layoutMatches(note))
issues.push(
"Recorded note layout differs from its aligned header/owner/descriptor ranges.",
);
add(note.segment_index, note.location);
}
for (const item of padding) {
if (!paddingMatches(item, segments[item.segment_index]))
issues.push(
"Recorded note padding must be a short zero-filled segment tail.",
);
add(item.segment_index, item.location);
}
const compare = (left: Range, right: Range) =>
BigInt(left.offset) < BigInt(right.offset)
? -1
: BigInt(left.offset) > BigInt(right.offset)
? 1
: 0;
let end = 0n;
for (const range of all.sort(compare)) {
const start = BigInt(range.offset);
if (start < end)
issues.push("Physical recorded note/padding ranges overlap or repeat.");
if (start + BigInt(range.bytes) > end) end = start + BigInt(range.bytes);
}
for (const segment of segments) {
if (segment.type !== "PT_NOTE") continue;
let cursor = BigInt(segment.offset);
for (const range of (bySegment.get(segment.index) ?? []).sort(compare)) {
if (BigInt(range.offset) !== cursor)
issues.push(
"Recorded note/padding ranges leave a gap or overlap in their segment.",
);
cursor = BigInt(range.offset) + BigInt(range.bytes);
}
if (cursor !== BigInt(segment.offset) + BigInt(segment.file_size))
issues.push(
"Recorded note/padding ranges do not completely cover their segment.",
);
}
return issues;
}