Let each patch carry variants written for different game builds

A game update used to fail a patch whenever any byte it compared moved, even
when only an address in the instruction changed. Patch definitions now say
what a change needs and read the rest from the code:

- patch.jsonc holds a list of variants, each written for one game build
  (written_for) with its own locate block and edit; locate.jsonc is merged
  into it. Exactly one variant must apply, otherwise the patch is left out.
  GUI script patches use the same variants rule.
- expect_original and the bytes to write use the signature syntax, so
  addresses that differ between builds can be wildcards.
- A locate block can capture values at the site (rel32 targets, immediates,
  displacements); a rel32 fixup fills a hole in the written bytes from a
  capture. allow-local-host-bot-spawns now jumps to the target of the
  conditional jump it replaces instead of a stored distance, which makes it
  apply to 2.61.0.43 as well.
- verified_on is gone from the definitions. patches/versions/<version>.jsonc
  records, per checked game build, which variant of every patch applies and
  where; scripts/record-game-version.ts writes it and the launcher reads the
  recorded versions from there.

The Python tools (check-patches, patch-exe, check-gui) read the same format;
check-patches assembles a variant whose assembly names captures at the site
it was located at.

Checked: root and launcher type checks; check-patches and check-gui on
2.61.0.37 and 2.61.0.43 (12 exe and 35 GUI patches each); check-patches and
check-gui report a deliberately broken patch with a non-zero exit;
build-game-copy from 2.61.0.43 into a temporary folder. The computed bytes of
allow-local-host-bot-spawns on 2.61.0.37 equal the bytes it stored before.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 11:47:08 +08:00
1 parent 3f366651bd
commit b819912733
94 files changed
+1884 -933

No files matched your search

