/** * Patch definitions as stored on disk, one directory per change to the program's behaviour, * under exe-patches///: * * patch.json what the program does, what it does after the patch, why the executable * has to change, which features depend on it, and the bytes to write * locate.json how to find the site * * This code reads only what applying needs; the explanatory fields are for people. */ import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; import { DefinitionError } from './errors.ts'; const PATCH_FILE = 'patch.json'; const LOCATE_FILE = 'locate.json'; export interface PatchEdit { /** Distance from the located site to the first byte written. */ readonly offset: number; readonly payload: Uint8Array; readonly expectOriginal: Uint8Array; } export interface LocateSpec { readonly method: string; readonly [key: string]: unknown; } export interface PatchDefinition { readonly id: string; readonly title: string; readonly features: readonly string[]; readonly requires: readonly string[]; readonly edit: PatchEdit; readonly locate: LocateSpec; readonly directory: string; } /** Every definition under `root`, sorted by id. */ export function loadPatches(root: string): PatchDefinition[] { const definitions = findDefinitionDirectories(root).map(readDefinition); rejectDuplicateIds(definitions); rejectUnknownRequirements(definitions); return definitions.sort((left, right) => left.id.localeCompare(right.id)); } function findDefinitionDirectories(root: string): string[] { const found: string[] = []; for (const entry of readdirSync(root, { withFileTypes: true })) { if (!entry.isDirectory()) continue; const directory = join(root, entry.name); if (isFile(join(directory, PATCH_FILE))) found.push(directory); else found.push(...findDefinitionDirectories(directory)); } return found; } function readDefinition(directory: string): PatchDefinition { const patch = readJson(join(directory, PATCH_FILE)); const locate = readJson(join(directory, LOCATE_FILE)); const where = join(directory, PATCH_FILE); if (typeof patch.id !== 'string' || typeof patch.title !== 'string') throw new DefinitionError(`${where}: needs string "id" and "title"`); if (typeof locate.method !== 'string') throw new DefinitionError(`${join(directory, LOCATE_FILE)}: needs a string "method"`); return { id: patch.id, title: patch.title, features: stringList(patch.features, where, 'features'), requires: stringList(patch.requires, where, 'requires'), edit: readEdit(patch.edit, where), locate: locate as LocateSpec, directory, }; } function readEdit(raw: unknown, where: string): PatchEdit { if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where}: "edit" must be an object`); const edit = raw as Record; const payload = hexBytes(edit.bytes, where, 'bytes'); const expectOriginal = hexBytes(edit.expect_original, where, 'expect_original'); if (payload.length !== expectOriginal.length) { throw new DefinitionError(`${where}: bytes is ${payload.length} bytes but expect_original is ${expectOriginal.length}`); } const offset = edit.offset ?? 0; if (typeof offset !== 'number' || !Number.isInteger(offset)) throw new DefinitionError(`${where}: edit.offset must be an integer`); return { offset, payload, expectOriginal }; } function hexBytes(value: unknown, where: string, key: string): Uint8Array { if (typeof value !== 'string' || !/^([0-9a-fA-F]{2})*$/.test(value)) throw new DefinitionError(`${where}: edit.${key} must be a hex string`); return Buffer.from(value, 'hex'); } function stringList(value: unknown, where: string, key: string): string[] { if (value === undefined) return []; if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) throw new DefinitionError(`${where}: "${key}" must be a list of strings`); return value; } function readJson(path: string): Record { let data: unknown; try { data = JSON.parse(readFileSync(path, 'utf-8')); } catch (error) { throw new DefinitionError(`${path}: ${(error as Error).message}`); } if (!data || typeof data !== 'object' || Array.isArray(data)) throw new DefinitionError(`${path}: expected a JSON object`); return data as Record; } function isFile(path: string): boolean { try { return statSync(path).isFile(); } catch { return false; } } function rejectDuplicateIds(definitions: readonly PatchDefinition[]): void { const seen = new Map(); for (const definition of definitions) { const previous = seen.get(definition.id); if (previous) throw new DefinitionError(`two definitions use id "${definition.id}": ${previous} and ${definition.directory}`); seen.set(definition.id, definition.directory); } } function rejectUnknownRequirements(definitions: readonly PatchDefinition[]): void { const known = new Set(definitions.map((definition) => definition.id)); for (const definition of definitions) { const unknown = definition.requires.filter((id) => !known.has(id)); if (unknown.length) throw new DefinitionError(`${definition.id} requires unknown patch(es): ${unknown.join(', ')}`); } }