From 1ba93c8a1bbddab3c775320ac37f8977717b4bca Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:59:06 -0500 Subject: [PATCH] refactor(elf): share fixed header declaration widths (#12391) --- scripts/verify/baselines/raw-buffer-read.json | 3 -- src/application/MipsElfMetadata.ts | 20 +++++++--- src/artifacts/bun/BunModuleGraphLayout.ts | 7 +++- src/artifacts/deno/DenoStandaloneLocation.ts | 20 +++++----- src/artifacts/nodeSea/NodeSeaLocation.ts | 18 +++++---- src/domain/desktop/elfDependencies.ts | 3 +- src/domain/elfDeclaredRanges.ts | 22 +++++++---- src/domain/elfFixedHeader.ts | 7 +++- src/domain/elfProgramHeader.test.ts | 8 +++- src/domain/elfProgramHeader.ts | 34 ++++++++++------- src/domain/elfRawTableDeclarations.test.ts | 11 +++++- src/domain/elfRawTableDeclarations.ts | 34 +++++++++-------- src/domain/elfSectionHeader.test.ts | 8 +++- src/domain/elfSectionHeader.ts | 38 +++++++++++-------- src/domain/native/nativeSectionDirectory.ts | 3 +- .../RecordedCrashStructureBindings.ts | 31 +++++++++++---- .../filesystem/elfDeclaredRanges.test.ts | 12 ++++++ .../boundary/filesystem/mipsAbiFlags.test.ts | 1 + 18 files changed, 184 insertions(+), 96 deletions(-) diff --git a/scripts/verify/baselines/raw-buffer-read.json b/scripts/verify/baselines/raw-buffer-read.json index 1aee860da4..487df47e94 100644 --- a/scripts/verify/baselines/raw-buffer-read.json +++ b/scripts/verify/baselines/raw-buffer-read.json @@ -13,10 +13,7 @@ "src/domain/apple/propertyListDecodeBudget.ts": 2, "src/domain/binaryTarget.ts": 10, "src/domain/desktop/openPgpKeys.ts": 2, - "src/domain/elfProgramHeader.ts": 4, - "src/domain/elfRawTableDeclarations.ts": 7, "src/domain/elfRelocation.ts": 6, - "src/domain/elfSectionHeader.ts": 6, "src/domain/gamecubeDol.ts": 6, "src/domain/inesContainer.ts": 5, "src/domain/managed/managedCliHeaderPrefix.ts": 5, diff --git a/src/application/MipsElfMetadata.ts b/src/application/MipsElfMetadata.ts index 660f442138..2f283f6fda 100644 --- a/src/application/MipsElfMetadata.ts +++ b/src/application/MipsElfMetadata.ts @@ -1,5 +1,9 @@ -import { readElfSectionHeader } from "../domain/elfSectionHeader.js"; import { + elfSectionHeaderWidth, + readElfSectionHeader, +} from "../domain/elfSectionHeader.js"; +import { + elfProgramHeaderWidth, readElfProgramHeader, type ElfProgramHeader, } from "../domain/elfProgramHeader.js"; @@ -12,7 +16,10 @@ import type { MipsElfMetadata, MipsGnuAttributes, } from "../domain/binaryTargetTypes.js"; -import { readElfFixedHeader } from "../domain/elfFixedHeader.js"; +import { + elfFixedHeaderWidth, + readElfFixedHeader, +} from "../domain/elfFixedHeader.js"; import { err, ok, type Result } from "../domain/result.js"; import { readMipsElfSharedLoad, @@ -95,7 +102,8 @@ export const readMipsElfMetadata = async ( fixedHeader.value.flags !== metadata.flags ) return err("MIPS ELF header no longer matches the resolved identity"); - if (fixedHeader.value.headerSize !== 52) + const headerWidth = elfFixedHeaderWidth(32); + if (fixedHeader.value.headerSize !== headerWidth) return err("invalid MIPS ELF32 version or header size"); const raw = readElfRawTableDeclarations(bytes, fixedHeader.value); @@ -107,7 +115,7 @@ export const readMipsElfMetadata = async ( offset: Number(programs.offset), count: programs.count, stride: programs.width, - entrySize: 32, + entrySize: elfProgramHeaderWidth(32), recordType: 0x70000003, // PT_MIPS_ABIFLAGS optional: false, }, @@ -116,7 +124,7 @@ export const readMipsElfMetadata = async ( offset: Number(sections.offset), count: sections.count, stride: sections.width, - entrySize: 40, + entrySize: elfSectionHeaderWidth(32), recordType: 0x7000002a, // SHT_MIPS_ABIFLAGS optional: true, }, @@ -137,7 +145,7 @@ export const readMipsElfMetadata = async ( return err(`unsupported extended or inconsistent MIPS ${table.label}`); continue; } - if (table.offset < 52 || table.stride !== table.entrySize) + if (table.offset < headerWidth || table.stride !== table.entrySize) return err(`invalid MIPS ${table.label} offset or entry size`); const count = table.optional ? Math.min( diff --git a/src/artifacts/bun/BunModuleGraphLayout.ts b/src/artifacts/bun/BunModuleGraphLayout.ts index 3aa1c10145..7f38e4f6f8 100644 --- a/src/artifacts/bun/BunModuleGraphLayout.ts +++ b/src/artifacts/bun/BunModuleGraphLayout.ts @@ -17,7 +17,10 @@ import { } from "../../domain/peSectionHeader.js"; import { readElfHeaderFacts } from "../../domain/elfFixedHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; -import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; +import { + elfSectionHeaderWidth, + readElfSectionHeader, +} from "../../domain/elfSectionHeader.js"; import { observeElfStringTableEntry } from "../../domain/elfStringTable.js"; import { readFatContainerHeader, @@ -808,7 +811,7 @@ const elfClaims = async ( const declarations = readElfRawTableDeclarations(header, format.value); if (!declarations.ok) return []; const { offset, width, count, namesIndex } = declarations.value.sections; - const sectionWidth = elfClass === 64 ? 64 : 40; + const sectionWidth = elfSectionHeaderWidth(elfClass); // Unsupported extended numbering does not establish a Bun graph. if ( (width !== 0 && width !== sectionWidth) || diff --git a/src/artifacts/deno/DenoStandaloneLocation.ts b/src/artifacts/deno/DenoStandaloneLocation.ts index 5e97602ab4..87d157a0a1 100644 --- a/src/artifacts/deno/DenoStandaloneLocation.ts +++ b/src/artifacts/deno/DenoStandaloneLocation.ts @@ -20,8 +20,14 @@ import { validateFatSliceIdentity, type FatSliceDeclaration, } from "../../domain/apple/machoContainer.js"; -import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; -import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; +import { + elfSectionHeaderWidth, + readElfSectionHeader, +} from "../../domain/elfSectionHeader.js"; +import { + elfProgramHeaderWidth, + readElfProgramHeader, +} from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; import { validateElfSectionTableFields } from "../../domain/elfDeclaredRanges.js"; import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; @@ -56,10 +62,6 @@ import { DENO_SECTION_MAGIC } from "./DenoSectionLayout.js"; const CPU_TYPE_ARM64 = 0x0100000c; const PT_NOTE = 4; const PN_XNUM = 0xffff; -const ELF64_PROGRAM_HEADER_BYTES = 56; -const ELF32_PROGRAM_HEADER_BYTES = 32; -const ELF64_SECTION_HEADER_BYTES = 64; -const ELF32_SECTION_HEADER_BYTES = 40; const RT_RCDATA = 10; const RESOURCE_NAME = "D3N0L4ND"; const SECTION_NAME = "d3n0l4nd"; @@ -551,7 +553,7 @@ const locateElfNotes = async (carrier: Carrier): Promise => { walk.damage ??= denoCarrierFailure(detail); }; const little = header.value.byteOrder === "little"; - const wide = header.value.elfClass === 64; + const { elfClass } = header.value; const { programs, sections } = raw.value; if (programs.count === PN_XNUM) damaged("ELF extended program numbering is unsupported"); @@ -567,7 +569,7 @@ const locateElfNotes = async (carrier: Carrier): Promise => { carrier, walk, programs, - wide ? ELF64_PROGRAM_HEADER_BYTES : ELF32_PROGRAM_HEADER_BYTES, + elfProgramHeaderWidth(elfClass), "program header table", ); const sectionHeaders = sectionTable.ok @@ -575,7 +577,7 @@ const locateElfNotes = async (carrier: Carrier): Promise => { carrier, walk, sections, - wide ? ELF64_SECTION_HEADER_BYTES : ELF32_SECTION_HEADER_BYTES, + elfSectionHeaderWidth(elfClass), "section header table", ) : undefined; diff --git a/src/artifacts/nodeSea/NodeSeaLocation.ts b/src/artifacts/nodeSea/NodeSeaLocation.ts index 8a30e1898e..8e34dae012 100644 --- a/src/artifacts/nodeSea/NodeSeaLocation.ts +++ b/src/artifacts/nodeSea/NodeSeaLocation.ts @@ -11,8 +11,14 @@ import { machoSectionBacking, readMachoSectionHeader, } from "../../domain/apple/machoSectionHeader.js"; -import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; -import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; +import { + elfSectionHeaderWidth, + readElfSectionHeader, +} from "../../domain/elfSectionHeader.js"; +import { + elfProgramHeaderWidth, + readElfProgramHeader, +} from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; import { validateElfSectionTableFields } from "../../domain/elfDeclaredRanges.js"; import { constants as bufferConstants } from "node:buffer"; @@ -423,7 +429,7 @@ const locateElfNotes = async ( const header = readElfFixedHeader(prefix, carrier.fileSize); if (!header.ok) return []; const little = header.value.byteOrder === "little"; - const elf64 = header.value.elfClass === 64; + const { elfClass } = header.value; const fields = await readExact( carrier, 0, @@ -446,8 +452,6 @@ const locateElfNotes = async ( const phnum = programDeclarations.count; const shentsize = sectionDeclarations.width; const shnum = sectionDeclarations.count; - const minimumProgram = elf64 ? 56 : 32; - const minimumSection = elf64 ? 64 : 40; const found: BlobRange[] = []; let opaque: string | undefined; // Each note header takes at least 12 file bytes. The containing program or @@ -461,7 +465,7 @@ const locateElfNotes = async ( offset: phoff, count: phnum, entrySize: phentsize, - minimumEntry: minimumProgram, + minimumEntry: elfProgramHeaderWidth(elfClass), }); if (programs === undefined && phnum > 0) opaque = NODE_SEA_ELF_TABLE_TRUNCATED; @@ -511,7 +515,7 @@ const locateElfNotes = async ( offset: shoff, count: shnum, entrySize: shentsize, - minimumEntry: minimumSection, + minimumEntry: elfSectionHeaderWidth(elfClass), }); if (sections === undefined && shnum > 0) opaque ??= NODE_SEA_ELF_TABLE_TRUNCATED; diff --git a/src/domain/desktop/elfDependencies.ts b/src/domain/desktop/elfDependencies.ts index 44e339bf2a..d3f3fc5d9c 100644 --- a/src/domain/desktop/elfDependencies.ts +++ b/src/domain/desktop/elfDependencies.ts @@ -18,6 +18,7 @@ import { import { admitElfLoadSegment, elfLoadSpans, + elfProgramHeaderWidth, readElfProgramHeader, type ElfProgramHeader, } from "../elfProgramHeader.js"; @@ -116,7 +117,7 @@ const programHeaders = async ( }); if (!declaration.ok) return err(declaration.error.message); const { offset, width: entrySize, count } = declaration.value.programs; - if (entrySize < (bits === 64 ? 56 : 32) || count === 0xffff) + if (entrySize < elfProgramHeaderWidth(bits) || count === 0xffff) return err("unsupported ELF program header table"); const table = await readBoundedExtent( read, diff --git a/src/domain/elfDeclaredRanges.ts b/src/domain/elfDeclaredRanges.ts index 8a288eaf73..003ba58a50 100644 --- a/src/domain/elfDeclaredRanges.ts +++ b/src/domain/elfDeclaredRanges.ts @@ -1,5 +1,12 @@ -import { readElfSectionHeader } from "./elfSectionHeader.js"; -import { readElfProgramHeader, PT_INTERP } from "./elfProgramHeader.js"; +import { + elfSectionHeaderWidth, + readElfSectionHeader, +} from "./elfSectionHeader.js"; +import { + elfProgramHeaderWidth, + readElfProgramHeader, + PT_INTERP, +} from "./elfProgramHeader.js"; import { readElfRawTableDeclarations } from "./elfRawTableDeclarations.js"; import { readElfFixedHeader, type ElfFixedHeader } from "./elfFixedHeader.js"; import { err, ok, type Result } from "./result.js"; @@ -52,8 +59,10 @@ const tableFailure = ( fileSize: number, ): string | undefined => { if (table.count === 0n) return undefined; - const wide = header.elfClass === 64; - const minimumWidth = kind === "program" ? (wide ? 56 : 32) : wide ? 64 : 40; + const minimumWidth = + kind === "program" + ? elfProgramHeaderWidth(header.elfClass) + : elfSectionHeaderWidth(header.elfClass); const label = `${kind} header table`; if (table.width < minimumWidth) return `invalid ELF ${label} entry width`; // e_ehsize can extend past the class minimum. Bytes below it are the header. @@ -78,8 +87,7 @@ const extendedCounts = ( header: ElfFixedHeader, initial: TableCounts, ): Result => { - const wide = header.elfClass === 64; - if (first.length !== (wide ? 64 : 40)) + if (first.length !== elfSectionHeaderWidth(header.elfClass)) return err("truncated ELF extended section-zero header"); const parsed = readElfSectionHeader( first, @@ -165,7 +173,7 @@ export function* readElfTableDeclarations( if (failure !== undefined) return err(failure); const first = yield { offset: Number(sectionOffset), - size: header.elfClass === 64 ? 64 : 40, + size: elfSectionHeaderWidth(header.elfClass), }; const counts = extendedCounts(first, header, { programCount, diff --git a/src/domain/elfFixedHeader.ts b/src/domain/elfFixedHeader.ts index a2001eb895..0aa90000cb 100644 --- a/src/domain/elfFixedHeader.ts +++ b/src/domain/elfFixedHeader.ts @@ -28,6 +28,9 @@ export interface ElfFixedHeader extends Omit { readonly architecture: ElfArchitecture | null; } +export const elfFixedHeaderWidth = (bits: 32 | 64): 52 | 64 => + bits === 32 ? 52 : 64; + /** * Decode common ELF framing and fixed fields; version and declared-size admission belong to consumers. * @@ -50,7 +53,7 @@ export const readElfHeaderFacts = ( if (bytes[6] !== 1) return err("unsupported ELF identification version"); const elfClass = classByte === 1 ? 32 : 64; - const minimumSize = elfClass === 32 ? 52 : 64; + const minimumSize = elfFixedHeaderWidth(elfClass); if ( !Number.isSafeInteger(totalBytes) || totalBytes < bytes.length || @@ -96,7 +99,7 @@ export const admitElfFixedHeaderFacts = ( // NVIDIA CUBIN uses ELFOSABI_CUDA and a vendor ABI version in e_version. if (facts.version !== 1 && !(facts.machine === 190 && facts.osAbi === 0x33)) return err("unsupported ELF header version"); - const minimumSize = facts.elfClass === 32 ? 52 : 64; + const minimumSize = elfFixedHeaderWidth(facts.elfClass); if (facts.headerSize < minimumSize || facts.headerSize > totalBytes) return err("invalid ELF header size"); return ok({ diff --git a/src/domain/elfProgramHeader.test.ts b/src/domain/elfProgramHeader.test.ts index 7f519d1b93..d0d8796d84 100644 --- a/src/domain/elfProgramHeader.test.ts +++ b/src/domain/elfProgramHeader.test.ts @@ -17,7 +17,11 @@ it.each(formats)( const wide = bits === 64; const length = wide ? 56 : 32; const backing = Buffer.alloc(length + 19, 0xa5); - const bytes = backing.subarray(7, 7 + length); + const bytes = new Uint8Array( + backing.buffer, + backing.byteOffset + 7, + length, + ); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const values = wide ? [ @@ -45,7 +49,7 @@ it.each(formats)( }); const before = Buffer.from(backing); const parsed = readElfProgramHeader( - backing.subarray(7), + new Uint8Array(backing.buffer, bytes.byteOffset, length + 5), bits, littleEndian, ); diff --git a/src/domain/elfProgramHeader.ts b/src/domain/elfProgramHeader.ts index d007aedddb..7ca06d1089 100644 --- a/src/domain/elfProgramHeader.ts +++ b/src/domain/elfProgramHeader.ts @@ -1,8 +1,12 @@ +import { BinaryReader } from "./binaryContainer.js"; import { err, ok } from "./result.js"; import type { FileMapping, ZeroFillMapping } from "./virtualFileMapping.js"; export const PT_INTERP = 3; +export const elfProgramHeaderWidth = (bits: 32 | 64): 32 | 56 => + bits === 64 ? 56 : 32; + export type ElfProgramHeader = Extract< ReturnType, { readonly ok: true } @@ -15,25 +19,27 @@ export const readElfProgramHeader = ( littleEndian: boolean, ) => { const wide = bits === 64; - if (bytes.byteLength < (wide ? 56 : 32)) + if (bytes.byteLength < elfProgramHeaderWidth(bits)) return err({ kind: "malformed" as const, message: "ELF program header is truncated", }); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const word = (at: number): bigint => - wide - ? view.getBigUint64(at, littleEndian) - : BigInt(view.getUint32(at, littleEndian)); + const reader = new BinaryReader( + Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), + littleEndian, + "elf", + ); return ok({ - type: view.getUint32(0, littleEndian), - flags: view.getUint32(wide ? 4 : 24, littleEndian), - offset: word(wide ? 8 : 4), - virtualAddress: word(wide ? 16 : 8), - physicalAddress: word(wide ? 24 : 12), - fileSize: word(wide ? 32 : 16), - memorySize: word(wide ? 40 : 20), - alignment: word(wide ? 48 : 28), + type: reader.u32(0), + flags: reader.u32(wide ? 4 : 24), + offset: reader.word(wide ? 8 : 4, bits), + virtualAddress: reader.word(wide ? 16 : 8, bits), + physicalAddress: reader.word(wide ? 24 : 12, bits), + fileSize: reader.word(wide ? 32 : 16, bits), + memorySize: reader.word(wide ? 40 : 20, bits), + alignment: reader.word(wide ? 48 : 28, bits), }); }; diff --git a/src/domain/elfRawTableDeclarations.test.ts b/src/domain/elfRawTableDeclarations.test.ts index e0a6854d70..6a1f053aba 100644 --- a/src/domain/elfRawTableDeclarations.test.ts +++ b/src/domain/elfRawTableDeclarations.test.ts @@ -15,7 +15,11 @@ it.each(formats)( const little = format.byteOrder === "little"; const length = wide ? 64 : 52; const backing = Buffer.alloc(length + 17, 0xa5); - const bytes = backing.subarray(7, 7 + length); + const bytes = new Uint8Array( + backing.buffer, + backing.byteOffset + 7, + length, + ); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const programOffset = wide ? 0xfedcba9876543210n : 0xfedcba98n; const sectionOffset = wide ? 0xffffffffffffffffn : 0xffffffffn; @@ -30,7 +34,10 @@ it.each(formats)( view.setUint16((wide ? 54 : 42) + index * 2, value, little), ); const before = Buffer.from(backing); - const parsed = readElfRawTableDeclarations(backing.subarray(7), format); + const parsed = readElfRawTableDeclarations( + new Uint8Array(backing.buffer, bytes.byteOffset, length + 5), + format, + ); expect(backing.equals(before)).toBe(true); backing.fill(0); expect(parsed).toEqual({ diff --git a/src/domain/elfRawTableDeclarations.ts b/src/domain/elfRawTableDeclarations.ts index 14e12dd063..4e1109fe62 100644 --- a/src/domain/elfRawTableDeclarations.ts +++ b/src/domain/elfRawTableDeclarations.ts @@ -1,3 +1,5 @@ +import { BinaryReader } from "./binaryContainer.js"; +import { elfFixedHeaderWidth } from "./elfFixedHeader.js"; import { err, ok } from "./result.js"; /** Fixed-header table words, before extended numbering or file-range admission. */ @@ -5,29 +7,31 @@ export const readElfRawTableDeclarations = ( bytes: Uint8Array, format: { readonly elfClass: 32 | 64; readonly byteOrder: "little" | "big" }, ) => { - const wide = format.elfClass === 64; - if (bytes.byteLength < (wide ? 64 : 52)) + const { elfClass, byteOrder } = format; + const wide = elfClass === 64; + if (bytes.byteLength < elfFixedHeaderWidth(elfClass)) return err({ kind: "malformed" as const, message: "ELF table declarations are truncated", }); - const little = format.byteOrder === "little"; - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const word = (offset: number): bigint => - wide - ? view.getBigUint64(offset, little) - : BigInt(view.getUint32(offset, little)); + const reader = new BinaryReader( + Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), + byteOrder === "little", + "elf", + ); return ok({ programs: { - offset: word(wide ? 32 : 28), - width: view.getUint16(wide ? 54 : 42, little), - count: view.getUint16(wide ? 56 : 44, little), + offset: reader.word(wide ? 32 : 28, elfClass), + width: reader.u16(wide ? 54 : 42), + count: reader.u16(wide ? 56 : 44), }, sections: { - offset: word(wide ? 40 : 32), - width: view.getUint16(wide ? 58 : 46, little), - count: view.getUint16(wide ? 60 : 48, little), - namesIndex: view.getUint16(wide ? 62 : 50, little), + offset: reader.word(wide ? 40 : 32, elfClass), + width: reader.u16(wide ? 58 : 46), + count: reader.u16(wide ? 60 : 48), + namesIndex: reader.u16(wide ? 62 : 50), }, }); }; diff --git a/src/domain/elfSectionHeader.test.ts b/src/domain/elfSectionHeader.test.ts index 671347d682..7a3a992e89 100644 --- a/src/domain/elfSectionHeader.test.ts +++ b/src/domain/elfSectionHeader.test.ts @@ -14,7 +14,11 @@ it.each(formats)( const wide = bits === 64; const length = wide ? 64 : 40; const backing = Buffer.alloc(length + 19, 0xa5); - const bytes = backing.subarray(7, 7 + length); + const bytes = new Uint8Array( + backing.buffer, + backing.byteOffset + 7, + length, + ); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const values = wide ? [ @@ -44,7 +48,7 @@ it.each(formats)( }); const before = Buffer.from(backing); const parsed = readElfSectionHeader( - backing.subarray(7), + new Uint8Array(backing.buffer, bytes.byteOffset, length + 5), bits, littleEndian, ); diff --git a/src/domain/elfSectionHeader.ts b/src/domain/elfSectionHeader.ts index a5ccbc3271..b4afb31d1c 100644 --- a/src/domain/elfSectionHeader.ts +++ b/src/domain/elfSectionHeader.ts @@ -1,5 +1,9 @@ +import { BinaryReader } from "./binaryContainer.js"; import { err, ok } from "./result.js"; +export const elfSectionHeaderWidth = (bits: 32 | 64): 40 | 64 => + bits === 64 ? 64 : 40; + /** Fixed ELF32/ELF64 section declarations; consumers own names, numbering and mapping admission. */ export const readElfSectionHeader = ( bytes: Uint8Array, @@ -7,28 +11,30 @@ export const readElfSectionHeader = ( littleEndian: boolean, ) => { const wide = bits === 64; - if (bytes.byteLength < (wide ? 64 : 40)) + if (bytes.byteLength < elfSectionHeaderWidth(bits)) return err({ kind: "malformed" as const, message: "ELF section header is truncated", }); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const word = (at: number): bigint => - wide - ? view.getBigUint64(at, littleEndian) - : BigInt(view.getUint32(at, littleEndian)); - const flags = word(8); + const reader = new BinaryReader( + Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), + littleEndian, + "elf", + ); + const flags = reader.word(8, bits); return ok({ - nameOffset: view.getUint32(0, littleEndian), - type: view.getUint32(4, littleEndian), + nameOffset: reader.u32(0), + type: reader.u32(4), flags, compressed: (flags & 0x800n) !== 0n, - address: word(wide ? 16 : 12), - offset: word(wide ? 24 : 16), - size: word(wide ? 32 : 20), - link: view.getUint32(wide ? 40 : 24, littleEndian), - info: view.getUint32(wide ? 44 : 28, littleEndian), - alignment: word(wide ? 48 : 32), - entrySize: word(wide ? 56 : 36), + address: reader.word(wide ? 16 : 12, bits), + offset: reader.word(wide ? 24 : 16, bits), + size: reader.word(wide ? 32 : 20, bits), + link: reader.u32(wide ? 40 : 24), + info: reader.u32(wide ? 44 : 28), + alignment: reader.word(wide ? 48 : 32, bits), + entrySize: reader.word(wide ? 56 : 36, bits), }); }; diff --git a/src/domain/native/nativeSectionDirectory.ts b/src/domain/native/nativeSectionDirectory.ts index dcba616148..0527e2320c 100644 --- a/src/domain/native/nativeSectionDirectory.ts +++ b/src/domain/native/nativeSectionDirectory.ts @@ -6,6 +6,7 @@ import { mzWindowsHeaderLayoutLimitation, parseMzHeaderEvidence, } from "../dosMz.js"; +import { elfFixedHeaderWidth } from "../elfFixedHeader.js"; import { readElfSectionHeader } from "../elfSectionHeader.js"; import { readElfProgramHeader } from "../elfProgramHeader.js"; import { observePeCoffFrame, PE_COFF_FRAME_BYTES } from "../peCoffHeader.js"; @@ -140,7 +141,7 @@ export function* readElfSectionDirectory( fileSize: number, ): Generator { const prefix = yield request(fileSize, 0n, 16n); - const headerSize = prefix[4] === 1 ? 52 : 64; + const headerSize = elfFixedHeaderWidth(prefix[4] === 1 ? 32 : 64); const bytes = yield request(fileSize, 0n, BigInt(headerSize)); const parsed = yield* readElfTableDeclarations(bytes, fileSize); if (!parsed.ok) return reject(parsed.error); diff --git a/src/native/pwntools/RecordedCrashStructureBindings.ts b/src/native/pwntools/RecordedCrashStructureBindings.ts index 6ec7177b04..c614ee7d4f 100644 --- a/src/native/pwntools/RecordedCrashStructureBindings.ts +++ b/src/native/pwntools/RecordedCrashStructureBindings.ts @@ -1,7 +1,16 @@ -import { readElfHeaderFacts } from "../../domain/elfFixedHeader.js"; +import { + elfFixedHeaderWidth, + readElfHeaderFacts, +} from "../../domain/elfFixedHeader.js"; import { readElfNoteHeader } from "../../domain/native/elfNoteLayout.js"; -import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; -import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; +import { + elfSectionHeaderWidth, + readElfSectionHeader, +} from "../../domain/elfSectionHeader.js"; +import { + elfProgramHeaderWidth, + readElfProgramHeader, +} from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; import { AnalysisOutputError } from "../../domain/analysisErrorCore.js"; import { @@ -94,7 +103,7 @@ export function validateRecordedCrashStructure( if (offset < 0n || offset > BigInt(snapshot.length - bytes)) return fail(); return snapshot.subarray(Number(offset), Number(offset) + bytes); }; - const header = bytesAt(0n, 64); + const header = bytesAt(0n, elfFixedHeaderWidth(64)); const expectedMachine = RECORDED_LINUX_CORE_PROFILES[report.architecture].machine; const parsedHeader = readElfHeaderFacts(header); @@ -120,12 +129,20 @@ export function validateRecordedCrashStructure( const entryBytes = programs.width; let count = programs.count; if (count === 0xffff) { - if (sections.width < 64) return fail(); - const zero = readElfSectionHeader(bytesAt(sections.offset, 64), 64, true); + const width = elfSectionHeaderWidth(64); + if (sections.width < width) return fail(); + const zero = readElfSectionHeader( + bytesAt(sections.offset, width), + 64, + true, + ); if (!zero.ok) return fail(); count = zero.value.info; } - if (count !== report.segments.length || (count > 0 && entryBytes < 56)) + if ( + count !== report.segments.length || + (count > 0 && entryBytes < elfProgramHeaderWidth(64)) + ) fail(); for (const segment of report.segments) { const offset = table + BigInt(segment.index) * BigInt(entryBytes); diff --git a/tests/boundary/filesystem/elfDeclaredRanges.test.ts b/tests/boundary/filesystem/elfDeclaredRanges.test.ts index 3ed649194d..8f527ddeef 100644 --- a/tests/boundary/filesystem/elfDeclaredRanges.test.ts +++ b/tests/boundary/filesystem/elfDeclaredRanges.test.ts @@ -67,6 +67,18 @@ const admit = async (bytes: Buffer) => { }; for (const bits of [32, 64] as const) { + it(`admits a padded declared stride for ELF${bits} program and section tables`, async () => { + const fixture = image(bits, true); + fixture.u16(bits === 64 ? 54 : 42, fixture.programWidth + 4); + fixture.u16(bits === 64 ? 58 : 46, fixture.sectionWidth + 4); + fixture.bytes.copyWithin( + fixture.section + 4, + fixture.section, + fixture.section + fixture.sectionWidth, + ); + fixture.bytes.fill(0, fixture.section, fixture.section + 4); + expect((await admit(fixture.bytes)).ok).toBe(true); + }); for (const little of [true, false]) { it(`refuses declared table and payload truncation before provider admission (ELF${bits} ${little ? "LE" : "BE"})`, async () => { const fixture = image(bits, little); diff --git a/tests/boundary/filesystem/mipsAbiFlags.test.ts b/tests/boundary/filesystem/mipsAbiFlags.test.ts index 286b868dfc..38a503c60a 100644 --- a/tests/boundary/filesystem/mipsAbiFlags.test.ts +++ b/tests/boundary/filesystem/mipsAbiFlags.test.ts @@ -408,6 +408,7 @@ const malformed: [string, (bytes: Buffer) => void, RegExp][] = [ ["short record", (b) => b.writeUInt32LE(23, 68), /record size/u], ["oversized record", (b) => b.writeUInt32LE(0xffffffff, 68), /record size/u], ["invalid table stride", (b) => b.writeUInt16LE(31, 42), /entry size/u], + ["padded MIPS program stride", (b) => b.writeUInt16LE(36, 42), /entry size/u], ["extended program count", (b) => b.writeUInt16LE(0xffff, 44), /numbering/u], ["extended section count", (b) => b.writeUInt16LE(0, 48), /extended/u], ["changed identity", (b) => b.writeUInt32LE(0x60001001, 36), /identity/u],