/** * Read-only view of a PE executable: its sections, and the mapping between RVAs (addresses * relative to the image base) and file offsets. Only what locating and writing patches needs. */ import { PeFormatError } from './errors.ts'; export interface Section { readonly name: string; readonly rva: number; readonly virtualSize: number; readonly rawOffset: number; readonly rawSize: number; } const SECTION_HEADER_SIZE = 40; export class PeImage { readonly data: Uint8Array; readonly sections: readonly Section[]; constructor(data: Uint8Array) { this.data = data; this.sections = readSections(data); } section(name: string): Section { const section = this.sections.find((item) => item.name === name); if (!section) throw new PeFormatError(`no section ${name}`); return section; } /** The bytes of a section that are present in the file. */ sectionBytes(name: string): Uint8Array { const section = this.section(name); return this.data.subarray(section.rawOffset, section.rawOffset + Math.min(section.virtualSize, section.rawSize)); } fileOffset(rva: number): number { const section = this.sections.find((item) => item.rva <= rva && rva < item.rva + Math.max(item.virtualSize, item.rawSize)); if (!section) throw new PeFormatError(`RVA 0x${rva.toString(16)} is outside every section`); if (rva - section.rva >= section.rawSize) throw new PeFormatError(`RVA 0x${rva.toString(16)} has no file bytes`); return rva - section.rva + section.rawOffset; } read(rva: number, size: number): Uint8Array { const offset = this.fileOffset(rva); return this.data.subarray(offset, offset + size); } } function readSections(data: Uint8Array): Section[] { const view = new DataView(data.buffer, data.byteOffset, data.byteLength); if (data.length < 0x40 || view.getUint16(0, true) !== 0x5a4d) throw new PeFormatError('missing MZ header'); const peOffset = view.getUint32(0x3c, true); if (peOffset + 24 > data.length || view.getUint32(peOffset, true) !== 0x0000_4550) throw new PeFormatError('missing PE signature'); const sectionCount = view.getUint16(peOffset + 6, true); const optionalHeaderSize = view.getUint16(peOffset + 20, true); const tableOffset = peOffset + 24 + optionalHeaderSize; if (tableOffset + sectionCount * SECTION_HEADER_SIZE > data.length) throw new PeFormatError('section table runs past the end of the file'); return Array.from({ length: sectionCount }, (_, index) => { const at = tableOffset + index * SECTION_HEADER_SIZE; const rawName = data.subarray(at, at + 8); const nameEnd = rawName.indexOf(0); return { name: Buffer.from(rawName.subarray(0, nameEnd < 0 ? 8 : nameEnd)).toString('latin1'), virtualSize: view.getUint32(at + 8, true), rva: view.getUint32(at + 12, true), rawSize: view.getUint32(at + 16, true), rawOffset: view.getUint32(at + 20, true), }; }); }