diff --git a/src/application/BinaryTargetExecutableProbes.ts b/src/application/BinaryTargetExecutableProbes.ts index 922cfb2aa7..eeee739903 100644 --- a/src/application/BinaryTargetExecutableProbes.ts +++ b/src/application/BinaryTargetExecutableProbes.ts @@ -29,7 +29,7 @@ import { type ExecutableMetadata, } from "../domain/binaryTarget.js"; import { - isRecordlessLegacyMips32Header, + isRecordlessLegacyMipsExecHeader, PE_CODEVIEW_PREFIX_BYTES, type PeCodeViewRecord, type UniversalMachOSlice, @@ -234,13 +234,13 @@ const readElfMetadata = async ( const { fileSize, hostArchitecture, signal } = options; const parsed = parseExecutableHeader(bytes, hostArchitecture, fileSize); if (!parsed.ok || parsed.value.format !== "elf") return parsed; + const isMips32 = + parsed.value.architecture === "mips" && parsed.value.mips.elfClass === 32; const ranges = await readElfDeclarations( handle, bytes, validateElfDeclaredRanges(bytes, fileSize, { - allowTruncatedSectionTable: - parsed.value.architecture === "mips" && - isRecordlessLegacyMips32Header(parsed.value.mips), + sectionRanges: isMips32 ? "observe" : "strict", }), signal, ); @@ -259,14 +259,23 @@ const readElfMetadata = async ( ), }, }); - if (parsed.value.architecture !== "mips" || parsed.value.mips.elfClass !== 32) - return parsed; + if (!isMips32) return parsed; + const { sectionTruncation } = ranges.value; + if (sectionTruncation?.kind === "truncated_section_payload") + return err(sectionTruncation.reason); const declarations = await readMipsElfMetadata( handle, parsed.value.mips, () => throwIfTargetResolutionCancelled(signal), ); if (!declarations.ok) return declarations; + if (sectionTruncation !== undefined) { + const admitsTruncatedSectionTable = + sectionTruncation.kind === "truncated_section_table" && + isRecordlessLegacyMipsExecHeader(parsed.value.mips) && + declarations.value.abiFlags === null; + if (!admitsTruncatedSectionTable) return err(sectionTruncation.reason); + } return ok({ ...parsed.value, mips: { diff --git a/src/application/MipsElfMetadata.ts b/src/application/MipsElfMetadata.ts index 96e07d03ae..6dc131346a 100644 --- a/src/application/MipsElfMetadata.ts +++ b/src/application/MipsElfMetadata.ts @@ -12,8 +12,9 @@ import { isElfRelocationSectionType } from "../domain/elfRelocation.js"; import type { FileHandle } from "node:fs/promises"; import { BinaryReader } from "../domain/binaryContainer.js"; import { - MIPS_SECTION_TABLE_TRUNCATION_PREFIX, + mipsLimitationMessages, type MipsAbiFlags, + type MipsElfLimitation, type MipsElfMetadata, type MipsGnuAttributes, } from "../domain/binaryTargetTypes.js"; @@ -35,7 +36,7 @@ const MIPS_GNU_ATTRIBUTES_MAX_BYTES = 4096; export interface MipsElfInspection { readonly abiFlags: MipsAbiFlags | null; readonly gnuAttributes: MipsGnuAttributes | null; - readonly limitations: readonly string[]; + readonly limitations: readonly MipsElfLimitation[]; readonly sharedLoad?: MipsElfMetadata["sharedLoad"]; } @@ -126,7 +127,6 @@ 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, @@ -136,7 +136,6 @@ export const readMipsElfMetadata = async ( }, { label: "section header table", - limitationPrefix: MIPS_SECTION_TABLE_TRUNCATION_PREFIX, offset: Number(sections.offset), count: sections.count, stride: sections.width, @@ -153,7 +152,7 @@ export const readMipsElfMetadata = async ( let sharedLoad: MipsElfMetadata["sharedLoad"]; let programHeaders: ElfProgramHeader[] | undefined; const relocationSections: MipsElfRelocationSection[] = []; - const limitations: string[] = []; + const limitations: MipsElfLimitation[] = []; let gnuAttributes: MipsGnuAttributes | null = null; for (const table of tables) { if (table.count === 0) { @@ -170,9 +169,13 @@ export const readMipsElfMetadata = async ( ) : table.count; if (count < table.count) - limitations.push( - `${table.limitationPrefix}${table.offset} extends beyond the captured file: examined ${count} of ${table.count} complete headers. ABI declarations in unavailable headers remain unknown.`, - ); + limitations.push({ + kind: "truncated_section_table", + offset: table.offset, + examined: count, + declared: table.count, + message: `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.`, + }); if (count === 0) continue; // Counts are bounded by the ELF16 fields and strides by their exact ELF32 // structure sizes. Never allocate according to an untrusted section size. @@ -259,7 +262,7 @@ export const readMipsElfMetadata = async ( if (limitations.length > 0) sharedLoad = { status: "unavailable", - reason: `MIPS shared-image relocation declaration sources are incomplete. ${limitations.join(" ")}`, + reason: `MIPS shared-image relocation declaration sources are incomplete. ${mipsLimitationMessages(limitations).join(" ")}`, }; else { const shared = await readMipsElfSharedLoad( diff --git a/src/domain/binaryTargetTypes.ts b/src/domain/binaryTargetTypes.ts index e7e266a47f..ccf86b7833 100644 --- a/src/domain/binaryTargetTypes.ts +++ b/src/domain/binaryTargetTypes.ts @@ -86,32 +86,56 @@ 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 "; +/** Typed declaration-inspection limitation; consumers switch on `kind`, never prose. */ +export type MipsElfLimitation = + | { + readonly kind: "truncated_section_table"; + readonly offset: number; + readonly examined: number; + readonly declared: number; + readonly message: string; + } + | { + readonly kind: "unexamined_declarations"; + readonly message: string; + }; + +/** Extract human-readable messages from typed MIPS ELF inspection limitations. */ +export const mipsLimitationMessages = ( + limitations?: readonly MipsElfLimitation[], +): readonly string[] => + (limitations ?? []).map((limitation) => limitation.message); + +const MIPS_ET_EXEC = 2; +const MIPS_ARCH_1 = 0x00000000; +const MIPS_ARCH_32 = 0x50000000; +const MIPS_ARCH_32R2 = 0x70000000; /** - * 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). + * Whether an ELF header has the recordless legacy ELF32 MIPS ET_EXEC shape: + * MIPS-I / MIPS32 / MIPS32r2 with unspecified ABI and no ASE, machine, + * FP64, NAN2008, n32, or 32bitmode flags. Does not by itself establish lane + * admission (ABI flags, GNU attributes, and limitations are checked by the + * provider profile). */ -export const isRecordlessLegacyMips32Header = ( - mips: Pick, +export const isRecordlessLegacyMipsExecHeader = ( + metadata: ElfFamilyMetadata, ): boolean => { - const arch = mips.flags & 0xf0000000; + const { flags } = metadata; + const arch = 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 + metadata.elfClass === 32 && + metadata.type === MIPS_ET_EXEC && + (arch === MIPS_ARCH_1 || + arch === MIPS_ARCH_32 || + arch === MIPS_ARCH_32R2) && + (flags & 0x0f000000) === 0 && + (flags & 0x00ff0000) === 0 && + (flags & 0x0000f000) === 0 && + (flags & 0x20) === 0 && + (flags & 0x40) === 0 && + (flags & 0x100) === 0 && + (flags & 0x600) === 0 ); }; @@ -122,7 +146,7 @@ export interface MipsElfMetadata extends ElfFamilyMetadata { /** Undefined until inspected; null means no GNU attribute section was observed. */ readonly gnuAttributes?: MipsGnuAttributes | null; /** Unavailable declaration sources; missing records there remain unknown. */ - readonly limitations?: readonly string[]; + readonly limitations?: readonly MipsElfLimitation[]; /** Complete dynamic REL declarations, or the reason they could not be inspected. */ readonly sharedLoad?: | { diff --git a/src/domain/elfDeclaredRanges.ts b/src/domain/elfDeclaredRanges.ts index 342bd9aee4..d41b57eceb 100644 --- a/src/domain/elfDeclaredRanges.ts +++ b/src/domain/elfDeclaredRanges.ts @@ -13,8 +13,30 @@ import { err, ok, type Result } from "./result.js"; const SHN_LORESERVE = 0xff00; +export type ElfSectionRangePolicy = "strict" | "observe"; + +/** Optional/trailing section-table or section-payload truncation observed in `"observe"` mode. */ +export type ElfSectionTruncation = + | { + readonly kind: "truncated_section_table"; + readonly offset: bigint; + readonly declaredCount: bigint; + readonly examinedCount: number; + readonly fileSize: number; + readonly reason: string; + } + | { + readonly kind: "truncated_section_payload"; + readonly sectionIndex: number; + readonly offset: bigint; + readonly size: bigint; + readonly fileSize: number; + readonly reason: string; + }; + export interface ElfDeclaredRangeFacts { readonly hasInterpreter: boolean; + readonly sectionTruncation?: ElfSectionTruncation; } /** Positional source requests; the caller owns the descriptor and cancellation. */ @@ -29,15 +51,10 @@ 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. */ @@ -57,11 +74,10 @@ interface RawTableDeclaration { readonly width: number; } -const tableFailure = ( +const tableStructureFailure = ( kind: "program" | "section", table: RawTableDeclaration, header: ElfFixedHeader, - fileSize: number, ): string | undefined => { if (table.count === 0n) return undefined; const minimumWidth = @@ -73,14 +89,32 @@ const tableFailure = ( // e_ehsize can extend past the class minimum. Bytes below it are the header. if (table.offset < BigInt(header.headerSize)) return `ELF ${label} overlaps the fixed header`; - return rangeFailure( - label, - table.offset, - table.count * BigInt(table.width), - fileSize, - ); + return undefined; }; +const tableRangeFailure = ( + kind: "program" | "section", + table: RawTableDeclaration, + fileSize: number, +): string | undefined => + table.count === 0n + ? undefined + : rangeFailure( + `${kind} header table`, + table.offset, + table.count * BigInt(table.width), + fileSize, + ); + +const tableFailure = ( + kind: "program" | "section", + table: RawTableDeclaration, + header: ElfFixedHeader, + fileSize: number, +): string | undefined => + tableStructureFailure(kind, table, header) ?? + tableRangeFailure(kind, table, fileSize); + interface TableCounts { programCount: bigint; sectionCount: bigint; @@ -145,12 +179,20 @@ export const validateElfSectionTableFields = (tables: { return ok(null); }; -/** Canonical table declarations, including extended counts in inactive section zero. */ -export function* readElfTableDeclarations( +interface TableDeclarationsWithObservation { + readonly declarations: ElfTableDeclarations; + readonly sectionTruncation?: ElfSectionTruncation; +} + +function* readElfTableDeclarationsWithPolicy( bytes: Buffer, fileSize: number, - options?: ElfDeclaredRangeOptions, -): Generator, Buffer> { + sectionRanges: ElfSectionRangePolicy, +): Generator< + ElfDeclarationRead, + Result, + Buffer +> { const fixed = readElfFixedHeader(bytes, fileSize); if (!fixed.ok) return fixed; const header = fixed.value; @@ -189,64 +231,96 @@ 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], - ] as const) { - const failure = tableFailure( - kind, - { offset, count, width }, - header, - fileSize, - ); - if (failure !== undefined) { - if ( - kind === "section" && - options?.allowTruncatedSectionTable === true && - failure.startsWith("truncated ELF section header table:") - ) { - sectionTableTruncated = true; - continue; - } - return err(failure); - } - } - if ( - !sectionTableTruncated && - sectionCount !== 0n && - BigInt(namesIndex) >= sectionCount - ) + const programFailure = tableFailure( + "program", + { offset: programOffset, count: programCount, width: programWidth }, + header, + fileSize, + ); + if (programFailure !== undefined) return err(programFailure); + const sectionStructureFailure = tableStructureFailure( + "section", + { offset: sectionOffset, count: sectionCount, width: sectionWidth }, + header, + ); + if (sectionStructureFailure !== undefined) + return err(sectionStructureFailure); + if (sectionCount !== 0n && BigInt(namesIndex) >= sectionCount) return err( "ELF section-name index lies outside the declared section table", ); - // A validated table fits the host-sized file, so its record count is exact. - return ok({ - header, - programs: { - offset: programOffset, - count: Number(programCount), - width: programWidth, - }, - sections: { + const sectionRangeError = tableRangeFailure( + "section", + { offset: sectionOffset, count: sectionCount, width: sectionWidth }, + fileSize, + ); + let sectionTruncation: ElfSectionTruncation | undefined; + let examinedSectionCount = sectionCount; + if (sectionRangeError !== undefined) { + if (sectionRanges === "strict") return err(sectionRangeError); + const availableBytes = + sectionOffset >= BigInt(fileSize) ? 0n : BigInt(fileSize) - sectionOffset; + const examinedCount = Number(availableBytes / BigInt(sectionWidth)); + examinedSectionCount = BigInt(examinedCount); + sectionTruncation = { + kind: "truncated_section_table", offset: sectionOffset, - count: Number(sectionCount), - width: sectionWidth, - namesIndex, + declaredCount: sectionCount, + examinedCount, + fileSize, + reason: sectionRangeError, + }; + } + // A validated table (or the captured prefix of one) fits the host-sized file, + // so its examined record count is exact. + return ok({ + declarations: { + header, + programs: { + offset: programOffset, + count: Number(programCount), + width: programWidth, + }, + sections: { + offset: sectionOffset, + count: Number(examinedSectionCount), + width: sectionWidth, + namesIndex, + }, }, - ...(sectionTableTruncated ? { sectionTableTruncated: true } : {}), + ...(sectionTruncation === undefined ? {} : { sectionTruncation }), }); } +/** Canonical table declarations, including extended counts in inactive section zero. */ +export function* readElfTableDeclarations( + bytes: Buffer, + fileSize: number, +): Generator, Buffer> { + const result = yield* readElfTableDeclarationsWithPolicy( + bytes, + fileSize, + "strict", + ); + return result.ok ? ok(result.value.declarations) : result; +} + /** Examine only header records; referenced payloads are range-checked, never copied. */ function* inspectTableRanges( kind: "program" | "section", table: ElfDeclaredTable, header: ElfFixedHeader, fileSize: number, + sectionRanges: ElfSectionRangePolicy = "strict", ): Generator< ElfDeclarationRead, - Result<{ readonly hasInterpreter: boolean }, string>, + Result< + { + readonly hasInterpreter: boolean; + readonly sectionTruncation?: ElfSectionTruncation; + }, + string + >, Buffer > { let hasInterpreter = false; @@ -285,7 +359,21 @@ function* inspectTableRanges( length, fileSize, ); - if (failure !== undefined) return err(failure); + if (failure !== undefined) { + if (kind === "section" && sectionRanges === "observe") + return ok({ + hasInterpreter: false, + sectionTruncation: { + kind: "truncated_section_payload", + sectionIndex: index + item, + offset, + size: length, + fileSize, + reason: failure, + }, + }); + return err(failure); + } if (kind === "program" && facts.type === PT_INTERP) { // The declared range must fit at least one pathname byte and its NUL. if (length < 2n) return err("invalid ELF PT_INTERP file size"); @@ -296,52 +384,59 @@ function* inspectTableRanges( return ok({ hasInterpreter }); } -/** Physical extent admission, independent of section names, CPU lanes and decoder budgets. */ +/** + * Physical extent admission, independent of section names, CPU lanes and decoder budgets. + * Under `sectionRanges: "strict"` (default), any out-of-file section table or payload fails + * closed. Under `sectionRanges: "observe"`, fatal framing and program-header checks still fail + * closed while trailing section-table/payload truncation is surfaced as `sectionTruncation`. + */ export function* validateElfDeclaredRanges( prefix: Buffer, fileSize: number, - options?: ElfDeclaredRangeOptions, + options?: { readonly sectionRanges?: ElfSectionRangePolicy }, ): Generator< ElfDeclarationRead, Result, Buffer > { - const declarations = yield* readElfTableDeclarations( + const sectionRanges = options?.sectionRanges ?? "strict"; + const resolved = yield* readElfTableDeclarationsWithPolicy( prefix, fileSize, - options, + sectionRanges, ); - if (!declarations.ok) return declarations; - const { header, programs, sections, sectionTableTruncated } = - declarations.value; + if (!resolved.ok) return resolved; + const { header, programs, sections } = resolved.value.declarations; let hasInterpreter = false; - for (const [kind, table] of [ - ["program", programs], - ["section", sections], - ] as const) { - if (table.count === 0) continue; - 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 }; - } + let sectionTruncation = resolved.value.sectionTruncation; + if (programs.count > 0) { const inspected = yield* inspectTableRanges( - kind, - inspectedTable, + "program", + programs, header, fileSize, + "strict", ); if (!inspected.ok) return inspected; - if (kind === "program") { - hasInterpreter = inspected.value.hasInterpreter; - } + hasInterpreter = inspected.value.hasInterpreter; } - return ok({ hasInterpreter }); + // Inspect every complete captured section header even when the table is + // truncated so an out-of-file section payload still overrides table-only + // truncation and prevents admission. + if (sections.count > 0) { + const inspected = yield* inspectTableRanges( + "section", + sections, + header, + fileSize, + sectionRanges, + ); + if (!inspected.ok) return inspected; + if (inspected.value.sectionTruncation !== undefined) + sectionTruncation = inspected.value.sectionTruncation; + } + return ok({ + hasInterpreter, + ...(sectionTruncation === undefined ? {} : { sectionTruncation }), + }); } diff --git a/src/ghidra/GhidraMipsProfile.test.ts b/src/ghidra/GhidraMipsProfile.test.ts index 6d361007e8..873b134326 100644 --- a/src/ghidra/GhidraMipsProfile.test.ts +++ b/src/ghidra/GhidraMipsProfile.test.ts @@ -311,7 +311,13 @@ describe("recordless legacy MIPS admission", () => { { 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.", + { + kind: "unexamined_declarations", + // Even if prose resembles a section-table truncation message, the + // typed discriminator governs admission — never string matching. + message: + "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.", + }, ], }, "complete ABI-record inspection", @@ -320,8 +326,19 @@ describe("recordless legacy MIPS admission", () => { { 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", + { + kind: "truncated_section_table", + offset: 96, + examined: 2, + declared: 5, + message: + "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.", + }, + { + kind: "unexamined_declarations", + message: + "MIPS ABI record at file offset 4096 extends beyond the captured file", + }, ], }, "complete ABI-record inspection", @@ -339,6 +356,63 @@ describe("recordless legacy MIPS admission", () => { }, ); + it("admits a recordless legacy MIPS32 ET_EXEC whose only limitation is a truncated section table and propagates it to session limitations", async () => { + const limitation = { + kind: "truncated_section_table" as const, + offset: 96, + examined: 2, + declared: 5, + message: + "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.", + }; + const carved = target({ + flags: 0x50000001, + abiFlags: null, + limitations: [limitation], + }); + const ghidra = new GhidraProvider(config, silentLogger, {}, host); + 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", + mips_elf: { + abi_flags_limitations: [limitation], + }, + }); + const { client } = await session(carved, undefined); + const health = await client.execute("health", {}); + if (!health.ok) throw health.error; + expect(health.value.limitations).toContain(limitation.message); + }); + + it.each([ + ["declared-ABI ET_EXEC", { flags: 0x70001001 }], + ["recordless ET_REL", { flags: 0x50000001, type: 1, abiFlags: null }], + ["PSP Allegrex", { flags: 0x10a23001 }], + ] as const)( + "keeps %s fail-closed when the section header table is truncated", + (_label, change) => { + const ghidra = new GhidraProvider(config, silentLogger, {}, host); + const value = target({ + ...change, + limitations: [ + { + kind: "truncated_section_table", + offset: 96, + examined: 2, + declared: 5, + message: + "MIPS section header table at file offset 96 extends beyond the captured file: examined 2 of 5 complete headers.", + }, + ], + }); + expect(ghidra.inspectTargetSupport(value).status).toBe("unsupported"); + }, + ); + it("a caller-selected language wins over the provider pin", () => { const parameters = ghidraMipsProfileParameters( target({ flags: 0x50000001, abiFlags: null }), @@ -403,51 +477,6 @@ 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, @@ -655,7 +684,26 @@ describe("MIPS16 shared-image profile", () => { }); it.each([ { flags: 0x74001045 }, - { limitations: ["Unexamined section declarations"] }, + { + limitations: [ + { + kind: "unexamined_declarations", + message: "Unexamined section declarations", + }, + ], + }, + { + limitations: [ + { + kind: "truncated_section_table", + offset: 96, + examined: 0, + declared: 2, + message: + "MIPS section header table at file offset 96 extends beyond the captured file: examined 0 of 2 complete headers.", + }, + ], + }, { sharedLoad: { status: "complete", diff --git a/src/ghidra/GhidraMipsProfile.ts b/src/ghidra/GhidraMipsProfile.ts index f2dfb37cd2..a41b2ca960 100644 --- a/src/ghidra/GhidraMipsProfile.ts +++ b/src/ghidra/GhidraMipsProfile.ts @@ -1,9 +1,10 @@ import { isDeepStrictEqual } from "node:util"; import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js"; import { - isRecordlessLegacyMips32Header, - MIPS_SECTION_TABLE_TRUNCATION_PREFIX, + isRecordlessLegacyMipsExecHeader, + mipsLimitationMessages, type BinaryTarget, + type MipsElfLimitation, type MipsElfMetadata, } from "../domain/binaryTargetTypes.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -52,16 +53,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. + * Whether every recorded inspection limitation is a truncated section header + * table. Recordless legacy ELF32 MIPS ET_EXEC images may omit trailing section + * tables when carved from firmware; any other incomplete declaration stays + * fail-closed. */ -const isCarvedSectionTableLimitation = (limitation: string): boolean => - limitation.startsWith(MIPS_SECTION_TABLE_TRUNCATION_PREFIX); +const isOnlyTruncatedSectionTable = ( + limitations?: readonly MipsElfLimitation[], +): boolean => + limitations === undefined || + limitations.every( + (limitation) => limitation.kind === "truncated_section_table", + ); /** * Recordless legacy ELF32 MIPS admission: the header declares no ABI field and @@ -79,18 +82,15 @@ const hasLegacyMipsHeaderShape = (target: BinaryTarget): boolean => { target.mips === undefined ) return false; - 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. - isRecordlessLegacyMips32Header(target.mips) && + isRecordlessLegacyMipsExecHeader(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, except - // for the carved section table whose limitation names exactly that table. - abiFlags === null && - (limitations === undefined || - limitations.every(isCarvedSectionTableLimitation)) + // absence establishes the recordless legacy admission. Only a truncated + // section header table may remain unexamined in this legacy lane. + target.mips.abiFlags === null && + isOnlyTruncatedSectionTable(target.mips.limitations) ); }; @@ -105,7 +105,7 @@ export const ghidraMipsIncompleteDeclarationsReason = ( (metadata.limitations?.length ?? 0) > 0 ? [ "MIPS ABI declaration inspection is incomplete; unsupported attributes or conflicting declaration sources may remain unknown.", - ...(metadata.limitations ?? []), + ...mipsLimitationMessages(metadata.limitations), ].join(" ") : null; @@ -188,7 +188,7 @@ export const ghidraMipsUnsupportedReason = ( // recordless admission is not established for this header. return [ "This recordless legacy admission requires a complete ABI-record inspection; ABI declarations in unavailable headers remain unknown.", - ...(metadata.limitations ?? []), + ...mipsLimitationMessages(metadata.limitations), ].join(" "); } if ( @@ -234,7 +234,7 @@ export const ghidraMipsUnsupportedReason = ( 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.", - ...(metadata.limitations ?? []), + ...mipsLimitationMessages(metadata.limitations), ].join(" "); if (abi.version !== 0) return "This Ghidra MIPS lane requires ABI flags version 0; newer record semantics are unsupported."; @@ -451,7 +451,11 @@ export const ghidraMipsProfileParameters = ( flags: target.mips.flags, ...(target.mips.limitations === undefined ? {} - : { abi_flags_limitations: [...target.mips.limitations] }), + : { + abi_flags_limitations: target.mips.limitations.map( + (limitation) => ({ ...limitation }), + ), + }), abi_flags: abi === undefined || abi === null ? null diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index c45f31f896..d8ca4f836b 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -607,7 +607,9 @@ export const createGhidraProviderClient = (input: { "Static analysis does not emulate reset vectors, memory-mapped I/O, or firmware boot sequences.", ] : []), - ...(target.architecture === "mips" ? (target.mips.limitations ?? []) : []), + ...(target.architecture === "mips" + ? (target.mips.limitations ?? []).map((limitation) => limitation.message) + : []), ...(committedProfile.parameters.mips_abi_basis === "inferred-o32-assumption" ? [ "The ELF header declares no ABI field and no ABI flags record was observed; o32 calling conventions are an analysis assumption of this lane, not a declared fact.", diff --git a/tests/boundary/filesystem/mipsAbiFlags.test.ts b/tests/boundary/filesystem/mipsAbiFlags.test.ts index c97e14b9e1..1e3c0cc7a5 100644 --- a/tests/boundary/filesystem/mipsAbiFlags.test.ts +++ b/tests/boundary/filesystem/mipsAbiFlags.test.ts @@ -274,8 +274,16 @@ for (const little of [true, false]) { ghidraMipsUnsupportedReason(partial) ?? "", /ABI declaration inspection is incomplete/u, ); + assert.equal(declarations.value.limitations.length, 1); + assert.deepEqual(declarations.value.limitations[0], { + kind: "truncated_section_table", + offset: sectionOffset, + examined: Math.floor(availableBytes / 40), + declared: 2, + message: declarations.value.limitations[0]?.message, + }); assert.match( - declarations.value.limitations.join(" "), + declarations.value.limitations[0]?.message ?? "", new RegExp( `section header table.*examined ${Math.floor(availableBytes / 40)} of 2 complete headers`, "u", @@ -315,8 +323,13 @@ it("refuses uncaptured section declarations while retaining unknown ABI evidence carvedRecordless.writeUInt32LE(0x50000001, 36); // Recordless legacy carve keeping truncated e_shoff. const resolvedCarve = await resolveFixture(carvedRecordless); assert.equal(resolvedCarve.mips.abiFlags, null); + assert.equal(resolvedCarve.mips.limitations?.length, 1); + assert.equal( + resolvedCarve.mips.limitations?.[0]?.kind, + "truncated_section_table", + ); assert.match( - (resolvedCarve.mips.limitations ?? []).join(" "), + resolvedCarve.mips.limitations?.[0]?.message ?? "", /MIPS section header table at file offset .* extends beyond the captured file/u, ); assert.equal(ghidraMipsUnsupportedReason(resolvedCarve), null); @@ -336,8 +349,10 @@ it("refuses a partly captured recordless MIPS32 section table when a captured he bytes.writeUInt32LE(52, sectionOffset + 16); bytes.writeUInt32LE(16, sectionOffset + 20); const admitted = await resolveFixture(bytes); + assert.equal(admitted.mips.limitations?.length, 1); + assert.equal(admitted.mips.limitations?.[0]?.kind, "truncated_section_table"); assert.match( - (admitted.mips.limitations ?? []).join(" "), + admitted.mips.limitations?.[0]?.message ?? "", /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. @@ -696,3 +711,120 @@ it("preserves cancellation instead of turning it into malformed target data", as if (result.ok) throw new Error("Cancelled target resolution succeeded"); assert.ok(result.error instanceof AnalysisCancelledError); }); + +const legacyFixture = (little = true, flags = 0x50000001, type = 2): Buffer => { + const bytes = fixture(little); + const u16 = (value: number, offset: number) => + little + ? bytes.writeUInt16LE(value, offset) + : bytes.writeUInt16BE(value, offset); + const u32 = (value: number, offset: number) => + little + ? bytes.writeUInt32LE(value, offset) + : bytes.writeUInt32BE(value, offset); + u16(type, 16); + u32(flags, 36); + u32(0, 52); // Clear PT_MIPS_ABIFLAGS so the image is recordless. + u32(0, 172); // Clear SHT_MIPS_ABIFLAGS. + return bytes; +}; + +for (const little of [true, false]) { + for (const availableBytes of [0, 47]) { + it(`admits a carved recordless legacy MIPS32 ET_EXEC with ${availableBytes} section-table bytes (${little ? "LE" : "BE"})`, async () => { + const original = legacyFixture(little); + const bytes = Buffer.concat([original, Buffer.alloc(availableBytes)]); + const sectionOffset = original.length + (availableBytes === 0 ? 1 : 0); + if (little) bytes.writeUInt32LE(sectionOffset, 32); + else bytes.writeUInt32BE(sectionOffset, 32); + const resolved = await resolveFixture(bytes); + assert.equal(resolved.mips.abiFlags, null); + assert.equal(resolved.mips.limitations?.length, 1); + assert.equal( + resolved.mips.limitations?.[0]?.kind, + "truncated_section_table", + ); + if (resolved.mips.limitations?.[0]?.kind === "truncated_section_table") { + assert.equal(resolved.mips.limitations[0].offset, sectionOffset); + assert.equal( + resolved.mips.limitations[0].examined, + Math.floor(availableBytes / 40), + ); + assert.equal(resolved.mips.limitations[0].declared, 2); + } + assert.equal(ghidraMipsUnsupportedReason(resolved), null); + const profileParameters = jsonObjectSchema.parse( + ghidraMipsProfileParameters(resolved), + ); + expect(profileParameters).toMatchObject({ + mips_support_lane: "elf32-exec-arch32-legacy-pinned", + language_id: `MIPS:${little ? "LE" : "BE"}:32:default`, + }); + }); + } +} + +it("still fails closed on carved recordless non-ET_EXEC and fatal ELF framing errors", async () => { + // Recordless ET_REL with truncated section table stays refused at target opening. + const rel = legacyFixture(true, 0x50000001, 1); + rel.writeUInt32LE(rel.length + 1, 32); + await refuseFixture( + rel, + `truncated ELF section header table: declared file range ${rel.length + 1}..${rel.length + 81} exceeds the ${rel.length}-byte file`, + ); + + // Fatal framing: section header table overlapping fixed header. + const overlap = legacyFixture(true); + overlap.writeUInt32LE(16, 32); + await refuseFixture( + overlap, + "ELF section header table overlaps the fixed header", + ); + + // Fatal framing: reserved direct section count e_shnum >= 0xff00. + const reserved = legacyFixture(true); + reserved.writeUInt16LE(0xff00, 48); + await refuseFixture( + reserved, + "ELF e_shnum uses a reserved direct section count", + ); + + // Fatal framing: e_shstrndx >= e_shnum. + const badNames = legacyFixture(true); + badNames.writeUInt32LE(badNames.length + 1, 32); + badNames.writeUInt16LE(2, 50); + await refuseFixture( + badNames, + "ELF section-name index lies outside the declared section table", + ); + + // Fatal framing: extended numbering with uncaptured section zero. + const extended = legacyFixture(true); + extended.writeUInt32LE(extended.length + 1, 32); + extended.writeUInt16LE(0, 48); + await refuseFixture( + extended, + `truncated ELF section header table: declared file range ${extended.length + 1}..${extended.length + 41} exceeds the ${extended.length}-byte file`, + ); + + // Fatal framing: truncated PT_LOAD program payload on a carved legacy MIPS32 ET_EXEC. + const badProgram = legacyFixture(true); + badProgram.writeUInt32LE(badProgram.length + 1, 32); + badProgram.writeUInt32LE(1, 52); // PT_LOAD + badProgram.writeUInt32LE(badProgram.length, 56); + badProgram.writeUInt32LE(16, 68); + await refuseFixture( + badProgram, + `truncated ELF program 0: declared file range ${badProgram.length}..${badProgram.length + 16} exceeds the ${badProgram.length}-byte file`, + ); + + // Complete section table with truncated SHT_PROGBITS section payload stays refused. + const badPayload = legacyFixture(true); + badPayload.writeUInt32LE(1, 172); // SHT_PROGBITS + badPayload.writeUInt32LE(badPayload.length, 184); + badPayload.writeUInt32LE(16, 188); + await refuseFixture( + badPayload, + `truncated ELF section 1: declared file range ${badPayload.length}..${badPayload.length + 16} exceeds the ${badPayload.length}-byte file`, + ); +}); diff --git a/tests/boundary/filesystem/mipsSharedLoad.test.ts b/tests/boundary/filesystem/mipsSharedLoad.test.ts index b4803c9bd3..aa0fd2f9be 100644 --- a/tests/boundary/filesystem/mipsSharedLoad.test.ts +++ b/tests/boundary/filesystem/mipsSharedLoad.test.ts @@ -303,8 +303,13 @@ it("does not treat uncaptured ABI declaration headers as an inspected absence", assert.ok(declarations.ok); assert.equal(declarations.value.abiFlags, null); assert.equal(declarations.value.sharedLoad?.status, "unavailable"); + assert.equal(declarations.value.limitations.length, 1); + assert.equal( + declarations.value.limitations[0]?.kind, + "truncated_section_table", + ); assert.match( - declarations.value.limitations.join(" "), + declarations.value.limitations[0]?.message ?? "", /extends beyond the captured file/u, ); });