/** * A "locate" block: how to find one place in the executable, and which values to read there. * Exe patch variants use it to find where to write; native definitions use it to find the * functions, globals and structure offsets the hook library needs. */ import { readCaptures, readCaptureSpecs, type Captures, type CaptureSpec } from './captures.ts'; import { DefinitionError, LocateError } from './errors.ts'; import { asObject, rejectUnknownKeys } from './json-fields.ts'; import { locateMethod, NO_CONTEXT, type LocateContext, type LocateMethod } from './locate/index.ts'; import type { PeImage } from './pe-image.ts'; export interface SiteSpec { readonly method: LocateMethod; /** The method's own keys (pattern, section, ...). */ readonly spec: Readonly>; readonly captures: readonly CaptureSpec[]; } export interface FoundSite { readonly rva: number; readonly captures: Captures; } export function readSiteSpec(raw: unknown, where: string): SiteSpec { const block = asObject(raw, where); const method = locateMethod(block.method); rejectUnknownKeys(block, new Set(['method', 'captures', ...method.keys]), where); let length: number; try { length = method.length(block); } catch (error) { throw new DefinitionError(`${where}: ${(error as Error).message}`); } return { method, spec: block, captures: readCaptureSpecs(block.captures, length, where) }; } /** The single place the spec matches, with its captures; anything else is a LocateError. */ export function findSite(image: PeImage, site: SiteSpec, context: LocateContext = NO_CONTEXT): FoundSite { const hits = site.method.locate(image, site.spec, context); if (!hits.length) throw new LocateError('site not found: this game build differs from the verified ones, or the executable is already patched'); if (hits.length > 1) throw new LocateError(`site found in ${hits.length} places, so it is ambiguous: ${hits.map(hex).join(', ')}`); return { rva: hits[0]!, captures: readCaptures(image, hits[0]!, site.captures) }; } export function hex(value: number): string { return `0x${value.toString(16)}`; }