feat(ghidra): add DOS MZ analysis and complete function extents (#556)
Validate DOS MZ load modules and import them with Ghidra's 16-bit real-mode profile. Preserve complete observed inclusive function body ranges through inventory, function analysis, Evidence and snapshots. Add a public source-generated DOS CLI/MCP verification lane and regressions for malformed headers, body membership and cache profiles. Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
This commit is contained in:
@@ -16,6 +16,50 @@ import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
|
||||
describe("analysis snapshot contract", () => {
|
||||
it("preserves DOS MZ target and subject formats with the x86 family", () => {
|
||||
const target = {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable" as const,
|
||||
format: "dos-mz" as const,
|
||||
architecture: "x86" as const,
|
||||
availableArchitectures: ["x86" as const],
|
||||
};
|
||||
const evidence = createEvidence(target, ANALYSIS_SNAPSHOT_PROVIDER, {
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
result: null,
|
||||
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
});
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const parsed = analysisSnapshotSchema.parse({
|
||||
target: snapshotTarget(target),
|
||||
binding,
|
||||
entries: [
|
||||
{
|
||||
query_id: `query_${"0".repeat(64)}`,
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
execution: {
|
||||
result: null,
|
||||
raw_result: null,
|
||||
provider: binding.provider,
|
||||
limitations: [],
|
||||
locations: [],
|
||||
subject: target,
|
||||
},
|
||||
},
|
||||
],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
});
|
||||
expect(parsed.target).toMatchObject({
|
||||
format: "dos-mz",
|
||||
architecture: "x86",
|
||||
});
|
||||
expect(parsed.entries[0]?.execution.subject?.format).toBe("dos-mz");
|
||||
expect(parsed.evidence_bundle.records[0]?.subject?.format).toBe("dos-mz");
|
||||
});
|
||||
|
||||
it("accepts snapshots with more than ten thousand analysis entries", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
|
||||
@@ -35,6 +35,7 @@ const formatSchema = z.enum([
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
|
||||
@@ -48,6 +48,7 @@ const artifactFormatSchema = z.enum([
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
|
||||
@@ -59,3 +59,19 @@ export const pe = (
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a DOS MZ image with a 32-byte header and a 16-bit entry point. */
|
||||
export const dosMz = (moduleSize = 128): Buffer => {
|
||||
const size = 32 + moduleSize;
|
||||
const bytes = Buffer.alloc(size);
|
||||
bytes.write("MZ", 0, "ascii");
|
||||
bytes.writeUInt16LE(size % 512, 2);
|
||||
bytes.writeUInt16LE(Math.ceil(size / 512), 4);
|
||||
bytes.writeUInt16LE(2, 8);
|
||||
bytes.writeUInt16LE(0xffff, 12);
|
||||
bytes.writeUInt16LE(28, 24);
|
||||
bytes.set([0xb8, 0x00, 0x4c, 0xcd, 0x21], 32);
|
||||
// This is module data, not an e_lfanew field in a Windows DOS stub.
|
||||
if (size >= 64) bytes.writeUInt32LE(0xfedcba98, 60);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseExecutableHeader } from "./binaryTarget.js";
|
||||
import { elf, fat, pe, thinMach } from "./binaryTarget.fixture.js";
|
||||
import { dosMz, elf, fat, pe, thinMach } from "./binaryTarget.fixture.js";
|
||||
|
||||
describe("executable header parsing", () => {
|
||||
it("recognizes a DOS MZ without interpreting load-module bytes as e_lfanew", () => {
|
||||
expect(parseExecutableHeader(dosMz(), "x64")).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
format: "dos-mz",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
[elf(1, 1, 62), "elf", "x86_64"],
|
||||
[elf(2, 2, 183), "elf", "arm64"],
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "./dosMz.js";
|
||||
|
||||
export type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
|
||||
|
||||
/** Format and architecture facts recovered from an executable header. */
|
||||
export type ExecutableMetadata =
|
||||
| {
|
||||
readonly format: "mach-o" | "elf";
|
||||
readonly format: "mach-o" | "elf" | "dos-mz";
|
||||
readonly architecture: BinaryArchitecture;
|
||||
readonly availableArchitectures: readonly BinaryArchitecture[];
|
||||
}
|
||||
@@ -28,6 +29,7 @@ export type ExecutableMetadata =
|
||||
export const parseExecutableHeader = (
|
||||
bytes: Buffer,
|
||||
hostArchitecture: NodeJS.Architecture,
|
||||
fileSize = bytes.length,
|
||||
): Result<ExecutableMetadata, string> => {
|
||||
if (
|
||||
bytes.length >= 4 &&
|
||||
@@ -35,7 +37,7 @@ export const parseExecutableHeader = (
|
||||
)
|
||||
return parseElf(bytes);
|
||||
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a)
|
||||
return parsePe(bytes);
|
||||
return parseMz(bytes, fileSize);
|
||||
if (bytes.length < 8) return err("truncated or unsupported binary header");
|
||||
const magic = bytes.readUInt32BE(0);
|
||||
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
|
||||
@@ -116,11 +118,27 @@ const parseElf = (bytes: Buffer): Result<ExecutableMetadata, string> => {
|
||||
});
|
||||
};
|
||||
|
||||
const parsePe = (bytes: Buffer): Result<ExecutableMetadata, string> => {
|
||||
if (bytes.length < 64) return err("truncated PE DOS header");
|
||||
const offset = bytes.readUInt32LE(0x3c);
|
||||
if (offset > bytes.length - 24) return err("invalid or truncated PE header");
|
||||
return parsePeRecord(bytes.subarray(offset));
|
||||
const parseMz = (
|
||||
bytes: Buffer,
|
||||
fileSize: number,
|
||||
): Result<ExecutableMetadata, string> => {
|
||||
const offset = mzWindowsHeaderOffset(bytes);
|
||||
if (offset !== null) {
|
||||
if (offset < 64 || offset > bytes.length - 24)
|
||||
return err("invalid or truncated Windows executable header in MZ image");
|
||||
const signature = bytes.toString("ascii", offset, offset + 2);
|
||||
if (["NE", "LE", "LX"].includes(signature))
|
||||
return err(`unsupported ${signature} executable in MZ image`);
|
||||
return parsePeRecord(bytes.subarray(offset));
|
||||
}
|
||||
const parsed = parseDosMzHeader(bytes, fileSize);
|
||||
return parsed.ok
|
||||
? ok({
|
||||
format: "dos-mz",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
})
|
||||
: parsed;
|
||||
};
|
||||
|
||||
/** Parse a bounded PE signature, COFF record, and optional header without I/O. */
|
||||
|
||||
@@ -26,7 +26,7 @@ type ExecutableTarget = BinaryTargetIdentity & {
|
||||
*/
|
||||
export type BinaryTarget =
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "mach-o" | "elf";
|
||||
readonly format: "mach-o" | "elf" | "dos-mz";
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { dosMz, pe } from "./binaryTarget.fixture.js";
|
||||
import { parseExecutableHeader } from "./binaryTarget.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "./dosMz.js";
|
||||
|
||||
describe("DOS MZ load-module validation", () => {
|
||||
it("separates initialized module and appended overlay bytes", () => {
|
||||
const image = dosMz(480);
|
||||
const bytes = Buffer.concat([image, Buffer.from("overlay")]);
|
||||
expect(parseDosMzHeader(bytes)).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
headerBytes: 32,
|
||||
imageBytes: 512,
|
||||
moduleBytes: 480,
|
||||
overlayBytes: 7,
|
||||
relocationCount: 0,
|
||||
relocationTableOffset: 28,
|
||||
entrySegment: 0,
|
||||
entryOffset: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts relocation records overlapping the Windows new-header field", () => {
|
||||
const bytes = Buffer.alloc(224);
|
||||
dosMz().copy(bytes, 0, 0, 28);
|
||||
bytes.writeUInt16LE(bytes.length, 2);
|
||||
bytes.writeUInt16LE(6, 8);
|
||||
bytes.writeUInt16LE(2, 6);
|
||||
bytes.writeUInt16LE(62, 24);
|
||||
bytes.writeUInt16LE(1, 62);
|
||||
bytes.writeUInt16LE(8, 66);
|
||||
expect(bytes.readUInt32LE(60)).toBe(65536);
|
||||
expect(mzWindowsHeaderOffset(bytes)).toBeNull();
|
||||
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: "dos-mz" },
|
||||
});
|
||||
expect(parseDosMzHeader(bytes)).toMatchObject({
|
||||
ok: true,
|
||||
value: { headerBytes: 96, relocationCount: 2, moduleBytes: 128 },
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the actual file length rather than the bounded prefix length", () => {
|
||||
const bytes = dosMz(8192);
|
||||
expect(parseDosMzHeader(bytes.subarray(0, 64), bytes.length).ok).toBe(true);
|
||||
expect(parseDosMzHeader(bytes.subarray(0, 64))).toMatchObject({
|
||||
ok: false,
|
||||
error: "truncated DOS MZ load module",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves PE classification when low relocation records do not overlap e_lfanew", () => {
|
||||
const bytes = pe(0x8664);
|
||||
bytes.writeUInt16LE(4, 8);
|
||||
bytes.writeUInt16LE(1, 6);
|
||||
bytes.writeUInt16LE(28, 24);
|
||||
expect(mzWindowsHeaderOffset(bytes)).toBe(64);
|
||||
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: "pe", architecture: "x86_64" },
|
||||
});
|
||||
expect(parseDosMzHeader(bytes).ok).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["page count", (bytes: Buffer) => bytes.writeUInt16LE(0, 4)],
|
||||
["final-page size", (bytes: Buffer) => bytes.writeUInt16LE(512, 2)],
|
||||
["header size", (bytes: Buffer) => bytes.writeUInt16LE(1, 8)],
|
||||
["entry point", (bytes: Buffer) => bytes.writeUInt16LE(128, 20)],
|
||||
[
|
||||
"relocation-table bounds",
|
||||
(bytes: Buffer) => {
|
||||
bytes.writeUInt16LE(2, 6);
|
||||
},
|
||||
],
|
||||
[
|
||||
"relocation target",
|
||||
(bytes: Buffer) => {
|
||||
bytes.writeUInt16LE(1, 6);
|
||||
bytes.writeUInt16LE(127, 28);
|
||||
},
|
||||
],
|
||||
] as const)("rejects invalid %s", (_name, damage) => {
|
||||
const bytes = dosMz();
|
||||
damage(bytes);
|
||||
expect(parseDosMzHeader(bytes).ok).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a truncated relocation table even when the file size is known", () => {
|
||||
const bytes = dosMz();
|
||||
bytes.writeUInt16LE(1, 6);
|
||||
expect(parseDosMzHeader(bytes.subarray(0, 30), bytes.length)).toMatchObject(
|
||||
{
|
||||
ok: false,
|
||||
error: "truncated DOS MZ relocation table",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["NE", "LE", "LX"])(
|
||||
"distinguishes unsupported %s from DOS",
|
||||
(signature) => {
|
||||
const bytes = pe(0x8664);
|
||||
bytes.writeUInt16LE(4, 8);
|
||||
bytes.writeUInt16LE(64, 24);
|
||||
bytes.write(signature, 64, "ascii");
|
||||
expect(parseExecutableHeader(bytes, "x64")).toEqual({
|
||||
ok: false,
|
||||
error: `unsupported ${signature} executable in MZ image`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("does not fall back to DOS when a Windows declaration is damaged", () => {
|
||||
const bytes = Buffer.alloc(256);
|
||||
dosMz().copy(bytes, 0, 0, 28);
|
||||
bytes.writeUInt16LE(256, 2);
|
||||
bytes.writeUInt16LE(4, 8);
|
||||
bytes.writeUInt16LE(64, 24);
|
||||
bytes.writeUInt32LE(192, 60);
|
||||
expect(parseDosMzHeader(bytes).ok).toBe(false);
|
||||
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({ ok: false });
|
||||
bytes.writeUInt32LE(0xfffffff0, 60);
|
||||
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({ ok: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** DOS load-module coordinates before applying the loader's segment relocation. */
|
||||
export interface DosMzHeader {
|
||||
readonly headerBytes: number;
|
||||
readonly imageBytes: number;
|
||||
readonly moduleBytes: number;
|
||||
readonly overlayBytes: number;
|
||||
readonly relocationCount: number;
|
||||
readonly relocationTableOffset: number;
|
||||
readonly entrySegment: number;
|
||||
readonly entryOffset: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate a Windows new-header declaration without interpreting a short DOS
|
||||
* header's load-module or relocation-table bytes at 0x3c as e_lfanew. A
|
||||
* new-header pointer must lie in a sufficiently large header and outside
|
||||
* actual relocation records. Zero-sized legacy stubs remain eligible for
|
||||
* PE signature validation.
|
||||
*/
|
||||
export const mzWindowsHeaderOffset = (bytes: Buffer): number | null => {
|
||||
if (bytes.length < 64) return null;
|
||||
const headerBytes = bytes.readUInt16LE(8) * 16;
|
||||
if (headerBytes !== 0 && headerBytes < 64) return null;
|
||||
const relocationCount = bytes.readUInt16LE(6);
|
||||
const tableStart = bytes.readUInt16LE(24);
|
||||
if (
|
||||
headerBytes !== 0 &&
|
||||
relocationCount > 0 &&
|
||||
tableStart < 64 &&
|
||||
tableStart + relocationCount * 4 > 60
|
||||
)
|
||||
return null;
|
||||
const offset = bytes.readUInt32LE(60);
|
||||
return offset === 0 ? null : offset;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate a DOS MZ load module using a bounded header/table and the actual
|
||||
* file length. Appended overlay bytes are retained separately; they are not
|
||||
* silently included in the initialized load module.
|
||||
*/
|
||||
export const parseDosMzHeader = (
|
||||
bytes: Buffer,
|
||||
fileSize = bytes.length,
|
||||
): Result<DosMzHeader, string> => {
|
||||
if (bytes.length < 28 || bytes.toString("ascii", 0, 2) !== "MZ")
|
||||
return err("invalid or truncated DOS MZ header");
|
||||
if (!Number.isSafeInteger(fileSize) || fileSize < bytes.length)
|
||||
return err("invalid DOS MZ file length");
|
||||
if (mzWindowsHeaderOffset(bytes) !== null)
|
||||
return err("MZ declares a Windows new header; it is not a DOS-only image");
|
||||
const lastPageBytes = bytes.readUInt16LE(2);
|
||||
const pages = bytes.readUInt16LE(4);
|
||||
if (pages === 0 || lastPageBytes > 511)
|
||||
return err("invalid DOS MZ page count or final-page size");
|
||||
const imageBytes =
|
||||
(pages - 1) * 512 + (lastPageBytes === 0 ? 512 : lastPageBytes);
|
||||
const headerBytes = bytes.readUInt16LE(8) * 16;
|
||||
if (headerBytes < 28 || headerBytes >= imageBytes)
|
||||
return err("invalid DOS MZ header size or empty load module");
|
||||
if (imageBytes > fileSize) return err("truncated DOS MZ load module");
|
||||
const relocationCount = bytes.readUInt16LE(6);
|
||||
const relocationTableOffset = bytes.readUInt16LE(24);
|
||||
const tableEnd = relocationTableOffset + relocationCount * 4;
|
||||
if (
|
||||
relocationCount > 0 &&
|
||||
(relocationTableOffset < 28 || tableEnd > headerBytes)
|
||||
)
|
||||
return err("DOS MZ relocation table lies outside its header");
|
||||
if (relocationCount > 0 && tableEnd > bytes.length)
|
||||
return err("truncated DOS MZ relocation table");
|
||||
const moduleBytes = imageBytes - headerBytes;
|
||||
const relocations = validateRelocations(
|
||||
bytes,
|
||||
relocationTableOffset,
|
||||
relocationCount,
|
||||
moduleBytes,
|
||||
);
|
||||
if (!relocations.ok) return relocations;
|
||||
const entryOffset = bytes.readUInt16LE(20);
|
||||
const entrySegment = bytes.readUInt16LE(22);
|
||||
if (entrySegment * 16 + entryOffset >= moduleBytes)
|
||||
return err("DOS MZ entry point lies outside its initialized load module");
|
||||
return ok({
|
||||
headerBytes,
|
||||
imageBytes,
|
||||
moduleBytes,
|
||||
overlayBytes: fileSize - imageBytes,
|
||||
relocationCount,
|
||||
relocationTableOffset,
|
||||
entrySegment,
|
||||
entryOffset,
|
||||
});
|
||||
};
|
||||
|
||||
const validateRelocations = (
|
||||
bytes: Buffer,
|
||||
relocationTableOffset: number,
|
||||
relocationCount: number,
|
||||
moduleBytes: number,
|
||||
): Result<void, string> => {
|
||||
for (let index = 0; index < relocationCount; index += 1) {
|
||||
const record = relocationTableOffset + index * 4;
|
||||
const offset = bytes.readUInt16LE(record);
|
||||
const segment = bytes.readUInt16LE(record + 2);
|
||||
if (segment * 16 + offset + 2 > moduleBytes)
|
||||
return err(`DOS MZ relocation ${index} points outside its load module`);
|
||||
}
|
||||
return ok(undefined);
|
||||
};
|
||||
@@ -190,3 +190,26 @@ it("derives byte-stable bundle manifests independent of record order", () => {
|
||||
captures: [{ evidence_id: captureEvidence.evidence_id }],
|
||||
});
|
||||
});
|
||||
|
||||
describe("DOS analysis evidence identity", () => {
|
||||
it("retains DOS MZ identity independently of PE identity", () => {
|
||||
const target = {
|
||||
path: TARGET.path,
|
||||
sha256: TARGET.sha256,
|
||||
kind: "executable" as const,
|
||||
format: "dos-mz" as const,
|
||||
architecture: "x86" as const,
|
||||
availableArchitectures: ["x86" as const],
|
||||
};
|
||||
const observation = { operation: "health", parameters: {}, result: true };
|
||||
const evidence = createEvidence(target, PROVIDER, observation);
|
||||
expect(parseEvidence(evidence).subject).toMatchObject({
|
||||
format: "dos-mz",
|
||||
architecture: "x86",
|
||||
});
|
||||
expect(evidence.evidence_id).not.toBe(
|
||||
createEvidence({ ...target, format: "pe" }, PROVIDER, observation)
|
||||
.evidence_id,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,7 @@ const subjectSchema = z.object({
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
|
||||
@@ -5,10 +5,22 @@ export const ghidraFunctionClassification = () => ({
|
||||
provenance: "ghidra-function-manager" as const,
|
||||
});
|
||||
|
||||
/** Wire-boundary fixture, not evidence that a real Ghidra run was performed. */
|
||||
export const ghidraFunctionBody = () => ({
|
||||
available: true as const,
|
||||
provenance: "ghidra-function-body-address-set",
|
||||
ranges: [{ start: "0x401000", end: "0x401005" }],
|
||||
total_bytes: 6,
|
||||
span_bytes: 6,
|
||||
non_contiguous: false,
|
||||
contains_entry: true,
|
||||
});
|
||||
|
||||
export const ghidraFunctionIdentity = () => ({
|
||||
address: "0x401000",
|
||||
name: "fixture_main",
|
||||
classification: ghidraFunctionClassification(),
|
||||
body: ghidraFunctionBody(),
|
||||
});
|
||||
|
||||
const ghidraReferenceKind = () => ({
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
functionBodySchema,
|
||||
procedureIdentitySchema,
|
||||
parseDocuments,
|
||||
parseListCount,
|
||||
parseNames,
|
||||
@@ -80,3 +82,132 @@ describe("Hopper boundary values", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("provider-neutral inclusive function body evidence", () => {
|
||||
const observed = () => ({
|
||||
available: true,
|
||||
provenance: "test-address-set",
|
||||
ranges: [
|
||||
{ start: "0x1000", end: "0x1002" },
|
||||
{ start: "0x1010", end: "0x1011" },
|
||||
],
|
||||
total_bytes: 5,
|
||||
span_bytes: 18,
|
||||
non_contiguous: true,
|
||||
contains_entry: true,
|
||||
});
|
||||
it("represents missing Hopper extent explicitly as unknown", () => {
|
||||
expect(
|
||||
procedureIdentitySchema.parse({ address: "0x1000", name: "main" }).body,
|
||||
).toEqual({
|
||||
available: false,
|
||||
reason: "The provider did not report complete function body ranges.",
|
||||
});
|
||||
});
|
||||
it("counts inclusive one-byte ranges without assuming an enclosing continuous body", () => {
|
||||
expect(
|
||||
functionBodySchema.safeParse({
|
||||
...observed(),
|
||||
ranges: [{ start: "0x1000", end: "0x1000" }],
|
||||
total_bytes: 1,
|
||||
span_bytes: 1,
|
||||
non_contiguous: false,
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(functionBodySchema.parse(observed())).toMatchObject({
|
||||
total_bytes: 5,
|
||||
span_bytes: 18,
|
||||
});
|
||||
});
|
||||
it("preserves address-space identity and leaves a multi-space span unknown", () => {
|
||||
expect(
|
||||
functionBodySchema.safeParse({
|
||||
...observed(),
|
||||
ranges: [
|
||||
{ start: "a:0x1000", end: "a:0x1000" },
|
||||
{ start: "b:0x1000", end: "b:0x1001" },
|
||||
],
|
||||
total_bytes: 3,
|
||||
span_bytes: null,
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
functionBodySchema.safeParse({
|
||||
...observed(),
|
||||
ranges: [{ start: "a:0x1000", end: "b:0x1000" }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
it("allows an observed empty set without manufacturing entry membership", () => {
|
||||
expect(
|
||||
procedureIdentitySchema.safeParse({
|
||||
address: "0x1000",
|
||||
name: "external",
|
||||
body: {
|
||||
...observed(),
|
||||
ranges: [],
|
||||
total_bytes: 0,
|
||||
span_bytes: 0,
|
||||
non_contiguous: false,
|
||||
contains_entry: false,
|
||||
},
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
it("checks entry membership using address space and inclusive endpoints", () => {
|
||||
expect(
|
||||
procedureIdentitySchema.safeParse({
|
||||
address: "0x1002",
|
||||
name: "last",
|
||||
body: observed(),
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
procedureIdentitySchema.safeParse({
|
||||
address: "0x1003",
|
||||
name: "gap",
|
||||
body: observed(),
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
procedureIdentitySchema.safeParse({
|
||||
address: "other:0x1000",
|
||||
name: "other",
|
||||
body: observed(),
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
it.each([
|
||||
{ total_bytes: 18 },
|
||||
{ span_bytes: 5 },
|
||||
{ non_contiguous: false },
|
||||
{
|
||||
ranges: [
|
||||
{ start: "0x1000", end: "0x1002" },
|
||||
{ start: "0x1003", end: "0x1004" },
|
||||
],
|
||||
},
|
||||
{
|
||||
ranges: [
|
||||
{ start: "0x1000", end: "0x1002" },
|
||||
{ start: "0x1002", end: "0x1004" },
|
||||
],
|
||||
},
|
||||
{
|
||||
ranges: [
|
||||
{ start: "0x1010", end: "0x1011" },
|
||||
{ start: "0x1000", end: "0x1002" },
|
||||
],
|
||||
},
|
||||
{
|
||||
ranges: [{ start: "0x0", end: "0x20000000000000" }],
|
||||
total_bytes: Number.MAX_SAFE_INTEGER,
|
||||
span_bytes: Number.MAX_SAFE_INTEGER,
|
||||
non_contiguous: false,
|
||||
},
|
||||
])("rejects contradictory or unsafe range facts %j", (change) => {
|
||||
expect(
|
||||
functionBodySchema.safeParse({ ...observed(), ...change }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
+131
-10
@@ -60,6 +60,123 @@ const segmentSchema = z.object({
|
||||
const unavailableAnalysisFactSchema = z
|
||||
.object({ available: z.literal(false), reason: z.string() })
|
||||
.strict();
|
||||
/** Complete observed function-body ranges; every range endpoint is inclusive. */
|
||||
export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
unavailableAnalysisFactSchema,
|
||||
z
|
||||
.strictObject({
|
||||
available: z.literal(true),
|
||||
provenance: z.string().min(1),
|
||||
ranges: z.array(
|
||||
z.strictObject({
|
||||
start: z.string(),
|
||||
end: z
|
||||
.string()
|
||||
.describe("Inclusive last address of this observed body range."),
|
||||
}),
|
||||
),
|
||||
total_bytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||||
span_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable(),
|
||||
non_contiguous: z.boolean(),
|
||||
contains_entry: z.boolean(),
|
||||
})
|
||||
.superRefine((body, context) => {
|
||||
let total = 0n;
|
||||
const bounds = new Map<string, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string>();
|
||||
let previousSpace: string | null = null;
|
||||
for (const range of body.ranges) {
|
||||
const start = addressCoordinate(range.start);
|
||||
const end = addressCoordinate(range.end);
|
||||
if (
|
||||
start === null ||
|
||||
end === null ||
|
||||
start.space !== end.space ||
|
||||
end.offset < start.offset
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Function body range has invalid inclusive endpoints",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (previousSpace !== null && previousSpace !== start.space)
|
||||
closedSpaces.add(previousSpace);
|
||||
const previous = bounds.get(start.space);
|
||||
if (
|
||||
closedSpaces.has(start.space) ||
|
||||
(previous !== undefined && start.offset <= previous.end + 1n)
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Function body ranges must be ordered, disjoint and maximal within each address space",
|
||||
});
|
||||
return;
|
||||
}
|
||||
bounds.set(start.space, {
|
||||
start: previous?.start ?? start.offset,
|
||||
end: end.offset,
|
||||
});
|
||||
previousSpace = start.space;
|
||||
total += end.offset - start.offset + 1n;
|
||||
}
|
||||
const onlyBounds =
|
||||
bounds.size === 1 ? [...bounds.values()][0] : undefined;
|
||||
const span =
|
||||
bounds.size === 0
|
||||
? 0n
|
||||
: onlyBounds === undefined
|
||||
? null
|
||||
: onlyBounds.end - onlyBounds.start + 1n;
|
||||
const reportedSpan =
|
||||
body.span_bytes === null ? null : BigInt(body.span_bytes);
|
||||
if (
|
||||
total !== BigInt(body.total_bytes) ||
|
||||
span !== reportedSpan ||
|
||||
body.non_contiguous !== body.ranges.length > 1
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Function body counts, enclosing span or contiguity disagree with inclusive ranges",
|
||||
});
|
||||
}),
|
||||
]);
|
||||
|
||||
const unknownFunctionBody = () =>
|
||||
functionBodySchema.default({
|
||||
available: false,
|
||||
reason: "The provider did not report complete function body ranges.",
|
||||
});
|
||||
|
||||
/** Check the declared entry membership against complete, inclusive body ranges. */
|
||||
export const functionBodyEntryAgrees = (
|
||||
body: z.infer<typeof functionBodySchema>,
|
||||
address: string,
|
||||
): boolean => {
|
||||
if (!body.available) return true;
|
||||
const entry = addressCoordinate(address);
|
||||
if (entry === null) return false;
|
||||
const contains = body.ranges.some((range) => {
|
||||
const start = addressCoordinate(range.start);
|
||||
const end = addressCoordinate(range.end);
|
||||
return (
|
||||
start !== null &&
|
||||
end !== null &&
|
||||
start.space === entry.space &&
|
||||
entry.offset >= start.offset &&
|
||||
entry.offset <= end.offset
|
||||
);
|
||||
});
|
||||
return contains === body.contains_entry;
|
||||
};
|
||||
|
||||
export const procedureClassificationSchema = z
|
||||
.object({
|
||||
external: z.boolean(),
|
||||
@@ -73,8 +190,17 @@ export const procedureIdentitySchema = z
|
||||
address: z.string(),
|
||||
name: z.string(),
|
||||
classification: procedureClassificationSchema.nullable().default(null),
|
||||
body: unknownFunctionBody(),
|
||||
})
|
||||
.strict();
|
||||
.strict()
|
||||
.superRefine((identity, context) => {
|
||||
if (!functionBodyEntryAgrees(identity.body, identity.address))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Function body entry membership disagrees with procedure identity",
|
||||
});
|
||||
});
|
||||
export const localVariableSchema = z
|
||||
.object({
|
||||
description: z.string(),
|
||||
@@ -125,15 +251,10 @@ const referenceEdgeSchema = z
|
||||
.strict();
|
||||
export const functionDossierSchema = z
|
||||
.object({
|
||||
procedure: z
|
||||
.object({
|
||||
address: z.string(),
|
||||
name: z.string(),
|
||||
classification: procedureClassificationSchema.nullable().default(null),
|
||||
signature: z.string().nullable(),
|
||||
locals: z.array(localVariableSchema),
|
||||
})
|
||||
.strict(),
|
||||
procedure: procedureIdentitySchema.safeExtend({
|
||||
signature: z.string().nullable(),
|
||||
locals: z.array(localVariableSchema),
|
||||
}),
|
||||
pseudocode: z.string(),
|
||||
assembly: z.array(z.string()),
|
||||
comments: z.array(
|
||||
|
||||
@@ -238,7 +238,7 @@ const familiesFor = (format: string, path: string): RuntimeFamily[] => {
|
||||
if (format === "javascript-bundle") families.add("javascript");
|
||||
if (format === "jvm-class" || /(?:^|\/)[^/]+\.class$/iu.test(path))
|
||||
families.add("jvm");
|
||||
if (["elf", "mach-o", "mach-o-universal", "pe"].includes(format))
|
||||
if (["elf", "mach-o", "mach-o-universal", "pe", "dos-mz"].includes(format))
|
||||
families.add("native");
|
||||
if (format === "webassembly" || /(?:^|\/)[^/]+\.wasm$/iu.test(path))
|
||||
families.add("webassembly");
|
||||
|
||||
Reference in New Issue
Block a user