feat(patcher): build a loopback client copy with TypeScript
Add the shared BLK, VROMFS, executable patch, and build packages. Preserve typed fields and shared name tables when reading BLK data. Rewrite the service endpoints in place so the original environment names remain available to the client, then build the client copy.
This commit is contained in:
1 parent
89aa5198c3
commit
c3914ec0d6
44 files changed
+1986
-1
No files matched your search
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Write a verified plan into a copy of the executable's bytes. The expected original bytes
|
||||
* are checked again right before each write, so a plan made against other bytes is refused
|
||||
* instead of landing half applied. The input is never modified.
|
||||
*/
|
||||
import { VerifyError } from './errors.ts';
|
||||
import type { PlannedWrite } from './plan.ts';
|
||||
|
||||
export function applyWrites(data: Uint8Array, writes: readonly PlannedWrite[]): Uint8Array {
|
||||
const patched = Uint8Array.from(data);
|
||||
for (const write of [...writes].sort((left, right) => left.fileOffset - right.fileOffset)) {
|
||||
const end = write.fileOffset + write.payload.length;
|
||||
const actual = Buffer.from(patched.subarray(write.fileOffset, end));
|
||||
if (!actual.equals(write.expectOriginal)) {
|
||||
throw new VerifyError(`${write.patchId}: bytes at file offset 0x${write.fileOffset.toString(16)} are ${actual.toString('hex')}, ` +
|
||||
`expected ${Buffer.from(write.expectOriginal).toString('hex')}; nothing was written`);
|
||||
}
|
||||
patched.set(write.payload, write.fileOffset);
|
||||
}
|
||||
return patched;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Patch definitions as stored on disk, one directory per change to the program's behaviour,
|
||||
* under exe-patches/<domain>/<name>/:
|
||||
*
|
||||
* 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<string, unknown>;
|
||||
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<string, unknown> {
|
||||
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<string, unknown>;
|
||||
}
|
||||
|
||||
function isFile(path: string): boolean {
|
||||
try {
|
||||
return statSync(path).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function rejectDuplicateIds(definitions: readonly PatchDefinition[]): void {
|
||||
const seen = new Map<string, string>();
|
||||
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(', ')}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/** A patch cannot be applied, so nothing was written. */
|
||||
export class PatchError extends Error {
|
||||
override name = 'PatchError';
|
||||
}
|
||||
|
||||
/** A patch definition on disk is malformed. */
|
||||
export class DefinitionError extends PatchError {
|
||||
override name = 'DefinitionError';
|
||||
}
|
||||
|
||||
/**
|
||||
* A patch site could not be found, or was found in more than one place. The caller reports
|
||||
* which patches and features are affected; it never falls back to a guessed address
|
||||
*.
|
||||
*/
|
||||
export class LocateError extends PatchError {
|
||||
override name = 'LocateError';
|
||||
}
|
||||
|
||||
/** The bytes at a located site are not what the definition expects: a different game build, or already patched. */
|
||||
export class VerifyError extends PatchError {
|
||||
override name = 'VerifyError';
|
||||
}
|
||||
|
||||
/** The file is not a PE executable this code understands. */
|
||||
export class PeFormatError extends Error {
|
||||
override name = 'PeFormatError';
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Apply the declarative patches under exe-patches/ to aces.exe: locate every site and verify
|
||||
* every original byte first, then write. A site that is missing or ambiguous is reported,
|
||||
* never guessed. Authoring patches (building signatures, assembling) is development-side
|
||||
* work done in tools/.
|
||||
*/
|
||||
export { applyWrites } from './apply.ts';
|
||||
export { loadPatches, type PatchDefinition, type PatchEdit } from './definition.ts';
|
||||
export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError } from './errors.ts';
|
||||
export { PeImage, type Section } from './pe-image.ts';
|
||||
export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Ways to find a patch site. Each method returns every RVA it matched; it never picks a
|
||||
* winner among several matches, the caller requires exactly one.
|
||||
*/
|
||||
import { DefinitionError } from '../errors.ts';
|
||||
import type { PeImage } from '../pe-image.ts';
|
||||
import * as signature from './signature.ts';
|
||||
|
||||
export type Locator = (image: PeImage, spec: Readonly<Record<string, unknown>>) => number[];
|
||||
|
||||
const METHODS: ReadonlyMap<string, Locator> = new Map([[signature.METHOD, signature.locateSignature]]);
|
||||
|
||||
export function locatorFor(method: string): Locator {
|
||||
const locator = METHODS.get(method);
|
||||
if (!locator) throw new DefinitionError(`unknown locate method "${method}"; known: ${[...METHODS.keys()].join(', ')}`);
|
||||
return locator;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Find a patch site by a byte pattern with wildcards, e.g. "41 57 41 56 48 81 ec ?? ?? ?? ??".
|
||||
*
|
||||
* Wildcards cover what legitimately differs between builds: addresses inside rip-relative
|
||||
* operands and the targets of relative calls and jumps. Patterns are produced on the
|
||||
* development side (tools/, which has a disassembler) and stored in the definition.
|
||||
*
|
||||
* The search uses the longest run of fixed bytes as an anchor, then checks the whole pattern
|
||||
* at each anchor match.
|
||||
*/
|
||||
import { DefinitionError } from '../errors.ts';
|
||||
import type { PeImage } from '../pe-image.ts';
|
||||
|
||||
export const METHOD = 'signature';
|
||||
const WILDCARD = '??';
|
||||
const DEFAULT_LIMIT = 8;
|
||||
|
||||
type Token = number | null;
|
||||
|
||||
export function locateSignature(image: PeImage, spec: Readonly<Record<string, unknown>>): number[] {
|
||||
if (typeof spec.pattern !== 'string') throw new DefinitionError('signature locate needs a string "pattern"');
|
||||
const sectionName = typeof spec.section === 'string' ? spec.section : '.text';
|
||||
const limit = typeof spec.limit === 'number' ? spec.limit : DEFAULT_LIMIT;
|
||||
|
||||
const tokens = parsePattern(spec.pattern);
|
||||
const anchor = longestFixedRun(tokens);
|
||||
const data = image.sectionBytes(sectionName);
|
||||
const base = image.section(sectionName).rva;
|
||||
|
||||
const haystack = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
||||
const hits: number[] = [];
|
||||
for (let from = 0; hits.length < limit;) {
|
||||
const found = haystack.indexOf(anchor.bytes, from);
|
||||
if (found < 0) break;
|
||||
const start = found - anchor.position;
|
||||
if (start >= 0 && matchesAt(data, start, tokens)) hits.push(base + start);
|
||||
from = found + 1;
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
function parsePattern(pattern: string): Token[] {
|
||||
const parts = pattern.split(/\s+/).filter(Boolean);
|
||||
if (!parts.length) throw new DefinitionError('signature pattern is empty');
|
||||
return parts.map((part) => {
|
||||
if (part === WILDCARD) return null;
|
||||
if (!/^[0-9a-fA-F]{2}$/.test(part)) throw new DefinitionError(`pattern token must be a hex byte or ${WILDCARD}, got "${part}"`);
|
||||
return Number.parseInt(part, 16);
|
||||
});
|
||||
}
|
||||
|
||||
function longestFixedRun(tokens: readonly Token[]): { position: number; bytes: Buffer } {
|
||||
let best = { position: 0, length: 0 };
|
||||
let runStart = 0;
|
||||
tokens.forEach((token, index) => {
|
||||
if (token === null) {
|
||||
runStart = index + 1;
|
||||
return;
|
||||
}
|
||||
if (index + 1 - runStart > best.length) best = { position: runStart, length: index + 1 - runStart };
|
||||
});
|
||||
if (!best.length) throw new DefinitionError('signature pattern has no fixed bytes');
|
||||
return { position: best.position, bytes: Buffer.from(tokens.slice(best.position, best.position + best.length) as number[]) };
|
||||
}
|
||||
|
||||
function matchesAt(data: Uint8Array, start: number, tokens: readonly Token[]): boolean {
|
||||
if (start + tokens.length > data.length) return false;
|
||||
return tokens.every((token, index) => token === null || data[start + index] === token);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* 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),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Work out every write first; nothing is written here.
|
||||
*
|
||||
* Per patch: find the site, require exactly one match, check the bytes there are the ones the
|
||||
* definition expects. A patch failing any of these gets a reason instead of a write, and so
|
||||
* does every patch that depends on it, so a game update yields a list of unavailable patches
|
||||
* and the features they cover rather than a broken executable.
|
||||
*/
|
||||
import type { PatchDefinition } from './definition.ts';
|
||||
import { DefinitionError, LocateError, PatchError, VerifyError } from './errors.ts';
|
||||
import { locatorFor } from './locate/index.ts';
|
||||
import type { PeImage } from './pe-image.ts';
|
||||
|
||||
export interface PlannedWrite {
|
||||
readonly patchId: string;
|
||||
readonly rva: number;
|
||||
readonly fileOffset: number;
|
||||
readonly payload: Uint8Array;
|
||||
readonly expectOriginal: Uint8Array;
|
||||
}
|
||||
|
||||
export interface PatchFailure {
|
||||
readonly patchId: string;
|
||||
readonly features: readonly string[];
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
export interface PatchPlan {
|
||||
readonly writes: readonly PlannedWrite[];
|
||||
readonly failures: readonly PatchFailure[];
|
||||
}
|
||||
|
||||
export function planPatches(image: PeImage, definitions: readonly PatchDefinition[]): PatchPlan {
|
||||
const planned = new Map<string, PlannedWrite>();
|
||||
const failed = new Map<string, string>();
|
||||
for (const definition of definitions) {
|
||||
try {
|
||||
planned.set(definition.id, planOne(image, definition));
|
||||
} catch (error) {
|
||||
if (!(error instanceof PatchError)) throw error;
|
||||
failed.set(definition.id, error.message);
|
||||
}
|
||||
}
|
||||
propagateFailures(definitions, failed);
|
||||
|
||||
const writes = definitions.filter((item) => !failed.has(item.id)).map((item) => planned.get(item.id)!);
|
||||
rejectOverlaps(writes);
|
||||
const failures = definitions.filter((item) => failed.has(item.id))
|
||||
.map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! }));
|
||||
return { writes, failures };
|
||||
}
|
||||
|
||||
export function describePlan(plan: PatchPlan): string {
|
||||
const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`];
|
||||
for (const write of plan.writes) lines.push(` ready ${write.patchId} at 0x${write.rva.toString(16)}`);
|
||||
for (const failure of plan.failures) lines.push(` FAILED ${failure.patchId}: ${failure.reason}`);
|
||||
const features = [...new Set(plan.failures.flatMap((failure) => failure.features))].sort();
|
||||
if (plan.failures.length) lines.push(` features affected: ${features.join(', ') || 'none recorded'}`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function planOne(image: PeImage, definition: PatchDefinition): PlannedWrite {
|
||||
const hits = locatorFor(definition.locate.method)(image, definition.locate);
|
||||
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(', ')}`);
|
||||
|
||||
const rva = hits[0]! + definition.edit.offset;
|
||||
const actual = image.read(rva, definition.edit.expectOriginal.length);
|
||||
if (!Buffer.from(actual).equals(definition.edit.expectOriginal)) {
|
||||
throw new VerifyError(`bytes at ${hex(rva)} are ${Buffer.from(actual).toString('hex')}, expected ` +
|
||||
`${Buffer.from(definition.edit.expectOriginal).toString('hex')} (different game build, or already patched)`);
|
||||
}
|
||||
return { patchId: definition.id, rva, fileOffset: image.fileOffset(rva), payload: definition.edit.payload, expectOriginal: definition.edit.expectOriginal };
|
||||
}
|
||||
|
||||
/** A patch whose prerequisite is unavailable cannot be applied either. */
|
||||
function propagateFailures(definitions: readonly PatchDefinition[], failed: Map<string, string>): void {
|
||||
for (let changed = true; changed;) {
|
||||
changed = false;
|
||||
for (const definition of definitions) {
|
||||
if (failed.has(definition.id)) continue;
|
||||
const blocking = definition.requires.filter((id) => failed.has(id));
|
||||
if (blocking.length) {
|
||||
failed.set(definition.id, `depends on unavailable patch(es): ${blocking.join(', ')}`);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rejectOverlaps(writes: readonly PlannedWrite[]): void {
|
||||
const sorted = [...writes].sort((left, right) => left.fileOffset - right.fileOffset);
|
||||
for (let index = 1; index < sorted.length; index++) {
|
||||
const earlier = sorted[index - 1]!;
|
||||
const later = sorted[index]!;
|
||||
if (later.fileOffset < earlier.fileOffset + earlier.payload.length) {
|
||||
throw new DefinitionError(`${earlier.patchId} and ${later.patchId} write overlapping bytes at ${hex(earlier.rva)} and ${hex(later.rva)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function hex(value: number): string {
|
||||
return `0x${value.toString(16)}`;
|
||||
}
|
||||
Reference in new issue
Block a user