feat(native): admit bounded MIPS ELF analysis through Ghidra (#1362)

* feat(native): admit bounded MIPS ELF analysis through Ghidra

Retain MIPS ELF identity and interpretation through Evidence and snapshots.
Keep provider admission bounded to ELF32 ET_EXEC o32 MIPS32r2, without
implicitly widening Hopper, IDA or Windows P0 coverage. Add source-owned
fixtures and an optional real-provider verifier; real Ghidra verification
remains pending in this contribution environment.

Refs #718

* fix(ghidra): bound MIPS floating-point mode admission

Reject explicit EF_MIPS_FP64 and EF_MIPS_NAN2008 declarations until their
semantics have a real-provider verification lane. Add PSP PRX/Allegrex,
o64/EABI and floating-point-mode refusal regressions. Document that the
header gate is not a full .MIPS.abiflags check and advance the profile lane
identity to invalidate older interpretation bindings.

Validation: 24 standalone checks against the transpiled production profile
module passed; the two new flag cases failed before this change. Clang 17
and LLD compiled the source-owned fixture for both endian targets. The
complete Vitest/typecheck suite and real Ghidra verification remain pending.

Refs morluto/rea#718; PSP support remains follow-up morluto/rea#1330.

* fix(native): validate MIPS ABI records before Ghidra admission

Read bounded ELF32 PT_MIPS_ABIFLAGS and SHT_MIPS_ABIFLAGS records through
the already-open target handle. Preserve declared ABI fields, reject
conflicting/duplicate/truncated records, and keep missing records unknown.
Wire inspection into target resolution before provider selection. Require
compatible declarations for the deliberately narrow Ghidra lane and bind
all ABI fields into profile identity (v3) for snapshot invalidation.

Clang 17 produced eight source-owned fixtures spanning both byte orders
and FPXX/FP32/FP64/soft-float modes with identical ELF header flags. The
new reader and policy distinguish them. 24 focused regression test bodies
passed after TypeScript transpilation using node:test in place of Vitest;
strict isolated TypeScript checking of the reader and target/result types
passed. These are limited checks, not full Vitest/project typechecking or
real-Ghidra verification, which remain pending.

Advances morluto/rea#718. PSP/Allegrex remains morluto/rea#1330 follow-up.

* fix(native): repair MIPS integration boundaries and test resolver behavior

Keep ELF targets out of Hopper Mach-O preparation and scope existing PE fixture types correctly. Move ABI tests into the filesystem boundary lane, use shared cleanup, add resolver regressions, apply the pinned formatter, and register the real MIPS verifier through the existing package-command pattern. Validated with repository-pinned Node/npm, check:ci, actual focused Vitest, discovery and docs:check. Real Ghidra conformance remains pending.

* fix(test): honor caller-selected JDK in real MIPS verification

* test(native): strengthen MIPS Ghidra conformance

Cross-check the source-owned fixture with bounded GNU readelf inspection, compare production ELF/ABI interpretation and independent symbol addresses, and verify effective Ghidra language/compiler identity through existing public operations. Add a source-owned fixed-encoding probe for immediate and conditional branch checks plus global/string byte assertions.

Add 16 assertion/producer-boundary regression cases without widening production admission, changing provider contracts, or introducing proprietary dependencies. Local focused suite: 99 passed, one existing root-permission test skipped. Typecheck, lint/module boundaries, formatting and 700-file discovery pass; full hosted checks and real Ghidra verification remain pending for this checkpoint.

* fix(ghidra): preserve native-tool architecture checks after MIPS integration

The conflict-free upstream merge failed TypeScript compilation because includes on the union of MIPS-only and other architecture arrays requires never. Use equality-based membership without casts or changing accepted native hosts. Extend the existing native-decompiler rejection table with a MIPS executable at a Linux x64 tool path; retain upstream FAT and unknown-header behavior. Hosted verification follows this commit; no success is claimed yet.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Jay-Alexander Elliot
2026-10-10 23:04:27 +08:00
committed by GitHub
co-authored by github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
parent 96fd98cce0
commit bddddccdee
32 changed files with 2028 additions and 35 deletions
+16 -1
View File
@@ -17,6 +17,7 @@ import {
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { err, ok, type Result } from "../domain/result.js";
import { readMipsElfAbiFlags } from "./MipsElfAbiFlags.js";
import {
resolveAppBundleExecutable,
type ResolvedAppBundle,
@@ -352,7 +353,21 @@ const readExecutableMetadata = async (
}
}
}
return parseExecutableHeader(bytes, hostArchitecture, fileSize);
const parsed = parseExecutableHeader(bytes, hostArchitecture, fileSize);
if (
!parsed.ok ||
parsed.value.architecture !== "mips" ||
parsed.value.mips.elfClass !== 32
)
return parsed;
const abiFlags = await readMipsElfAbiFlags(handle, parsed.value.mips, () =>
throwIfTargetResolutionCancelled(signal),
);
if (!abiFlags.ok) return abiFlags;
return ok({
...parsed.value,
mips: { ...parsed.value.mips, abiFlags: abiFlags.value },
});
};
const readPeMetadata = async (
+153
View File
@@ -0,0 +1,153 @@
import type { FileHandle } from "node:fs/promises";
import type {
MipsAbiFlags,
MipsElfMetadata,
} from "../domain/binaryTargetTypes.js";
import { err, ok, type Result } from "../domain/result.js";
/**
* Read ELF32 MIPS ABI declarations from the caller's already-open file.
* Inspect both typed tables (not section names), including records beyond the
* initial header probe. A missing record is unknown, not a default FP ABI.
* The caller supplies its cancellation check so its tagged error is preserved.
*/
export const readMipsElfAbiFlags = async (
handle: FileHandle,
metadata: MipsElfMetadata,
checkCancelled: () => void,
): Promise<Result<MipsAbiFlags | null, string>> => {
checkCancelled();
if (metadata.elfClass !== 32)
return err("MIPS ABI record inspection currently supports ELF32 only");
const fileSize = (await handle.stat()).size;
checkCancelled();
const read = async (
offset: number,
length: number,
label: string,
): Promise<Result<Buffer, string>> => {
checkCancelled();
if (
!Number.isSafeInteger(fileSize) ||
offset < 0 ||
length < 0 ||
offset > fileSize - length
)
return err(`MIPS ${label} lies outside the file`);
const bytes = Buffer.alloc(length);
let total = 0;
while (total < length) {
checkCancelled();
const observed = await handle.read(
bytes,
total,
length - total,
offset + total,
);
checkCancelled();
if (observed.bytesRead === 0) return err(`truncated MIPS ${label}`);
total += observed.bytesRead;
}
return ok(bytes);
};
const header = await read(0, 52, "ELF32 header");
if (!header.ok) return header;
const bytes = header.value;
const little = metadata.byteOrder === "little";
const u16 = (data: Buffer, offset: number): number =>
little ? data.readUInt16LE(offset) : data.readUInt16BE(offset);
const u32 = (data: Buffer, offset: number): number =>
little ? data.readUInt32LE(offset) : data.readUInt32BE(offset);
if (
bytes.toString("hex", 0, 4) !== "7f454c46" ||
bytes[4] !== 1 ||
bytes[5] !== (little ? 1 : 2) ||
u16(bytes, 18) !== 8 ||
u16(bytes, 16) !== metadata.type ||
u32(bytes, 36) !== metadata.flags
)
return err("MIPS ELF header no longer matches the resolved identity");
if (bytes[6] !== 1 || u32(bytes, 20) !== 1 || u16(bytes, 40) !== 52)
return err("invalid MIPS ELF32 version or header size");
const tables = [
{
label: "program header table",
offset: u32(bytes, 28),
count: u16(bytes, 44),
stride: u16(bytes, 42),
entrySize: 32,
typeOffset: 0,
dataOffset: 4,
sizeOffset: 16,
recordType: 0x70000003, // PT_MIPS_ABIFLAGS
},
{
label: "section header table",
offset: u32(bytes, 32),
count: u16(bytes, 48),
stride: u16(bytes, 46),
entrySize: 40,
typeOffset: 4,
dataOffset: 16,
sizeOffset: 20,
recordType: 0x7000002a, // SHT_MIPS_ABIFLAGS
},
];
// Extended numbering needs a separate section-zero reader. Refuse it rather
// than silently treating an unexamined table as having no ABI declarations.
if (u16(bytes, 44) === 0xffff || u16(bytes, 48) >= 0xff00)
return err("extended or reserved MIPS ELF table numbering is unsupported");
let record: Buffer | undefined;
for (const table of tables) {
if (table.count === 0) {
if (table.offset !== 0)
return err(`unsupported extended or inconsistent MIPS ${table.label}`);
continue;
}
if (table.offset < 52 || table.stride !== table.entrySize)
return err(`invalid MIPS ${table.label} offset or entry size`);
// Counts are bounded by the ELF16 fields and strides by their exact ELF32
// structure sizes. Never allocate according to an untrusted section size.
const contents = await read(
table.offset,
table.count * table.entrySize,
table.label,
);
if (!contents.ok) return contents;
let found = false;
for (let i = 0; i < table.count; i += 1) {
checkCancelled();
const position = i * table.entrySize;
if (u32(contents.value, position + table.typeOffset) !== table.recordType)
continue;
if (found) return err(`duplicate MIPS ABI records in ${table.label}`);
found = true;
const offset = u32(contents.value, position + table.dataOffset);
const size = u32(contents.value, position + table.sizeOffset);
if (size !== 24)
return err("unsupported MIPS ABI record size; expected 24 bytes");
const candidate = await read(offset, 24, "ABI record");
if (!candidate.ok) return candidate;
if (record !== undefined && !record.equals(candidate.value))
return err("conflicting MIPS program/section ABI declarations");
record = candidate.value;
}
}
if (record === undefined) return ok(null);
// Preserve declarations verbatim, including unknown versions/values. Provider
// admission, not parsing, decides which interpretations have been verified.
return ok({
version: u16(record, 0),
isaLevel: record.readUInt8(2),
isaRevision: record.readUInt8(3),
gprSize: record.readUInt8(4),
cpr1Size: record.readUInt8(5),
cpr2Size: record.readUInt8(6),
fpAbi: record.readUInt8(7),
isaExtension: u32(record, 8),
ases: u32(record, 12),
flags1: u32(record, 16),
flags2: u32(record, 20),
});
};
@@ -2,7 +2,11 @@ import { z } from "zod";
import { AnalysisProtocolError } from "../../domain/analysisErrorCore.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
createEvidence,
type Evidence,
type EvidenceSubjectTarget,
} from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import {
managedApplicationGraphResultSchema,
@@ -68,14 +72,7 @@ const createManagedApplicationGraphEvidence = (
const subjectTarget = (
input: ProjectManagedApplicationGraphInput,
):
| {
readonly path: string;
readonly sha256: string;
readonly format: "pe";
readonly architecture?: "x86" | "x86_64" | "arm" | "arm64";
}
| undefined => {
): EvidenceSubjectTarget | undefined => {
const subject =
input.managed_artifact?.subject ??
input.managed_members?.subject ??
+3 -2
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { BINARY_ARCHITECTURES } from "../domain/binaryTargetTypes.js";
import { nativeFunctionAnnotationsSchema } from "../domain/native/nativeFunctionAnnotations.js";
import { nativeLoadImageSchema } from "../domain/native/nativeLoadImage.js";
import { nativeUiResultSchema } from "../domain/native/nativeUiObservation.js";
@@ -415,7 +416,7 @@ export const sessionOutputSchemas = {
format: targetFormatSchema,
kind: targetKindSchema,
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
}),
),
close_binary: lifecycleResultOf(
@@ -456,7 +457,7 @@ export const sessionOutputSchemas = {
format: targetFormatSchema,
kind: targetKindSchema,
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
}),
]),
]),
+5 -2
View File
@@ -11,7 +11,10 @@ import {
committedProviderSchema,
type AnalysisProfileCommitment,
} from "./analysisProfile.js";
import type { BinaryTarget } from "./binaryTargetTypes.js";
import {
BINARY_ARCHITECTURES,
type BinaryTarget,
} from "./binaryTargetTypes.js";
import {
evidenceBundleForTarget,
evidenceBundleSchema,
@@ -31,7 +34,7 @@ import {
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
const architectureSchema = z.enum(["x86", "x86_64", "arm", "arm64"]);
const architectureSchema = z.enum(BINARY_ARCHITECTURES);
const formatSchema = z.enum([
"analysis-database",
"mach-o",
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import { parseExecutableHeader } from "./binaryTarget.js";
const header = (little: boolean, bits: 32 | 64 = 32): Buffer => {
const bytes = Buffer.alloc(bits === 32 ? 52 : 64);
bytes.set([0x7f, 0x45, 0x4c, 0x46, bits === 32 ? 1 : 2, little ? 1 : 2, 1]);
if (little) {
bytes.writeUInt16LE(2, 16);
bytes.writeUInt16LE(8, 18);
bytes.writeUInt32LE(0x70001001, bits === 32 ? 36 : 48);
} else {
bytes.writeUInt16BE(2, 16);
bytes.writeUInt16BE(8, 18);
bytes.writeUInt32BE(0x70001001, bits === 32 ? 36 : 48);
}
return bytes;
};
describe("MIPS ELF header boundaries", () => {
it.each([true, false])(
"retains source endian and ABI/ISA flags (little=%s)",
(little) => {
const parsed = parseExecutableHeader(header(little), "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toEqual({
format: "elf",
architecture: "mips",
availableArchitectures: ["mips"],
mips: {
elfClass: 32,
byteOrder: little ? "little" : "big",
type: 2,
flags: 0x70001001,
},
});
},
);
it("reads ELF64 flags at their own offset without claiming o32 support", () => {
const bytes = header(false, 64);
bytes.writeUInt32BE(0xfeedface, 36);
bytes.writeUInt32BE(0x80000001, 48);
const parsed = parseExecutableHeader(bytes, "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toMatchObject({
architecture: "mips",
mips: { elfClass: 64, byteOrder: "big", flags: 0x80000001 },
});
});
it("retains a PSP declaration without claiming Allegrex provider support", () => {
const bytes = header(true);
bytes.writeUInt32LE(0x10a23001, 36);
const parsed = parseExecutableHeader(bytes, "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toMatchObject({
architecture: "mips",
mips: { flags: 0x10a23001 },
});
});
it("rejects a truncated header before reading flags", () => {
const parsed = parseExecutableHeader(header(true).subarray(0, 39), "x64");
expect(parsed).toEqual({
ok: false,
error:
"truncated ELF header: an ELF32 header needs 52 bytes; the file has 39",
});
});
it("does not turn invalid byte order into little-endian MIPS", () => {
const bytes = header(true);
bytes[5] = 0;
expect(parseExecutableHeader(bytes, "x64")).toEqual({
ok: false,
error: "unsupported ELF endianness",
});
});
});
+43 -8
View File
@@ -1,18 +1,33 @@
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
import type {
BinaryArchitecture,
MipsElfMetadata,
} from "./binaryTargetTypes.js";
import { err, ok, type Result } from "./result.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "./dosMz.js";
/** Format and architecture facts recovered from an executable header. */
export type ExecutableMetadata =
| {
readonly format: "elf";
readonly architecture: "mips";
readonly availableArchitectures: readonly "mips"[];
readonly mips: MipsElfMetadata;
}
| {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly architecture: BinaryArchitecture;
readonly availableArchitectures: readonly BinaryArchitecture[];
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
}
| {
readonly format: "pe";
readonly architecture: BinaryArchitecture;
readonly availableArchitectures: readonly BinaryArchitecture[];
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
readonly executableRole:
| "application"
| "shared-library"
@@ -88,7 +103,7 @@ const parseFatMachO = (
const entrySize = is64 ? 32 : 20;
if (count === 0 || count > 128 || bytes.length < 8 + count * entrySize)
return err("truncated or invalid FAT architecture table");
const architectures: BinaryArchitecture[] = [];
const architectures: Exclude<BinaryArchitecture, "mips">[] = [];
const sliceEnds = new Map<BinaryArchitecture, bigint>();
for (let index = 0; index < count; index += 1) {
const entry = 8 + index * entrySize;
@@ -148,6 +163,20 @@ const parseElf = (
const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18);
const architecture = elfArchitecture(machine);
if (architecture === undefined) return err("unsupported ELF architecture");
if (architecture === "mips")
return ok({
format: "elf",
architecture,
availableArchitectures: [architecture],
mips: {
elfClass: bytes[4] === 1 ? 32 : 64,
byteOrder: little ? "little" : "big",
type: little ? bytes.readUInt16LE(16) : bytes.readUInt16BE(16),
flags: little
? bytes.readUInt32LE(bytes[4] === 1 ? 36 : 48)
: bytes.readUInt32BE(bytes[4] === 1 ? 36 : 48),
},
});
return ok({
format: "elf",
architecture,
@@ -239,7 +268,9 @@ const peManagedStatus = (
);
};
const machArchitecture = (cpu: number): BinaryArchitecture | undefined => {
const machArchitecture = (
cpu: number,
): Exclude<BinaryArchitecture, "mips"> | undefined => {
switch (cpu) {
case 7:
return "x86";
@@ -259,6 +290,8 @@ const elfArchitecture = (machine: number): BinaryArchitecture | undefined => {
return "x86";
case 62:
return "x86_64";
case 8: // EM_MIPS: ISA, ABI and byte order remain separate ELF facts.
return "mips";
case 40:
return "arm";
case 183:
@@ -267,7 +300,9 @@ const elfArchitecture = (machine: number): BinaryArchitecture | undefined => {
return undefined;
};
const peArchitecture = (machine: number): BinaryArchitecture | undefined => {
const peArchitecture = (
machine: number,
): Exclude<BinaryArchitecture, "mips"> | undefined => {
switch (machine) {
case 0x14c:
return "x86";
+47 -3
View File
@@ -1,5 +1,37 @@
/** Provider-neutral CPU families detected from supported executable headers. */
export type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
export const BINARY_ARCHITECTURES = [
"x86",
"x86_64",
"arm",
"arm64",
"mips",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
/** Raw ELF facts; family recognition does not establish ISA or ABI support. */
export interface MipsElfMetadata {
readonly elfClass: 32 | 64;
readonly byteOrder: "little" | "big";
readonly type: number;
readonly flags: number;
/** Undefined until inspected; null means neither typed table has a record. */
readonly abiFlags?: MipsAbiFlags | null;
}
/** Declared fields of the 24-byte MIPS ABI flags record, not inferred semantics. */
export interface MipsAbiFlags {
readonly version: number;
readonly isaLevel: number;
readonly isaRevision: number;
readonly gprSize: number;
readonly cpr1Size: number;
readonly cpr2Size: number;
readonly fpAbi: number;
readonly isaExtension: number;
readonly ases: number;
readonly flags1: number;
readonly flags2: number;
}
interface BinaryTargetIdentity {
readonly path: string;
@@ -18,8 +50,11 @@ type NonExecutableMetadata = {
type ExecutableTarget = BinaryTargetIdentity & {
readonly kind: "executable";
readonly architecture: BinaryArchitecture;
readonly availableArchitectures: readonly BinaryArchitecture[];
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
"mips"
>[];
};
/**
@@ -27,6 +62,15 @@ type ExecutableTarget = BinaryTargetIdentity & {
* Each variant carries only metadata established for that exact file kind.
*/
export type BinaryTarget =
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "elf";
readonly architecture: "mips";
readonly availableArchitectures: readonly "mips"[];
readonly mips: MipsElfMetadata;
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly executableRole?: never;
+7 -3
View File
@@ -7,7 +7,11 @@ import {
analysisProfileSchema,
type AnalysisProfileCommitment,
} from "./analysisProfile.js";
import type { BinaryTarget } from "./binaryTargetTypes.js";
import {
BINARY_ARCHITECTURES,
type BinaryArchitecture,
type BinaryTarget,
} from "./binaryTargetTypes.js";
import {
jsonObjectSchema,
jsonValueSchema,
@@ -57,7 +61,7 @@ const subjectSchema = z.object({
"javascript-bundle",
"entitlements",
]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
local_path: z.string(),
});
/** Source location attached to an evidence observation. */
@@ -171,7 +175,7 @@ export interface EvidenceSubjectTarget {
readonly path: string;
readonly sha256: string;
readonly format: z.infer<typeof subjectSchema>["format"];
readonly architecture?: "x86" | "x86_64" | "arm" | "arm64";
readonly architecture?: BinaryArchitecture;
}
type EvidenceAuthority = z.infer<typeof evidenceAuthoritySchema>;
type ExecutionEnvironment = z.infer<typeof executionEnvironmentSchema>;
+20 -1
View File
@@ -4,11 +4,18 @@ import type {
} from "../application/AnalysisProvider.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
import {
ghidraMipsProfileParameters,
ghidraMipsUnsupportedReason,
} from "./GhidraMipsProfile.js";
/** Resolve version-bound, deterministic semantics before Ghidra imports a target. */
export const resolveGhidraAnalysisProfile = (
@@ -25,6 +32,17 @@ export const resolveGhidraAnalysisProfile = (
return Promise.resolve(
err(new ProviderAdapterError(identity.id, "resolve_analysis_profile")),
);
const mipsReason = ghidraMipsUnsupportedReason(target);
if (mipsReason !== null)
return Promise.resolve(
err(
new AnalysisUnsupportedTargetError(
"resolve_analysis_profile",
target.path,
mipsReason,
),
),
);
const provider = { ...identity, version: installation.providerVersion };
const dosMz = target.format === "dos-mz";
const dosCom = target.format === "dos-com";
@@ -90,6 +108,7 @@ export const resolveGhidraAnalysisProfile = (
}
: {}),
analyzer_preset: "ghidra-default",
...ghidraMipsProfileParameters(target),
}),
}),
);
+13
View File
@@ -569,6 +569,19 @@ describe("Ghidra FAT native decompiler admission", () => {
describe("Ghidra native decompiler admission", () => {
it.each([
{
name: "a MIPS decompiler at the Linux x64 path",
options: {
environment: {},
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
executableHeader: (path: string) =>
path === LINUX_DECOMPILER
? { bytes: elf(1, 1, 8), size: 52 }
: undefined,
},
{
name: "a Linux x86-64 decompiler at the macOS arm64 path",
options: {
+3 -1
View File
@@ -116,7 +116,9 @@ const assessNativeDecompiler = (
const alternative = parseExecutableHeader(probe.bytes, node, probe.size);
if (
alternative.ok &&
!alternative.value.availableArchitectures.includes(expectedArchitecture)
!alternative.value.availableArchitectures.some(
(available) => available === expectedArchitecture,
)
) {
parsed = alternative;
break;
+142
View File
@@ -0,0 +1,142 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../config/parseConfig.js";
import type {
BinaryTarget,
MipsElfMetadata,
} from "../domain/binaryTargetTypes.js";
import { silentLogger } from "../logger.js";
import { HopperProvider } from "../hopper/HopperProvider.js";
import { hopperLoaderArgsForTarget } from "../hopper/HopperAnalysisProfile.js";
import { IdaProvider } from "../ida/IdaProvider.js";
import { GhidraProvider } from "./GhidraProvider.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
// Fake installation inspection tests admission/profile contracts, not Ghidra.
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/jdk-21",
bits: 64,
runtime: "jdk",
}),
};
const parsed = parseConfig({ GHIDRA_INSTALL_DIR: "/ghidra" });
if (!parsed.ok) throw parsed.error;
const config = parsed.value;
const target = (change: Partial<MipsElfMetadata> = {}): BinaryTarget => ({
path: "/fixture.elf",
sha256: "a".repeat(64),
kind: "executable",
format: "elf",
architecture: "mips",
availableArchitectures: ["mips"],
mips: {
elfClass: 32,
byteOrder: "little",
type: 2,
flags: 0x70001001,
abiFlags: {
version: 0,
isaLevel: 32,
isaRevision: 2,
gprSize: 1,
cpr1Size: 1,
cpr2Size: 0,
fpAbi: 5,
isaExtension: 0,
ases: 0,
flags1: 0,
flags2: 0,
},
...change,
},
});
describe("bounded Ghidra MIPS admission", () => {
it("binds endian and flags without widening Windows P0", async () => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const little = target();
const big = target({ byteOrder: "big" });
expect(ghidra.inspectTargetSupport(little).status).toBe("supported");
expect(ghidra.inspectTargetSupport(big).status).toBe("supported");
const left = await ghidra.resolveAnalysisProfile(little);
const right = await ghidra.resolveAnalysisProfile(big);
if (!left.ok) throw left.error;
if (!right.ok) throw right.error;
expect(left.value.profile?.parameters.mips_elf).toEqual({
elf_class: 32,
byte_order: "little",
type: 2,
flags: 0x70001001,
abi_flags: {
version: 0,
isa_level: 32,
isa_revision: 2,
gpr_size: 1,
cpr1_size: 1,
cpr2_size: 0,
fp_abi: 5,
isa_extension: 0,
ases: 0,
flags1: 0,
flags2: 0,
},
});
expect(left.value.profile?.digest).not.toBe(right.value.profile?.digest);
const windows = new GhidraProvider(
config,
silentLogger,
{},
{
...host,
platform: "win32",
},
);
expect(windows.inspectTargetSupport(little).status).toBe("unsupported");
});
it.each([
[{ elfClass: 64 }, "ELF32"],
[{ type: 1 }, "ET_EXEC"],
[{ type: 3 }, "ET_EXEC"],
[{ type: 0xffa0 }, "ET_EXEC"],
[{ flags: 0x10a23001 }, "Machine-specific"],
[{ flags: 0x70001021 }, "o32"],
[{ flags: 0x70000001 }, "o32"],
[{ flags: 0x70002001 }, "o32"],
[{ flags: 0x70003001 }, "o32"],
[{ flags: 0x70004001 }, "o32"],
[{ flags: 0x72001001 }, "ASE"],
[{ flags: 0x74001001 }, "ASE"],
[{ flags: 0x70911001 }, "Machine-specific"],
[{ flags: 0x60001001 }, "32R2"],
[{ flags: 0x70001201 }, "EF_MIPS_FP64"],
[{ flags: 0x70001401 }, "EF_MIPS_NAN2008"],
[{ abiFlags: null }, "inspected ABI"],
] satisfies [Partial<MipsElfMetadata>, string][])(
"refuses an unverified MIPS interpretation %j",
async (change, reason) => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const value = target(change);
expect(ghidra.inspectTargetSupport(value)).toMatchObject({
status: "unsupported",
reason: expect.stringContaining(reason),
});
const resolved = await ghidra.resolveAnalysisProfile(value);
expect(resolved.ok).toBe(false);
},
);
it("keeps MIPS out of unverified Hopper and IDA adapter lanes", () => {
const hopper = new HopperProvider(config, silentLogger, {}, "linux");
expect(hopper.inspectTargetSupport(target()).status).toBe("unsupported");
expect(hopperLoaderArgsForTarget(target()).ok).toBe(false);
const ida = new IdaProvider(config, {});
expect(ida.inspectTargetSupport(target()).status).toBe("unsupported");
});
});
+86
View File
@@ -0,0 +1,86 @@
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
/** Keep family recognition separate from the deliberately bounded Ghidra lane. */
export const ghidraMipsUnsupportedReason = (
target: BinaryTarget,
): string | null => {
if (target.kind !== "executable" || target.architecture !== "mips")
return null;
const metadata = target.mips;
if (target.format !== "elf" || metadata === undefined)
return "MIPS analysis requires ELF header metadata; a family name alone does not select an ISA or ABI.";
if (metadata.elfClass !== 32)
return "This Ghidra MIPS lane supports ELF32 only; MIPS64 and n64 remain unsupported.";
if (metadata.type !== 2)
return "This Ghidra MIPS lane supports ET_EXEC only; relocatable objects, shared images and PSP PRX need separate load verification.";
if ((metadata.flags & 0x0f000000) !== 0)
return "MIPS16, microMIPS and other ASE encodings are outside this standard-instruction MIPS lane.";
if ((metadata.flags & 0x00ff0000) !== 0)
return "Machine-specific MIPS variants, including PSP Allegrex, need a separately supported processor profile.";
if ((metadata.flags & 0xf0000000) !== 0x70000000)
return "This Ghidra MIPS lane requires EF_MIPS_ARCH_32R2; other ISA revisions need separate verification.";
if (
(metadata.flags & 0x0000f000) !== 0x00001000 ||
(metadata.flags & 0x20) !== 0
)
return "This Ghidra MIPS lane requires an explicit o32 ABI; unspecified, n32 and EABI targets remain unsupported.";
if ((metadata.flags & 0x00000200) !== 0)
return "EF_MIPS_FP64 requires separate verification of 64-bit floating-point register semantics in this Ghidra lane.";
if ((metadata.flags & 0x00000400) !== 0)
return "EF_MIPS_NAN2008 requires separate verification of NaN encoding semantics in this Ghidra lane.";
const abi = metadata.abiFlags;
if (abi === undefined || abi === null)
return "This Ghidra MIPS lane requires an inspected ABI flags record; header flags alone do not establish the floating-point ABI.";
if (abi.version !== 0)
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.isaExtension !== 0 || abi.ases !== 0)
return "MIPS ABI flags declare an ISA extension or ASE outside this standard-instruction lane.";
if ((abi.flags1 & ~1) !== 0 || abi.flags2 !== 0)
return "MIPS ABI flags contain unsupported general flags.";
return null;
};
/** Commit source ELF interpretation without confusing target ISA with host CPU. */
export const ghidraMipsProfileParameters = (
target: BinaryTarget,
): Readonly<Record<string, JsonValue>> => {
if (
target.kind !== "executable" ||
target.architecture !== "mips" ||
target.mips === undefined
)
return {};
const abi = target.mips.abiFlags;
return {
mips_elf: {
elf_class: target.mips.elfClass,
byte_order: target.mips.byteOrder,
type: target.mips.type,
flags: target.mips.flags,
abi_flags:
abi === undefined || abi === null
? null
: {
version: abi.version,
isa_level: abi.isaLevel,
isa_revision: abi.isaRevision,
gpr_size: abi.gprSize,
cpr1_size: abi.cpr1Size,
cpr2_size: abi.cpr2Size,
fp_abi: abi.fpAbi,
isa_extension: abi.isaExtension,
ases: abi.ases,
flags1: abi.flags1,
flags2: abi.flags2,
},
},
mips_support_lane: "elf32-exec-o32-arch32r2-standard-v3",
};
};
+2 -2
View File
@@ -752,7 +752,7 @@ const sessionInfo = () => ({
const executableTarget = (
format: "mach-o" | "elf" | "pe",
architecture: NonNullable<BinaryTarget["architecture"]>,
architecture: Extract<BinaryTarget, { format: "pe" }>["architecture"],
): BinaryTarget =>
format === "pe"
? peTarget(architecture)
@@ -766,7 +766,7 @@ const executableTarget = (
};
const peTarget = (
architecture: NonNullable<BinaryTarget["architecture"]>,
architecture: Extract<BinaryTarget, { format: "pe" }>["architecture"],
): Extract<BinaryTarget, { format: "pe" }> => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
+17 -2
View File
@@ -30,6 +30,7 @@ import {
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
import { ghidraMipsUnsupportedReason } from "./GhidraMipsProfile.js";
import { resolveGhidraExtensions } from "./extensions/GhidraExtensions.js";
import {
CAPABILITIES,
@@ -47,7 +48,13 @@ import {
windowsNativeCapabilities,
} from "../process/WindowsAuthority.js";
const SUPPORTED_ARCHITECTURES = new Set(["x86", "x86_64", "arm", "arm64"]);
const SUPPORTED_ARCHITECTURES = new Set([
"x86",
"x86_64",
"arm",
"arm64",
"mips",
]);
/** Ghidra candidate backed by an isolated ephemeral headless import. */
export class GhidraProvider implements AnalysisProviderCandidate {
@@ -135,6 +142,14 @@ export class GhidraProvider implements AnalysisProviderCandidate {
};
if (hostPlatform === "win32")
return inspectWindowsP0TargetSupport(target, diagnostics);
const mipsReason = ghidraMipsUnsupportedReason(target);
if (mipsReason !== null)
return {
status: "unsupported",
code: "architecture_unsupported",
reason: mipsReason,
diagnostics,
};
if (target.format === "mach-o" && target.availableArchitectures.length > 1)
return {
status: "unsupported",
@@ -148,7 +163,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
status: "unsupported",
code: "architecture_unsupported",
reason:
"Ghidra v1 requires a concrete x86, x86_64, arm, or arm64 target architecture.",
"Ghidra v1 requires a supported x86, x86_64, arm, arm64, or MIPS target profile.",
diagnostics,
};
return {
+11 -1
View File
@@ -110,6 +110,14 @@ export const hopperLoaderArgsForTarget = (
if (target.kind !== "executable")
return err(new ProviderAdapterError("hopper", "resolve_analysis_profile"));
const architecture = target.architecture;
if (architecture === "mips")
return err(
new AnalysisCapabilityUnavailableError(
"hopper",
"resolve_analysis_profile",
"REA's Hopper adapter does not admit MIPS targets. Select a verified Ghidra MIPS profile instead.",
),
);
const flag = hopperArchitectureFlag(architecture);
switch (target.format) {
case "mach-o":
@@ -138,7 +146,9 @@ export const hopperLoaderArgsForTarget = (
}
};
const hopperArchitectureFlag = (architecture: BinaryArchitecture): string => {
const hopperArchitectureFlag = (
architecture: Exclude<BinaryArchitecture, "mips">,
): string => {
switch (architecture) {
case "x86":
return "--intel-32";
+22
View File
@@ -35,3 +35,25 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
}
},
);
it("rejects an ELF target before attempting FAT64 source preparation", async () => {
const directory = await createTestTempDirectory("rea-hopper-mips-boundary-");
// No file is created: format validation must precede any filesystem lookup.
const path = join(directory, "mips.elf");
const result = await resolveHopperMachOImage({
path,
sha256: "0".repeat(64),
kind: "executable",
format: "elf",
architecture: "mips",
availableArchitectures: ["mips"],
mips: { elfClass: 32, byteOrder: "little", type: 2, flags: 0x70001001 },
});
if (result.ok)
throw new Error("An ELF target entered Mach-O image preparation");
expect(result.error).toMatchObject({
_tag: "BinaryTargetError",
path,
reason: "Hopper FAT64 image preparation requires a Mach-O target",
});
});
+2
View File
@@ -44,6 +44,8 @@ export const resolveHopperMachOImage = async (
),
);
if (signal?.aborted) return err(new AnalysisCancelledError("open_binary"));
if (target.format !== "mach-o")
return invalid("Hopper FAT64 image preparation requires a Mach-O target");
let file: FileHandle;
try {
file = await open(target.path, "r");
+7
View File
@@ -116,6 +116,13 @@ export class HopperProvider implements AnalysisProviderCandidate {
reason: null,
diagnostics,
};
if (target.architecture === "mips")
return {
status: "unsupported",
code: "architecture_unsupported",
reason: "REA's Hopper adapter does not admit MIPS targets.",
diagnostics,
};
if (target.format === "dos-mz" || target.format === "dos-com")
return {
status: "unsupported",
+8
View File
@@ -101,6 +101,14 @@ export class IdaProvider implements AnalysisProviderCandidate {
target_kind: target.kind,
target_format: target.format,
};
if (target.kind === "executable" && target.architecture === "mips")
return {
status: "unsupported",
code: "architecture_unsupported",
reason:
"REA's IDA adapter has no verified MIPS lane. Select a supported Ghidra profile instead.",
diagnostics,
};
return target.kind === "executable"
? { status: "supported", code: null, reason: null, diagnostics }
: {