/** * Read-only view of a PE executable: its sections, the mapping between RVAs (addresses relative * to the image base) and file offsets, and the function ranges of its exception directory. 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; } /** A function, or one part of a function, from the exception directory: [begin, end). */ export interface FunctionRange { readonly begin: number; readonly end: number; } const SECTION_HEADER_SIZE = 40; const PE32_PLUS_MAGIC = 0x20b; /** Offset of the data directories in a PE32+ optional header. */ const DATA_DIRECTORIES = 112; const EXCEPTION_DIRECTORY = 3; const RUNTIME_FUNCTION_SIZE = 12; export class PeImage { readonly data: Uint8Array; readonly sections: readonly Section[]; #functions: readonly FunctionRange[] | undefined; readonly #cache = new Map(); constructor(data: Uint8Array) { this.data = data; this.sections = readSections(data); } /** The function range containing `rva`, or null when the exception directory has none. */ functionContaining(rva: number): FunctionRange | null { const functions = (this.#functions ??= readFunctions(this)); let low = 0; let high = functions.length - 1; while (low <= high) { const middle = (low + high) >> 1; const range = functions[middle]!; if (rva < range.begin) high = middle - 1; else if (rva >= range.end) low = middle + 1; else return range; } return null; } /** A value derived from this image, computed once (indexes the locate methods build). */ cached(key: string, compute: () => T): T { if (!this.#cache.has(key)) this.#cache.set(key, compute()); return this.#cache.get(key) as T; } 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), }; }); } function readFunctions(image: PeImage): FunctionRange[] { const view = new DataView(image.data.buffer, image.data.byteOffset, image.data.byteLength); const optionalHeader = view.getUint32(0x3c, true) + 24; if (view.getUint16(optionalHeader, true) !== PE32_PLUS_MAGIC) throw new PeFormatError('not a PE32+ executable'); const directory = optionalHeader + DATA_DIRECTORIES + EXCEPTION_DIRECTORY * 8; const rva = view.getUint32(directory, true); const size = view.getUint32(directory + 4, true); const table = image.read(rva, size); const entries = new DataView(table.buffer, table.byteOffset, table.byteLength); const functions: FunctionRange[] = []; for (let at = 0; at + RUNTIME_FUNCTION_SIZE <= size; at += RUNTIME_FUNCTION_SIZE) { functions.push({ begin: entries.getUint32(at, true), end: entries.getUint32(at + 4, true) }); } return functions.sort((left, right) => left.begin - right.begin); }