feat(ghidra): admit verified MIPS16 shared ELF images
Admit the verified ELF32 o32 MIPS32r2 MIPS16 shared-image profile after complete source load and relocation inspection. Preserve caller-selected bytes, pin the endian-matched language, and report per-address decoder context. Refuse unverified relocation shapes with explicit reasons. Verified on Linux x64 with Ghidra 12.1.4: eight source-owned public CLI/MCP controls, original-artifact instruction/pseudocode/export replay, snapshot restore and owned cleanup. 152 integrated focused tests, static checks and documentation checks passed. Fixes #1851 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
parent
6395e8d300
commit
e9fe6437a7
@@ -17,7 +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 { readMipsElfMetadata } from "./MipsElfMetadata.js";
|
||||
import {
|
||||
resolveAppBundleExecutable,
|
||||
type ResolvedAppBundle,
|
||||
@@ -430,18 +430,23 @@ const readExecutableMetadata = async (
|
||||
parsed.value.mips.elfClass !== 32
|
||||
)
|
||||
return parsed;
|
||||
const abiFlags = await readMipsElfAbiFlags(handle, parsed.value.mips, () =>
|
||||
throwIfTargetResolutionCancelled(signal),
|
||||
const declarations = await readMipsElfMetadata(
|
||||
handle,
|
||||
parsed.value.mips,
|
||||
() => throwIfTargetResolutionCancelled(signal),
|
||||
);
|
||||
if (!abiFlags.ok) return abiFlags;
|
||||
if (!declarations.ok) return declarations;
|
||||
return ok({
|
||||
...parsed.value,
|
||||
mips: {
|
||||
...parsed.value.mips,
|
||||
abiFlags: abiFlags.value.abiFlags,
|
||||
...(abiFlags.value.limitations.length === 0
|
||||
abiFlags: declarations.value.abiFlags,
|
||||
...(declarations.value.sharedLoad === undefined
|
||||
? {}
|
||||
: { limitations: abiFlags.value.limitations }),
|
||||
: { sharedLoad: declarations.value.sharedLoad }),
|
||||
...(declarations.value.limitations.length === 0
|
||||
? {}
|
||||
: { limitations: declarations.value.limitations }),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -4,24 +4,29 @@ import type {
|
||||
MipsElfMetadata,
|
||||
} from "../domain/binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
readMipsElfSharedLoad,
|
||||
type MipsElfRelocationSection,
|
||||
} from "./MipsElfSharedLoad.js";
|
||||
|
||||
/** Observed ABI declarations and coverage of their source tables. */
|
||||
export interface MipsAbiFlagsInspection {
|
||||
/** Observed ABI and load declarations, retaining unavailable source coverage. */
|
||||
export interface MipsElfInspection {
|
||||
readonly abiFlags: MipsAbiFlags | null;
|
||||
readonly limitations: readonly string[];
|
||||
readonly sharedLoad?: MipsElfMetadata["sharedLoad"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read ELF32 MIPS ABI declarations from the caller's already-open file.
|
||||
* Read ELF32 MIPS ABI and shared-load 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 (
|
||||
export const readMipsElfMetadata = async (
|
||||
handle: FileHandle,
|
||||
metadata: MipsElfMetadata,
|
||||
checkCancelled: () => void,
|
||||
): Promise<Result<MipsAbiFlagsInspection, string>> => {
|
||||
): Promise<Result<MipsElfInspection, string>> => {
|
||||
checkCancelled();
|
||||
if (metadata.elfClass !== 32)
|
||||
return err("MIPS ABI record inspection currently supports ELF32 only");
|
||||
@@ -107,6 +112,9 @@ export const readMipsElfAbiFlags = async (
|
||||
if (u16(bytes, 44) === 0xffff || u16(bytes, 48) >= 0xff00)
|
||||
return err("extended or reserved MIPS ELF table numbering is unsupported");
|
||||
let record: Buffer | undefined;
|
||||
let sharedLoad: MipsElfMetadata["sharedLoad"];
|
||||
let programHeaders: Buffer | undefined;
|
||||
const relocationSections: MipsElfRelocationSection[] = [];
|
||||
const limitations: string[] = [];
|
||||
for (const table of tables) {
|
||||
if (table.count === 0) {
|
||||
@@ -135,12 +143,20 @@ export const readMipsElfAbiFlags = async (
|
||||
table.label,
|
||||
);
|
||||
if (!contents.ok) return contents;
|
||||
if (!table.optional && metadata.type === 3) programHeaders = contents.value;
|
||||
let found = false;
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
checkCancelled();
|
||||
const position = i * table.entrySize;
|
||||
if (u32(contents.value, position + table.typeOffset) !== table.recordType)
|
||||
continue;
|
||||
const type = u32(contents.value, position + table.typeOffset);
|
||||
if (metadata.type === 3 && table.optional && (type === 4 || type === 9))
|
||||
relocationSections.push({
|
||||
type,
|
||||
offset: u32(contents.value, position + 16),
|
||||
size: u32(contents.value, position + 20),
|
||||
entrySize: u32(contents.value, position + 36),
|
||||
});
|
||||
if (type !== table.recordType) continue;
|
||||
if (found) return err(`duplicate MIPS ABI records in ${table.label}`);
|
||||
found = true;
|
||||
const offset = u32(contents.value, position + table.dataOffset);
|
||||
@@ -154,7 +170,37 @@ export const readMipsElfAbiFlags = async (
|
||||
record = candidate.value;
|
||||
}
|
||||
}
|
||||
if (record === undefined) return ok({ abiFlags: null, limitations });
|
||||
if (metadata.type === 3 && programHeaders !== undefined) {
|
||||
if (limitations.length > 0)
|
||||
sharedLoad = {
|
||||
status: "unavailable",
|
||||
reason: `MIPS shared-image relocation declaration sources are incomplete. ${limitations.join(" ")}`,
|
||||
};
|
||||
else {
|
||||
const shared = await readMipsElfSharedLoad(
|
||||
programHeaders,
|
||||
little,
|
||||
fileSize,
|
||||
read,
|
||||
checkCancelled,
|
||||
relocationSections,
|
||||
);
|
||||
sharedLoad = shared.ok
|
||||
? shared.value
|
||||
: { status: "unavailable", reason: shared.error };
|
||||
}
|
||||
}
|
||||
const shared =
|
||||
metadata.type === 3
|
||||
? {
|
||||
sharedLoad: sharedLoad ?? {
|
||||
status: "unavailable" as const,
|
||||
reason: "MIPS shared image has no inspected program header table",
|
||||
},
|
||||
}
|
||||
: {};
|
||||
if (record === undefined)
|
||||
return ok({ abiFlags: null, limitations, ...shared });
|
||||
// Preserve declarations verbatim, including unknown versions/values. Provider
|
||||
// admission, not parsing, decides which interpretations have been verified.
|
||||
const abiFlags: MipsAbiFlags = {
|
||||
@@ -170,5 +216,5 @@ export const readMipsElfAbiFlags = async (
|
||||
flags1: u32(record, 16),
|
||||
flags2: u32(record, 20),
|
||||
};
|
||||
return ok({ abiFlags, limitations });
|
||||
return ok({ abiFlags, limitations, ...shared });
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
import type { MipsElfMetadata } from "../domain/binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type ReadRange = (
|
||||
offset: number,
|
||||
length: number,
|
||||
label: string,
|
||||
) => Promise<Result<Buffer, string>>;
|
||||
|
||||
export interface MipsElfRelocationSection {
|
||||
readonly type: number;
|
||||
readonly offset: number;
|
||||
readonly size: number;
|
||||
readonly entrySize: number;
|
||||
}
|
||||
type SharedLoadFacts = Extract<
|
||||
NonNullable<MipsElfMetadata["sharedLoad"]>,
|
||||
{ status: "complete" }
|
||||
>;
|
||||
|
||||
/** Source ELF facts only; the provider owns interpretation and admission. */
|
||||
export const readMipsElfSharedLoad = async (
|
||||
programHeaders: Buffer,
|
||||
little: boolean,
|
||||
fileSize: number,
|
||||
read: ReadRange,
|
||||
checkCancelled: () => void,
|
||||
sections: readonly MipsElfRelocationSection[],
|
||||
): Promise<Result<SharedLoadFacts, string>> => {
|
||||
const u32 = (bytes: Buffer, offset: number): number =>
|
||||
little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
|
||||
const loads: {
|
||||
offset: number;
|
||||
address: number;
|
||||
size: number;
|
||||
memorySize: number;
|
||||
}[] = [];
|
||||
let dynamic: { offset: number; address: number; size: number } | undefined;
|
||||
for (let position = 0; position < programHeaders.length; position += 32) {
|
||||
checkCancelled();
|
||||
const type = u32(programHeaders, position);
|
||||
const offset = u32(programHeaders, position + 4);
|
||||
const size = u32(programHeaders, position + 16);
|
||||
if (type === 1) {
|
||||
const address = u32(programHeaders, position + 8);
|
||||
const memorySize = u32(programHeaders, position + 20);
|
||||
if (
|
||||
offset > fileSize - size ||
|
||||
size > memorySize ||
|
||||
address + memorySize > 0x100000000
|
||||
)
|
||||
return err("invalid or incomplete MIPS PT_LOAD range");
|
||||
loads.push({ offset, address, size, memorySize });
|
||||
}
|
||||
if (type === 2) {
|
||||
if (dynamic !== undefined) return err("duplicate MIPS PT_DYNAMIC tables");
|
||||
dynamic = { offset, address: u32(programHeaders, position + 8), size };
|
||||
}
|
||||
}
|
||||
if (dynamic === undefined)
|
||||
return err("MIPS shared image has no PT_DYNAMIC table");
|
||||
if (dynamic.size === 0 || dynamic.size % 8 !== 0)
|
||||
return err("invalid MIPS ELF32 dynamic table size");
|
||||
if (dynamic.offset > fileSize - dynamic.size)
|
||||
return err("MIPS PT_DYNAMIC range extends beyond the file");
|
||||
const ranges = loads
|
||||
.filter((load) => load.memorySize > 0)
|
||||
.sort((left, right) => left.address - right.address);
|
||||
for (let i = 1; i < ranges.length; i += 1) {
|
||||
checkCancelled();
|
||||
const previous = ranges[i - 1]!;
|
||||
if (ranges[i]!.address < previous.address + previous.memorySize)
|
||||
return err(
|
||||
"overlapping MIPS PT_LOAD memory ranges require separate mapping verification",
|
||||
);
|
||||
}
|
||||
// One normalized index prevents relocation count * program-header count work.
|
||||
const mapped = (address: number, length: number, fileBacked: boolean) => {
|
||||
let low = 0;
|
||||
let high = ranges.length;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
if (ranges[middle]!.address <= address) low = middle + 1;
|
||||
else high = middle;
|
||||
}
|
||||
const range = ranges[low - 1];
|
||||
return range !== undefined &&
|
||||
address - range.address <=
|
||||
(fileBacked ? range.size : range.memorySize) - length
|
||||
? range
|
||||
: undefined;
|
||||
};
|
||||
const dynamicMapping = mapped(dynamic.address, dynamic.size, true);
|
||||
if (
|
||||
dynamicMapping === undefined ||
|
||||
dynamicMapping.offset + dynamic.address - dynamicMapping.address !==
|
||||
dynamic.offset
|
||||
)
|
||||
return err(
|
||||
"MIPS PT_DYNAMIC has no unique matching file-backed PT_LOAD range",
|
||||
);
|
||||
|
||||
// Bound temporary storage, not admitted artifact size. ELF32 records are
|
||||
// exact eight-byte structures; every declared record is examined or refused.
|
||||
const chunkBytes = 64 * 1024;
|
||||
const relevant = new Set([2, 7, 8, 9, 17, 18, 19, 20, 23]);
|
||||
const tags = new Map<number, number>();
|
||||
let terminated = false;
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < dynamic.size && !terminated;
|
||||
offset += chunkBytes
|
||||
) {
|
||||
const chunk = await read(
|
||||
dynamic.offset + offset,
|
||||
Math.min(chunkBytes, dynamic.size - offset),
|
||||
"dynamic table",
|
||||
);
|
||||
if (!chunk.ok) return chunk;
|
||||
for (let position = 0; position < chunk.value.length; position += 8) {
|
||||
checkCancelled();
|
||||
const tag = u32(chunk.value, position);
|
||||
if (tag === 0) {
|
||||
terminated = true;
|
||||
break;
|
||||
}
|
||||
if (!relevant.has(tag)) continue;
|
||||
if (tags.has(tag)) return err(`duplicate MIPS dynamic tag ${tag}`);
|
||||
tags.set(tag, u32(chunk.value, position + 4));
|
||||
}
|
||||
}
|
||||
if (!terminated) return err("MIPS dynamic table has no DT_NULL terminator");
|
||||
if ([2, 7, 8, 9, 23].some((tag) => (tags.get(tag) ?? 0) !== 0))
|
||||
return err(
|
||||
"MIPS shared RELA or PLT relocation declarations require separate verification",
|
||||
);
|
||||
const address = tags.get(17);
|
||||
const size = tags.get(18);
|
||||
const stride = tags.get(19);
|
||||
const checkSections = (
|
||||
offset: number,
|
||||
length: number,
|
||||
): string | undefined => {
|
||||
let observed = 0;
|
||||
for (const section of sections) {
|
||||
checkCancelled();
|
||||
if (section.size === 0) continue;
|
||||
if (
|
||||
section.type !== 9 ||
|
||||
section.entrySize !== 8 ||
|
||||
section.offset !== offset ||
|
||||
section.size !== length
|
||||
)
|
||||
return "MIPS section relocation declarations outside the dynamic REL table require separate verification";
|
||||
observed += 1;
|
||||
}
|
||||
return observed > 1
|
||||
? "duplicate MIPS section relocation declarations require separate verification"
|
||||
: undefined;
|
||||
};
|
||||
const emptyRelocations = (): Result<SharedLoadFacts, string> => {
|
||||
const reason = checkSections(0, 0);
|
||||
return reason === undefined
|
||||
? ok({
|
||||
status: "complete",
|
||||
relocationCount: 0,
|
||||
relocationTypes: [],
|
||||
symbolRelativeCount: 0,
|
||||
})
|
||||
: err(reason);
|
||||
};
|
||||
if (address === undefined && size === undefined && stride === undefined)
|
||||
return emptyRelocations();
|
||||
if (
|
||||
address === undefined ||
|
||||
size === undefined ||
|
||||
stride !== 8 ||
|
||||
size % 8 !== 0
|
||||
)
|
||||
return err(
|
||||
"incomplete or invalid MIPS DT_REL/DT_RELSZ/DT_RELENT declaration",
|
||||
);
|
||||
if (size === 0) return emptyRelocations();
|
||||
const mapping = mapped(address, size, true);
|
||||
if (mapping === undefined)
|
||||
return err(
|
||||
"MIPS DT_REL range has no unique complete file-backed PT_LOAD mapping",
|
||||
);
|
||||
const fileOffset = mapping.offset + address - mapping.address;
|
||||
const sectionReason = checkSections(fileOffset, size);
|
||||
if (sectionReason !== undefined) return err(sectionReason);
|
||||
let symbolRelativeCount = 0;
|
||||
const types = new Set<number>();
|
||||
for (let offset = 0; offset < size; offset += chunkBytes) {
|
||||
const chunk = await read(
|
||||
fileOffset + offset,
|
||||
Math.min(chunkBytes, size - offset),
|
||||
"dynamic REL records",
|
||||
);
|
||||
if (!chunk.ok) return chunk;
|
||||
for (let position = 0; position < chunk.value.length; position += 8) {
|
||||
checkCancelled();
|
||||
const info = u32(chunk.value, position + 4);
|
||||
const type = info & 0xff;
|
||||
const relocationAddress = u32(chunk.value, position);
|
||||
if (type === 3 && mapped(relocationAddress, 4, false) === undefined)
|
||||
return err(
|
||||
"MIPS REL32 destination has no unique complete PT_LOAD memory range",
|
||||
);
|
||||
types.add(type);
|
||||
if (type === 3 && info >>> 8 !== 0) symbolRelativeCount += 1;
|
||||
}
|
||||
}
|
||||
return ok({
|
||||
status: "complete",
|
||||
relocationCount: size / 8,
|
||||
relocationTypes: [...types].sort((left, right) => left - right),
|
||||
symbolRelativeCount,
|
||||
});
|
||||
};
|
||||
@@ -18,6 +18,15 @@ export interface MipsElfMetadata {
|
||||
readonly abiFlags?: MipsAbiFlags | null;
|
||||
/** Unavailable declaration sources; missing records there remain unknown. */
|
||||
readonly limitations?: readonly string[];
|
||||
/** Complete dynamic REL declarations, or the reason they could not be inspected. */
|
||||
readonly sharedLoad?:
|
||||
| {
|
||||
readonly status: "complete";
|
||||
readonly relocationCount: number;
|
||||
readonly relocationTypes: readonly number[];
|
||||
readonly symbolRelativeCount: number;
|
||||
}
|
||||
| { readonly status: "unavailable"; readonly reason: string };
|
||||
}
|
||||
|
||||
/** Declared fields of the 24-byte MIPS ABI flags record, not inferred semantics. */
|
||||
|
||||
@@ -53,7 +53,23 @@ export const nativeInstructionSchema = z.strictObject({
|
||||
]),
|
||||
procedure: z.string().nullable(),
|
||||
architecture: z.string(),
|
||||
mode: z.string(),
|
||||
mode: z
|
||||
.string()
|
||||
.describe(
|
||||
"Provider-reported mode label. Per-address decoder context, when available, is reported separately; a program-wide label does not establish runtime encoding mode.",
|
||||
),
|
||||
decoder_context: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
register: z.string().min(1),
|
||||
value: z.string().min(1).nullable(),
|
||||
source: z.string().min(1),
|
||||
}),
|
||||
)
|
||||
.optional()
|
||||
.describe(
|
||||
"Observed per-address decoder context. Null means no value was available; omission means the provider or older capture does not expose this facet. The separate mode field retains the program language variant.",
|
||||
),
|
||||
bytes: z.string().nullable(),
|
||||
length: z.number().int().positive().nullable(),
|
||||
mnemonic: z.string().nullable(),
|
||||
|
||||
@@ -13,7 +13,10 @@ 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 } from "./GhidraMipsProfile.js";
|
||||
import {
|
||||
ghidraMipsProfileParameters,
|
||||
ghidraMipsSharedLanguageOverride,
|
||||
} from "./GhidraMipsProfile.js";
|
||||
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
|
||||
|
||||
import {
|
||||
@@ -132,6 +135,22 @@ export const resolveGhidraAnalysisProfile = async (
|
||||
const dosMz = target.format === "dos-mz";
|
||||
const dosCom = target.format === "dos-com";
|
||||
const dos = dosMz || dosCom;
|
||||
const mipsLanguage = ghidraMipsSharedLanguageOverride(target);
|
||||
if (
|
||||
mipsLanguage !== undefined &&
|
||||
languageOverride !== undefined &&
|
||||
(languageOverride.languageId !== mipsLanguage.languageId ||
|
||||
(languageOverride.compilerSpecId !== undefined &&
|
||||
languageOverride.compilerSpecId !== mipsLanguage.compilerSpecId))
|
||||
)
|
||||
return err(
|
||||
new AnalysisUnsupportedTargetError(
|
||||
"resolve_analysis_profile",
|
||||
target.path,
|
||||
"The caller-selected processor or compiler specification is outside the verified endian-matched MIPS32 shared-image profile. The requested override has not been changed.",
|
||||
),
|
||||
);
|
||||
const selectedLanguage = languageOverride ?? mipsLanguage;
|
||||
// DOS imports already force an admitted loader, language, and context.
|
||||
if (dos && languageOverride !== undefined)
|
||||
return Promise.resolve(
|
||||
@@ -199,14 +218,16 @@ export const resolveGhidraAnalysisProfile = async (
|
||||
: "auto-from-header",
|
||||
language_id: dos
|
||||
? "x86:LE:16:Real Mode"
|
||||
: (languageOverride?.languageId ?? "auto-from-header"),
|
||||
: (selectedLanguage?.languageId ?? "auto-from-header"),
|
||||
compiler_spec_id: dos
|
||||
? "default"
|
||||
: languageOverride === undefined
|
||||
: selectedLanguage === undefined
|
||||
? "auto-default"
|
||||
: (languageOverride.compilerSpecId ?? "language-default"),
|
||||
: (selectedLanguage.compilerSpecId ?? "language-default"),
|
||||
...(languageOverride === undefined
|
||||
? {}
|
||||
? mipsLanguage === undefined
|
||||
? {}
|
||||
: { language_selection: "provider-pinned-v1" }
|
||||
: { language_selection: "configured-v1" }),
|
||||
...(dos
|
||||
? {
|
||||
@@ -246,7 +267,11 @@ export const resolveGhidraAnalysisProfile = async (
|
||||
export const ghidraProfileLanguageOverride = (
|
||||
parameters: Readonly<Record<string, unknown>>,
|
||||
): GhidraLanguageOverride | undefined => {
|
||||
if (parameters.language_selection !== "configured-v1") return undefined;
|
||||
if (
|
||||
parameters.language_selection !== "configured-v1" &&
|
||||
parameters.language_selection !== "provider-pinned-v1"
|
||||
)
|
||||
return undefined;
|
||||
const languageId = parameters.language_id;
|
||||
const compilerSpecId = parameters.compiler_spec_id;
|
||||
if (typeof languageId !== "string" || typeof compilerSpecId !== "string")
|
||||
|
||||
@@ -13,6 +13,7 @@ import { GhidraProvider } from "./GhidraProvider.js";
|
||||
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
|
||||
import type { GhidraMipsSoftFloatReport } from "./GhidraMipsProfile.js";
|
||||
import { ghidraProfileLanguageOverride } from "./GhidraAnalysisProfile.js";
|
||||
|
||||
// Fake installation inspection tests admission/profile contracts, not Ghidra.
|
||||
const host: GhidraInstallationHost = {
|
||||
@@ -217,6 +218,130 @@ const session = async (
|
||||
};
|
||||
};
|
||||
|
||||
describe("MIPS16 shared-image profile", () => {
|
||||
const shared = (change: Partial<MipsElfMetadata> = {}) =>
|
||||
target({
|
||||
type: 3,
|
||||
flags: 0x74001005,
|
||||
abiFlags: null,
|
||||
sharedLoad: {
|
||||
status: "complete",
|
||||
relocationCount: 14,
|
||||
relocationTypes: [0, 3],
|
||||
symbolRelativeCount: 0,
|
||||
},
|
||||
...change,
|
||||
});
|
||||
it.each(["little", "big"] as const)(
|
||||
"pins a generic 32-bit %s language and retains the source ABI uncertainty",
|
||||
async (byteOrder) => {
|
||||
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
|
||||
const value = shared({ byteOrder });
|
||||
expect(ghidra.inspectTargetSupport(value).status).toBe("supported");
|
||||
const resolved = await ghidra.resolveAnalysisProfile(value);
|
||||
if (!resolved.ok || resolved.value.profile === null)
|
||||
throw new Error("expected shared profile");
|
||||
const parameters = resolved.value.profile.parameters;
|
||||
expect(parameters).toMatchObject({
|
||||
language_id: `MIPS:${byteOrder === "little" ? "LE" : "BE"}:32:default`,
|
||||
compiler_spec_id: "default",
|
||||
language_selection: "provider-pinned-v1",
|
||||
mips_support_lane: "elf32-dyn-o32-arch32r2-mips16-local-rel32-v1",
|
||||
mips_elf: { abi_flags: null },
|
||||
});
|
||||
expect(ghidraProfileLanguageOverride(parameters)).toEqual({
|
||||
languageId: parameters.language_id,
|
||||
compilerSpecId: "default",
|
||||
});
|
||||
},
|
||||
);
|
||||
it("retains shared-image and unknown floating-point limitations on the session", async () => {
|
||||
const { client } = await session(shared(), undefined);
|
||||
const health = await client.execute("health", {});
|
||||
if (!health.ok) throw health.error;
|
||||
expect(health.value.limitations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("External GOT bindings"),
|
||||
expect.stringContaining("does not establish the floating-point ABI"),
|
||||
]),
|
||||
);
|
||||
});
|
||||
it("continues to admit a declared FPXX record only when its MIPS16 ASE agrees", () => {
|
||||
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(shared(abi({ ases: 0x400 }))).status,
|
||||
).toBe("supported");
|
||||
expect(ghidra.inspectTargetSupport(shared(abi({ ases: 0 }))).status).toBe(
|
||||
"unsupported",
|
||||
);
|
||||
});
|
||||
it.each([
|
||||
{ flags: 0x74001045 },
|
||||
{ limitations: ["Unexamined section declarations"] },
|
||||
{
|
||||
sharedLoad: {
|
||||
status: "complete",
|
||||
relocationCount: 1,
|
||||
relocationTypes: [3],
|
||||
symbolRelativeCount: 1,
|
||||
},
|
||||
},
|
||||
] satisfies Partial<MipsElfMetadata>[])(
|
||||
"refuses incomplete or unverified source declarations %j",
|
||||
(change) => {
|
||||
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
|
||||
expect(ghidra.inspectTargetSupport(shared(change)).status).toBe(
|
||||
"unsupported",
|
||||
);
|
||||
},
|
||||
);
|
||||
it.each(["sharedLoad", "abiFlags"] as const)(
|
||||
"refuses an uninspected %s declaration",
|
||||
(declaration) => {
|
||||
const value = shared();
|
||||
if (value.kind !== "executable" || value.architecture !== "mips")
|
||||
throw new Error("expected MIPS target");
|
||||
const facts = { ...value.mips };
|
||||
delete facts[declaration];
|
||||
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({ ...value, mips: facts }),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
reason: expect.stringContaining(
|
||||
declaration === "abiFlags"
|
||||
? "inspected ABI flags"
|
||||
: "have not been inspected",
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
it("refuses an endian pin committed for a different target", async () => {
|
||||
const { counts, client } = await session(
|
||||
shared({ byteOrder: "big" }),
|
||||
undefined,
|
||||
shared(),
|
||||
);
|
||||
const health = await client.execute("health", {});
|
||||
expect(health.ok).toBe(false);
|
||||
expect(counts.starts).toBe(0);
|
||||
});
|
||||
it("rejects a caller-selected global MIPS16 processor without replacing the request", async () => {
|
||||
const parsed = parseConfig({
|
||||
GHIDRA_INSTALL_DIR: "/ghidra",
|
||||
REA_GHIDRA_LANGUAGE_ID: "MIPS:LE:32:16e",
|
||||
});
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const ghidra = new GhidraProvider(parsed.value, silentLogger, {}, host);
|
||||
const resolved = await ghidra.resolveAnalysisProfile(shared());
|
||||
expect(resolved.ok).toBe(false);
|
||||
if (!resolved.ok)
|
||||
expect(resolved.error.message).toContain(
|
||||
"requested override has not been changed",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("soft-float MIPS storage", () => {
|
||||
it("admits soft-float o32 and commits its storage policy only for it", async () => {
|
||||
const soft = target(softFloat);
|
||||
|
||||
@@ -1,9 +1,30 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
|
||||
|
||||
const MIPS_FP_ABI_SOFT = 3;
|
||||
const MIPS_ET_REL = 1;
|
||||
const MIPS_ET_EXEC = 2;
|
||||
const MIPS_ET_DYN = 3;
|
||||
const MIPS16_HEADER_ASE = 0x04000000;
|
||||
|
||||
/** A distinct compressed shared-image shape; admission still checks every declaration. */
|
||||
const isGhidraMips16SharedTarget = (target: BinaryTarget): boolean =>
|
||||
target.kind === "executable" &&
|
||||
target.architecture === "mips" &&
|
||||
target.mips.type === MIPS_ET_DYN &&
|
||||
(target.mips.flags & 0x0f000000) === MIPS16_HEADER_ASE;
|
||||
|
||||
/** Generic MIPS32 permits per-function ISA_MODE; a global 16e processor does not. */
|
||||
export const ghidraMipsSharedLanguageOverride = (
|
||||
target: BinaryTarget,
|
||||
): GhidraLanguageOverride | undefined =>
|
||||
isGhidraMips16SharedTarget(target) && target.architecture === "mips"
|
||||
? {
|
||||
languageId: `MIPS:${target.mips.byteOrder === "little" ? "LE" : "BE"}:32:default`,
|
||||
compilerSpecId: "default",
|
||||
}
|
||||
: undefined;
|
||||
|
||||
/** Keep family recognition separate from the deliberately bounded Ghidra lane. */
|
||||
export const ghidraMipsUnsupportedReason = (
|
||||
@@ -14,11 +35,16 @@ export const ghidraMipsUnsupportedReason = (
|
||||
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.";
|
||||
const shared = isGhidraMips16SharedTarget(target);
|
||||
if (metadata.elfClass !== 32)
|
||||
return "This Ghidra MIPS lane supports ELF32 only; MIPS64 and n64 remain unsupported.";
|
||||
if (metadata.type !== MIPS_ET_EXEC && metadata.type !== MIPS_ET_REL)
|
||||
if (
|
||||
metadata.type !== MIPS_ET_EXEC &&
|
||||
metadata.type !== MIPS_ET_REL &&
|
||||
!shared
|
||||
)
|
||||
return "This Ghidra MIPS lane supports ET_EXEC and ET_REL only; shared images and PSP PRX need separate load verification.";
|
||||
if ((metadata.flags & 0x0f000000) !== 0)
|
||||
if ((metadata.flags & 0x0f000000) !== 0 && !shared)
|
||||
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.";
|
||||
@@ -33,7 +59,20 @@ export const ghidraMipsUnsupportedReason = (
|
||||
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.";
|
||||
if (shared) {
|
||||
if ((metadata.flags & 0x40) !== 0)
|
||||
return "EF_MIPS_ABI_ON32 declares an unverified ABI for the MIPS16 shared-image lane.";
|
||||
const load = metadata.sharedLoad;
|
||||
if (load === undefined || load.status !== "complete")
|
||||
return `MIPS16 shared images require complete dynamic relocation inspection. ${load?.reason ?? "The source declarations have not been inspected."}`;
|
||||
if (load.relocationTypes.some((type) => type !== 0 && type !== 3))
|
||||
return "This MIPS16 shared-image lane verifies R_MIPS_NONE and R_MIPS_REL32 only; other dynamic relocation types require separate verification.";
|
||||
if (load.symbolRelativeCount !== 0)
|
||||
return "Symbol-bearing R_MIPS_REL32 is unsupported: Ghidra normalizes MIPS16 function addresses and can lose the source function-pointer mode tag. Symbol-index-zero REL32 is verified separately.";
|
||||
}
|
||||
const abi = metadata.abiFlags;
|
||||
if (shared && abi === null && (metadata.limitations?.length ?? 0) === 0)
|
||||
return null; // Inspected absence leaves FP semantics unknown, never inferred.
|
||||
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.",
|
||||
@@ -49,8 +88,8 @@ export const ghidraMipsUnsupportedReason = (
|
||||
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.";
|
||||
if (abi.isaExtension !== 0 || abi.ases !== (shared ? 0x400 : 0))
|
||||
return "MIPS ABI flags declare an ISA extension or ASE outside this profile's verified instruction declarations.";
|
||||
// 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.
|
||||
@@ -116,6 +155,22 @@ export const ghidraMipsRelocatableLimitations = (
|
||||
]
|
||||
: [];
|
||||
|
||||
/** Shared-image results are analysis observations, not dynamic-loader execution. */
|
||||
export const ghidraMipsSharedLimitations = (
|
||||
target: BinaryTarget,
|
||||
): readonly string[] =>
|
||||
isGhidraMips16SharedTarget(target) && target.architecture === "mips"
|
||||
? [
|
||||
"MIPS16 shared ELF: the endian-matched generic MIPS32 language uses the provider's per-address ISA_MODE context. The program language variant is not the instruction's encoding mode.",
|
||||
"Shared-image addresses are Ghidra analysis coordinates, not runtime addresses. The source bytes remain unchanged; inspect_native_load_image retains original relocation bytes, loaded memory bytes and provider relocation status. External GOT bindings remain unverified without their defining images.",
|
||||
...(target.mips.abiFlags === null
|
||||
? [
|
||||
"No MIPS ABI flags record was found in the completely examined declaration tables. The header declares o32 but does not establish the floating-point ABI; the default compiler specification does not verify floating-point argument or return storage.",
|
||||
]
|
||||
: []),
|
||||
]
|
||||
: [];
|
||||
|
||||
/** Commit source ELF interpretation without confusing target ISA with host CPU. */
|
||||
export const ghidraMipsProfileParameters = (
|
||||
target: BinaryTarget,
|
||||
@@ -152,12 +207,33 @@ export const ghidraMipsProfileParameters = (
|
||||
flags1: abi.flags1,
|
||||
flags2: abi.flags2,
|
||||
},
|
||||
...(target.mips.sharedLoad === undefined
|
||||
? {}
|
||||
: {
|
||||
shared_load:
|
||||
target.mips.sharedLoad.status === "complete"
|
||||
? {
|
||||
status: "complete",
|
||||
relocation_count: target.mips.sharedLoad.relocationCount,
|
||||
relocation_types: [
|
||||
...target.mips.sharedLoad.relocationTypes,
|
||||
],
|
||||
symbol_relative_count:
|
||||
target.mips.sharedLoad.symbolRelativeCount,
|
||||
}
|
||||
: {
|
||||
status: "unavailable",
|
||||
reason: target.mips.sharedLoad.reason,
|
||||
},
|
||||
}),
|
||||
},
|
||||
...(isGhidraMipsSoftFloatTarget(target)
|
||||
? { mips_soft_float_storage: GHIDRA_MIPS_SOFT_FLOAT_STORAGE }
|
||||
: {}),
|
||||
mips_support_lane:
|
||||
target.mips.type === MIPS_ET_REL
|
||||
instruction_context_evidence: "per-address-isa-mode-v1",
|
||||
mips_support_lane: isGhidraMips16SharedTarget(target)
|
||||
? "elf32-dyn-o32-arch32r2-mips16-local-rel32-v1"
|
||||
: target.mips.type === MIPS_ET_REL
|
||||
? "elf32-rel-o32-arch32r2-standard-v1"
|
||||
: "elf32-exec-o32-arch32r2-standard-v3",
|
||||
};
|
||||
|
||||
@@ -60,6 +60,8 @@ import {
|
||||
GHIDRA_MIPS_SOFT_FLOAT_STORAGE,
|
||||
ghidraMipsSoftFloatFailure,
|
||||
ghidraMipsRelocatableLimitations,
|
||||
ghidraMipsSharedLimitations,
|
||||
ghidraMipsSharedLanguageOverride,
|
||||
ghidraMipsSoftFloatLimitations,
|
||||
isGhidraMipsSoftFloatTarget,
|
||||
} from "./GhidraMipsProfile.js";
|
||||
@@ -444,7 +446,10 @@ export const createGhidraProviderClient = (input: {
|
||||
committedProfile.parameters,
|
||||
);
|
||||
if (
|
||||
!sameGhidraLanguageOverride(languageOverride, config.ghidraLanguageOverride)
|
||||
!sameGhidraLanguageOverride(
|
||||
languageOverride,
|
||||
config.ghidraLanguageOverride ?? ghidraMipsSharedLanguageOverride(target),
|
||||
)
|
||||
)
|
||||
return unavailableClient(
|
||||
new ProviderAdapterError("ghidra", "open_binary", {
|
||||
@@ -512,6 +517,7 @@ export const createGhidraProviderClient = (input: {
|
||||
? (target.mips.limitations ?? [])
|
||||
: []),
|
||||
...ghidraMipsRelocatableLimitations(target),
|
||||
...ghidraMipsSharedLimitations(target),
|
||||
];
|
||||
const providerLimitations =
|
||||
installation.platform === "win32"
|
||||
|
||||
Reference in New Issue
Block a user