feat(ghidra): admit soft-float MIPS32r2 ELF with integer-register float storage (#1949)

* feat(ghidra): admit soft-float MIPS32r2 ELF with integer-register float storage

Soft-float o32 executables (Linux kernel builds, bare-metal firmware) were
refused because their ABI flags record declares no CPR1 and FP ABI 3.
Ghidra's MIPS32 compiler specifications model only hard-float o32, so typed
float/double signatures (DWARF) would be bound to $f12/$f14/$f0 and the
decompiler loses the real dataflow: `return sel ? a : b` decompiled to
`return in_f0;`, and callers passed phantom FPU inputs.

Admit ELF32 ET_EXEC o32 MIPS32r2 targets whose ABI record declares soft-float
with no CPR1, and commit `mips_soft_float_storage: o32-integer-registers-v1`
in their analysis profile only (hard-float profile digests are unchanged).
ReaGhidraMipsSoftFloat.java runs after auto-analysis and, for each function
with a float/double formal type, either keeps the types with the storage
Ghidra's o32 model assigns to a same-size integer (pair alignment, stack
spill), or, for auto-parameters such as hidden struct-return pointers, swaps
float types for same-size integers under dynamic storage. No function is left
on hard-float storage. The report is written last; the provider client
requires it exactly when the profile commits the policy and refuses the
session before any operation otherwise.

Verification: real Ghidra 12.1.4 lane (verify:ghidra:mips) now builds
hard- and soft-float fixtures in both byte orders and checks exact
parameter/return storage through inspect_native_api, caller constants,
snapshot profile and Evidence outcome; test:fast, verify:package and an
installed-tarball soft-float run pass.

* fix(ghidra): model soft-float MIPS as a prototype for every typed callable

Review feedback on #1949: rewriting storage per Function left external
functions and indirect calls through typed function pointers on Ghidra's
hard-float o32 prototype, which still read $f12/$f14/$f0 while the session
reported success. A negative control confirms it: without the change,
`(*rea_mips_soft_callback)(8.5f, 9.5f, sel)` decompiles to
`(*rea_mips_soft_callback)(in_f12, in_f14, sel)`.

ReaGhidraMipsSoftFloat.java now derives a `__rea_soft_float` prototype from
the program's own default o32 model (encoded, float pentries and
float-consuming rules removed, so byte-order-specific aggregate rules and the
hidden struct-return pointer are kept), installs it as a specification
extension, and assigns it with dynamic storage to every non-thunk function,
external function and function-pointer definition whose formal types use
float or double. Thunks follow their targets. Float types are kept
everywhere, so the integer-retype fallback is removed. The script fails
without writing its report if the derived prototype or any reassigned
function still uses an FPU register.

The policy becomes `o32-soft-float-prototype-v1` with a
{functions, definitions} report. The soft-float fixture adds an indirect
call through a typed pointer; the real-Ghidra lane requires its constants
with no FPU inputs and the struct return's `float scale` in $a1.

* test(ghidra): pin ODDSPREG acceptance for soft-float MIPS ABI records

