diff --git a/docs/providers/ghidra-mips.md b/docs/providers/ghidra-mips.md index 4af2e59e3bc..978e1256922 100644 --- a/docs/providers/ghidra-mips.md +++ b/docs/providers/ghidra-mips.md @@ -40,18 +40,25 @@ pin; combining the pinned profile with an environment override is a typed refusal. A header that declares an ABI field but carries no record is still refused. Two further boundaries apply: an inspection that could not examine every ABI declaration source does not establish the recordless admission -(target opening already refuses a carved ELF whose section table extends past -the captured bytes, as described below), and an `EF_MIPS_ARCH_1` or -`EF_MIPS_ARCH_32` header that _declares_ an ABI is refused rather than -relabeled, because the declared-ABI lane is verified for -`EF_MIPS_ARCH_32R2` headers only. The recordless MIPS-I lane pins the same -generic 32-bit language, which also decodes later MIPS32 instructions; the -session states that conformance to the MIPS-I subset is not established from +(target opening refuses a carved ELF whose section table extends past the +captured bytes, except for the recordless legacy `ET_EXEC` carve described +below), and an `EF_MIPS_ARCH_1` or `EF_MIPS_ARCH_32` header that _declares_ an +ABI is refused rather than relabeled, because the declared-ABI lane is verified +for `EF_MIPS_ARCH_32R2` headers only. One carved shape is the exception to the +first boundary: when a recordless legacy `ET_EXEC` ELF's only limitation is a +section header table that extends past the captured bytes, and the complete +program header table carries no `PT_MIPS_ABIFLAGS` record, the file is admitted +on this recordless lane. The unread section headers (including any uncaptured +`SHT_GNU_ATTRIBUTES` or `SHT_MIPS_ABIFLAGS`) stay unknown and are recorded as a +limitation in the profile and in Evidence, beside the o32 assumption. Any other +limitation, alone or with that one, is refused. The recordless MIPS-I lane pins +the same generic 32-bit language, which also decodes later MIPS32 instructions; +the session states that conformance to the MIPS-I subset is not established from the header alone, and names the committed language when the caller selected a -variant instead of the pin. A committed profile is bound to the current -target's lane and captured ELF metadata before startup; reusing a profile -resolved for the other recordless lane is refused rather than exporting -attribution for a target it did not describe. +variant instead of the pin. A committed profile is bound to the current target's +lane and captured ELF metadata before startup; reusing a profile resolved for the +other recordless lane is refused rather than exporting attribution for a target +it did not describe. Explicit `EF_MIPS_FP64` and `EF_MIPS_NAN2008` declarations are refused. Their absence is insufficient: Clang can emit identical `e_flags` for FP32, FP64 and @@ -78,16 +85,19 @@ argument ABI and unknown nonzero MSA values remain unsupported. Without a separate ABI flags record, FP attribute values are admitted only when absent, `ANY` (0), double precision (1), or FPXX (5), the values covered by the recordless profile. Parsed values are retained in the MIPS analysis profile. -A carved ELF whose section header table extends beyond the captured file is -refused when the target is opened, before provider selection, as is every ELF -declaration beyond EOF ([installation](../getting-started/installation.md#ghidra)). The refusal +Except for the recordless legacy `ET_EXEC` carve admitted above, a carved ELF +whose section header table extends beyond the captured file is refused when the +target is opened, before provider selection, as is every ELF declaration beyond +EOF ([installation](../getting-started/installation.md#ghidra)). The refusal names the declared range and the file size. It applies even when a -program-header ABI record was captured: an uncaptured section header could -carry an unsupported or conflicting declaration, so the captured bytes are not -analyzed as a complete smaller program. The provider also refuses any ABI -declaration inspection that reports unexamined headers. A missing -program-header record does not make ABI declarations in uncaptured sections -absent or supply a default ABI. +program-header ABI record was captured: an uncaptured section header could carry +an unsupported or conflicting declaration, so the captured bytes are not +analyzed as a complete smaller program. The provider also refuses any other +incomplete ABI declaration inspection. A missing program-header record does not +make ABI declarations or `SHT_GNU_ATTRIBUTES` in uncaptured sections absent or +supply a default ABI: the recordless carve admitted above keeps them as an +unknown, recorded limitation, and its o32 basis remains an assumption, not a +declaration. The field layout follows [`Elf_MIPS_ABIFlags_v0`](https://github.com/bminor/glibc/blob/master/elf/elf.h). diff --git a/src/application/BinaryTargetExecutableProbes.ts b/src/application/BinaryTargetExecutableProbes.ts index a806d21ac4b..534820c6074 100644 --- a/src/application/BinaryTargetExecutableProbes.ts +++ b/src/application/BinaryTargetExecutableProbes.ts @@ -28,6 +28,7 @@ import { type ExecutableMetadata, } from "../domain/binaryTarget.js"; import { + isRecordlessLegacyMips32Header, PE_CODEVIEW_PREFIX_BYTES, type PeCodeViewRecord, type UniversalMachOSlice, @@ -240,7 +241,11 @@ const readElfMetadata = async ( const ranges = await readElfDeclarations( handle, bytes, - validateElfDeclaredRanges(bytes, fileSize), + validateElfDeclaredRanges(bytes, fileSize, { + allowTruncatedSectionTable: + parsed.value.architecture === "mips" && + isRecordlessLegacyMips32Header(parsed.value.mips), + }), signal, ); if (!ranges.ok) return ranges; diff --git a/src/application/MipsElfMetadata.ts b/src/application/MipsElfMetadata.ts index 2f283f6fda0..96e07d03ae0 100644 --- a/src/application/MipsElfMetadata.ts +++ b/src/application/MipsElfMetadata.ts @@ -11,10 +11,11 @@ import { readElfRawTableDeclarations } from "../domain/elfRawTableDeclarations.j import { isElfRelocationSectionType } from "../domain/elfRelocation.js"; import type { FileHandle } from "node:fs/promises"; import { BinaryReader } from "../domain/binaryContainer.js"; -import type { - MipsAbiFlags, - MipsElfMetadata, - MipsGnuAttributes, +import { + MIPS_SECTION_TABLE_TRUNCATION_PREFIX, + type MipsAbiFlags, + type MipsElfMetadata, + type MipsGnuAttributes, } from "../domain/binaryTargetTypes.js"; import { elfFixedHeaderWidth, @@ -39,21 +40,14 @@ export interface MipsElfInspection { } /** - * 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. + * Build the bounded whole-region reader used for every declaration source. * The caller supplies its cancellation check so its tagged error is preserved. */ -export const readMipsElfMetadata = async ( +const createMipsRegionReader = ( handle: FileHandle, - metadata: MipsElfMetadata, + fileSize: number, checkCancelled: () => void, -): Promise> => { - 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, @@ -88,6 +82,26 @@ export const readMipsElfMetadata = async ( } return ok(bytes); }; + return read; +}; + +/** + * 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 readMipsElfMetadata = async ( + handle: FileHandle, + metadata: MipsElfMetadata, + checkCancelled: () => void, +): Promise> => { + checkCancelled(); + if (metadata.elfClass !== 32) + return err("MIPS ABI record inspection currently supports ELF32 only"); + const fileSize = (await handle.stat()).size; + checkCancelled(); + const read = createMipsRegionReader(handle, fileSize, checkCancelled); const header = await read(0, 52, "ELF32 header"); if (!header.ok) return header; const bytes = header.value; @@ -112,6 +126,7 @@ export const readMipsElfMetadata = async ( const tables = [ { label: "program header table", + limitationPrefix: "MIPS program header table at file offset ", offset: Number(programs.offset), count: programs.count, stride: programs.width, @@ -121,6 +136,7 @@ export const readMipsElfMetadata = async ( }, { label: "section header table", + limitationPrefix: MIPS_SECTION_TABLE_TRUNCATION_PREFIX, offset: Number(sections.offset), count: sections.count, stride: sections.width, @@ -155,7 +171,7 @@ export const readMipsElfMetadata = async ( : table.count; if (count < table.count) limitations.push( - `MIPS ${table.label} at file offset ${table.offset} extends beyond the captured file: examined ${count} of ${table.count} complete headers. ABI declarations in unavailable headers remain unknown.`, + `${table.limitationPrefix}${table.offset} extends beyond the captured file: examined ${count} of ${table.count} complete headers. ABI declarations in unavailable headers remain unknown.`, ); if (count === 0) continue; // Counts are bounded by the ELF16 fields and strides by their exact ELF32 diff --git a/src/domain/binaryTargetTypes.ts b/src/domain/binaryTargetTypes.ts index 6f2e41f3fd5..abd0f5de353 100644 --- a/src/domain/binaryTargetTypes.ts +++ b/src/domain/binaryTargetTypes.ts @@ -86,6 +86,35 @@ export type HeaderArchitecture = Exclude< (typeof HEADER_ARCHITECTURE_EXCLUSIONS)[number] >; +/** + * Prefix of the limitation recorded when an optional ELF32 MIPS section header + * table extends past the captured file, leaving unread headers unknown. + */ +export const MIPS_SECTION_TABLE_TRUNCATION_PREFIX = + "MIPS section header table at file offset "; + +/** + * True when an ELF32 MIPS header has the recordless legacy ET_EXEC shape + * (unspecified ABI, MIPS-I/MIPS32/MIPS32r2, no ASE/machine/FP64/NAN2008/n32/32bitmode flags). + */ +export const isRecordlessLegacyMips32Header = ( + mips: Pick, +): boolean => { + const arch = mips.flags & 0xf0000000; + return ( + mips.elfClass === 32 && + mips.type === 2 && + (arch === 0x00000000 || arch === 0x50000000 || arch === 0x70000000) && + (mips.flags & 0x0f000000) === 0 && + (mips.flags & 0x00ff0000) === 0 && + (mips.flags & 0x0000f000) === 0 && + (mips.flags & 0x20) === 0 && + (mips.flags & 0x40) === 0 && + (mips.flags & 0x100) === 0 && + (mips.flags & 0x600) === 0 + ); +}; + /** Raw ELF facts; family recognition does not establish ISA or ABI support. */ export interface MipsElfMetadata extends ElfFamilyMetadata { /** Undefined until inspected; null means no ABI record was observed. */ diff --git a/src/domain/elfDeclaredRanges.ts b/src/domain/elfDeclaredRanges.ts index 003ba58a50e..342bd9aee4e 100644 --- a/src/domain/elfDeclaredRanges.ts +++ b/src/domain/elfDeclaredRanges.ts @@ -29,10 +29,15 @@ interface ElfDeclaredTable { readonly width: number; } +export interface ElfDeclaredRangeOptions { + readonly allowTruncatedSectionTable?: boolean; +} + export interface ElfTableDeclarations { readonly header: ElfFixedHeader; readonly programs: ElfDeclaredTable; readonly sections: ElfDeclaredTable & { readonly namesIndex: number }; + readonly sectionTableTruncated?: boolean; } /** Zero-sized/inactive declarations own no file bytes. Arithmetic stays exact. */ @@ -144,6 +149,7 @@ export const validateElfSectionTableFields = (tables: { export function* readElfTableDeclarations( bytes: Buffer, fileSize: number, + options?: ElfDeclaredRangeOptions, ): Generator, Buffer> { const fixed = readElfFixedHeader(bytes, fileSize); if (!fixed.ok) return fixed; @@ -183,6 +189,7 @@ export function* readElfTableDeclarations( if (!counts.ok) return counts; ({ programCount, sectionCount, namesIndex } = counts.value); } + let sectionTableTruncated = false; for (const [kind, offset, count, width] of [ ["program", programOffset, programCount, programWidth], ["section", sectionOffset, sectionCount, sectionWidth], @@ -193,9 +200,23 @@ export function* readElfTableDeclarations( header, fileSize, ); - if (failure !== undefined) return err(failure); + if (failure !== undefined) { + if ( + kind === "section" && + options?.allowTruncatedSectionTable === true && + failure.startsWith("truncated ELF section header table:") + ) { + sectionTableTruncated = true; + continue; + } + return err(failure); + } } - if (sectionCount !== 0n && BigInt(namesIndex) >= sectionCount) + if ( + !sectionTableTruncated && + sectionCount !== 0n && + BigInt(namesIndex) >= sectionCount + ) return err( "ELF section-name index lies outside the declared section table", ); @@ -213,6 +234,7 @@ export function* readElfTableDeclarations( width: sectionWidth, namesIndex, }, + ...(sectionTableTruncated ? { sectionTableTruncated: true } : {}), }); } @@ -278,21 +300,44 @@ function* inspectTableRanges( export function* validateElfDeclaredRanges( prefix: Buffer, fileSize: number, + options?: ElfDeclaredRangeOptions, ): Generator< ElfDeclarationRead, Result, Buffer > { - const declarations = yield* readElfTableDeclarations(prefix, fileSize); + const declarations = yield* readElfTableDeclarations( + prefix, + fileSize, + options, + ); if (!declarations.ok) return declarations; - const { header, programs, sections } = declarations.value; + const { header, programs, sections, sectionTableTruncated } = + declarations.value; let hasInterpreter = false; for (const [kind, table] of [ ["program", programs], ["section", sections], ] as const) { if (table.count === 0) continue; - const inspected = yield* inspectTableRanges(kind, table, header, fileSize); + let inspectedTable = table; + if (kind === "section" && sectionTableTruncated) { + const capturedCount = + table.offset >= BigInt(fileSize) + ? 0 + : Math.min( + table.count, + Number((BigInt(fileSize) - table.offset) / BigInt(table.width)), + ); + if (capturedCount === 0) continue; + inspectedTable = { ...table, count: capturedCount }; + } + const inspected = yield* inspectTableRanges( + kind, + inspectedTable, + header, + fileSize, + ); if (!inspected.ok) return inspected; if (kind === "program") { hasInterpreter = inspected.value.hasInterpreter; diff --git a/src/ghidra/GhidraMipsProfile.test.ts b/src/ghidra/GhidraMipsProfile.test.ts index 14e6adfac1e..6d361007e83 100644 --- a/src/ghidra/GhidraMipsProfile.test.ts +++ b/src/ghidra/GhidraMipsProfile.test.ts @@ -307,11 +307,21 @@ describe("recordless legacy MIPS admission", () => { [{ flags: 0x50000201 }, "EF_MIPS_FP64"], [{ flags: 0x50000401 }, "EF_MIPS_NAN2008"], [{ flags: 0x60000001 }, "32R2"], + [ + { + flags: 0x50000001, + limitations: [ + "MIPS program header table at file offset 52 extends beyond the captured file: examined 0 of 3 complete headers. ABI declarations in unavailable headers remain unknown.", + ], + }, + "complete ABI-record inspection", + ], [ { flags: 0x50000001, limitations: [ "MIPS section header table at file offset 96 extends beyond the captured file: examined 2 of 5 complete headers. ABI declarations in unavailable headers remain unknown.", + "MIPS ABI record at file offset 4096 extends beyond the captured file", ], }, "complete ABI-record inspection", @@ -393,6 +403,51 @@ describe("caller-selected MIPS-I language", () => { }); }); +describe("recordless legacy MIPS32 carve admission", () => { + it("admits a recordless legacy carve whose only limitation is its section table", async () => { + const ghidra = new GhidraProvider(config, silentLogger, {}, host); + const carved = target({ + flags: 0x50000001, + abiFlags: null, + limitations: [ + "MIPS section header table at file offset 2952 extends beyond the captured file: examined 0 of 24 complete headers. ABI declarations in unavailable headers remain unknown.", + ], + }) as BinaryTarget & { mips: MipsElfMetadata }; + expect(ghidra.inspectTargetSupport(carved).status).toBe("supported"); + const resolved = await ghidra.resolveAnalysisProfile(carved); + if (!resolved.ok) throw resolved.error; + expect(resolved.value.profile?.parameters).toMatchObject({ + mips_support_lane: "elf32-exec-arch32-legacy-pinned", + mips_abi_basis: "inferred-o32-assumption", + language_id: "MIPS:LE:32:default", + language_selection: "provider-pinned", + mips_elf: { + abi_flags: null, + abi_flags_limitations: [ + "MIPS section header table at file offset 2952 extends beyond the captured file: examined 0 of 24 complete headers. ABI declarations in unavailable headers remain unknown.", + ], + }, + }); + }); + + it("admits a carve with partial section headers and preserves the o32 assumption", () => { + expect( + ghidraMipsProfileParameters( + target({ + flags: 0x50000001, + abiFlags: null, + limitations: [ + "MIPS section header table at file offset 96 extends beyond the captured file: examined 2 of 5 complete headers. ABI declarations in unavailable headers remain unknown.", + ], + }), + ), + ).toMatchObject({ + mips_support_lane: "elf32-exec-arch32-legacy-pinned", + mips_abi_basis: "inferred-o32-assumption", + }); + }); +}); + const report: GhidraMipsSoftFloatReport = { policy: "o32-soft-float-prototype-v1", functions: 5, diff --git a/src/ghidra/GhidraMipsProfile.ts b/src/ghidra/GhidraMipsProfile.ts index 493d6bd10b4..f2dfb37cd2a 100644 --- a/src/ghidra/GhidraMipsProfile.ts +++ b/src/ghidra/GhidraMipsProfile.ts @@ -1,8 +1,10 @@ import { isDeepStrictEqual } from "node:util"; import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js"; -import type { - BinaryTarget, - MipsElfMetadata, +import { + isRecordlessLegacyMips32Header, + MIPS_SECTION_TABLE_TRUNCATION_PREFIX, + type BinaryTarget, + type MipsElfMetadata, } from "../domain/binaryTargetTypes.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -49,6 +51,18 @@ export const ghidraMipsLanguageOverride = ( } : undefined; +/** + * A carved firmware image keeps its original section header table offset while + * the captured file ends before it. The optional section table is the only + * table this inspection records as a limitation; the required program header + * table must be read whole or the inspection fails outright. Every program + * header therefore has been checked and none declares PT_MIPS_ABIFLAGS, so the + * unread section headers can only hold declarations that stay unknown — the + * same o32-assumption footing as a complete recordless header. + */ +const isCarvedSectionTableLimitation = (limitation: string): boolean => + limitation.startsWith(MIPS_SECTION_TABLE_TRUNCATION_PREFIX); + /** * Recordless legacy ELF32 MIPS admission: the header declares no ABI field and * carries no ABI flags record, so o32 is an analysis assumption derived from @@ -65,27 +79,18 @@ const hasLegacyMipsHeaderShape = (target: BinaryTarget): boolean => { target.mips === undefined ) return false; - const { flags, abiFlags, limitations } = target.mips; - const arch = flags & 0xf0000000; + const { abiFlags, limitations } = target.mips; return ( // The lane and its verification cover executable firmware images only; // recordless relocatable objects stay outside the inferred-o32 assumption. - target.mips.elfClass === 32 && - target.mips.type === MIPS_ET_EXEC && - (arch === MIPS_ARCH_1 || - arch === MIPS_ARCH_32 || - arch === MIPS_ARCH_32R2) && - (flags & 0x0000f000) === 0 && - (flags & 0x20) === 0 && - // EF_MIPS_ABI_ON32 (bit 0x40) declares the old n32 ABI; it is not an - // unspecified-ABI header and must not inherit the o32 assumption. - (flags & 0x40) === 0 && - (flags & 0x100) === 0 && + isRecordlessLegacyMips32Header(target.mips) && // Undefined means the record was not inspected; only an inspected // absence establishes the recordless legacy admission. An inspection - // that could not examine every declaration source stays unknown. + // that could not examine every declaration source stays unknown, except + // for the carved section table whose limitation names exactly that table. abiFlags === null && - (limitations === undefined || limitations.length === 0) + (limitations === undefined || + limitations.every(isCarvedSectionTableLimitation)) ); }; diff --git a/tests/boundary/filesystem/mipsAbiFlags.test.ts b/tests/boundary/filesystem/mipsAbiFlags.test.ts index 38a503c60a1..c97e14b9e1a 100644 --- a/tests/boundary/filesystem/mipsAbiFlags.test.ts +++ b/tests/boundary/filesystem/mipsAbiFlags.test.ts @@ -309,6 +309,44 @@ it("refuses uncaptured section declarations while retaining unknown ABI evidence assert.equal(resolved.mips.abiFlags, null); assert.equal(resolved.mips.limitations, undefined); assert.equal(ghidraMipsUnsupportedReason(resolved), null); + const carvedRecordless = Buffer.from(bytes); + carvedRecordless.writeUInt32LE(0, 28); + carvedRecordless.writeUInt16LE(0, 44); + carvedRecordless.writeUInt32LE(0x50000001, 36); // Recordless legacy carve keeping truncated e_shoff. + const resolvedCarve = await resolveFixture(carvedRecordless); + assert.equal(resolvedCarve.mips.abiFlags, null); + assert.match( + (resolvedCarve.mips.limitations ?? []).join(" "), + /MIPS section header table at file offset .* extends beyond the captured file/u, + ); + assert.equal(ghidraMipsUnsupportedReason(resolvedCarve), null); +}); +it("refuses a partly captured recordless MIPS32 section table when a captured header points past EOF", async () => { + const base = withoutSectionTable(fixture()); + base.writeUInt32LE(0, 28); + base.writeUInt16LE(0, 44); + base.writeUInt32LE(0x50000001, 36); // Recordless legacy MIPS32 header. + // Place a 2-entry section table at EOF with 1 complete header and 7 trailing bytes. + const sectionOffset = base.length; + const bytes = Buffer.concat([base, Buffer.alloc(47)]); + bytes.writeUInt32LE(sectionOffset, 32); + bytes.writeUInt16LE(2, 48); + // Captured section 0: SHT_PROGBITS with valid in-file payload is admitted with limitation. + bytes.writeUInt32LE(1, sectionOffset + 4); + bytes.writeUInt32LE(52, sectionOffset + 16); + bytes.writeUInt32LE(16, sectionOffset + 20); + const admitted = await resolveFixture(bytes); + assert.match( + (admitted.mips.limitations ?? []).join(" "), + /MIPS section header table at file offset .* examined 1 of 2 complete headers/u, + ); + // Captured section 0: SHT_PROGBITS pointing past EOF must be refused. + const badPayloadOffset = bytes.length + 1; + bytes.writeUInt32LE(badPayloadOffset, sectionOffset + 16); + await refuseFixture( + bytes, + `truncated ELF section 0: declared file range ${badPayloadOffset}..${badPayloadOffset + 16} exceeds the ${bytes.length}-byte file`, + ); }); for (const little of [true, false]) { it(`matches the real MIPS lane's carved-copy refusal (${little ? "LE" : "BE"})`, async () => {