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:
1 parent
3f366651bd
commit
b819912733
94 files changed
+1884
-933
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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(' ');
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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)) };
|
||||
}
|
||||
@@ -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)}`;
|
||||
}
|
||||
@@ -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)}`;
|
||||
}
|
||||
@@ -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]!;
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
|
||||
files,
|
||||
endpoint,
|
||||
exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures },
|
||||
guiPatches: { applied: guiPack.applied.map((patch) => patch.id), failures: guiPack.failures },
|
||||
guiPatches: { applied: guiPack.applied.map((item) => item.patch.id), failures: guiPack.failures },
|
||||
blocking: blockingFailures(failures),
|
||||
charPack: charReport,
|
||||
engineAddresses: mainPack.addresses,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
/**
|
||||
* The game version of a stock folder, and the versions the patches were verified on
|
||||
* (a version that differs is only pointed out, never refused).
|
||||
* The game version of a stock folder (a version without a record in patches/versions/ is only
|
||||
* pointed out, never refused; version-record.ts).
|
||||
*
|
||||
* The version is the file version of win64/aces.exe: the VS_FIXEDFILEINFO block in its version
|
||||
* resource, which Windows shows as "File version" (2.61.0.37 for the target build).
|
||||
*/
|
||||
import { loadPatches, PeImage } from '@wto/exepatch';
|
||||
import { loadGuiPatches } from './gui-patch-definition.ts';
|
||||
import { PeImage } from '@wto/exepatch';
|
||||
|
||||
/** VS_FIXEDFILEINFO.dwSignature, little-endian. */
|
||||
const FIXED_FILE_INFO_SIGNATURE = 0xfeef04bd;
|
||||
@@ -29,14 +28,3 @@ export function executableVersion(executable: Uint8Array): string | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The game versions every exe patch and every GUI patch names in `verified_on`. */
|
||||
export function verifiedGameVersions(exePatches: string, guiPatches: string): string[] {
|
||||
const lists = [
|
||||
...loadPatches(exePatches).map((patch) => patch.verifiedOn),
|
||||
...loadGuiPatches(guiPatches).map((patch) => patch.verifiedOn),
|
||||
];
|
||||
const [first, ...rest] = lists;
|
||||
if (!first) return [];
|
||||
return first.filter((version) => rest.every((list) => list.includes(version))).sort();
|
||||
}
|
||||
@@ -2,25 +2,34 @@
|
||||
* Rebuild gui.vromfs.bin by applying the script patch definitions in the GUI patch folder
|
||||
* (format in gui-patch-definition.ts).
|
||||
*
|
||||
* Every edit must find its stock text exactly once in the current script. A patch with an edit
|
||||
* that does not is left out whole, never half applied, and listed with the features it covers, the same way an unavailable exe patch is; the other patches are applied.
|
||||
* A variant applies when every one of its edits finds its stock text exactly once in the current
|
||||
* script; exactly one variant of a patch must apply. A patch with no applicable variant is left
|
||||
* out whole, never half applied, and listed with the features it covers, the same way an
|
||||
* unavailable exe patch is; the other patches are applied.
|
||||
*/
|
||||
import type { PatchFailure } from '@wto/exepatch';
|
||||
import { chooseVariant, PatchError, type PatchFailure } from '@wto/exepatch';
|
||||
import { getFile, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
|
||||
import { loadGuiPatches, type GuiScriptPatch } from './gui-patch-definition.ts';
|
||||
import { loadGuiPatches, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts';
|
||||
import type { LocalEndpoint } from './network/local-endpoint.ts';
|
||||
|
||||
const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}';
|
||||
|
||||
export interface AppliedGuiPatch {
|
||||
readonly patch: GuiScriptPatch;
|
||||
readonly variant: GuiScriptVariant;
|
||||
}
|
||||
|
||||
export interface GuiPackResult {
|
||||
/** The data pack with every applicable patch written. */
|
||||
readonly pack: Uint8Array;
|
||||
readonly applied: readonly GuiScriptPatch[];
|
||||
readonly applied: readonly AppliedGuiPatch[];
|
||||
readonly failures: readonly PatchFailure[];
|
||||
}
|
||||
|
||||
/** The stock text of an edit was not found exactly once, or the target script is missing. */
|
||||
class GuiPatchMismatch extends Error {}
|
||||
class GuiPatchMismatch extends PatchError {
|
||||
override name = 'GuiPatchMismatch';
|
||||
}
|
||||
|
||||
export function rebuildGuiPack(
|
||||
stockPack: Uint8Array,
|
||||
@@ -30,15 +39,16 @@ export function rebuildGuiPack(
|
||||
const patches = loadGuiPatches(patchesFolder);
|
||||
const archive = readArchive(stockPack);
|
||||
const hostPortText = `${endpoint.host}:${endpoint.port}`;
|
||||
const applied: GuiScriptPatch[] = [];
|
||||
const applied: AppliedGuiPatch[] = [];
|
||||
const failures: PatchFailure[] = [];
|
||||
|
||||
for (const patch of patches) {
|
||||
try {
|
||||
putFile(archive, patch.file, Buffer.from(patchedScript(archive, patch, hostPortText), 'utf8'));
|
||||
applied.push(patch);
|
||||
const chosen = chooseVariant(patch.variants, (variant) => patchedScript(archive, variant, hostPortText));
|
||||
putFile(archive, chosen.variant.file, Buffer.from(chosen.value, 'utf8'));
|
||||
applied.push({ patch, variant: chosen.variant });
|
||||
} catch (error) {
|
||||
if (!(error instanceof GuiPatchMismatch)) throw error;
|
||||
if (!(error instanceof PatchError)) throw error;
|
||||
failures.push({ patchId: patch.id, features: patch.features, reason: error.message });
|
||||
}
|
||||
}
|
||||
@@ -46,14 +56,14 @@ export function rebuildGuiPack(
|
||||
return { pack: writeArchive(archive), applied, failures };
|
||||
}
|
||||
|
||||
/** The target script with every edit of `patch` made; throws GuiPatchMismatch before any change. */
|
||||
function patchedScript(archive: Archive, patch: GuiScriptPatch, hostPortText: string): string {
|
||||
if (!archive.files.has(patch.file)) throw new GuiPatchMismatch(`the data pack has no script ${patch.file}`);
|
||||
let current = Buffer.from(getFile(archive, patch.file)).toString('utf8');
|
||||
/** The target script with every edit of `variant` made; throws GuiPatchMismatch before any change. */
|
||||
function patchedScript(archive: Archive, variant: GuiScriptVariant, hostPortText: string): string {
|
||||
if (!archive.files.has(variant.file)) throw new GuiPatchMismatch(`the data pack has no script ${variant.file}`);
|
||||
let current = Buffer.from(getFile(archive, variant.file)).toString('utf8');
|
||||
const newline = current.includes('\r\n') ? '\r\n' : '\n';
|
||||
for (const [index, edit] of patch.edits.entries()) {
|
||||
for (const [index, edit] of variant.edits.entries()) {
|
||||
const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
|
||||
current = replaceUnique(current, edit.find, replace, `edit ${index + 1} in ${patch.file}`);
|
||||
current = replaceUnique(current, edit.find, replace, `edit ${index + 1} in ${variant.file}`);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
* GUI script patch definitions as stored on disk, one folder per change under
|
||||
* `patches/gui/<domain>/<name>/`:
|
||||
*
|
||||
* patch.jsonc id, title, target script, features, the game versions it was verified on,
|
||||
* and the list of edits; comments explain what the change does and why the
|
||||
* local server cannot provide it
|
||||
* <name>.nut the edit fragments named by `edits` (stock text to find, text to put there)
|
||||
* patch.jsonc id, title, features, and the variants; comments explain what the change does
|
||||
* and why the local server cannot provide it
|
||||
* <name>.nut the edit fragments a variant names (stock text to find, text to put there)
|
||||
*
|
||||
* A variant is the change written for one game build: the target script and its edits. Most
|
||||
* patches have one; when an update changes the stock text, a variant with its own fragment files
|
||||
* is added, and exactly one variant must apply (the same rule as exe patches, @wto/exepatch).
|
||||
*
|
||||
* Fragment files hold the exact script text followed by one terminating newline, which is not
|
||||
* part of the fragment. Line endings are normalised to `\n` here; applying matches regardless of
|
||||
@@ -14,10 +17,12 @@
|
||||
*/
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parseJsonc } from '@wto/jsonc';
|
||||
import { DefinitionError, readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from '@wto/exepatch';
|
||||
|
||||
const PATCH_FILE = 'patch.jsonc';
|
||||
const ALLOWED_KEYS = new Set(['id', 'title', 'file', 'features', 'verified_on', 'edits']);
|
||||
const PATCH_KEYS = new Set(['id', 'title', 'features', 'variants']);
|
||||
const VARIANT_KEYS = new Set(['written_for', 'file', 'edits']);
|
||||
const EDIT_KEYS = new Set(['find', 'replace']);
|
||||
|
||||
export interface GuiScriptEdit {
|
||||
/** Stock text that must occur exactly once in the target script, with `\n` line endings. */
|
||||
@@ -26,14 +31,19 @@ export interface GuiScriptEdit {
|
||||
readonly replace: string;
|
||||
}
|
||||
|
||||
export interface GuiScriptVariant {
|
||||
/** The game version this variant was written against; names the variant. */
|
||||
readonly writtenFor: string;
|
||||
/** Script path inside gui.vromfs.bin. */
|
||||
readonly file: string;
|
||||
readonly edits: readonly GuiScriptEdit[];
|
||||
}
|
||||
|
||||
export interface GuiScriptPatch {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
/** Script path inside gui.vromfs.bin. */
|
||||
readonly file: string;
|
||||
readonly features: readonly string[];
|
||||
readonly verifiedOn: readonly string[];
|
||||
readonly edits: readonly GuiScriptEdit[];
|
||||
readonly variants: readonly GuiScriptVariant[];
|
||||
readonly directory: string;
|
||||
}
|
||||
|
||||
@@ -57,76 +67,51 @@ function findDefinitionDirectories(root: string): string[] {
|
||||
|
||||
function readDefinition(directory: string): GuiScriptPatch {
|
||||
const where = join(directory, PATCH_FILE);
|
||||
const raw = readObject(where);
|
||||
const unknown = Object.keys(raw).filter((key) => !ALLOWED_KEYS.has(key));
|
||||
if (unknown.length) {
|
||||
throw new Error(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`);
|
||||
}
|
||||
const raw = readJsonObject(where);
|
||||
rejectUnknownKeys(raw, PATCH_KEYS, where);
|
||||
return {
|
||||
id: requiredString(raw.id, where, 'id'),
|
||||
title: requiredString(raw.title, where, 'title'),
|
||||
file: requiredString(raw.file, where, 'file'),
|
||||
features: stringList(raw.features, where, 'features'),
|
||||
verifiedOn: nonEmptyStringList(raw.verified_on, where, 'verified_on'),
|
||||
edits: readEdits(raw.edits, directory, where),
|
||||
id: requiredString(raw.id, `${where} id`),
|
||||
title: requiredString(raw.title, `${where} title`),
|
||||
features: stringList(raw.features, `${where} features`),
|
||||
variants: variantObjects(raw.variants, where).map((variant) => readVariant(variant, directory, `${where} variant ${String(variant.written_for)}`)),
|
||||
directory,
|
||||
};
|
||||
}
|
||||
|
||||
function readVariant(variant: Record<string, unknown>, directory: string, where: string): GuiScriptVariant {
|
||||
rejectUnknownKeys(variant, VARIANT_KEYS, where);
|
||||
return {
|
||||
writtenFor: variant.written_for as string,
|
||||
file: requiredString(variant.file, `${where} file`),
|
||||
edits: readEdits(variant.edits, directory, where),
|
||||
};
|
||||
}
|
||||
|
||||
function readEdits(value: unknown, directory: string, where: string): GuiScriptEdit[] {
|
||||
if (!Array.isArray(value) || value.length === 0) throw new Error(`${where}: "edits" must be a non-empty list`);
|
||||
if (!Array.isArray(value) || value.length === 0) throw new DefinitionError(`${where}: "edits" must be a non-empty list`);
|
||||
return value.map((item, index) => {
|
||||
if (!item || typeof item !== 'object') throw new Error(`${where}: edits[${index}] must be an object`);
|
||||
const label = `${where} edits[${index}]`;
|
||||
if (!item || typeof item !== 'object') throw new DefinitionError(`${label} must be an object`);
|
||||
const edit = item as Record<string, unknown>;
|
||||
const find = readFragment(directory, requiredString(edit.find, where, `edits[${index}].find`));
|
||||
if (find === '') throw new Error(`${where}: edits[${index}].find is empty`);
|
||||
const replace = readFragment(directory, requiredString(edit.replace, where, `edits[${index}].replace`));
|
||||
return { find, replace };
|
||||
rejectUnknownKeys(edit, EDIT_KEYS, label);
|
||||
const find = readFragment(directory, requiredString(edit.find, `${label}.find`));
|
||||
if (find === '') throw new DefinitionError(`${label}.find is empty`);
|
||||
return { find, replace: readFragment(directory, requiredString(edit.replace, `${label}.replace`)) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Fragment text with `\n` line endings and the file's terminating newline removed. */
|
||||
export function readFragment(directory: string, name: string): string {
|
||||
if (name.includes('/') || name.includes('\\')) throw new Error(`${directory}: fragment "${name}" must be a file in the patch folder`);
|
||||
if (name.includes('/') || name.includes('\\')) throw new DefinitionError(`${directory}: fragment "${name}" must be a file in the patch folder`);
|
||||
const text = readFileSync(join(directory, name), 'utf8').replace(/^/, '').replace(/\r\n/g, '\n');
|
||||
return text.endsWith('\n') ? text.slice(0, -1) : text;
|
||||
}
|
||||
|
||||
function readObject(path: string): Record<string, unknown> {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = parseJsonc(readFileSync(path, 'utf8'));
|
||||
} catch (error) {
|
||||
throw new Error(`${path}: ${(error as Error).message}`);
|
||||
}
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`${path}: expected an object`);
|
||||
return data as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function requiredString(value: unknown, where: string, key: string): string {
|
||||
if (typeof value !== 'string' || value === '') throw new Error(`${where}: "${key}" must be a non-empty string`);
|
||||
return value;
|
||||
}
|
||||
|
||||
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 Error(`${where}: "${key}" must be a list of strings`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function nonEmptyStringList(value: unknown, where: string, key: string): string[] {
|
||||
const list = stringList(value, where, key);
|
||||
if (list.length === 0) throw new Error(`${where}: "${key}" must name at least one game version`);
|
||||
return list;
|
||||
}
|
||||
|
||||
function rejectDuplicateIds(patches: readonly GuiScriptPatch[]): void {
|
||||
const seen = new Map<string, string>();
|
||||
for (const patch of patches) {
|
||||
const previous = seen.get(patch.id);
|
||||
if (previous) throw new Error(`two GUI patches use id "${patch.id}": ${previous} and ${patch.directory}`);
|
||||
if (previous) throw new DefinitionError(`two GUI patches use id "${patch.id}": ${previous} and ${patch.directory}`);
|
||||
seen.set(patch.id, patch.directory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,9 +17,9 @@ export { copyPlayerDecalCache, playerDecalCacheProblem } from './decals/player-d
|
||||
export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
|
||||
export { patchExecutable, type ExecutableResult } from './executable.ts';
|
||||
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
|
||||
export { executableVersion, verifiedGameVersions } from './game-version.ts';
|
||||
export { rebuildGuiPack, type GuiPackResult } from './gui-pack.ts';
|
||||
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch } from './gui-patch-definition.ts';
|
||||
export { executableVersion } from './game-version.ts';
|
||||
export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts';
|
||||
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts';
|
||||
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
|
||||
export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
|
||||
export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts';
|
||||
@@ -27,4 +27,14 @@ export { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hoo
|
||||
export { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts';
|
||||
export { patchFeatures, type PatchFeature } from './patch-features.ts';
|
||||
export { offlinePackBundleGuids } from './store/offline-bundles.ts';
|
||||
export {
|
||||
checkGameBuild,
|
||||
compareVersions,
|
||||
formatVersionRecord,
|
||||
loadVersionRecords,
|
||||
recordedGameVersions,
|
||||
recordFileName,
|
||||
type RecordInputs,
|
||||
type VersionRecord,
|
||||
} from './version-record.ts';
|
||||
export { writeGameCopy } from './write-game-copy.ts';
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Version records: one file per game build the patches were checked on, under patches/versions/
|
||||
* (`<game version>.jsonc`). A record says which variant of every patch applies to that build and
|
||||
* where, and which patches are unavailable on it. The developer writes it with
|
||||
* scripts/record-game-version.ts once the build has been checked, and commits it after the
|
||||
* build was played in the game, so a record is what makes a game version "adapted".
|
||||
*
|
||||
* Patch definitions themselves carry no version list: a patch that keeps applying unchanged on a
|
||||
* new build needs no edit, only the new record names it.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { asObject, DefinitionError, loadPatches, PeImage, planPatches, readJsonObject, requiredString } from '@wto/exepatch';
|
||||
import { executableVersion } from './game-version.ts';
|
||||
import { rebuildGuiPack } from './gui-pack.ts';
|
||||
import { localEndpoint } from './network/local-endpoint.ts';
|
||||
|
||||
const RECORD_SUFFIX = '.jsonc';
|
||||
/** Any port: the record only says whether each GUI edit matches, not what it writes. */
|
||||
const CHECK_PORT = 47115;
|
||||
|
||||
export interface VersionRecord {
|
||||
readonly gameVersion: string;
|
||||
readonly executableSha256: string;
|
||||
readonly guiPackSha256: string;
|
||||
/** Patch id -> the variant that applies and the RVA it writes at. */
|
||||
readonly exePatches: Readonly<Record<string, { readonly variant: string; readonly rva: string }>>;
|
||||
/** Patch id -> the variant that applies. */
|
||||
readonly guiPatches: Readonly<Record<string, { readonly variant: string }>>;
|
||||
/** Patch id -> why it is unavailable on this build. */
|
||||
readonly unavailable: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface RecordInputs {
|
||||
readonly executable: Uint8Array;
|
||||
readonly guiPack: Uint8Array;
|
||||
readonly exePatches: string;
|
||||
readonly guiPatches: string;
|
||||
}
|
||||
|
||||
/** Check every patch against the stock files of one build. */
|
||||
export function checkGameBuild(inputs: RecordInputs): VersionRecord {
|
||||
const gameVersion = executableVersion(inputs.executable);
|
||||
if (!gameVersion) throw new DefinitionError('the executable has no version resource');
|
||||
const exePlan = planPatches(new PeImage(inputs.executable), loadPatches(inputs.exePatches));
|
||||
const gui = rebuildGuiPack(inputs.guiPack, localEndpoint(CHECK_PORT), inputs.guiPatches);
|
||||
return {
|
||||
gameVersion,
|
||||
executableSha256: sha256(inputs.executable),
|
||||
guiPackSha256: sha256(inputs.guiPack),
|
||||
exePatches: Object.fromEntries(exePlan.writes.map((write) => [write.patchId, { variant: write.variant, rva: `0x${write.rva.toString(16)}` }])),
|
||||
guiPatches: Object.fromEntries(gui.applied.map((item) => [item.patch.id, { variant: item.variant.writtenFor }])),
|
||||
unavailable: Object.fromEntries([...exePlan.failures, ...gui.failures].map((failure) => [failure.patchId, failure.reason])),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatVersionRecord(record: VersionRecord): string {
|
||||
const body = {
|
||||
game_version: record.gameVersion,
|
||||
executable_sha256: record.executableSha256,
|
||||
gui_pack_sha256: record.guiPackSha256,
|
||||
exe_patches: record.exePatches,
|
||||
gui_patches: record.guiPatches,
|
||||
unavailable: record.unavailable,
|
||||
};
|
||||
return `// Patch check results for this game build; written by scripts/record-game-version.ts.\n${JSON.stringify(body, null, 2)}\n`;
|
||||
}
|
||||
|
||||
export function recordFileName(gameVersion: string): string {
|
||||
return `${gameVersion}${RECORD_SUFFIX}`;
|
||||
}
|
||||
|
||||
/** Every record in `folder`, sorted by game version. */
|
||||
export function loadVersionRecords(folder: string): VersionRecord[] {
|
||||
return readdirSync(folder)
|
||||
.filter((name) => name.endsWith(RECORD_SUFFIX))
|
||||
.map((name) => readRecord(join(folder, name)))
|
||||
.sort((left, right) => compareVersions(left.gameVersion, right.gameVersion));
|
||||
}
|
||||
|
||||
/** The game versions that have a record. */
|
||||
export function recordedGameVersions(folder: string): string[] {
|
||||
return loadVersionRecords(folder).map((record) => record.gameVersion);
|
||||
}
|
||||
|
||||
function readRecord(path: string): VersionRecord {
|
||||
const raw = readJsonObject(path);
|
||||
const gameVersion = requiredString(raw.game_version, `${path} game_version`);
|
||||
if (!path.endsWith(recordFileName(gameVersion))) throw new DefinitionError(`${path}: file name does not match game_version ${gameVersion}`);
|
||||
return {
|
||||
gameVersion,
|
||||
executableSha256: requiredString(raw.executable_sha256, `${path} executable_sha256`),
|
||||
guiPackSha256: requiredString(raw.gui_pack_sha256, `${path} gui_pack_sha256`),
|
||||
exePatches: asObject(raw.exe_patches, `${path} exe_patches`) as VersionRecord['exePatches'],
|
||||
guiPatches: asObject(raw.gui_patches, `${path} gui_patches`) as VersionRecord['guiPatches'],
|
||||
unavailable: asObject(raw.unavailable ?? {}, `${path} unavailable`) as VersionRecord['unavailable'],
|
||||
};
|
||||
}
|
||||
|
||||
export function compareVersions(left: string, right: string): number {
|
||||
const a = left.split('.').map(Number);
|
||||
const b = right.split('.').map(Number);
|
||||
for (let index = 0; index < Math.max(a.length, b.length); index++) {
|
||||
const difference = (a[index] ?? 0) - (b[index] ?? 0);
|
||||
if (difference) return difference;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function sha256(data: Uint8Array): string {
|
||||
return createHash('sha256').update(data).digest('hex');
|
||||
}
|
||||
Reference in new issue
Block a user