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

+1 -1
View File
@@ -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,
+3 -15
View File
@@ -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();
}
+26 -16
View File
@@ -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;
}
+44 -59
View File
@@ -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);
}
}
+13 -3
View File
@@ -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';
+113
View File
@@ -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');
}