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:
N0zoM1z0
2026-10-05 20:09:45 +08:00
committed by GitHub
parent 53fe7d6d3b
commit 4f099a10f8
55 changed files with 2206 additions and 92 deletions
+13 -5
View File
@@ -28,6 +28,7 @@ export const resolveGhidraAnalysisProfile = (
err(new ProviderAdapterError(identity.id, "resolve_analysis_profile")),
);
const provider = { ...identity, version: installation.providerVersion };
const dosMz = target.format === "dos-mz";
return Promise.resolve(
ok({
profile: createAnalysisProfile(provider, {
@@ -38,14 +39,21 @@ export const resolveGhidraAnalysisProfile = (
...(target.availableArchitectures ?? []),
].sort(),
import_mode: "ephemeral-read-only",
loader: "auto-from-header",
language_id: "auto-from-header",
compiler_spec_id: "auto-default",
function_body_evidence: "complete-inclusive-ranges-v1",
loader: dosMz ? "MzLoader" : "auto-from-header",
language_id: dosMz ? "x86:LE:16:Real Mode" : "auto-from-header",
compiler_spec_id: dosMz ? "default" : "auto-default",
...(dosMz
? {
load_segment: "0x1000",
address_coordinates: "linear-byte-offset",
}
: {}),
analyzer_preset: "ghidra-default",
}),
compatibility: {
languageId: "auto",
compilerSpecId: "auto",
languageId: dosMz ? "x86:LE:16:Real Mode" : "auto",
compilerSpecId: dosMz ? "default" : "auto",
},
}),
);
+6
View File
@@ -347,6 +347,12 @@ export class GhidraClient {
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
targetSha256: this.#options.targetSha256,
...(this.#options.expectedLanguageId === undefined
? {}
: { expectedLanguageId: this.#options.expectedLanguageId }),
...(this.#options.expectedCompilerSpecId === undefined
? {}
: { expectedCompilerSpecId: this.#options.expectedCompilerSpecId }),
});
if (parsed.ok) return parsed;
return err(
+2
View File
@@ -39,6 +39,8 @@ export interface GhidraClientOptions {
readonly transport?: GhidraTransportKind;
readonly providerVersion: string;
readonly profileDigest: string;
readonly expectedLanguageId?: string;
readonly expectedCompilerSpecId?: string;
readonly startupTimeoutMs?: number;
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
readonly logger?: Logger;
+108
View File
@@ -9,6 +9,7 @@ import {
} from "./GhidraFunctionValues.js";
import {
ghidraFunctionClassification,
ghidraFunctionBody,
ghidraFunctionDossier,
ghidraFunctionIdentity,
ghidraNativeApiBoundary,
@@ -96,6 +97,7 @@ describe("Ghidra function-analysis result values", () => {
},
],
classification: ghidraFunctionClassification(),
body: ghidraFunctionBody(),
}),
).toMatchObject({ ok: true });
expect(
@@ -321,3 +323,109 @@ const malformedOutputs = (): Array<
],
];
};
// Inclusive ranges are a wire-boundary fixture, not a claim of real-provider acceptance.
describe("complete Ghidra function body range evidence", () => {
const body = () => ({
available: true,
provenance: "ghidra-function-body-address-set",
ranges: [
{ start: "0x401000", end: "0x401002" },
{ start: "0x401010", end: "0x401011" },
],
total_bytes: 5,
span_bytes: 18,
non_contiguous: true,
contains_entry: true,
});
const info = () => ({
name: "fixture_main",
entrypoint: "0x401000",
basicblock_count: 2,
length: 5,
signature: null,
locals: [],
classification: ghidraFunctionClassification(),
body: body(),
});
it("preserves inclusive disjoint ranges and distinguishes owned bytes from enclosing span", () => {
expect(parseGhidraFunctionResult("procedure_info", info())).toMatchObject({
ok: true,
value: { body: body(), length: 5 },
});
});
it("rejects omitted body evidence instead of accepting a length as complete coverage", () => {
const { body: omitted, ...withoutBody } = info();
expect(omitted.total_bytes).toBe(5);
expect(parseGhidraFunctionResult("procedure_info", withoutBody).ok).toBe(
false,
);
});
it("requires local entry coverage but permits an observed empty external body", () => {
const empty = {
...body(),
ranges: [],
total_bytes: 0,
span_bytes: 0,
non_contiguous: false,
contains_entry: false,
};
expect(
parseGhidraFunctionResult("procedure_info", {
...info(),
body: empty,
length: 0,
}).ok,
).toBe(false);
expect(
parseGhidraFunctionResult("procedure_info", {
...info(),
classification: { ...ghidraFunctionClassification(), external: true },
body: empty,
length: 0,
}).ok,
).toBe(true);
});
it("rejects a missing body on nested dossier identities", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
const { body: omitted, ...identity } = ghidraFunctionIdentity();
expect(omitted.total_bytes).toBe(6);
expect(
parseGhidraFunctionResult("analyze_function", {
...dossier,
callers: [identity],
}).ok,
).toBe(false);
});
it("requires body length and Ghidra-specific body provenance", () => {
expect(
parseGhidraFunctionResult("procedure_info", { ...info(), length: 18 }).ok,
).toBe(false);
expect(
parseGhidraFunctionResult("procedure_info", {
...info(),
body: { ...body(), provenance: "unreviewed" },
}).ok,
).toBe(false);
});
it.each([
{ total_bytes: 18 },
{ span_bytes: 5 },
{ non_contiguous: false },
{ contains_entry: false },
{
ranges: [
{ start: "0x401000", end: "0x401002" },
{ start: "0x401002", end: "0x401004" },
],
},
{ ranges: [{ start: "0x401002", end: "0x401000" }] },
])("rejects contradictory complete body facts %j", (change) => {
expect(
parseGhidraFunctionResult("procedure_info", {
...info(),
body: { ...body(), ...change },
}).ok,
).toBe(false);
});
});
+29 -17
View File
@@ -7,6 +7,7 @@ import {
import { AnalysisInputError, AnalysisOutputError } from "../domain/errors.js";
import {
functionBodyEntryAgrees,
functionInstructionWindowSchema,
functionDossierSchema,
type FunctionDossier,
@@ -18,6 +19,9 @@ import { err, ok, type Result } from "../domain/result.js";
import {
ghidraIdentifierSchema,
ghidraCanonicalAddressSchema,
ghidraFunctionClassificationSchema as classification,
ghidraFunctionBodySchema as ghidraFunctionBody,
ghidraProcedureIdentitySchema as procedureIdentity,
} from "./GhidraInventoryValues.js";
/** Read-only function operations admitted by the Ghidra adapter. */
@@ -104,21 +108,6 @@ export const parseGhidraFunctionInput = (
: err(new AnalysisInputError(operation, { cause: parsed.error }));
};
const classification = z
.object({
external: z.boolean(),
thunk: z.boolean(),
thunk_target: ghidraCanonicalAddressSchema.nullable(),
provenance: z.literal("ghidra-function-manager"),
})
.strict();
const procedureIdentity = z
.object({
address: ghidraCanonicalAddressSchema,
name: z.string().min(1),
classification,
})
.strict();
const localVariable = z
.object({
description: z.string(),
@@ -179,8 +168,21 @@ const procedureInfo = z
signature: z.string().nullable(),
locals: z.array(localVariable),
classification,
body: ghidraFunctionBody,
})
.strict();
.strict()
.superRefine((value, context) => {
if (
!functionBodyEntryAgrees(value.body, value.entrypoint) ||
(value.body.available &&
(value.length !== value.body.total_bytes ||
(!value.classification.external && !value.body.contains_entry)))
)
context.addIssue({
code: "custom",
message: "Ghidra function body disagrees with entry point or length",
});
});
const ghidraNativeApiBoundary = nativeApiBoundarySchema.superRefine(
(value, context) => {
@@ -263,6 +265,10 @@ const ghidraNativeValueFlow = nativeValueFlowSchema.superRefine(
const ghidraFunctionDossier = functionDossierSchema
.extend({
procedure: functionDossierSchema.shape.procedure.safeExtend({
classification,
body: ghidraFunctionBody,
}),
native_api: ghidraNativeApiBoundary,
native_value_flow: ghidraNativeValueFlow,
})
@@ -307,7 +313,13 @@ const ghidraFunctionDossier = functionDossierSchema
];
if (
identities.some(
({ classification: facts }) => !classification.safeParse(facts).success,
(identity) =>
!classification.safeParse(identity.classification).success ||
!ghidraFunctionBody.safeParse(identity.body).success ||
!functionBodyEntryAgrees(identity.body, identity.address) ||
(identity.body.available &&
identity.classification?.external === false &&
!identity.body.contains_entry),
)
)
context.addIssue({
+119
View File
@@ -64,3 +64,122 @@ describe("Ghidra inventory boundary values", () => {
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
});
});
// Wire-boundary fixture only; real-provider acceptance belongs to the DOS verifier.
describe("containing-procedure complete body evidence", () => {
const identity = () => ({
address: "0x1000",
name: "fixture_function",
classification: {
external: false,
thunk: false,
thunk_target: null,
provenance: "ghidra-function-manager",
},
body: {
available: true,
provenance: "ghidra-function-body-address-set",
ranges: [
{ start: "0x1000", end: "0x1002" },
{ start: "0x1020", end: "0x1021" },
],
total_bytes: 5,
span_bytes: 34,
non_contiguous: true,
contains_entry: true,
},
});
const found = () => ({
query_address: "0x1001",
found: true,
procedure: identity(),
});
it("accepts the Java producer identity including complete inclusive body ranges", () => {
const value = found();
expect(
parseGhidraInventoryResult("resolve_containing_procedure", value),
).toEqual({ ok: true, value });
expect(
parseGhidraInventoryResult("resolve_containing_procedure", {
...value,
query_address: "0x1021",
}).ok,
).toBe(true);
});
it("rejects a missing body rather than treating a legacy identity as complete", () => {
const { body: omitted, ...legacy } = identity();
expect(omitted.total_bytes).toBe(5);
expect(
parseGhidraInventoryResult("resolve_containing_procedure", {
...found(),
procedure: legacy,
}).ok,
).toBe(false);
});
it.each([
{ total_bytes: 34 },
{ span_bytes: 5 },
{ contains_entry: false },
{ provenance: "unreviewed" },
{
ranges: [
{ start: "0x1000", end: "0x1002" },
{ start: "bad space:0x1020", end: "bad space:0x1021" },
],
span_bytes: null,
},
{ non_contiguous: false },
{ ranges: [{ start: "0X1000", end: "0x1002" }] },
{
ranges: [
{ start: "0x1000", end: "0x1002" },
{ start: "0x1002", end: "0x1004" },
],
},
])("rejects malformed or contradictory body evidence %j", (change) => {
const procedure = identity();
expect(
parseGhidraInventoryResult("resolve_containing_procedure", {
...found(),
procedure: { ...procedure, body: { ...procedure.body, ...change } },
}).ok,
).toBe(false);
});
it("accepts canonically encoded address-space endpoints with an unknown enclosing span", () => {
const procedure = identity();
const body = {
...procedure.body,
ranges: [
{ start: "0x1000", end: "0x1002" },
{ start: "other%20space:0x1020", end: "other%20space:0x1021" },
],
span_bytes: null,
};
expect(
parseGhidraInventoryResult("resolve_containing_procedure", {
...found(),
procedure: { ...procedure, body },
}).ok,
).toBe(true);
});
it("does not accept a found query that lies in the gap between body ranges", () => {
expect(
parseGhidraInventoryResult("resolve_containing_procedure", {
...found(),
query_address: "0x1010",
}).ok,
).toBe(false);
});
it("retains explicit not-found outcomes without fabricating a body", () => {
const value = {
query_address: "0x1010",
found: false,
procedure: null,
reason: "not_in_procedure",
};
expect(
parseGhidraInventoryResult("resolve_containing_procedure", value),
).toEqual({ ok: true, value });
});
});
+65 -9
View File
@@ -1,6 +1,10 @@
import { z } from "zod";
import { AnalysisInputError, AnalysisOutputError } from "../domain/errors.js";
import {
functionBodySchema,
functionBodyEntryAgrees,
} from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -87,9 +91,52 @@ const procedureFacts = z
thunk_target: canonicalAddress.nullable(),
})
.strict();
const functionClassification = procedureFacts
/** Ghidra FunctionManager classification, independent of body ownership inference. */
export const ghidraFunctionClassificationSchema = procedureFacts
.extend({ provenance: z.literal("ghidra-function-manager") })
.strict();
/** Require complete canonical AddressSet evidence on every Ghidra function identity. */
export const ghidraFunctionBodySchema = functionBodySchema.superRefine(
(body, context) => {
if (
!body.available ||
body.provenance !== "ghidra-function-body-address-set" ||
body.ranges.some(
({ start, end }) =>
!ghidraCanonicalAddressSchema.safeParse(start).success ||
!ghidraCanonicalAddressSchema.safeParse(end).success,
)
)
context.addIssue({
code: "custom",
message:
"Ghidra omitted complete canonical function-body AddressSet evidence",
});
},
);
/** Strict provider identity shared by inventory and function-analysis results. */
export const ghidraProcedureIdentitySchema = z
.object({
address: ghidraCanonicalAddressSchema,
name: z.string().min(1),
classification: ghidraFunctionClassificationSchema,
body: ghidraFunctionBodySchema,
})
.strict()
.superRefine((value, context) => {
if (
!functionBodyEntryAgrees(value.body, value.address) ||
(value.body.available &&
!value.classification.external &&
!value.body.contains_entry)
)
context.addIssue({
code: "custom",
message: "Ghidra function body disagrees with its entry point",
});
});
const stringFacts = z
.object({
encoding: z.string().min(1),
@@ -138,15 +185,24 @@ const containingProcedure = z.discriminatedUnion("found", [
.object({
query_address: canonicalAddress,
found: z.literal(true),
procedure: z
.object({
address: canonicalAddress,
name: z.string().min(1),
classification: functionClassification,
})
.strict(),
procedure: ghidraProcedureIdentitySchema,
})
.strict(),
.strict()
.superRefine((value, context) => {
const body = value.procedure.body;
if (
body.available &&
!functionBodyEntryAgrees(
{ ...body, contains_entry: true },
value.query_address,
)
)
context.addIssue({
code: "custom",
message:
"Found containing procedure body does not contain the query address",
});
}),
z
.object({
query_address: canonicalAddress,
+16
View File
@@ -61,6 +61,8 @@ export interface GhidraHeadlessLauncherOptions {
readonly bridgeScriptPath: string;
readonly platform?: NodeJS.Platform;
readonly comSpec?: string;
/** Select the admitted 16-bit real-mode MZ import instead of auto-detection. */
readonly dosMz?: true;
}
/** Launch Ghidra without copying scripts into or modifying its installation. */
@@ -109,6 +111,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
descriptorPath: paths.descriptorPath,
ghidraLogPath: paths.ghidraLogPath,
scriptLogPath: paths.scriptLogPath,
...(this.options.dosMz === undefined
? {}
: { dosMz: this.options.dosMz }),
});
const command = ghidraHeadlessCommand({
platform,
@@ -255,6 +260,7 @@ export interface GhidraHeadlessArgumentOptions {
readonly descriptorPath: string;
readonly ghidraLogPath: string;
readonly scriptLogPath: string;
readonly dosMz?: true;
}
/** Build the complete read-only headless invocation in deterministic order. */
@@ -265,6 +271,16 @@ export const ghidraHeadlessArguments = (
"rea-project",
"-import",
options.targetPath,
...(options.dosMz === true
? [
"-loader",
"MzLoader",
"-processor",
"x86:LE:16:Real Mode",
"-cspec",
"default",
]
: []),
"-readOnly",
"-deleteProject",
"-log",
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { parseConfig } from "../config.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_TOOL_CONTRACTS,
@@ -39,6 +40,55 @@ const provider = (
};
describe("Ghidra provider", () => {
it("separates complete body evidence from legacy length-only cache profiles", async () => {
const resolved = await provider().resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected a committed Ghidra profile");
const profile = resolved.value.profile;
const legacy = createAnalysisProfile(
profile.provider,
Object.fromEntries(
Object.entries(profile.parameters).filter(
([key]) => key !== "function_body_evidence",
),
),
);
expect(profile.digest).not.toBe(legacy.digest);
expect(profile.parameters.function_body_evidence).toBe(
"complete-inclusive-ranges-v1",
);
});
it("commits DOS loader and real-mode language while retaining the CPU family", async () => {
const ghidra = provider();
const target: BinaryTarget = {
path: "/tmp/legacy.exe",
sha256: "a".repeat(64),
kind: "executable",
format: "dos-mz",
architecture: "x86",
availableArchitectures: ["x86"],
};
expect(ghidra.inspectTargetSupport(target).status).toBe("supported");
const resolved = await ghidra.resolveAnalysisProfile(target);
expect(resolved.ok && resolved.value).toMatchObject({
profile: {
parameters: {
target_format: "dos-mz",
architecture: "x86",
loader: "MzLoader",
language_id: "x86:LE:16:Real Mode",
compiler_spec_id: "default",
load_segment: "0x1000",
address_coordinates: "linear-byte-offset",
},
},
});
const windows = provider({ ...installationHost(), platform: "win32" });
expect(windows.inspectTargetSupport(target).status).toBe("unsupported");
});
it("discovers the exact installation once without launching Ghidra", () => {
let probeCount = 0;
const host: GhidraInstallationHost = {
+24 -2
View File
@@ -189,6 +189,13 @@ export class GhidraProvider implements AnalysisProviderCandidate {
);
if (!prerequisites.ok) return unavailableClient(prerequisites.error);
const committedProfile = prerequisites.value.profile;
const targetLimitations =
target.format === "dos-mz"
? [
"DOS MZ uses 16-bit x86 real mode with the Ghidra load segment 0x1000. Returned addresses are linear byte coordinates; they do not identify a unique segment:offset alias.",
"Static DOS analysis does not emulate BIOS, DOS interrupts, device ports, or self-modifying unpacking code. Packed targets require a separately identified unpacked artifact for original-program analysis; appended overlays are not the initialized load module.",
]
: [];
const providerLimitations =
installation.platform === "win32"
? windowsP0Limitations
@@ -206,6 +213,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
bridgeScriptPath: fileURLToPath(
new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
),
...(target.format === "dos-mz" ? { dosMz: true } : {}),
platform: installation.platform,
}),
targetPath: target.path,
@@ -216,6 +224,12 @@ export class GhidraProvider implements AnalysisProviderCandidate {
: "unix-socket",
providerVersion: prerequisites.value.providerVersion,
profileDigest: committedProfile.digest,
...(target.format === "dos-mz"
? {
expectedLanguageId: "x86:LE:16:Real Mode",
expectedCompilerSpecId: "default",
}
: {}),
...(context === undefined ? {} : { runId: context.runId }),
logger: this.logger.child({ layer: "ghidra-bridge" }),
});
@@ -240,7 +254,11 @@ export class GhidraProvider implements AnalysisProviderCandidate {
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
analysisProfile: committedProfile,
limitations: [...healthLimitations, ...providerLimitations],
limitations: [
...healthLimitations,
...providerLimitations,
...targetLimitations,
],
}),
);
}
@@ -263,7 +281,11 @@ export class GhidraProvider implements AnalysisProviderCandidate {
createAnalysisExecution(result.value, committedProfile.provider, {
rawResult: called.value,
analysisProfile: committedProfile,
limitations: [...limitationsFor(operation), ...providerLimitations],
limitations: [
...limitationsFor(operation),
...providerLimitations,
...targetLimitations,
],
}),
);
},
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import {
GHIDRA_SESSION_CAPABILITIES,
parseGhidraSessionInfo,
} from "./GhidraSessionValues.js";
const expected = {
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
providerVersion: "12.1.4",
profileDigest: "a".repeat(64),
targetSha256: "b".repeat(64),
expectedLanguageId: "x86:LE:16:Real Mode",
expectedCompilerSpecId: "default",
};
const session = (
language = expected.expectedLanguageId,
compiler = "default",
) => ({
name: "REA Ghidra bridge",
run_id: expected.runId,
profile_digest: expected.profileDigest,
provider: { id: "ghidra", version: expected.providerVersion },
read_only: true,
analysis_complete: true,
analysis_timed_out: false,
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
target: {
name: "legacy.exe",
language_id: language,
compiler_spec_id: compiler,
image_base: "0x0",
default_address_space: "ram",
sha256: expected.targetSha256,
},
});
describe("Ghidra DOS import commitment", () => {
it("accepts the exact admitted real-mode language and compiler", () => {
expect(parseGhidraSessionInfo(session(), expected).ok).toBe(true);
});
it("rejects a 32-bit interpretation even when artifact and profile hashes match", () => {
expect(
parseGhidraSessionInfo(session("x86:LE:32:default"), expected).ok,
).toBe(false);
});
it("rejects compiler drift independently of the language", () => {
expect(
parseGhidraSessionInfo(session(undefined, "windows"), expected).ok,
).toBe(false);
});
});
+7
View File
@@ -56,6 +56,8 @@ export const parseGhidraSessionInfo = (
readonly providerVersion: string;
readonly profileDigest: string;
readonly targetSha256: string;
readonly expectedLanguageId?: string;
readonly expectedCompilerSpecId?: string;
},
): Result<GhidraSessionInfo, Error> => {
const parsed = sessionInfoSchema.safeParse(value);
@@ -65,6 +67,11 @@ export const parseGhidraSessionInfo = (
parsed.data.provider.version !== expected.providerVersion ||
parsed.data.profile_digest !== expected.profileDigest ||
parsed.data.target.sha256 !== expected.targetSha256 ||
(expected.expectedLanguageId !== undefined &&
parsed.data.target.language_id !== expected.expectedLanguageId) ||
(expected.expectedCompilerSpecId !== undefined &&
parsed.data.target.compiler_spec_id !==
expected.expectedCompilerSpecId) ||
new Set(parsed.data.capabilities).size !==
GHIDRA_SESSION_CAPABILITIES.length ||
GHIDRA_SESSION_CAPABILITIES.some(