Review on #1949 suggested requiring flags1 == 0 for soft-float, since MIPS_AFL_FLAGS1_ODDSPREG names CPR1 registers. GCC 5.2 kernel modules, LLVM/Rust firmware and Clang -msoft-float objects all record flags1 = 1 with FP ABI soft-float: it is the MIPS32 o32 toolchain default and selects nothing without CPR1. Keep accepting it, say why at the check, and test that soft-float with ODDSPREG is admitted while any other general flag is refused.
This commit is contained in:
Aurelio Bernal
2026-10-12 04:54:38 +08:00
committed by GitHub
parent 5ba1642a7d
commit 5e219de441
17 changed files with 958 additions and 34 deletions
+23
View File
@@ -114,6 +114,8 @@ export interface GhidraHeadlessLauncherOptions {
readonly analysisSeeds?: GhidraSeedCommitment;
readonly analysisExtensions?: readonly GhidraExtension[];
readonly pspExtension?: GhidraPspExtension;
/** Remap typed float storage for the soft-float o32 ABI after analysis. */
readonly mipsSoftFloat?: true;
/** Spawn seam for provider-boundary lifecycle tests. */
readonly spawnProcess?: typeof spawnOwnedProviderProcess;
}
@@ -196,6 +198,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
const headlessArguments = ghidraHeadlessArguments({
platform,
...(psp === undefined ? {} : { psp: true as const }),
...(this.options.mipsSoftFloat === undefined
? {}
: { mipsSoftFloat: this.options.mipsSoftFloat }),
projectRoot: paths.projectRoot,
targetPath: session.targetPath,
bridgeScriptPath: this.options.bridgeScriptPath,
@@ -422,6 +427,7 @@ export interface GhidraHeadlessArgumentOptions {
readonly ghidraLogPath: string;
readonly scriptLogPath: string;
readonly psp?: true;
readonly mipsSoftFloat?: true;
readonly dosMz?: true;
readonly dosCom?: true;
readonly rawBinary?: {
@@ -460,6 +466,16 @@ export const ghidraHeadlessArguments = (
throw new Error(
"A PSP ELF import cannot be combined with a raw-binary import.",
);
if (
options.mipsSoftFloat === true &&
(options.psp === true ||
options.dosMz === true ||
options.dosCom === true ||
rawBinary !== undefined)
)
throw new Error(
"MIPS soft-float storage applies only to a generic MIPS ELF import.",
);
if (
override !== undefined &&
(options.dosMz === true || options.dosCom === true)
@@ -578,6 +594,13 @@ export const ghidraHeadlessArguments = (
"-postScript",
scriptPath.join(bridgeDirectory, "ReaGhidraNoReturnFix.java"),
]),
// After analysis and the no-return refit, before the bridge serves results.
...(options.mipsSoftFloat === true
? [
"-postScript",
scriptPath.join(bridgeDirectory, "ReaGhidraMipsSoftFloat.java"),
]
: []),
"-postScript",
// Ghidra checks the caller's cwd before scriptPath for a basename. Select
// the packaged source explicitly so unrelated entries cannot shadow it.
+153
View File
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { ok } from "../domain/result.js";
import { parseConfig } from "../config/parseConfig.js";
import type {
BinaryTarget,
@@ -10,6 +11,8 @@ import { hopperLoaderArgsForTarget } from "../hopper/HopperAnalysisProfile.js";
import { IdaProvider } from "../ida/IdaProvider.js";
import { GhidraProvider } from "./GhidraProvider.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
import type { GhidraMipsSoftFloatReport } from "./GhidraMipsProfile.js";
// Fake installation inspection tests admission/profile contracts, not Ghidra.
const host: GhidraInstallationHost = {
@@ -56,6 +59,18 @@ const target = (change: Partial<MipsElfMetadata> = {}): BinaryTarget => ({
...change,
},
});
const abi = (
change: Partial<NonNullable<MipsElfMetadata["abiFlags"]>>,
): Partial<MipsElfMetadata> => {
const base = target();
if (base.kind !== "executable" || base.architecture !== "mips")
throw new Error("expected a MIPS fixture target");
const flags = base.mips.abiFlags;
if (flags === undefined || flags === null)
throw new Error("expected fixture ABI flags");
return { abiFlags: { ...flags, ...change } };
};
const softFloat = abi({ cpr1Size: 0, fpAbi: 3 });
describe("bounded Ghidra MIPS admission", () => {
it("binds endian and flags without widening Windows P0", async () => {
@@ -118,6 +133,11 @@ describe("bounded Ghidra MIPS admission", () => {
[{ flags: 0x70001201 }, "EF_MIPS_FP64"],
[{ flags: 0x70001401 }, "EF_MIPS_NAN2008"],
[{ abiFlags: null }, "inspected ABI"],
[abi({ cpr1Size: 0, fpAbi: 1 }), "soft-float without CPR1"],
[abi({ cpr1Size: 1, fpAbi: 3 }), "soft-float without CPR1"],
[abi({ cpr1Size: 1, fpAbi: 2 }), "single-float"],
[abi({ cpr1Size: 1, fpAbi: 0 }), "unspecified"],
[abi({ cpr1Size: 2, fpAbi: 6 }), "FP64"],
] satisfies [Partial<MipsElfMetadata>, string][])(
"refuses an unverified MIPS interpretation %j",
async (change, reason) => {
@@ -140,3 +160,136 @@ describe("bounded Ghidra MIPS admission", () => {
expect(ida.inspectTargetSupport(target()).status).toBe("unsupported");
});
});
describe("soft-float MIPS storage", () => {
const report: GhidraMipsSoftFloatReport = {
policy: "o32-soft-float-prototype-v1",
functions: 5,
definitions: 1,
};
const session = async (
value: BinaryTarget,
reported: GhidraMipsSoftFloatReport | undefined,
profileFor: BinaryTarget = value,
) => {
const counts = { starts: 0, calls: 0, closes: 0 };
const ghidra = new GhidraProvider(config, silentLogger, {}, host, () => ({
start: () => {
counts.starts++;
return Promise.resolve(
ok({
name: "REA Ghidra bridge" as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: "a".repeat(64),
provider: { id: "ghidra" as const, version: "12.1.4" },
read_only: false,
analysis_complete: true,
analysis_timed_out: false,
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
target: {
name: "fixture.elf",
language_id: "MIPS:LE:32:default",
compiler_spec_id: "default",
image_base: "0x0",
default_address_space: "ram",
sha256: "a".repeat(64),
},
...(reported === undefined
? {}
: { mips_soft_float_storage: reported }),
}),
);
},
callTool: () => {
counts.calls++;
return Promise.resolve(ok(null));
},
close: () => {
counts.closes++;
return Promise.resolve(ok(null));
},
}));
const resolved = await ghidra.resolveAnalysisProfile(profileFor);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected a MIPS profile");
return {
counts,
profile: resolved.value.profile,
client: ghidra.createClient(value, resolved.value.profile),
};
};
it("admits soft-float o32 and commits its storage policy only for it", async () => {
const soft = target(softFloat);
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
expect(ghidra.inspectTargetSupport(soft).status).toBe("supported");
const { profile } = await session(soft, report);
expect(profile.parameters.mips_soft_float_storage).toBe(
"o32-soft-float-prototype-v1",
);
const hard = await session(target(), undefined);
expect(hard.profile.parameters).not.toHaveProperty(
"mips_soft_float_storage",
);
});
it("admits the ODDSPREG default that soft-float toolchains emit, but no other flags", () => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
// GCC 5.2 kernel modules and LLVM/Rust firmware both record flags1 = 1.
expect(
ghidra.inspectTargetSupport(
target(abi({ cpr1Size: 0, fpAbi: 3, flags1: 1 })),
).status,
).toBe("supported");
expect(
ghidra.inspectTargetSupport(
target(abi({ cpr1Size: 0, fpAbi: 3, flags1: 2 })),
),
).toMatchObject({
status: "unsupported",
reason: expect.stringContaining("general flags"),
});
});
it("reports the prototype outcome as session limitations", async () => {
const { client } = await session(target(softFloat), report);
const health = await client.execute("health", {});
if (!health.ok) throw health.error;
expect(health.value.limitations).toEqual(
expect.arrayContaining([
expect.stringContaining("model hard-float o32 only"),
expect.stringContaining(
"5 functions and 1 function-pointer definitions use __rea_soft_float.",
),
]),
);
});
it("fails closed on a soft-float session without a storage report before any analysis call", async () => {
const { counts, client } = await session(target(softFloat), undefined);
const failed = await client.execute("list_procedures", {});
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error._tag).toBe("ProviderAdapterError");
expect(counts).toEqual({ starts: 1, calls: 0, closes: 1 });
});
it("rejects soft-float storage reported by a hard-float session", async () => {
const { counts, client } = await session(target(), report);
const failed = await client.execute("health", {});
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error._tag).toBe("ProviderAdapterError");
expect(counts).toEqual({ starts: 1, calls: 0, closes: 1 });
});
it("refuses a profile whose storage policy disagrees with the target", async () => {
for (const [value, profileFor] of [
[target(softFloat), target()],
[target(), target(softFloat)],
] as const) {
const { counts, client } = await session(value, report, profileFor);
const failed = await client.execute("health", {});
expect(failed.ok).toBe(false);
expect(counts.starts).toBe(0);
}
});
});
+58 -4
View File
@@ -1,6 +1,8 @@
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
const MIPS_FP_ABI_SOFT = 3;
/** Keep family recognition separate from the deliberately bounded Ghidra lane. */
export const ghidraMipsUnsupportedReason = (
target: BinaryTarget,
@@ -39,17 +41,66 @@ export const ghidraMipsUnsupportedReason = (
return "This Ghidra MIPS lane requires ABI flags version 0; newer record semantics are unsupported.";
if (abi.isaLevel !== 32 || abi.isaRevision !== 2)
return "MIPS ABI flags must agree with the declared MIPS32r2 ISA.";
if (abi.gprSize !== 1 || abi.cpr1Size !== 1 || abi.cpr2Size !== 0)
return "This Ghidra MIPS lane requires 32-bit GPR/CPR1 and no CPR2; other register modes need separate verification.";
if (abi.fpAbi !== 1 && abi.fpAbi !== 5)
return "This Ghidra MIPS lane admits double-precision or FPXX ABI declarations only; soft-float, FP64 and unspecified modes need separate verification.";
if (abi.gprSize !== 1 || abi.cpr2Size !== 0)
return "This Ghidra MIPS lane requires 32-bit GPRs and no CPR2; other register modes need separate verification.";
const hardFloat = abi.cpr1Size === 1 && (abi.fpAbi === 1 || abi.fpAbi === 5);
const softFloat = abi.cpr1Size === 0 && abi.fpAbi === MIPS_FP_ABI_SOFT;
if (!hardFloat && !softFloat)
return "This Ghidra MIPS lane admits double-precision or FPXX ABI declarations with 32-bit CPR1, or soft-float without CPR1; single-float, FP64 and unspecified modes need separate verification.";
if (abi.isaExtension !== 0 || abi.ases !== 0)
return "MIPS ABI flags declare an ISA extension or ASE outside this standard-instruction lane.";
// MIPS_AFL_FLAGS1_ODDSPREG (bit 0) is the GCC and LLVM default for MIPS32 o32
// whatever the FP ABI; soft-float objects from both carry it. With no CPR1 it
// selects nothing, so it is accepted for soft-float as well as hard-float.
if ((abi.flags1 & ~1) !== 0 || abi.flags2 !== 0)
return "MIPS ABI flags contain unsupported general flags.";
return null;
};
/** Soft-float prototype policy applied by ReaGhidraMipsSoftFloat.java after analysis. */
export const GHIDRA_MIPS_SOFT_FLOAT_STORAGE = "o32-soft-float-prototype-v1";
/** Whether the admitted target declares the soft-float o32 ABI. */
export const isGhidraMipsSoftFloatTarget = (target: BinaryTarget): boolean =>
target.kind === "executable" &&
target.architecture === "mips" &&
target.mips?.abiFlags?.cpr1Size === 0 &&
target.mips.abiFlags.fpAbi === MIPS_FP_ABI_SOFT;
/** Prototype outcome the post-analysis script records for the bridge handshake. */
export interface GhidraMipsSoftFloatReport {
readonly policy: typeof GHIDRA_MIPS_SOFT_FLOAT_STORAGE;
readonly functions: number;
readonly definitions: number;
}
/** Fail closed unless soft-float storage ran exactly for soft-float targets. */
export const ghidraMipsSoftFloatFailure = (
expected: boolean,
report: GhidraMipsSoftFloatReport | undefined,
): string | undefined =>
expected === (report !== undefined)
? undefined
: expected
? "The Ghidra session did not report the committed MIPS soft-float prototype."
: "The Ghidra session reported MIPS soft-float storage that the profile did not commit.";
/** Keep REA's soft-float prototype distinct from Ghidra's hard-float o32 model. */
export const ghidraMipsSoftFloatLimitations = (
expected: boolean,
report?: GhidraMipsSoftFloatReport,
): readonly string[] =>
expected
? [
"Soft-float o32: Ghidra's MIPS32 compiler specifications model hard-float o32 only. After analysis REA installs a program-specific `__rea_soft_float` prototype, derived from the default o32 model without its floating-point registers and rules, and assigns it to every function, external function and function-pointer definition whose declared types use float or double, so those values keep their types and use integer registers and stack slots.",
...(report === undefined
? []
: [
`Soft-float prototype outcome: ${report.functions} functions and ${report.definitions} function-pointer definitions use __rea_soft_float.`,
]),
]
: [];
/** Commit source ELF interpretation without confusing target ISA with host CPU. */
export const ghidraMipsProfileParameters = (
target: BinaryTarget,
@@ -87,6 +138,9 @@ export const ghidraMipsProfileParameters = (
flags2: abi.flags2,
},
},
...(isGhidraMipsSoftFloatTarget(target)
? { mips_soft_float_storage: GHIDRA_MIPS_SOFT_FLOAT_STORAGE }
: {}),
mips_support_lane: "elf32-exec-o32-arch32r2-standard-v3",
};
};
+47 -2
View File
@@ -56,6 +56,12 @@ import {
GHIDRA_PSP_LIMITATIONS,
} from "./GhidraPspProfile.js";
import { ghidraPspExtensionSchema } from "./GhidraPspExtension.js";
import {
GHIDRA_MIPS_SOFT_FLOAT_STORAGE,
ghidraMipsSoftFloatFailure,
ghidraMipsSoftFloatLimitations,
isGhidraMipsSoftFloatTarget,
} from "./GhidraMipsProfile.js";
import { unverifiedGhidraBuildLimitation } from "./GhidraInstallationPolicy.js";
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import { attestGhidraNativeLoadImage } from "./GhidraLoadImageAttest.js";
@@ -386,6 +392,20 @@ export const createGhidraProviderClient = (input: {
},
}),
);
const softFloat = isGhidraMipsSoftFloatTarget(target);
if (
softFloat !==
(committedProfile.parameters.mips_soft_float_storage ===
GHIDRA_MIPS_SOFT_FLOAT_STORAGE)
)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"Resolve the soft-float MIPS storage policy into the analysis profile before opening the session.",
},
}),
);
const extensionProfile = ghidraExtensionSchema
.array()
.safeParse(committedProfile.parameters.analysis_extensions ?? []);
@@ -465,6 +485,10 @@ export const createGhidraProviderClient = (input: {
let extensionFailure: AnalysisError | undefined;
// Replaced by the reported outcome once the session handshake is checked.
const seedLimitations: string[] = [...ghidraSeedLimitations(seeds)];
// Replaced by the reported storage outcome once the handshake is checked.
const softFloatLimitations: string[] = [
...ghidraMipsSoftFloatLimitations(softFloat),
];
const rawLanguage =
target.format === "raw-binary"
? ghidraRawBinaryLanguage(target.architecture)
@@ -508,6 +532,7 @@ export const createGhidraProviderClient = (input: {
...(pspExtension?.success === true
? { pspExtension: pspExtension.data }
: {}),
...(softFloat ? { mipsSoftFloat: true as const } : {}),
...(target.format === "dos-mz" ? { dosMz: true } : {}),
...(target.format === "dos-com" ? { dosCom: true } : {}),
...(rawLanguage === undefined || target.format !== "raw-binary"
@@ -569,18 +594,37 @@ export const createGhidraProviderClient = (input: {
operation: AnalysisOperation,
info: GhidraSessionInfo,
): Promise<AnalysisError | undefined> => {
const softFloatReason = ghidraMipsSoftFloatFailure(
softFloat,
info.mips_soft_float_storage,
);
extensionFailure =
ghidraExtensionFailure(
extensions,
info.analysis_extensions ?? [],
operation,
) ?? ghidraSeedFailure(seeds, info.analysis_seeds, operation);
) ??
ghidraSeedFailure(seeds, info.analysis_seeds, operation) ??
(softFloatReason === undefined
? undefined
: new ProviderAdapterError("ghidra", operation, {
diagnostics: { reason: softFloatReason },
}));
if (extensionFailure === undefined && info.analysis_seeds !== undefined)
seedLimitations.splice(
0,
seedLimitations.length,
...ghidraSeedLimitations(seeds, info.analysis_seeds),
);
if (extensionFailure === undefined)
softFloatLimitations.splice(
0,
softFloatLimitations.length,
...ghidraMipsSoftFloatLimitations(
softFloat,
info.mips_soft_float_storage,
),
);
if (extensionFailure === undefined) return undefined;
const closed = await client.close();
return closed.ok
@@ -598,6 +642,7 @@ export const createGhidraProviderClient = (input: {
...providerLimitations,
...targetLimitations,
...(psp ? GHIDRA_PSP_LIMITATIONS : []),
...softFloatLimitations,
...ghidraExtensionLimitations(extensions),
...seedLimitations,
...(releaseLimitation === undefined ? [] : [releaseLimitation]),
@@ -648,7 +693,7 @@ export const createGhidraProviderClient = (input: {
? parseGhidraFunctionInput(operation, parameters)
: parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
if (extensions.length > 0 || seeds !== undefined) {
if (extensions.length > 0 || seeds !== undefined || softFloat) {
const started = await client.start(options?.signal, options?.progress);
if (!started.ok)
return err(
+34
View File
@@ -52,6 +52,40 @@ describe("Ghidra DOS import commitment", () => {
});
});
describe("Ghidra MIPS soft-float storage report", () => {
const valid = {
policy: "o32-soft-float-prototype-v1",
functions: 2,
definitions: 1,
};
it("accepts the exact committed policy outcome", () => {
const parsed = parseGhidraSessionInfo(
{ ...session(), mips_soft_float_storage: valid },
expected,
);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.mips_soft_float_storage).toEqual(valid);
});
it.each([
[
"the superseded storage policy",
{ policy: "o32-integer-registers-v1", remapped: 2, retyped: 1 },
],
["a negative count", { ...valid, definitions: -1 }],
["a fractional count", { ...valid, functions: 1.5 }],
["a missing count", { policy: valid.policy, functions: 2 }],
["an undeclared field", { ...valid, skipped: 0 }],
["a non-object report", "functions"],
])("rejects %s", (_label, report) => {
expect(
parseGhidraSessionInfo(
{ ...session(), mips_soft_float_storage: report },
expected,
).ok,
).toBe(false);
});
});
describe("Ghidra mutation handshake", () => {
it("requires the exact mutation authority and rejects duplicate capabilities", () => {
const value = session();
+9
View File
@@ -9,6 +9,7 @@ import {
} from "./GhidraInventoryValues.js";
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
import { ghidraExtensionResultSchema } from "./extensions/GhidraExtensions.js";
import { GHIDRA_MIPS_SOFT_FLOAT_STORAGE } from "./GhidraMipsProfile.js";
/** Exact methods proved by the bridge handshake after auto-analysis. */
export const GHIDRA_SESSION_CAPABILITIES = [
@@ -42,6 +43,14 @@ const sessionInfoSchema = z
analysis_timed_out: z.boolean(),
analysis_extensions: z.array(ghidraExtensionResultSchema).optional(),
analysis_seeds: ghidraSeedReportSchema.optional(),
mips_soft_float_storage: z
.object({
policy: z.literal(GHIDRA_MIPS_SOFT_FLOAT_STORAGE),
functions: z.number().int().nonnegative(),
definitions: z.number().int().nonnegative(),
})
.strict()
.optional(),
capabilities: z.array(capabilitySchema),
target: z
.object({