+8 -8
View File
@@ -1,19 +1,19 @@
/**
* 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.
* Write a verified plan into a copy of the executable's bytes. The bytes seen when planning 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 { formatBytes } from './byte-pattern.ts';
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`);
const actual = patched.subarray(write.fileOffset, write.fileOffset + write.original.length);
if (!Buffer.from(actual).equals(write.original)) {
throw new VerifyError(`${write.patchId}: bytes at file offset 0x${write.fileOffset.toString(16)} are ${formatBytes(actual)}, ` +
`expected ${formatBytes(write.original)}; nothing was written`);
}
patched.set(write.payload, write.fileOffset);
}
+45
View File
@@ -0,0 +1,45 @@
/**
* Byte patterns as written in patch definitions: hex bytes separated by spaces, "??" for a byte
* that is not fixed, e.g. "48 83 3d ?? ?? ?? ?? 00". Signatures, the expected original bytes of
* an edit and the bytes an edit writes all use this form.
*
* In a signature or an expected original a "??" matches any byte; in the bytes to write it is a
* hole that a fixup fills (fixups.ts).
*/
import { DefinitionError } from './errors.ts';
export const WILDCARD = '??';
export interface BytePattern {
/** The fixed bytes; 0 where the pattern has a wildcard. */
readonly bytes: Uint8Array;
/** true where the byte is fixed. */
readonly fixed: readonly boolean[];
}
export function parseBytePattern(text: unknown, where: string): BytePattern {
if (typeof text !== 'string') throw new DefinitionError(`${where} must be a string of hex bytes`);
const tokens = text.split(/\s+/).filter(Boolean);
if (!tokens.length) throw new DefinitionError(`${where} is empty`);
const bytes = new Uint8Array(tokens.length);
const fixed = tokens.map((token, index) => {
if (token === WILDCARD) return false;
if (!/^[0-9a-fA-F]{2}$/.test(token)) throw new DefinitionError(`${where}: token must be a hex byte or ${WILDCARD}, got "${token}"`);
bytes[index] = Number.parseInt(token, 16);
return true;
});
return { bytes, fixed };
}
export function patternMatches(pattern: BytePattern, data: Uint8Array, start = 0): boolean {
if (start < 0 || start + pattern.bytes.length > data.length) return false;
return pattern.fixed.every((isFixed, index) => !isFixed || data[start + index] === pattern.bytes[index]);
}
export function formatBytePattern(pattern: BytePattern): string {
return Array.from(pattern.bytes, (byte, index) => (pattern.fixed[index] ? byte.toString(16).padStart(2, '0') : WILDCARD)).join(' ');
}
export function formatBytes(bytes: Uint8Array): string {
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(' ');
}
+79
View File
@@ -0,0 +1,79 @@
/**
* Values read from the code at a located site: the target of a relative jump, call or
* rip-relative operand, or an immediate or displacement such as a structure field offset.
* A fixup can write a captured value into the bytes of an edit (fixups.ts), and the native
* hook library receives resolved values the same way, so nothing that moves between game
* builds has to be written down as a constant.
*
* Positions are counted from the site. A capture must lie inside the bytes the locate method
* checked, so its meaning is fixed by the surrounding code.
*/
import { DefinitionError } from './errors.ts';
import { rejectUnknownKeys } from './json-fields.ts';
import type { PeImage } from './pe-image.ts';
/** rel32: a 32-bit displacement, captured as the RVA it points to. The others are read as is. */
export const CAPTURE_TYPES = ['rel32', 'u8', 'u16', 'u32', 'i8', 'i16', 'i32'] as const;
export type CaptureType = (typeof CAPTURE_TYPES)[number];
const SIZES: Readonly<Record<CaptureType, number>> = { rel32: 4, u8: 1, u16: 2, u32: 4, i8: 1, i16: 2, i32: 4 };
const KEYS = new Set(['offset', 'type', 'end']);
export interface CaptureSpec {
readonly name: string;
readonly offset: number;
readonly type: CaptureType;
/**
* rel32 only: where the instruction holding the displacement ends, which is what the
* displacement is relative to. Defaults to right after the displacement; an instruction with
* an immediate after a rip-relative operand ends later.
*/
readonly end: number;
}
export type Captures = ReadonlyMap<string, number>;
export function readCaptureSpecs(raw: unknown, checkedLength: number, where: string): CaptureSpec[] {
if (raw === undefined) return [];
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new DefinitionError(`${where}: "captures" must be an object of named captures`);
return Object.entries(raw as Record<string, unknown>).map(([name, value]) => readCaptureSpec(name, value, checkedLength, `${where} capture "${name}"`));
}
function readCaptureSpec(name: string, raw: unknown, checkedLength: number, where: string): CaptureSpec {
if (!/^[a-z][a-z0-9_]*$/.test(name)) throw new DefinitionError(`${where}: names are lower case letters, digits and "_"`);
if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where} must be an object`);
const spec = raw as Record<string, unknown>;
rejectUnknownKeys(spec, KEYS, where);
const type = spec.type as CaptureType;
if (!CAPTURE_TYPES.includes(type)) throw new DefinitionError(`${where}: "type" must be one of ${CAPTURE_TYPES.join(', ')}`);
const offset = integer(spec.offset, `${where} offset`);
const size = SIZES[type];
if (offset < 0 || offset + size > checkedLength) throw new DefinitionError(`${where}: bytes ${offset}..${offset + size} are outside the ${checkedLength} checked bytes`);
if (spec.end !== undefined && type !== 'rel32') throw new DefinitionError(`${where}: "end" applies to rel32 only`);
const end = spec.end === undefined ? offset + size : integer(spec.end, `${where} end`);
if (end < offset + size) throw new DefinitionError(`${where}: the instruction cannot end before its displacement`);
return { name, offset, type, end };
}
export function readCaptures(image: PeImage, site: number, specs: readonly CaptureSpec[]): Captures {
return new Map(specs.map((spec) => [spec.name, readCapture(image, site, spec)]));
}
function readCapture(image: PeImage, site: number, spec: CaptureSpec): number {
const bytes = image.read(site + spec.offset, SIZES[spec.type]);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
switch (spec.type) {
case 'rel32': return site + spec.end + view.getInt32(0, true);
case 'u8': return view.getUint8(0);
case 'u16': return view.getUint16(0, true);
case 'u32': return view.getUint32(0, true);
case 'i8': return view.getInt8(0);
case 'i16': return view.getInt16(0, true);
case 'i32': return view.getInt32(0, true);
}
}
function integer(value: unknown, where: string): number {
if (typeof value !== 'number' || !Number.isInteger(value)) throw new DefinitionError(`${where} must be an integer`);
return value;
}
+52 -75
View File
@@ -1,36 +1,46 @@
/**
* Patch definitions as stored on disk, one directory per change to the program's behaviour,
* under patches/exe/<domain>/<name>/:
* Exe patch definitions as stored on disk, one directory per change to the program's behaviour,
* under patches/exe/<domain>/<name>/patch.jsonc:
*
* patch.jsonc id, title, features, required patches, the game versions it was verified
* on, and the bytes to write; comments explain the change and why the local
* server cannot provide it
* locate.jsonc how to find the site
* id, title, features, requires what the patch is; comments explain the change and why the
* local server cannot provide it
* variants ways to make the change, each written for one game build:
* where it goes ("locate") and what to write ("edit")
*
* Unknown keys are rejected so that explanations stay in comments and in the patch notes
* instead of growing into data fields.
* Most patches have one variant. When a game update changes the code a variant relies on, a
* new variant is added for that patch alone; the engine tries every variant and requires that
* exactly one applies. Which builds a variant was checked on is recorded per game version in
* patches/versions/, not here.
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc';
import { parseBytePattern, type BytePattern } from './byte-pattern.ts';
import { DefinitionError } from './errors.ts';
import { readFixupSpecs, type FixupSpec } from './fixups.ts';
import { readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from './json-fields.ts';
import { readSiteSpec, type SiteSpec } from './site.ts';
const PATCH_FILE = 'patch.jsonc';
const LOCATE_FILE = 'locate.jsonc';
const PATCH_KEYS = new Set(['id', 'title', 'features', 'requires', 'verified_on', 'edit']);
const EDIT_KEYS = new Set(['offset', 'asm', 'data', 'bytes', 'expect_original']);
const LOCATE_KEYS = new Set(['method', 'section', 'pattern']);
const PATCH_KEYS = new Set(['id', 'title', 'features', 'requires', 'variants']);
const VARIANT_KEYS = new Set(['written_for', 'locate', 'edit']);
/** asm and data are the human-readable source of `bytes`; tools/ checks they agree. */
const EDIT_KEYS = new Set(['offset', 'asm', 'data', 'bytes', 'expect_original', 'fixups']);
export interface PatchEdit {
/** Distance from the located site to the first byte written. */
readonly offset: number;
readonly payload: Uint8Array;
readonly expectOriginal: Uint8Array;
/** The bytes to write; holes are filled by `fixups`. */
readonly payload: BytePattern;
readonly fixups: readonly FixupSpec[];
/** The bytes that must be there; wildcards accept any byte. */
readonly expectOriginal: BytePattern;
}
export interface LocateSpec {
readonly method: string;
readonly [key: string]: unknown;
export interface PatchVariant {
/** The game version this variant was written against; names the variant. */
readonly writtenFor: string;
readonly locate: SiteSpec;
readonly edit: PatchEdit;
}
export interface PatchDefinition {
@@ -38,9 +48,7 @@ export interface PatchDefinition {
readonly title: string;
readonly features: readonly string[];
readonly requires: readonly string[];
readonly verifiedOn: readonly string[];
readonly edit: PatchEdit;
readonly locate: LocateSpec;
readonly variants: readonly PatchVariant[];
readonly directory: string;
}
@@ -65,68 +73,37 @@ function findDefinitionDirectories(root: string): string[] {
function readDefinition(directory: string): PatchDefinition {
const where = join(directory, PATCH_FILE);
const locateWhere = join(directory, LOCATE_FILE);
const patch = readJson(where);
const locate = readJson(locateWhere);
const patch = readJsonObject(where);
rejectUnknownKeys(patch, PATCH_KEYS, where);
rejectUnknownKeys(locate, LOCATE_KEYS, locateWhere);
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(`${locateWhere}: needs a string "method"`);
const verifiedOn = stringList(patch.verified_on, where, 'verified_on');
if (verifiedOn.length === 0) throw new DefinitionError(`${where}: "verified_on" must name at least one game version`);
return {
id: patch.id,
title: patch.title,
features: stringList(patch.features, where, 'features'),
requires: stringList(patch.requires, where, 'requires'),
verifiedOn,
edit: readEdit(patch.edit, where),
locate: locate as LocateSpec,
id: requiredString(patch.id, `${where} id`),
title: requiredString(patch.title, `${where} title`),
features: stringList(patch.features, `${where} features`),
requires: stringList(patch.requires, `${where} requires`),
variants: variantObjects(patch.variants, where).map((variant) => readVariant(variant, `${where} variant ${String(variant.written_for)}`)),
directory,
};
}
function readEdit(raw: unknown, where: string): PatchEdit {
if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where}: "edit" must be an object`);
function readVariant(variant: Record<string, unknown>, where: string): PatchVariant {
rejectUnknownKeys(variant, VARIANT_KEYS, where);
const locate = readSiteSpec(variant.locate, `${where} locate`);
return { writtenFor: variant.written_for as string, locate, edit: readEdit(variant.edit, locate, `${where} edit`) };
}
function readEdit(raw: unknown, locate: SiteSpec, where: string): PatchEdit {
if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where} must be an object`);
const edit = raw as Record<string, unknown>;
rejectUnknownKeys(edit, EDIT_KEYS, `${where} edit`);
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}`);
rejectUnknownKeys(edit, EDIT_KEYS, where);
const payload = parseBytePattern(edit.bytes, `${where} bytes`);
const expectOriginal = parseBytePattern(edit.expect_original, `${where} expect_original`);
if (payload.bytes.length !== expectOriginal.bytes.length) {
throw new DefinitionError(`${where}: bytes is ${payload.bytes.length} bytes but expect_original is ${expectOriginal.bytes.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 = parseJsonc(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 rejectUnknownKeys(object: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
const unknown = Object.keys(object).filter((key) => !allowed.has(key));
if (unknown.length) {
throw new DefinitionError(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`);
}
if (typeof offset !== 'number' || !Number.isInteger(offset)) throw new DefinitionError(`${where}: offset must be an integer`);
const captureNames = new Set(locate.captures.map((capture) => capture.name));
return { offset, payload, fixups: readFixupSpecs(edit.fixups, payload, captureNames, where), expectOriginal };
}
function isFile(path: string): boolean {
+74
View File
@@ -0,0 +1,74 @@
/**
* Filling the holes ("??") in the bytes an edit writes. A fixup computes the value from a capture
* at the site, so an edit that jumps to existing code names that code (for example the target
* of the conditional jump it replaces) instead of storing a distance that changes between builds.
*
* Every hole must be filled by exactly one fixup, and a fixup may only write into holes, so the
* fixed bytes of an edit are exactly what the definition stores.
*/
import type { BytePattern } from './byte-pattern.ts';
import type { Captures } from './captures.ts';
import { DefinitionError } from './errors.ts';
import { asObject, rejectUnknownKeys, requiredString } from './json-fields.ts';
/** rel32: the displacement from the end of the written instruction to the captured RVA. */
export const FIXUP_TYPES = ['rel32'] as const;
export type FixupType = (typeof FIXUP_TYPES)[number];
const KEYS = new Set(['at', 'type', 'target', 'end']);
const REL32_SIZE = 4;
export interface FixupSpec {
/** Position of the hole in the written bytes. */
readonly at: number;
readonly type: FixupType;
/** Name of the capture whose value is written. */
readonly target: string;
/** Where the written instruction ends; defaults to right after the displacement. */
readonly end: number;
}
export function readFixupSpecs(raw: unknown, payload: BytePattern, captureNames: ReadonlySet<string>, where: string): FixupSpec[] {
const list = raw === undefined ? [] : raw;
if (!Array.isArray(list)) throw new DefinitionError(`${where}: "fixups" must be a list`);
const fixups = list.map((item, index) => readFixupSpec(item, captureNames, `${where} fixups[${index}]`));
requireHolesFilledOnce(payload, fixups, where);
return fixups;
}
function readFixupSpec(raw: unknown, captureNames: ReadonlySet<string>, where: string): FixupSpec {
const spec = asObject(raw, where);
rejectUnknownKeys(spec, KEYS, where);
if (!FIXUP_TYPES.includes(spec.type as FixupType)) throw new DefinitionError(`${where}: "type" must be one of ${FIXUP_TYPES.join(', ')}`);
const target = requiredString(spec.target, `${where} target`);
if (!captureNames.has(target)) throw new DefinitionError(`${where}: no capture named "${target}" in this variant`);
if (typeof spec.at !== 'number' || !Number.isInteger(spec.at)) throw new DefinitionError(`${where}: "at" must be an integer`);
const end = spec.end ?? spec.at + REL32_SIZE;
if (typeof end !== 'number' || !Number.isInteger(end) || end < spec.at + REL32_SIZE) throw new DefinitionError(`${where}: "end" must be an integer after the displacement`);
return { at: spec.at, type: spec.type as FixupType, target, end };
}
function requireHolesFilledOnce(payload: BytePattern, fixups: readonly FixupSpec[], where: string): void {
const filled = payload.fixed.map(() => 0);
for (const fixup of fixups) {
for (let index = fixup.at; index < fixup.at + REL32_SIZE; index++) {
if (index >= filled.length || payload.fixed[index]) throw new DefinitionError(`${where}: a fixup at ${fixup.at} writes over fixed bytes or past the end`);
filled[index]! += 1;
}
}
const wrong = filled.findIndex((count, index) => !payload.fixed[index] && count !== 1);
if (wrong >= 0) throw new DefinitionError(`${where}: byte ${wrong} of "bytes" is a hole that no fixup fills`);
}
/** The bytes to write at `rva`, with every hole filled from `captures`. */
export function resolvePayload(payload: BytePattern, fixups: readonly FixupSpec[], rva: number, captures: Captures): Uint8Array {
const bytes = Uint8Array.from(payload.bytes);
const view = new DataView(bytes.buffer);
for (const fixup of fixups) {
const target = captures.get(fixup.target)!;
const displacement = target - (rva + fixup.end);
if (displacement < -0x8000_0000 || displacement > 0x7fff_ffff) throw new DefinitionError(`fixup at ${fixup.at}: target 0x${target.toString(16)} is out of rel32 range`);
view.setInt32(fixup.at, displacement, true);
}
return bytes;
}
+9 -3
View File
@@ -1,11 +1,17 @@
/**
* Apply the declarative patches under patches/exe/ 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/.
* never guessed. The same locating (sites with captures) serves the native hook library's
* definitions. 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 { formatBytePattern, formatBytes, parseBytePattern, patternMatches, type BytePattern } from './byte-pattern.ts';
export { CAPTURE_TYPES, type Captures, type CaptureSpec, type CaptureType } from './captures.ts';
export { loadPatches, type PatchDefinition, type PatchEdit, type PatchVariant } from './definition.ts';
export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError } from './errors.ts';
export { asObject, readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from './json-fields.ts';
export { PeImage, type Section } from './pe-image.ts';
export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
export { findSite, readSiteSpec, type FoundSite, type SiteSpec } from './site.ts';
export { chooseVariant, type Chosen, type Variant } from './variants.ts';
+50
View File
@@ -0,0 +1,50 @@
/**
* Reading definition files: JSONC objects whose unknown keys are refused, so explanations stay
* in comments and in the patch notes instead of growing into data fields.
*/
import { readFileSync } from 'node:fs';
import { parseJsonc } from '@wto/jsonc';
import { DefinitionError } from './errors.ts';
export function readJsonObject(path: string): Record<string, unknown> {
let data: unknown;
try {
data = parseJsonc(readFileSync(path, 'utf-8'));
} catch (error) {
throw new DefinitionError(`${path}: ${(error as Error).message}`);
}
return asObject(data, path);
}
export function asObject(value: unknown, where: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new DefinitionError(`${where}: expected an object`);
return value as Record<string, unknown>;
}
export function rejectUnknownKeys(object: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
const unknown = Object.keys(object).filter((key) => !allowed.has(key));
if (unknown.length) {
throw new DefinitionError(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`);
}
}
export function requiredString(value: unknown, where: string): string {
if (typeof value !== 'string' || value === '') throw new DefinitionError(`${where} must be a non-empty string`);
return value;
}
export function stringList(value: unknown, where: string): string[] {
if (value === undefined) return [];
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) throw new DefinitionError(`${where} must be a list of strings`);
return value;
}
/** The "variants" list of a definition, each entry an object, and their written_for names unique. */
export function variantObjects(value: unknown, where: string): Record<string, unknown>[] {
if (!Array.isArray(value) || value.length === 0) throw new DefinitionError(`${where}: "variants" must be a non-empty list`);
const variants = value.map((item, index) => asObject(item, `${where} variants[${index}]`));
const names = variants.map((variant, index) => requiredString(variant.written_for, `${where} variants[${index}].written_for`));
const duplicate = names.find((name, index) => names.indexOf(name) !== index);
if (duplicate) throw new DefinitionError(`${where}: two variants are written for ${duplicate}`);
return variants;
}
+16 -8
View File
@@ -1,17 +1,25 @@
/**
* 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.
* Ways to find a 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[];
export interface LocateMethod {
/** Keys of a locate block this method reads, besides "method" and "captures". */
readonly keys: readonly string[];
locate(image: PeImage, spec: Readonly<Record<string, unknown>>): number[];
/** Number of bytes from the site that the method checked; captures must lie inside them. */
length(spec: Readonly<Record<string, unknown>>): number;
}
const METHODS: ReadonlyMap<string, Locator> = new Map([[signature.METHOD, signature.locateSignature]]);
const METHODS: ReadonlyMap<string, LocateMethod> = new Map([
[signature.METHOD, { keys: signature.KEYS, locate: signature.locateSignature, length: signature.signatureLength }],
]);
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;
export function locateMethod(method: unknown): LocateMethod {
const found = typeof method === 'string' ? METHODS.get(method) : undefined;
if (!found) throw new DefinitionError(`unknown locate method "${String(method)}"; known: ${[...METHODS.keys()].join(', ')}`);
return found;
}
+17 -30
View File
@@ -1,5 +1,5 @@
/**
* Find a patch site by a byte pattern with wildcards, e.g. "41 57 41 56 48 81 ec ?? ?? ?? ??".
* Find a 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
@@ -8,62 +8,49 @@
* The search uses the longest run of fixed bytes as an anchor, then checks the whole pattern
* at each anchor match.
*/
import { parseBytePattern, patternMatches, type BytePattern } from '../byte-pattern.ts';
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 const KEYS: readonly string[] = ['section', 'pattern'];
const DEFAULT_SECTION = '.text';
const HIT_LIMIT = 8;
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 sectionName = typeof spec.section === 'string' ? spec.section : DEFAULT_SECTION;
const pattern = parseBytePattern(spec.pattern, 'signature pattern');
const anchor = longestFixedRun(pattern);
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;) {
for (let from = 0; hits.length < HIT_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);
if (patternMatches(pattern, data, start)) 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);
});
/** Number of bytes a signature covers. */
export function signatureLength(spec: Readonly<Record<string, unknown>>): number {
return parseBytePattern(spec.pattern, 'signature pattern').bytes.length;
}
function longestFixedRun(tokens: readonly Token[]): { position: number; bytes: Buffer } {
function longestFixedRun(pattern: BytePattern): { position: number; bytes: Buffer } {
let best = { position: 0, length: 0 };
let runStart = 0;
tokens.forEach((token, index) => {
if (token === null) {
pattern.fixed.forEach((isFixed, index) => {
if (!isFixed) {
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);
return { position: best.position, bytes: Buffer.from(pattern.bytes.subarray(best.position, best.position + best.length)) };
}
+27 -24
View File
@@ -1,22 +1,29 @@
/**
* 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.
* Per patch: choose the variant that fits (variants.ts); for it, find the site, require exactly
* one match, check the bytes there against the expected original, and fill the holes of the
* bytes to write from the site's captures. 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 { formatBytePattern, formatBytes, patternMatches } from './byte-pattern.ts';
import type { PatchDefinition, PatchVariant } from './definition.ts';
import { DefinitionError, PatchError, VerifyError } from './errors.ts';
import { resolvePayload } from './fixups.ts';
import type { PeImage } from './pe-image.ts';
import { findSite, hex } from './site.ts';
import { chooseVariant } from './variants.ts';
export interface PlannedWrite {
readonly patchId: string;
/** written_for of the variant that applies. */
readonly variant: string;
readonly rva: number;
readonly fileOffset: number;
readonly payload: Uint8Array;
readonly expectOriginal: Uint8Array;
/** The bytes found at the site when planning; writing requires they are still there. */
readonly original: Uint8Array;
}
export interface PatchFailure {
@@ -35,7 +42,8 @@ export function planPatches(image: PeImage, definitions: readonly PatchDefinitio
const failed = new Map<string, string>();
for (const definition of definitions) {
try {
planned.set(definition.id, planOne(image, definition));
const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant));
planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
failed.set(definition.id, error.message);
@@ -52,25 +60,24 @@ export function planPatches(image: PeImage, definitions: readonly PatchDefinitio
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 write of plan.writes) lines.push(` ready ${write.patchId} at ${hex(write.rva)} (variant ${write.variant})`);
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(', ')}`);
type VariantWrite = Omit<PlannedWrite, 'patchId' | 'variant'>;
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)`);
function planVariant(image: PeImage, variant: PatchVariant): VariantWrite {
const site = findSite(image, variant.locate);
const { edit } = variant;
const rva = site.rva + edit.offset;
const original = Uint8Array.from(image.read(rva, edit.expectOriginal.bytes.length));
if (!patternMatches(edit.expectOriginal, original)) {
throw new VerifyError(`bytes at ${hex(rva)} are ${formatBytes(original)}, expected ${formatBytePattern(edit.expectOriginal)} (different game build, or already patched)`);
}
return { patchId: definition.id, rva, fileOffset: image.fileOffset(rva), payload: definition.edit.payload, expectOriginal: definition.edit.expectOriginal };
return { rva, fileOffset: image.fileOffset(rva), payload: resolvePayload(edit.payload, edit.fixups, rva, site.captures), original };
}
/** A patch whose prerequisite is unavailable cannot be applied either. */
@@ -98,7 +105,3 @@ function rejectOverlaps(writes: readonly PlannedWrite[]): void {
}
}
}
function hex(value: number): string {
return `0x${value.toString(16)}`;
}
+47
View File
@@ -0,0 +1,47 @@
/**
* 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, 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<Record<string, unknown>>;
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): FoundSite {
const hits = site.method.locate(image, site.spec);
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)}`;
}
+37
View File
@@ -0,0 +1,37 @@
/**
* Choosing the variant of a patch that fits the game files at hand. Every variant is tried; the
* patch applies only when exactly one of them does. None applying means the build differs from
* every build a variant was written for; two applying means the variants do not tell builds
* apart, which is a definition bug, so the patch is refused rather than guessed.
*
* Used for exe patches here and for GUI script patches in @wto/patcher.
*/
import { LocateError, PatchError } from './errors.ts';
export interface Variant {
readonly writtenFor: string;
}
export interface Chosen<V extends Variant, T> {
readonly variant: V;
readonly value: T;
}
/** `attempt` returns the variant's result, or throws a PatchError saying why it does not apply. */
export function chooseVariant<V extends Variant, T>(variants: readonly V[], attempt: (variant: V) => T): Chosen<V, T> {
const applied: Chosen<V, T>[] = [];
const reasons: string[] = [];
for (const variant of variants) {
try {
applied.push({ variant, value: attempt(variant) });
} catch (error) {
if (!(error instanceof PatchError)) throw error;
reasons.push(variants.length === 1 ? error.message : `variant ${variant.writtenFor}: ${error.message}`);
}
}
if (applied.length > 1) {
throw new LocateError(`variants ${applied.map((item) => item.variant.writtenFor).join(' and ')} all apply, so the choice is ambiguous`);
}
if (!applied.length) throw new LocateError(reasons.join('; '));
return applied[0]!;
}