diff --git a/README.md b/README.md index 6b41d14..cf7108e 100644 --- a/README.md +++ b/README.md @@ -113,10 +113,10 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不 每个补丁是一个目录,以 JSONC 描述,文件内的注释说明修改原因和不修改时的后果。 -- **exe 补丁**:`locate.jsonc` 给出特征码和所在节,`patch.jsonc` 给出写入的字节和预期的原始字节(`expect_original`)。特征码未命中或原始字节不符时,不写入该补丁。 -- **界面脚本补丁**:`patch.jsonc` 指定目标脚本,`find.nut` 和 `replace.nut` 是替换前后的原文。原文必须在目标文件中唯一命中,否则构建失败。 +- **exe 补丁**:`patch.jsonc` 的 `variants` 列出一种或多种写法,每种写法针对一个客户端版本(`written_for`)。`locate` 给出特征码、所在节,以及要从代码中读出的值(`captures`,例如跳转目标);`edit` 给出写入的字节和预期的原始字节(`expect_original`)。两者都可以用 `??`,写入字节中的 `??` 由 `fixups` 按读出的值填写。恰好一种写法命中时才写入,否则不写入该补丁。 +- **界面脚本补丁**:每种写法指定目标脚本和替换片段(如 `find.nut`、`replace.nut`)。片段原文必须在目标文件中唯一命中,同样恰好一种写法命中时才写入。 -每个补丁在 `features` 中列出依赖它的功能,在 `verified_on` 中列出验证过的客户端版本。补丁不可用时,安装器列出受影响的功能。涉及离线启动、正版隔离或断开 Gaijin 连接的补丁不可用时,安装会被阻止(`packages/patcher/src/essential-features.ts`)。 +每个补丁在 `features` 中列出依赖它的功能。`patches/versions/<版本>.jsonc` 是每个已适配客户端版本的核对记录(由 `scripts/record-game-version.ts` 生成),记下每个补丁命中的写法和位置。补丁不可用时,安装器列出受影响的功能。涉及离线启动、正版隔离或断开 Gaijin 连接的补丁不可用时,安装会被阻止(`packages/patcher/src/essential-features.ts`)。 ## 数据目录 @@ -370,10 +370,10 @@ The offline copy and the online game can be installed on the same computer. The Each patch is a folder described in JSONC. Comments in the files explain why the change is needed and what happens without it. -- **exe patches**: `locate.jsonc` gives the signature and the section to search, and `patch.jsonc` gives the bytes to write and the expected original bytes (`expect_original`). If the signature does not match or the original bytes differ, the patch is not written. -- **UI script patches**: `patch.jsonc` names the target script, and `find.nut` and `replace.nut` hold the text before and after the change. The text must match exactly once in the target file, or the build fails. +- **exe patches**: `variants` in `patch.jsonc` lists one or more ways to make the change, each written for one client version (`written_for`). `locate` gives the signature, the section to search and the values to read from the code (`captures`, such as a jump target); `edit` gives the bytes to write and the expected original bytes (`expect_original`). Both may contain `??`; in the bytes to write, `fixups` fill them from the captured values. A patch is written only when exactly one variant matches. +- **UI script patches**: each variant names the target script and its fragments (such as `find.nut` and `replace.nut`). The text to find must match exactly once in the target file; here too a patch is written only when exactly one variant matches. -Every patch lists the features that depend on it in `features` and the client versions it was verified on in `verified_on`. When a patch is unavailable, the installer lists the affected features. If a patch needed for offline startup, isolation from the online game, or blocking Gaijin connections is unavailable, installation stops (`packages/patcher/src/essential-features.ts`). +Every patch lists the features that depend on it in `features`. `patches/versions/.jsonc` is the check record of each adapted client version (written by `scripts/record-game-version.ts`): which variant of every patch applies and where. When a patch is unavailable, the installer lists the affected features. If a patch needed for offline startup, isolation from the online game, or blocking Gaijin connections is unavailable, installation stops (`packages/patcher/src/essential-features.ts`). ## Data folder diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index b068d1c..69ebc8c 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -1,5 +1,5 @@ import { app, BrowserWindow, dialog, shell } from 'electron'; -import { patchFeatures, verifiedGameVersions } from '@wto/patcher'; +import { patchFeatures, recordedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import { listBackgroundPictures } from '../services/background-art/art-catalog.ts'; import { getSettings, updateSettings } from '../services/config/settings-store.ts'; @@ -20,7 +20,7 @@ export function registerIpcHandlers(): void { electron: process.versions.electron, systemLocale: app.getLocale(), userDataPath: app.getPath('userData'), - supportedGameVersions: verifiedGameVersions(resources.exePatches, resources.guiPatches), + supportedGameVersions: recordedGameVersions(resources.versionRecords), }; }); handle('app:listBackgrounds', async () => { diff --git a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts index 65ef5fa..bad988c 100644 --- a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts +++ b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts @@ -1,6 +1,6 @@ import { access, readFile, stat } from 'node:fs/promises'; import { join } from 'node:path'; -import { executableVersion, GAME_FILES, isInSteamLibrary, verifiedGameVersions } from '@wto/patcher'; +import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { GameFolderInspection } from '@shared/schemas/install.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; @@ -21,7 +21,7 @@ export async function inspectGameFolder(path: string): Promise 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); } diff --git a/packages/exepatch/src/byte-pattern.ts b/packages/exepatch/src/byte-pattern.ts new file mode 100644 index 0000000..5a0d0d1 --- /dev/null +++ b/packages/exepatch/src/byte-pattern.ts @@ -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(' '); +} diff --git a/packages/exepatch/src/captures.ts b/packages/exepatch/src/captures.ts new file mode 100644 index 0000000..20b14f0 --- /dev/null +++ b/packages/exepatch/src/captures.ts @@ -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> = { 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; + +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).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; + 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; +} diff --git a/packages/exepatch/src/definition.ts b/packages/exepatch/src/definition.ts index 66693b1..8cb3075 100644 --- a/packages/exepatch/src/definition.ts +++ b/packages/exepatch/src/definition.ts @@ -1,36 +1,46 @@ /** - * Patch definitions as stored on disk, one directory per change to the program's behaviour, - * under patches/exe///: + * Exe patch definitions as stored on disk, one directory per change to the program's behaviour, + * under patches/exe///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, 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; - 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 { - 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; -} - -function rejectUnknownKeys(object: Record, allowed: ReadonlySet, 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 { diff --git a/packages/exepatch/src/fixups.ts b/packages/exepatch/src/fixups.ts new file mode 100644 index 0000000..a7405d6 --- /dev/null +++ b/packages/exepatch/src/fixups.ts @@ -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, 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, 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; +} diff --git a/packages/exepatch/src/index.ts b/packages/exepatch/src/index.ts index 6ee8074..4823a6f 100644 --- a/packages/exepatch/src/index.ts +++ b/packages/exepatch/src/index.ts @@ -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'; diff --git a/packages/exepatch/src/json-fields.ts b/packages/exepatch/src/json-fields.ts new file mode 100644 index 0000000..8533bab --- /dev/null +++ b/packages/exepatch/src/json-fields.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 { + 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 { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new DefinitionError(`${where}: expected an object`); + return value as Record; +} + +export function rejectUnknownKeys(object: Record, allowed: ReadonlySet, 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[] { + 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; +} diff --git a/packages/exepatch/src/locate/index.ts b/packages/exepatch/src/locate/index.ts index cc275cc..fa3d258 100644 --- a/packages/exepatch/src/locate/index.ts +++ b/packages/exepatch/src/locate/index.ts @@ -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>) => 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>): number[]; + /** Number of bytes from the site that the method checked; captures must lie inside them. */ + length(spec: Readonly>): number; +} -const METHODS: ReadonlyMap = new Map([[signature.METHOD, signature.locateSignature]]); +const METHODS: ReadonlyMap = 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; } diff --git a/packages/exepatch/src/locate/signature.ts b/packages/exepatch/src/locate/signature.ts index 506b5f2..44a858e 100644 --- a/packages/exepatch/src/locate/signature.ts +++ b/packages/exepatch/src/locate/signature.ts @@ -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>): 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>): 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)) }; } diff --git a/packages/exepatch/src/plan.ts b/packages/exepatch/src/plan.ts index 21736b3..d7ac99a 100644 --- a/packages/exepatch/src/plan.ts +++ b/packages/exepatch/src/plan.ts @@ -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(); 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; - 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)}`; -} diff --git a/packages/exepatch/src/site.ts b/packages/exepatch/src/site.ts new file mode 100644 index 0000000..7494d36 --- /dev/null +++ b/packages/exepatch/src/site.ts @@ -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>; + 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)}`; +} diff --git a/packages/exepatch/src/variants.ts b/packages/exepatch/src/variants.ts new file mode 100644 index 0000000..486cc2f --- /dev/null +++ b/packages/exepatch/src/variants.ts @@ -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 { + 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(variants: readonly V[], attempt: (variant: V) => T): Chosen { + const applied: Chosen[] = []; + 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]!; +} diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index 06c25ad..614702c 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -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, diff --git a/packages/patcher/src/game-version.ts b/packages/patcher/src/game-version.ts index c836cfd..394e6b0 100644 --- a/packages/patcher/src/game-version.ts +++ b/packages/patcher/src/game-version.ts @@ -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(); -} diff --git a/packages/patcher/src/gui-pack.ts b/packages/patcher/src/gui-pack.ts index 17dd651..188e843 100644 --- a/packages/patcher/src/gui-pack.ts +++ b/packages/patcher/src/gui-pack.ts @@ -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; } diff --git a/packages/patcher/src/gui-patch-definition.ts b/packages/patcher/src/gui-patch-definition.ts index 500ca3e..02e9167 100644 --- a/packages/patcher/src/gui-patch-definition.ts +++ b/packages/patcher/src/gui-patch-definition.ts @@ -2,10 +2,13 @@ * GUI script patch definitions as stored on disk, one folder per change under * `patches/gui///`: * - * 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 - * .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 + * .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, 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; - 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 { - 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; -} - -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(); 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); } } diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index 67af317..3455ab2 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -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'; diff --git a/packages/patcher/src/version-record.ts b/packages/patcher/src/version-record.ts new file mode 100644 index 0000000..34a6882 --- /dev/null +++ b/packages/patcher/src/version-record.ts @@ -0,0 +1,113 @@ +/** + * Version records: one file per game build the patches were checked on, under patches/versions/ + * (`.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>; + /** Patch id -> the variant that applies. */ + readonly guiPatches: Readonly>; + /** Patch id -> why it is unavailable on this build. */ + readonly unavailable: Readonly>; +} + +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'); +} diff --git a/patches/exe/battle/allow-local-host-bot-spawns/locate.jsonc b/patches/exe/battle/allow-local-host-bot-spawns/locate.jsonc deleted file mode 100644 index 4c8f2ab..0000000 --- a/patches/exe/battle/allow-local-host-bot-spawns/locate.jsonc +++ /dev/null @@ -1,8 +0,0 @@ -// Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010) -// to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards. -// 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a). -{ - "method": "signature", - "section": ".text", - "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20" -} diff --git a/patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc b/patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc index f4cf2fb..d4429a2 100644 --- a/patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc +++ b/patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc @@ -10,24 +10,49 @@ "K-AI opponents and teammates" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 38, - "asm": [ - "jmp 0x514", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop", - "nop" - ], - "bytes": "e90f050000909090909090909090", - "expect_original": "48833d6e109d06000f8406050000" - } + "variants": [ + // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010) + // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards. + // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a). + // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there + // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard. + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20", + "captures": { + "spawn_call": { + "offset": 48, + "type": "rel32" + } + } + }, + "edit": { + "offset": 38, + "asm": [ + "jmp {spawn_call}", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop", + "nop" + ], + "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90", + "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??", + "fixups": [ + { + "at": 1, + "type": "rel32", + "target": "spawn_call" + } + ] + } + } + ] } diff --git a/patches/exe/battle/allow-local-host-player-respawn/locate.jsonc b/patches/exe/battle/allow-local-host-player-respawn/locate.jsonc deleted file mode 100644 index 81331a3..0000000 --- a/patches/exe/battle/allow-local-host-player-respawn/locate.jsonc +++ /dev/null @@ -1,8 +0,0 @@ -// Masked signature of the 0xf02f (UnitRespawnRequest) branch of Unit::onEvent (0x103fbc0), from the -// human player check (call 0xfd34a0) to the spawn logic entry, 0x68 bytes; relative targets are wildcards. -// 2.61.0.37: unique hit at 0x1044e9b, edited instruction at +49 (0x1044ecc). -{ - "method": "signature", - "section": ".text", - "pattern": "48 89 d9 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 8b 05 ?? ?? ?? ?? 83 c0 fd 49 8b 95 98 0f 00 00 83 f8 02 72 ?? 0f b6 4a 08 83 ba f8 0b 00 00 00 79 ?? 83 ba f4 0b 00 00 00 0f 88 ?? ?? ?? ?? ba 06 00 00 00 e8 ?? ?? ?? ?? 4c 89 e9 b2 01 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 31 d2" -} diff --git a/patches/exe/battle/allow-local-host-player-respawn/patch.jsonc b/patches/exe/battle/allow-local-host-player-respawn/patch.jsonc index 04196be..189d366 100644 --- a/patches/exe/battle/allow-local-host-player-respawn/patch.jsonc +++ b/patches/exe/battle/allow-local-host-player-respawn/patch.jsonc @@ -10,15 +10,25 @@ "K-Spawn score and respawns" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 49, - "asm": [ - "jmp 0x37" - ], - "bytes": "eb35", - "expect_original": "7235" - } + "variants": [ + // Masked signature of the 0xf02f (UnitRespawnRequest) branch of Unit::onEvent (0x103fbc0), from the + // human player check (call 0xfd34a0) to the spawn logic entry, 0x68 bytes; relative targets are wildcards. + // 2.61.0.37: unique hit at 0x1044e9b, edited instruction at +49 (0x1044ecc). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "48 89 d9 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 8b 05 ?? ?? ?? ?? 83 c0 fd 49 8b 95 98 0f 00 00 83 f8 02 72 ?? 0f b6 4a 08 83 ba f8 0b 00 00 00 79 ?? 83 ba f4 0b 00 00 00 0f 88 ?? ?? ?? ?? ba 06 00 00 00 e8 ?? ?? ?? ?? 4c 89 e9 b2 01 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 31 d2" + }, + "edit": { + "offset": 49, + "asm": [ + "jmp 0x37" + ], + "bytes": "eb 35", + "expect_original": "72 35" + } + } + ] } diff --git a/patches/exe/battle/allow-local-host-ucav-launch/locate.jsonc b/patches/exe/battle/allow-local-host-ucav-launch/locate.jsonc deleted file mode 100644 index 16ca104..0000000 --- a/patches/exe/battle/allow-local-host-ucav-launch/locate.jsonc +++ /dev/null @@ -1,8 +0,0 @@ -// Masked signature of ucavLaunch from its prologue to the g_multiplayer->isHost early return, 0x35 -// bytes; the rip-relative load of g_multiplayer and the branch targets are wildcards. -// 2.61.0.37: unique hit at 0x101ccd0, edited instruction (jne to the return) at +51 (0x101cd03). -{ - "method": "signature", - "section": ".text", - "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 18 02 00 00 0f 29 bc 24 00 02 00 00 0f 29 b4 24 f0 01 00 00 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? 80 78 60 00 75 ??" -} diff --git a/patches/exe/battle/allow-local-host-ucav-launch/patch.jsonc b/patches/exe/battle/allow-local-host-ucav-launch/patch.jsonc index 1e93ef5..fe7e0ef 100644 --- a/patches/exe/battle/allow-local-host-ucav-launch/patch.jsonc +++ b/patches/exe/battle/allow-local-host-ucav-launch/patch.jsonc @@ -10,16 +10,26 @@ "K-Scouting" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 51, - "asm": [ - "nop", - "nop" - ], - "bytes": "9090", - "expect_original": "753a" - } + "variants": [ + // Masked signature of ucavLaunch from its prologue to the g_multiplayer->isHost early return, 0x35 + // bytes; the rip-relative load of g_multiplayer and the branch targets are wildcards. + // 2.61.0.37: unique hit at 0x101ccd0, edited instruction (jne to the return) at +51 (0x101cd03). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 18 02 00 00 0f 29 bc 24 00 02 00 00 0f 29 b4 24 f0 01 00 00 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? 80 78 60 00 75 ??" + }, + "edit": { + "offset": 51, + "asm": [ + "nop", + "nop" + ], + "bytes": "90 90", + "expect_original": "75 3a" + } + } + ] } diff --git a/patches/exe/battle/count-bots-as-active-players/locate.jsonc b/patches/exe/battle/count-bots-as-active-players/locate.jsonc deleted file mode 100644 index ddb4481..0000000 --- a/patches/exe/battle/count-bots-as-active-players/locate.jsonc +++ /dev/null @@ -1,7 +0,0 @@ -// Masked signature of countActivePlayers (prologue through the player filter mask), 0x1b bytes. -// 2.61.0.37: unique hit at 0x11b9b60, edited instruction (or eax, 0x3a) at +24 (0x11b9b78). -{ - "method": "signature", - "section": ".text", - "pattern": "41 57 41 56 41 54 56 57 53 48 83 ec 38 89 cf 80 f2 01 0f b6 c2 c1 e0 0a 83 c8 3a" -} diff --git a/patches/exe/battle/count-bots-as-active-players/patch.jsonc b/patches/exe/battle/count-bots-as-active-players/patch.jsonc index 7a62360..a19dd07 100644 --- a/patches/exe/battle/count-bots-as-active-players/patch.jsonc +++ b/patches/exe/battle/count-bots-as-active-players/patch.jsonc @@ -12,15 +12,24 @@ "K-Kill, assist and capture scoring" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 24, - "asm": [ - "or eax, 0x32" - ], - "bytes": "83c832", - "expect_original": "83c83a" - } + "variants": [ + // Masked signature of countActivePlayers (prologue through the player filter mask), 0x1b bytes. + // 2.61.0.37: unique hit at 0x11b9b60, edited instruction (or eax, 0x3a) at +24 (0x11b9b78). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "41 57 41 56 41 54 56 57 53 48 83 ec 38 89 cf 80 f2 01 0f b6 c2 c1 e0 0a 83 c8 3a" + }, + "edit": { + "offset": 24, + "asm": [ + "or eax, 0x32" + ], + "bytes": "83 c8 32", + "expect_original": "83 c8 3a" + } + } + ] } diff --git a/patches/exe/isolation/never-load-battleye/locate.jsonc b/patches/exe/isolation/never-load-battleye/locate.jsonc deleted file mode 100644 index 5105d9c..0000000 --- a/patches/exe/isolation/never-load-battleye/locate.jsonc +++ /dev/null @@ -1,8 +0,0 @@ -// Anti-cheat init, from the already-initialised check to the end of the "Disabled from CMD" branch, 109 bytes; -// rip-relative and branch targets are wildcards. -// 2.61.0.37: unique hit at 0x30c7112, edited je at +0x4a (0x30c715c). -{ - "method": "signature", - "section": ".text", - "pattern": "48 83 3d ?? ?? ?? ?? 00 74 ?? 48 8d 15 ?? ?? ?? ?? 31 db b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 49 89 ce c7 44 24 50 01 00 00 00 48 8d 0d ?? ?? ?? ?? 48 8d 54 24 50 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 74 ?? 48 8d 15 ?? ?? ?? ?? b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? bb 01 00 00 00 e9 ?? ?? ?? ??" -} diff --git a/patches/exe/isolation/never-load-battleye/patch.jsonc b/patches/exe/isolation/never-load-battleye/patch.jsonc index 542d62a..10f04d6 100644 --- a/patches/exe/isolation/never-load-battleye/patch.jsonc +++ b/patches/exe/isolation/never-load-battleye/patch.jsonc @@ -9,16 +9,26 @@ "A-No Gaijin connections" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 74, - "asm": [ - "nop", - "nop" - ], - "bytes": "9090", - "expect_original": "7421" - } + "variants": [ + // Anti-cheat init, from the already-initialised check to the end of the "Disabled from CMD" branch, 109 bytes; + // rip-relative and branch targets are wildcards. + // 2.61.0.37: unique hit at 0x30c7112, edited je at +0x4a (0x30c715c). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "48 83 3d ?? ?? ?? ?? 00 74 ?? 48 8d 15 ?? ?? ?? ?? 31 db b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 49 89 ce c7 44 24 50 01 00 00 00 48 8d 0d ?? ?? ?? ?? 48 8d 54 24 50 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 74 ?? 48 8d 15 ?? ?? ?? ?? b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? bb 01 00 00 00 e9 ?? ?? ?? ??" + }, + "edit": { + "offset": 74, + "asm": [ + "nop", + "nop" + ], + "bytes": "90 90", + "expect_original": "74 21" + } + } + ] } diff --git a/patches/exe/isolation/never-upload-crash-reports/locate.jsonc b/patches/exe/isolation/never-upload-crash-reports/locate.jsonc deleted file mode 100644 index e0a1ce2..0000000 --- a/patches/exe/isolation/never-upload-crash-reports/locate.jsonc +++ /dev/null @@ -1,7 +0,0 @@ -// Command line switch lookup that sets dl and calls the crashpad setter, 45 bytes; call targets are wildcards. -// 2.61.0.37: unique hit at 0x40f5930, edited sete dl at +0x1a (0x40f594a). -{ - "method": "signature", - "section": ".text", - "pattern": "48 8d 0d ?? ?? ?? ?? 48 8d 94 24 f0 00 00 00 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 0f 94 c2 48 89 d9 e8 ?? ?? ?? ?? 48 89 f9 ba 01 00 00 00" -} diff --git a/patches/exe/isolation/never-upload-crash-reports/patch.jsonc b/patches/exe/isolation/never-upload-crash-reports/patch.jsonc index f10c300..b59fd43 100644 --- a/patches/exe/isolation/never-upload-crash-reports/patch.jsonc +++ b/patches/exe/isolation/never-upload-crash-reports/patch.jsonc @@ -8,16 +8,25 @@ "A-No Gaijin connections" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 26, - "asm": [ - "xor dl, dl", - "nop" - ], - "bytes": "30d290", - "expect_original": "0f94c2" - } + "variants": [ + // Command line switch lookup that sets dl and calls the crashpad setter, 45 bytes; call targets are wildcards. + // 2.61.0.37: unique hit at 0x40f5930, edited sete dl at +0x1a (0x40f594a). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "48 8d 0d ?? ?? ?? ?? 48 8d 94 24 f0 00 00 00 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 0f 94 c2 48 89 d9 e8 ?? ?? ?? ?? 48 89 f9 ba 01 00 00 00" + }, + "edit": { + "offset": 26, + "asm": [ + "xor dl, dl", + "nop" + ], + "bytes": "30 d2 90", + "expect_original": "0f 94 c2" + } + } + ] } diff --git a/patches/exe/isolation/registry-key/locate.jsonc b/patches/exe/isolation/registry-key/locate.jsonc deleted file mode 100644 index 9289ee9..0000000 --- a/patches/exe/isolation/registry-key/locate.jsonc +++ /dev/null @@ -1,7 +0,0 @@ -// The wide string L"Software\Gaijin\WarThunder" with its terminating zero, 54 bytes. -// 2.61.0.37: unique hit at 0x7a39c4e. -{ - "method": "signature", - "section": ".rdata", - "pattern": "53 00 6f 00 66 00 74 00 77 00 61 00 72 00 65 00 5c 00 47 00 61 00 69 00 6a 00 69 00 6e 00 5c 00 57 00 61 00 72 00 54 00 68 00 75 00 6e 00 64 00 65 00 72 00 00 00" -} diff --git a/patches/exe/isolation/registry-key/patch.jsonc b/patches/exe/isolation/registry-key/patch.jsonc index 472c68e..74977bc 100644 --- a/patches/exe/isolation/registry-key/patch.jsonc +++ b/patches/exe/isolation/registry-key/patch.jsonc @@ -8,16 +8,25 @@ "A-Isolation from the official game" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 0, - "data": { - "encoding": "utf-16-le", - "text": "Software\\WTOffline" - }, - "bytes": "53006f006600740077006100720065005c00570054004f00660066006c0069006e006500000000000000000000000000000000000000", - "expect_original": "53006f006600740077006100720065005c004700610069006a0069006e005c005700610072005400680075006e006400650072000000" - } + "variants": [ + // The wide string L"Software\Gaijin\WarThunder" with its terminating zero, 54 bytes. + // 2.61.0.37: unique hit at 0x7a39c4e. + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".rdata", + "pattern": "53 00 6f 00 66 00 74 00 77 00 61 00 72 00 65 00 5c 00 47 00 61 00 69 00 6a 00 69 00 6e 00 5c 00 57 00 61 00 72 00 54 00 68 00 75 00 6e 00 64 00 65 00 72 00 00 00" + }, + "edit": { + "offset": 0, + "data": { + "encoding": "utf-16-le", + "text": "Software\\WTOffline" + }, + "bytes": "53 00 6f 00 66 00 74 00 77 00 61 00 72 00 65 00 5c 00 57 00 54 00 4f 00 66 00 66 00 6c 00 69 00 6e 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", + "expect_original": "53 00 6f 00 66 00 74 00 77 00 61 00 72 00 65 00 5c 00 47 00 61 00 69 00 6a 00 69 00 6e 00 5c 00 57 00 61 00 72 00 54 00 68 00 75 00 6e 00 64 00 65 00 72 00 00 00" + } + } + ] } diff --git a/patches/exe/isolation/user-data-folder-name/locate.jsonc b/patches/exe/isolation/user-data-folder-name/locate.jsonc deleted file mode 100644 index 1f258bf..0000000 --- a/patches/exe/isolation/user-data-folder-name/locate.jsonc +++ /dev/null @@ -1,8 +0,0 @@ -// "WarThunder" with the preceding string terminator and the following "War Thunder", 24 bytes, -// so the hit is the copy referenced by the game identity table. -// 2.61.0.37: unique hit at 0x777eb96, string at 0x777eb97. -{ - "method": "signature", - "section": ".rdata", - "pattern": "00 57 61 72 54 68 75 6e 64 65 72 00 57 61 72 20 54 68 75 6e 64 65 72 00" -} diff --git a/patches/exe/isolation/user-data-folder-name/patch.jsonc b/patches/exe/isolation/user-data-folder-name/patch.jsonc index 4db0136..ad65699 100644 --- a/patches/exe/isolation/user-data-folder-name/patch.jsonc +++ b/patches/exe/isolation/user-data-folder-name/patch.jsonc @@ -8,16 +8,26 @@ "A-Isolation from the official game" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 1, - "data": { - "encoding": "ascii", - "text": "WTOffline" - }, - "bytes": "57544f66666c696e6500", - "expect_original": "5761725468756e646572" - } + "variants": [ + // "WarThunder" with the preceding string terminator and the following "War Thunder", 24 bytes, + // so the hit is the copy referenced by the game identity table. + // 2.61.0.37: unique hit at 0x777eb96, string at 0x777eb97. + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".rdata", + "pattern": "00 57 61 72 54 68 75 6e 64 65 72 00 57 61 72 20 54 68 75 6e 64 65 72 00" + }, + "edit": { + "offset": 1, + "data": { + "encoding": "ascii", + "text": "WTOffline" + }, + "bytes": "57 54 4f 66 66 6c 69 6e 65 00", + "expect_original": "57 61 72 54 68 75 6e 64 65 72" + } + } + ] } diff --git a/patches/exe/online/accept-local-tls-certificate/locate.jsonc b/patches/exe/online/accept-local-tls-certificate/locate.jsonc deleted file mode 100644 index 1bfe73d..0000000 --- a/patches/exe/online/accept-local-tls-certificate/locate.jsonc +++ /dev/null @@ -1,7 +0,0 @@ -// libcurl Curl_clone_primary_ssl_config from entry to the cert_blob null check, 176 bytes; branch targets are wildcards. -// 2.61.0.37: unique hit at 0x56463c0, edited instruction at +0x52 (0x5646412). -{ - "method": "signature", - "section": ".text", - "pattern": "56 57 53 48 83 ec 20 48 89 d6 48 89 cf 8b 82 98 00 00 00 83 c8 20 89 82 98 00 00 00 0f b6 89 95 00 00 00 88 8a 95 00 00 00 8b 8f 90 00 00 00 89 8a 90 00 00 00 8b 8f 98 00 00 00 83 e1 01 83 e0 fe 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 02 83 e0 fd 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 04 83 e0 fb 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 08 83 e0 f7 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 10 83 e0 ef 09 c8 89 82 98 00 00 00 0f b6 87 94 00 00 00 88 82 94 00 00 00 48 8b 5f 68 48 85 db 74 ??" -} diff --git a/patches/exe/online/accept-local-tls-certificate/patch.jsonc b/patches/exe/online/accept-local-tls-certificate/patch.jsonc index 326fe68..d17b886 100644 --- a/patches/exe/online/accept-local-tls-certificate/patch.jsonc +++ b/patches/exe/online/accept-local-tls-certificate/patch.jsonc @@ -12,17 +12,26 @@ "requires": [ "online/network-hook-library" ], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 82, - "asm": [ - "and eax, -4", - "nop", - "nop" - ], - "bytes": "83e0fc9090", - "expect_original": "83e0fd09c8" - } + "variants": [ + // libcurl Curl_clone_primary_ssl_config from entry to the cert_blob null check, 176 bytes; branch targets are wildcards. + // 2.61.0.37: unique hit at 0x56463c0, edited instruction at +0x52 (0x5646412). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "56 57 53 48 83 ec 20 48 89 d6 48 89 cf 8b 82 98 00 00 00 83 c8 20 89 82 98 00 00 00 0f b6 89 95 00 00 00 88 8a 95 00 00 00 8b 8f 90 00 00 00 89 8a 90 00 00 00 8b 8f 98 00 00 00 83 e1 01 83 e0 fe 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 02 83 e0 fd 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 04 83 e0 fb 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 08 83 e0 f7 09 c8 89 82 98 00 00 00 8b 8f 98 00 00 00 83 e1 10 83 e0 ef 09 c8 89 82 98 00 00 00 0f b6 87 94 00 00 00 88 82 94 00 00 00 48 8b 5f 68 48 85 db 74 ??" + }, + "edit": { + "offset": 82, + "asm": [ + "and eax, -4", + "nop", + "nop" + ], + "bytes": "83 e0 fc 90 90", + "expect_original": "83 e0 fd 09 c8" + } + } + ] } diff --git a/patches/exe/online/matching-server-public-key/locate.jsonc b/patches/exe/online/matching-server-public-key/locate.jsonc deleted file mode 100644 index 0677c75..0000000 --- a/patches/exe/online/matching-server-public-key/locate.jsonc +++ /dev/null @@ -1,9 +0,0 @@ -// PEM header plus the DER prefix shared by every 2048-bit RSA key with exponent 65537; -// Gaijin's key bytes are not part of the pattern, so a rotated key is still found and expect_original checks it. -// The 1024-bit PEM at 0x7a3543d has a different prefix and does not match. -// 2.61.0.37: unique hit at 0x73422b0. -{ - "method": "signature", - "section": ".rdata", - "pattern": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41" -} diff --git a/patches/exe/online/matching-server-public-key/patch.jsonc b/patches/exe/online/matching-server-public-key/patch.jsonc index 4ae849e..30192a6 100644 --- a/patches/exe/online/matching-server-public-key/patch.jsonc +++ b/patches/exe/online/matching-server-public-key/patch.jsonc @@ -9,16 +9,27 @@ "B-Hangar and vehicles" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 0, - "data": { - "encoding": "ascii", - "text": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsPgD//C1npQhtyOpbO4A\npdBsJJStEDHapfM9SlKfhjuaXxJg7gn9iNkYDX9qCijXEH9iu/BVgI2d2RmHI1fC\nhmEnRtYvHiBgYYhB8lkMr0THDWgW7U6EmSjyPZ1w2uZuUKDuqkl8rksnveT0+Pz5\ngAK1SyczQteu0xoHhs/QuPN9RG/utuCWq/h6qPndPh+VQrMwr1n88eX4WFDMIRR0\n5Xoz0SLP1q5m2PrnK1jQ8asSTvU/dTbHzMX+XYyU9i5GSX2buOPug8QD1UmEJWxo\njSd8R9zs8YXAcni3IbFygDlNvP1C3r1fjtg1oqaYRXx4PDTGa8vtNpm45d7XtTyK\nWQIDAQAB\n-----END PUBLIC KEY-----\n" - }, - "bytes": "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b4341514541735067442f2f43316e70516874794f70624f34410a706442734a4a53744544486170664d39536c4b66686a756158784a6737676e39694e6b594458397143696a5845483969752f42566749326432526d48493166430a686d456e527459764869426759596842386c6b4d7230544844576757375536456d536a79505a317732755a75554b4475716b6c38726b736e766554302b507a350a67414b315379637a5174657530786f4868732f5175504e3952472f7574754357712f683671506e6450682b5651724d7772316e38386558345746444d495252300a35586f7a30534c503171356d3250726e4b316a51386173535476552f645462487a4d582b585979553969354753583262754f50756738514431556d454a57786f0a6a53643852397a7338595841636e69334962467967446c4e76503143337231666a7467316f7161595258783450445447613876744e706d34356437587454794b0a57514944415141420a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a", - "expect_original": "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b434151454135566b754b6e6d5a3131777a66696169646b4c710a6256436f6f6448755a4b716c30547577516b2b4148306151625834773350373976584b57455751504c556156734f7a2b7a6166564455344b64764f374a2b62360a78706a6e49387632666c305653684e4e6a77664762386844364b32794532684f6466564f4e35676e6b3274456764654147443065324d38744e457869344d35770a707145545348336a6438376b6a30707a3941377231584c304d505163475664397236746e5a6f4d74754b6b786276754f326669452b4368306e41716b336461340a63424d756a43634963553849766362374733464841463572426d456c58524c6a485746566859446835336b52524c2f472f6d6e4a4a6e4b684e3638575070414d0a7167506457566f6f495731573646467a6c6f6a627338644241662f4e33616c5a4f46616378422f35373537516c7647364b38734952796d556b71396f4f6839500a62514944415141420a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a" - } + "variants": [ + // PEM header plus the DER prefix shared by every 2048-bit RSA key with exponent 65537; + // Gaijin's key bytes are not part of the pattern, so a rotated key is still found and expect_original checks it. + // The 1024-bit PEM at 0x7a3543d has a different prefix and does not match. + // 2.61.0.37: unique hit at 0x73422b0. + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".rdata", + "pattern": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41" + }, + "edit": { + "offset": 0, + "data": { + "encoding": "ascii", + "text": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsPgD//C1npQhtyOpbO4A\npdBsJJStEDHapfM9SlKfhjuaXxJg7gn9iNkYDX9qCijXEH9iu/BVgI2d2RmHI1fC\nhmEnRtYvHiBgYYhB8lkMr0THDWgW7U6EmSjyPZ1w2uZuUKDuqkl8rksnveT0+Pz5\ngAK1SyczQteu0xoHhs/QuPN9RG/utuCWq/h6qPndPh+VQrMwr1n88eX4WFDMIRR0\n5Xoz0SLP1q5m2PrnK1jQ8asSTvU/dTbHzMX+XYyU9i5GSX2buOPug8QD1UmEJWxo\njSd8R9zs8YXAcni3IbFygDlNvP1C3r1fjtg1oqaYRXx4PDTGa8vtNpm45d7XtTyK\nWQIDAQAB\n-----END PUBLIC KEY-----\n" + }, + "bytes": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41 73 50 67 44 2f 2f 43 31 6e 70 51 68 74 79 4f 70 62 4f 34 41 0a 70 64 42 73 4a 4a 53 74 45 44 48 61 70 66 4d 39 53 6c 4b 66 68 6a 75 61 58 78 4a 67 37 67 6e 39 69 4e 6b 59 44 58 39 71 43 69 6a 58 45 48 39 69 75 2f 42 56 67 49 32 64 32 52 6d 48 49 31 66 43 0a 68 6d 45 6e 52 74 59 76 48 69 42 67 59 59 68 42 38 6c 6b 4d 72 30 54 48 44 57 67 57 37 55 36 45 6d 53 6a 79 50 5a 31 77 32 75 5a 75 55 4b 44 75 71 6b 6c 38 72 6b 73 6e 76 65 54 30 2b 50 7a 35 0a 67 41 4b 31 53 79 63 7a 51 74 65 75 30 78 6f 48 68 73 2f 51 75 50 4e 39 52 47 2f 75 74 75 43 57 71 2f 68 36 71 50 6e 64 50 68 2b 56 51 72 4d 77 72 31 6e 38 38 65 58 34 57 46 44 4d 49 52 52 30 0a 35 58 6f 7a 30 53 4c 50 31 71 35 6d 32 50 72 6e 4b 31 6a 51 38 61 73 53 54 76 55 2f 64 54 62 48 7a 4d 58 2b 58 59 79 55 39 69 35 47 53 58 32 62 75 4f 50 75 67 38 51 44 31 55 6d 45 4a 57 78 6f 0a 6a 53 64 38 52 39 7a 73 38 59 58 41 63 6e 69 33 49 62 46 79 67 44 6c 4e 76 50 31 43 33 72 31 66 6a 74 67 31 6f 71 61 59 52 58 78 34 50 44 54 47 61 38 76 74 4e 70 6d 34 35 64 37 58 74 54 79 4b 0a 57 51 49 44 41 51 41 42 0a 2d 2d 2d 2d 2d 45 4e 44 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a", + "expect_original": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41 35 56 6b 75 4b 6e 6d 5a 31 31 77 7a 66 69 61 69 64 6b 4c 71 0a 62 56 43 6f 6f 64 48 75 5a 4b 71 6c 30 54 75 77 51 6b 2b 41 48 30 61 51 62 58 34 77 33 50 37 39 76 58 4b 57 45 57 51 50 4c 55 61 56 73 4f 7a 2b 7a 61 66 56 44 55 34 4b 64 76 4f 37 4a 2b 62 36 0a 78 70 6a 6e 49 38 76 32 66 6c 30 56 53 68 4e 4e 6a 77 66 47 62 38 68 44 36 4b 32 79 45 32 68 4f 64 66 56 4f 4e 35 67 6e 6b 32 74 45 67 64 65 41 47 44 30 65 32 4d 38 74 4e 45 78 69 34 4d 35 77 0a 70 71 45 54 53 48 33 6a 64 38 37 6b 6a 30 70 7a 39 41 37 72 31 58 4c 30 4d 50 51 63 47 56 64 39 72 36 74 6e 5a 6f 4d 74 75 4b 6b 78 62 76 75 4f 32 66 69 45 2b 43 68 30 6e 41 71 6b 33 64 61 34 0a 63 42 4d 75 6a 43 63 49 63 55 38 49 76 63 62 37 47 33 46 48 41 46 35 72 42 6d 45 6c 58 52 4c 6a 48 57 46 56 68 59 44 68 35 33 6b 52 52 4c 2f 47 2f 6d 6e 4a 4a 6e 4b 68 4e 36 38 57 50 70 41 4d 0a 71 67 50 64 57 56 6f 6f 49 57 31 57 36 46 46 7a 6c 6f 6a 62 73 38 64 42 41 66 2f 4e 33 61 6c 5a 4f 46 61 63 78 42 2f 35 37 35 37 51 6c 76 47 36 4b 38 73 49 52 79 6d 55 6b 71 39 6f 4f 68 39 50 0a 62 51 49 44 41 51 41 42 0a 2d 2d 2d 2d 2d 45 4e 44 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a" + } + } + ] } diff --git a/patches/exe/online/network-hook-library/locate.jsonc b/patches/exe/online/network-hook-library/locate.jsonc deleted file mode 100644 index 62203e3..0000000 --- a/patches/exe/online/network-hook-library/locate.jsonc +++ /dev/null @@ -1,7 +0,0 @@ -// The import name "WS2_32.dll" with its terminating zero, 11 bytes. -// 2.61.0.37: unique hit at 0x7a4b090 (referenced by the import descriptor Name field). -{ - "method": "signature", - "section": ".rdata", - "pattern": "57 53 32 5f 33 32 2e 64 6c 6c 00" -} diff --git a/patches/exe/online/network-hook-library/patch.jsonc b/patches/exe/online/network-hook-library/patch.jsonc index 3eb9d2d..ea375d9 100644 --- a/patches/exe/online/network-hook-library/patch.jsonc +++ b/patches/exe/online/network-hook-library/patch.jsonc @@ -11,16 +11,25 @@ "G-Redeem codes" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 0, - "data": { - "encoding": "ascii", - "text": "wto_ws.dll" - }, - "bytes": "77746f5f77732e646c6c00", - "expect_original": "5753325f33322e646c6c00" - } + "variants": [ + // The import name "WS2_32.dll" with its terminating zero, 11 bytes. + // 2.61.0.37: unique hit at 0x7a4b090 (referenced by the import descriptor Name field). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".rdata", + "pattern": "57 53 32 5f 33 32 2e 64 6c 6c 00" + }, + "edit": { + "offset": 0, + "data": { + "encoding": "ascii", + "text": "wto_ws.dll" + }, + "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00", + "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00" + } + } + ] } diff --git a/patches/exe/startup/skip-resource-archive-signature-check/locate.jsonc b/patches/exe/startup/skip-resource-archive-signature-check/locate.jsonc deleted file mode 100644 index b0a3584..0000000 --- a/patches/exe/startup/skip-resource-archive-signature-check/locate.jsonc +++ /dev/null @@ -1,9 +0,0 @@ -// First 0x60 bytes of the function, masked; a shorter prologue matches dozens of functions. -// Contains the "VRFx" archive magic comparison (56 52 46 78), a stable semantic anchor. -// Fallback: the first 0x40 bytes are also unique on 2.61.0.37; try them first if this pattern stops matching. -// 2.61.0.37: unique hit at 0x4073d30 (function 0x4073d30-0x407497d). -{ - "method": "signature", - "section": ".text", - "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 68 01 00 00 0f 29 b4 24 50 01 00 00 48 8b 7a 40 48 85 ff 74 ?? 8b 5a 48 85 db 74 ?? 8b 42 08 83 f8 10 73 ?? 31 c0 0f 28 b4 24 50 01 00 00 48 81 c4 68 01 00 00 5b 5d 5f 5e 41 5c 41 5d 41 5e 41 5f c3 48 89 ce 4c 8b 32 41 81 3e 56 52 46 78 75 ??" -} diff --git a/patches/exe/startup/skip-resource-archive-signature-check/patch.jsonc b/patches/exe/startup/skip-resource-archive-signature-check/patch.jsonc index cbef496..d4981db 100644 --- a/patches/exe/startup/skip-resource-archive-signature-check/patch.jsonc +++ b/patches/exe/startup/skip-resource-archive-signature-check/patch.jsonc @@ -8,16 +8,27 @@ "A-Offline startup" ], "requires": [], - "verified_on": [ - "2.61.0.37" - ], - "edit": { - "offset": 0, - "asm": [ - "mov al, 1", - "ret" - ], - "bytes": "b001c3", - "expect_original": "415741" - } + "variants": [ + // First 0x60 bytes of the function, masked; a shorter prologue matches dozens of functions. + // Contains the "VRFx" archive magic comparison (56 52 46 78), a stable semantic anchor. + // Fallback: the first 0x40 bytes are also unique on 2.61.0.37; try them first if this pattern stops matching. + // 2.61.0.37: unique hit at 0x4073d30 (function 0x4073d30-0x407497d). + { + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "section": ".text", + "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 68 01 00 00 0f 29 b4 24 50 01 00 00 48 8b 7a 40 48 85 ff 74 ?? 8b 5a 48 85 db 74 ?? 8b 42 08 83 f8 10 73 ?? 31 c0 0f 28 b4 24 50 01 00 00 48 81 c4 68 01 00 00 5b 5d 5f 5e 41 5c 41 5d 41 5e 41 5f c3 48 89 ce 4c 8b 32 41 81 3e 56 52 46 78 75 ??" + }, + "edit": { + "offset": 0, + "asm": [ + "mov al, 1", + "ret" + ], + "bytes": "b0 01 c3", + "expect_original": "41 57 41" + } + } + ] } diff --git a/patches/gui/battle/append-extra-battle-slots/patch.jsonc b/patches/gui/battle/append-extra-battle-slots/patch.jsonc index 756f1d7..93b2a41 100644 --- a/patches/gui/battle/append-extra-battle-slots/patch.jsonc +++ b/patches/gui/battle/append-extra-battle-slots/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/append-extra-battle-slots", "title": "Add the LocalMP battle's extra vehicles to the in-battle crew list", - "file": "scripts/slotbar/crewslist.nut", "features": [ "K-Additional vehicles" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/slotbar/crewslist.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/force-extra-slot-weapons/patch.jsonc b/patches/gui/battle/force-extra-slot-weapons/patch.jsonc index 879d0fd..eff54aa 100644 --- a/patches/gui/battle/force-extra-slot-weapons/patch.jsonc +++ b/patches/gui/battle/force-extra-slot-weapons/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/force-extra-slot-weapons", "title": "Lock the weapon presets of LocalMP extra vehicles", - "file": "scripts/miscustomrules/rulebase.nut", "features": [ "K-Additional vehicles" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/miscustomrules/rulebase.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/launch-local-battle-from-queue/patch.jsonc b/patches/gui/battle/launch-local-battle-from-queue/patch.jsonc index d95ce92..5dc6f5d 100644 --- a/patches/gui/battle/launch-local-battle-from-queue/patch.jsonc +++ b/patches/gui/battle/launch-local-battle-from-queue/patch.jsonc @@ -6,19 +6,21 @@ { "id": "battle/launch-local-battle-from-queue", "title": "Launch local authoritative multiplayer battle on queue notification", - "file": "scripts/matching/servicenotifications/match.nut", "features": [ "J-Ground arcade and realistic", "J-Air arcade and realistic", "J-Naval arcade and realistic" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/matching/servicenotifications/match.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/lineup-br-for-submodes/patch.jsonc b/patches/gui/battle/lineup-br-for-submodes/patch.jsonc index 1155a51..b15efd5 100644 --- a/patches/gui/battle/lineup-br-for-submodes/patch.jsonc +++ b/patches/gui/battle/lineup-br-for-submodes/patch.jsonc @@ -5,17 +5,19 @@ { "id": "battle/lineup-br-for-submodes", "title": "Decide extra game modes by the matching server's lineup battle rating", - "file": "scripts/events/secondgamemodesutils.nut", "features": [ "J-Sub-modes" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/events/secondgamemodesutils.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/local-host-spawn-score/patch.jsonc b/patches/gui/battle/local-host-spawn-score/patch.jsonc index b3b01b4..634f84d 100644 --- a/patches/gui/battle/local-host-spawn-score/patch.jsonc +++ b/patches/gui/battle/local-host-spawn-score/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/local-host-spawn-score", "title": "Register the LocalMP host's spawn score callbacks", - "file": "scripts/respawn/respawnstate.nut", "features": [ "K-Spawn score and respawns" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/respawn/respawnstate.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/match-settled-battle-room-logs/patch.jsonc b/patches/gui/battle/match-settled-battle-room-logs/patch.jsonc index f0fb4f0..80e9aeb 100644 --- a/patches/gui/battle/match-settled-battle-room-logs/patch.jsonc +++ b/patches/gui/battle/match-settled-battle-room-logs/patch.jsonc @@ -7,23 +7,25 @@ { "id": "battle/match-settled-battle-room-logs", "title": "Match the logs of a settled LocalMP battle by its room id", - "file": "scripts/userlog/userlogutils.nut", "features": [ "L-Debriefing", "G-Boosters", "H-Contracts and wagers" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" - }, - { - "find": "find-room-check.nut", - "replace": "replace-room-check.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogutils.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + }, + { + "find": "find-room-check.nut", + "replace": "replace-room-check.nut" + } + ] } ] } diff --git a/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc b/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc index 6afbd8d..bcc8ed9 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc +++ b/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/pass-spawn-modifications-blk", "title": "Pass enabled modifications and extra-slot loadout on LocalMP spawn", - "file": "scripts/respawn/respawn.nut", "features": [ "K-Spawn score and respawns" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/respawn/respawn.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/quit-local-host-spectator-to-debriefing/patch.jsonc b/patches/gui/battle/quit-local-host-spectator-to-debriefing/patch.jsonc index 2ecd325..ae8e45b 100644 --- a/patches/gui/battle/quit-local-host-spectator-to-debriefing/patch.jsonc +++ b/patches/gui/battle/quit-local-host-spectator-to-debriefing/patch.jsonc @@ -5,17 +5,19 @@ { "id": "battle/quit-local-host-spectator-to-debriefing", "title": "Quit a LocalMP battle from the respawn screen to the debriefing", - "file": "scripts/hud/starthud.nut", "features": [ "L-Debriefing" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/hud/starthud.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/quit-local-host-to-debriefing/patch.jsonc b/patches/gui/battle/quit-local-host-to-debriefing/patch.jsonc index b97aca5..3498cb1 100644 --- a/patches/gui/battle/quit-local-host-to-debriefing/patch.jsonc +++ b/patches/gui/battle/quit-local-host-to-debriefing/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/quit-local-host-to-debriefing", "title": "Quit a LocalMP battle from the flight menu to the debriefing", - "file": "scripts/flightmenu/flightmenu.nut", "features": [ "L-Debriefing" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/flightmenu/flightmenu.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/ready-local-host-respawn/patch.jsonc b/patches/gui/battle/ready-local-host-respawn/patch.jsonc index 4284484..e09bfa3 100644 --- a/patches/gui/battle/ready-local-host-respawn/patch.jsonc +++ b/patches/gui/battle/ready-local-host-respawn/patch.jsonc @@ -5,17 +5,19 @@ { "id": "battle/ready-local-host-respawn", "title": "Open the respawn screen on a LocalMP host", - "file": "scripts/respawn/misloadingstate.nut", "features": [ "K-Spawn score and respawns" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/respawn/misloadingstate.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/record-local-battle-awards/patch.jsonc b/patches/gui/battle/record-local-battle-awards/patch.jsonc index e8e7754..472a2de 100644 --- a/patches/gui/battle/record-local-battle-awards/patch.jsonc +++ b/patches/gui/battle/record-local-battle-awards/patch.jsonc @@ -9,18 +9,20 @@ { "id": "battle/record-local-battle-awards", "title": "Record LocalMP battle facts and show their reward and award banners", - "file": "scripts/hud/hudrewardmessage.nut", "features": [ "K-Kill, assist and capture scoring", "L-Battle awards" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/hud/hudrewardmessage.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/report-local-battle-settlement/patch.jsonc b/patches/gui/battle/report-local-battle-settlement/patch.jsonc index c0d3928..846bfab 100644 --- a/patches/gui/battle/report-local-battle-settlement/patch.jsonc +++ b/patches/gui/battle/report-local-battle-settlement/patch.jsonc @@ -6,22 +6,24 @@ { "id": "battle/report-local-battle-settlement", "title": "Report LocalMP battle facts to local server and show the settled debriefing", - "file": "scripts/debriefing/debriefingmodal.nut", "features": [ "L-Debriefing", "L-Battle awards" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" - }, - { - "find": "find-summary-layout.nut", - "replace": "replace-summary-layout.nut" + "written_for": "2.61.0.37", + "file": "scripts/debriefing/debriefingmodal.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + }, + { + "find": "find-summary-layout.nut", + "replace": "replace-summary-layout.nut" + } + ] } ] } diff --git a/patches/gui/battle/scoreboard-team-country-flags/patch.jsonc b/patches/gui/battle/scoreboard-team-country-flags/patch.jsonc index 1a7a1ca..2f156f1 100644 --- a/patches/gui/battle/scoreboard-team-country-flags/patch.jsonc +++ b/patches/gui/battle/scoreboard-team-country-flags/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/scoreboard-team-country-flags", "title": "Fall back to the battle's countries for scoreboard flags before anyone spawns", - "file": "scripts/statistics/mpstatistics.nut", "features": [ "K-Scoreboard" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/statistics/mpstatistics.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/stabilize-respawn-countdown-button/patch.jsonc b/patches/gui/battle/stabilize-respawn-countdown-button/patch.jsonc index b124717..6de1e58 100644 --- a/patches/gui/battle/stabilize-respawn-countdown-button/patch.jsonc +++ b/patches/gui/battle/stabilize-respawn-countdown-button/patch.jsonc @@ -6,17 +6,19 @@ { "id": "battle/stabilize-respawn-countdown-button", "title": "Keep the respawn countdown in the rebuilt Cancel button text", - "file": "scripts/respawn/respawn.nut", "features": [ "K-Spawn score and respawns" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/respawn/respawn.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/battle/use-settled-debriefing-stats/patch.jsonc b/patches/gui/battle/use-settled-debriefing-stats/patch.jsonc index 22adba5..dbaf38e 100644 --- a/patches/gui/battle/use-settled-debriefing-stats/patch.jsonc +++ b/patches/gui/battle/use-settled-debriefing-stats/patch.jsonc @@ -6,25 +6,27 @@ { "id": "battle/use-settled-debriefing-stats", "title": "Use the local server's settled battle in the LocalMP debriefing", - "file": "scripts/debriefing/debriefingfull.nut", "features": [ "L-Debriefing" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find-gather.nut", - "replace": "replace-gather.nut" - }, - { - "find": "find.nut", - "replace": "replace.nut" - }, - { - "find": "find-after-exp.nut", - "replace": "replace-after-exp.nut" + "written_for": "2.61.0.37", + "file": "scripts/debriefing/debriefingfull.nut", + "edits": [ + { + "find": "find-gather.nut", + "replace": "replace-gather.nut" + }, + { + "find": "find.nut", + "replace": "replace.nut" + }, + { + "find": "find-after-exp.nut", + "replace": "replace-after-exp.nut" + } + ] } ] } diff --git a/patches/gui/inventory/local-content-public-key/patch.jsonc b/patches/gui/inventory/local-content-public-key/patch.jsonc index 4c23eeb..14b151e 100644 --- a/patches/gui/inventory/local-content-public-key/patch.jsonc +++ b/patches/gui/inventory/local-content-public-key/patch.jsonc @@ -4,20 +4,22 @@ { "id": "inventory/local-content-public-key", "title": "外部库存内容验签公钥替换为本地服务器的固定公钥", - "file": "scripts/inventory/inventorycontentsign.nut", "features": [ "G-Marketplace", "H-Supply chests", "H-Recycling and crafting", "H-Coupons" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/inventory/inventorycontentsign.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/inventory/show-coupon-redemption-reward/patch.jsonc b/patches/gui/inventory/show-coupon-redemption-reward/patch.jsonc index 79f2932..e4d66b5 100644 --- a/patches/gui/inventory/show-coupon-redemption-reward/patch.jsonc +++ b/patches/gui/inventory/show-coupon-redemption-reward/patch.jsonc @@ -4,18 +4,20 @@ { "id": "inventory/show-coupon-redemption-reward", "title": "Show the granted reward after manual coupon redemption", - "file": "scripts/items/itemsclasses/itemexternal.nut", "features": [ "G-Marketplace", "H-Coupons" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/items/itemsclasses/itemexternal.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/bypass-external-sso-for-local-urls/patch.jsonc b/patches/gui/online-shop/bypass-external-sso-for-local-urls/patch.jsonc index 73dcce7..bead123 100644 --- a/patches/gui/online-shop/bypass-external-sso-for-local-urls/patch.jsonc +++ b/patches/gui/online-shop/bypass-external-sso-for-local-urls/patch.jsonc @@ -4,19 +4,21 @@ { "id": "online-shop/bypass-external-sso-for-local-urls", "title": "本地服务器地址打开网页时跳过 Gaijin 外网单点登录跳转", - "file": "scripts/onlineshop/url.nut", "features": [ "A-No Gaijin connections", "G-Store", "G-Marketplace" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/url.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/collect-entitlement-purchase-rewards/patch.jsonc b/patches/gui/online-shop/collect-entitlement-purchase-rewards/patch.jsonc index fdd23b3..1d52ff6 100644 --- a/patches/gui/online-shop/collect-entitlement-purchase-rewards/patch.jsonc +++ b/patches/gui/online-shop/collect-entitlement-purchase-rewards/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/collect-entitlement-purchase-rewards", "title": "Track entitlement purchases by user log", - "file": "scripts/userlog/userlogdata.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogdata.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/defer-explicit-browser-update-to-close/patch.jsonc b/patches/gui/online-shop/defer-explicit-browser-update-to-close/patch.jsonc index aa60c6a..4635158 100644 --- a/patches/gui/online-shop/defer-explicit-browser-update-to-close/patch.jsonc +++ b/patches/gui/online-shop/defer-explicit-browser-update-to-close/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/defer-explicit-browser-update-to-close", "title": "Refresh local commerce once from the browser close handler", - "file": "scripts/onlineshop/browserwnd.nut", "features": [ "G-Store", "G-Marketplace" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/browserwnd.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/free-offline-payment-method/patch.jsonc b/patches/gui/online-shop/free-offline-payment-method/patch.jsonc index aa36862..daac78f 100644 --- a/patches/gui/online-shop/free-offline-payment-method/patch.jsonc +++ b/patches/gui/online-shop/free-offline-payment-method/patch.jsonc @@ -4,19 +4,21 @@ { "id": "online-shop/free-offline-payment-method", "title": "游戏内支付方式窗口增加「老福爷付过了」免 GJN 直接购买选项", - "file": "scripts/onlineshop/onlinepurchase.nut", "features": [ "G-Currencies", "G-Premium account", "G-Store" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/onlinepurchase.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/localize-vehicle-pack-titles/patch.jsonc b/patches/gui/online-shop/localize-vehicle-pack-titles/patch.jsonc index d12704c..78f4f36 100644 --- a/patches/gui/online-shop/localize-vehicle-pack-titles/patch.jsonc +++ b/patches/gui/online-shop/localize-vehicle-pack-titles/patch.jsonc @@ -4,17 +4,19 @@ { "id": "online-shop/localize-vehicle-pack-titles", "title": "Display localized titles for offline vehicle packs", - "file": "scripts/onlineshop/entitlements.nut", "features": [ "G-Store" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/entitlements.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/open-entitlement-purchase-receipts/patch.jsonc b/patches/gui/online-shop/open-entitlement-purchase-receipts/patch.jsonc index bede383..672dbe1 100644 --- a/patches/gui/online-shop/open-entitlement-purchase-receipts/patch.jsonc +++ b/patches/gui/online-shop/open-entitlement-purchase-receipts/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/open-entitlement-purchase-receipts", "title": "Acknowledge each purchase after its receipt opens", - "file": "scripts/userlog/userlogdata.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogdata.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/present-saved-entitlement-grants/patch.jsonc b/patches/gui/online-shop/present-saved-entitlement-grants/patch.jsonc index 886cf08..85b1b06 100644 --- a/patches/gui/online-shop/present-saved-entitlement-grants/patch.jsonc +++ b/patches/gui/online-shop/present-saved-entitlement-grants/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/present-saved-entitlement-grants", "title": "Present the benefits recorded by the purchase", - "file": "scripts/userlog/userlogdata.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogdata.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/refresh-profile-after-browser-close/patch.jsonc b/patches/gui/online-shop/refresh-profile-after-browser-close/patch.jsonc index 9eeb4e2..3b8d08d 100644 --- a/patches/gui/online-shop/refresh-profile-after-browser-close/patch.jsonc +++ b/patches/gui/online-shop/refresh-profile-after-browser-close/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/refresh-profile-after-browser-close", "title": "Refresh the current profile when the embedded commerce browser closes", - "file": "scripts/onlineshop/browserwnd.nut", "features": [ "G-Store", "G-Marketplace" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/browserwnd.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc b/patches/gui/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc index b800a33..83a7632 100644 --- a/patches/gui/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc +++ b/patches/gui/online-shop/refresh-profile-after-currency-shop-close/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/refresh-profile-after-currency-shop-close", "title": "Refresh the current profile after the currency shop closes", - "file": "scripts/onlineshop/onlineshop.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/onlineshop.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc b/patches/gui/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc index 4b8fb20..17f29ce 100644 --- a/patches/gui/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc +++ b/patches/gui/online-shop/refresh-profile-after-premium-shop-close/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/refresh-profile-after-premium-shop-close", "title": "Refresh the current profile after the Premium Account shop closes", - "file": "scripts/onlineshop/buypremiumhandler.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/buypremiumhandler.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/render-retired-entitlement-log/patch.jsonc b/patches/gui/online-shop/render-retired-entitlement-log/patch.jsonc index 477f253..c8be372 100644 --- a/patches/gui/online-shop/render-retired-entitlement-log/patch.jsonc +++ b/patches/gui/online-shop/render-retired-entitlement-log/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/render-retired-entitlement-log", "title": "Keep purchase history readable after a product is removed", - "file": "scripts/userlog/userlogviewdata.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogviewdata.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc b/patches/gui/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc index 3fe09f8..2f33be4 100644 --- a/patches/gui/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc +++ b/patches/gui/online-shop/resume-purchase-receipts-after-price-update/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/resume-purchase-receipts-after-price-update", "title": "Open pending receipts when the price table arrives", - "file": "scripts/userlog/userlogdata.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogdata.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/return-entitlement-reward-handler/patch.jsonc b/patches/gui/online-shop/return-entitlement-reward-handler/patch.jsonc index 0f840b5..b80e1db 100644 --- a/patches/gui/online-shop/return-entitlement-reward-handler/patch.jsonc +++ b/patches/gui/online-shop/return-entitlement-reward-handler/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/return-entitlement-reward-handler", "title": "Open a receipt using the persisted grant", - "file": "scripts/onlineshop/entitlementrewardwnd.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/entitlementrewardwnd.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/show-direct-entitlement-gift-icons/patch.jsonc b/patches/gui/online-shop/show-direct-entitlement-gift-icons/patch.jsonc index 25514fa..a68e1a6 100644 --- a/patches/gui/online-shop/show-direct-entitlement-gift-icons/patch.jsonc +++ b/patches/gui/online-shop/show-direct-entitlement-gift-icons/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/show-direct-entitlement-gift-icons", "title": "Include awarded Premium Account days in the receipt icon list", - "file": "scripts/onlineshop/entitlementview.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/entitlementview.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/show-direct-entitlement-gifts/patch.jsonc b/patches/gui/online-shop/show-direct-entitlement-gifts/patch.jsonc index f6b81e0..1eb005e 100644 --- a/patches/gui/online-shop/show-direct-entitlement-gifts/patch.jsonc +++ b/patches/gui/online-shop/show-direct-entitlement-gifts/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/show-direct-entitlement-gifts", "title": "Render awarded Premium Account days in purchase receipts", - "file": "scripts/onlineshop/entitlementview.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/entitlementview.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/show-entitlement-purchase-rewards/patch.jsonc b/patches/gui/online-shop/show-entitlement-purchase-rewards/patch.jsonc index 914f982..82aa7f5 100644 --- a/patches/gui/online-shop/show-entitlement-purchase-rewards/patch.jsonc +++ b/patches/gui/online-shop/show-entitlement-purchase-rewards/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/show-entitlement-purchase-rewards", "title": "Read each saved entitlement purchase", - "file": "scripts/userlog/userlogdata.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/userlog/userlogdata.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc b/patches/gui/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc index c73d2b6..753762c 100644 --- a/patches/gui/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc +++ b/patches/gui/online-shop/use-entitlement-receipt-for-native-payment/patch.jsonc @@ -4,18 +4,20 @@ { "id": "online-shop/use-entitlement-receipt-for-native-payment", "title": "Use the entitlement receipt as the native payment confirmation", - "file": "scripts/onlineshop/onlinepurchase.nut", "features": [ "G-Store", "G-Premium account" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/onlineshop/onlinepurchase.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/patches/gui/tutorials/immediate-save-skip-tutorial/patch.jsonc b/patches/gui/tutorials/immediate-save-skip-tutorial/patch.jsonc index d24db06..cdaaf7e 100644 --- a/patches/gui/tutorials/immediate-save-skip-tutorial/patch.jsonc +++ b/patches/gui/tutorials/immediate-save-skip-tutorial/patch.jsonc @@ -4,17 +4,19 @@ { "id": "tutorials/immediate-save-skip-tutorial", "title": "新手教程询问窗勾选「不再询问」后立即落盘保存", - "file": "scripts/tutorials/nexttutorialhandler.nut", "features": [ "A-Tutorials" ], - "verified_on": [ - "2.61.0.37" - ], - "edits": [ + "variants": [ { - "find": "find.nut", - "replace": "replace.nut" + "written_for": "2.61.0.37", + "file": "scripts/tutorials/nexttutorialhandler.nut", + "edits": [ + { + "find": "find.nut", + "replace": "replace.nut" + } + ] } ] } diff --git a/scripts/record-game-version.ts b/scripts/record-game-version.ts new file mode 100644 index 0000000..23df60f --- /dev/null +++ b/scripts/record-game-version.ts @@ -0,0 +1,63 @@ +/** + * Development script: check every exe and GUI patch against one game build and write its version + * record (packages/patcher/src/version-record.ts). + * + * node scripts/record-game-version.ts --game [--out ] + * [--patches ] [--gui-patches ] + * + * The game folder is only read. The record goes to /.jsonc (default + * patches/versions). Nothing is written when an essential patch is unavailable + * (essential-features.ts), since such a build cannot be adapted by a record alone. + */ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; +import { loadPatches } from '@wto/exepatch'; +import { blockingFailures, checkGameBuild, formatVersionRecord, GAME_FILES, loadGuiPatches, recordFileName } from '@wto/patcher'; + +const REPOSITORY = fileURLToPath(new URL('..', import.meta.url)); +const USAGE = 'usage: record-game-version.ts --game [--out ] [--patches ] [--gui-patches ]'; + +function main(): number { + const { values } = parseArgs({ + options: { + game: { type: 'string' }, + out: { type: 'string', default: join(REPOSITORY, 'patches', 'versions') }, + patches: { type: 'string', default: join(REPOSITORY, 'patches', 'exe') }, + 'gui-patches': { type: 'string', default: join(REPOSITORY, 'patches', 'gui') }, + }, + }); + if (!values.game) { + console.error(USAGE); + return 2; + } + const record = checkGameBuild({ + executable: readFileSync(join(values.game, GAME_FILES.executable)), + guiPack: readFileSync(join(values.game, GAME_FILES.guiPack)), + exePatches: values.patches, + guiPatches: values['gui-patches'], + }); + const exeCount = Object.keys(record.exePatches).length; + const guiCount = Object.keys(record.guiPatches).length; + console.log(`${record.gameVersion}: ${exeCount} exe patch(es) and ${guiCount} GUI patch(es) apply`); + for (const [id, reason] of Object.entries(record.unavailable)) console.log(` unavailable ${id}: ${reason}`); + + const blocking = blockingFailures(unavailableFailures(record.unavailable, values.patches, values['gui-patches'])); + if (blocking.length) { + console.error(`essential patch(es) unavailable: ${blocking.map((failure) => failure.patchId).join(', ')}; nothing was written`); + return 1; + } + const path = join(values.out, recordFileName(record.gameVersion)); + writeFileSync(path, formatVersionRecord(record), 'utf-8'); + console.log(`wrote ${path}`); + return 0; +} + +/** The unavailable patches with their feature tags, as the essential-features check takes them. */ +function unavailableFailures(unavailable: Readonly>, exePatches: string, guiPatches: string) { + const features = new Map([...loadPatches(exePatches), ...loadGuiPatches(guiPatches)].map((patch) => [patch.id, patch.features])); + return Object.entries(unavailable).map(([patchId, reason]) => ({ patchId, reason, features: features.get(patchId) ?? [] })); +} + +process.exitCode = main(); diff --git a/tools/src/wtotools/cli/exe_commands.py b/tools/src/wtotools/cli/exe_commands.py index 6cd4d3c..98d0f3e 100644 --- a/tools/src/wtotools/cli/exe_commands.py +++ b/tools/src/wtotools/cli/exe_commands.py @@ -15,7 +15,7 @@ import sys from pathlib import Path from ..exepatch import apply_writes, changed_ranges, load_patches, plan_patches -from ..exepatch.assemble import disagreement +from ..exepatch.assemble import disagreement, needs_site from ..offset_check import parse_offset_header, verify_offsets from ..pe import PeImage @@ -48,19 +48,31 @@ def _add_common(parser: argparse.ArgumentParser) -> None: def _check_patches(args: argparse.Namespace) -> int: definitions = load_patches(args.patches) print(f"{len(definitions)} patch definition(s) in {args.patches}") - - mismatched = 0 - for definition in definitions: - problem = disagreement(definition) - if problem: - mismatched += 1 - print(f" source disagrees with stored bytes: {definition.identifier}: {problem}") - if not mismatched: - print(" every patch's source (assembly or data text) encodes to its stored bytes") - plan = plan_patches(PeImage(args.exe.read_bytes()), definitions) + + problems = _source_problems(definitions, plan) + for problem in problems: + print(f" source disagrees with bytes: {problem}") + if not problems: + print(" every variant's source (assembly or data text) encodes to its bytes " + "(variants naming captures: where they apply on this build)") print(plan.describe()) - return 0 if plan.complete and not mismatched else 1 + return 0 if plan.complete and not problems else 1 + + +def _source_problems(definitions, plan) -> list[str]: + """Variants whose assembly or data text does not encode to their bytes.""" + planned = {(write.patch_id, write.variant.written_for): write for write in plan.writes} + problems = [] + for definition in definitions: + for variant in definition.variants: + write = planned.get((definition.identifier, variant.written_for)) + if needs_site(variant) and write is None: + continue + problem = disagreement(variant, write) + if problem: + problems.append(f"{definition.identifier} variant {variant.written_for}: {problem}") + return problems def _check_offsets(args: argparse.Namespace) -> int: diff --git a/tools/src/wtotools/exepatch/__init__.py b/tools/src/wtotools/exepatch/__init__.py index 68e16f9..45e64d9 100644 --- a/tools/src/wtotools/exepatch/__init__.py +++ b/tools/src/wtotools/exepatch/__init__.py @@ -10,22 +10,28 @@ than a broken executable. assembler, and are imported explicitly rather than from here. """ from .apply import apply_writes, changed_ranges -from .definition import PatchDefinition, PatchEdit, load_patches +from .definition import LocateSpec, PatchDefinition, PatchEdit, PatchVariant, load_patches, read_locate from .errors import DefinitionError, LocateError, PatchError, VerifyError -from .plan import PatchFailure, PatchPlan, PlannedWrite, plan_patches +from .plan import PatchFailure, PatchPlan, PlannedWrite, find_site, plan_patches +from .variants import choose_variant __all__ = [ "DefinitionError", "LocateError", + "LocateSpec", "PatchDefinition", "PatchEdit", "PatchError", "PatchFailure", "PatchPlan", + "PatchVariant", "PlannedWrite", "VerifyError", "apply_writes", "changed_ranges", + "choose_variant", + "find_site", "load_patches", "plan_patches", + "read_locate", ] diff --git a/tools/src/wtotools/exepatch/apply.py b/tools/src/wtotools/exepatch/apply.py index bc77c2a..c994065 100644 --- a/tools/src/wtotools/exepatch/apply.py +++ b/tools/src/wtotools/exepatch/apply.py @@ -1,6 +1,6 @@ """Write a verified plan into a copy of the executable's bytes. -The expected original bytes are checked once more immediately before each write, so a plan +The bytes seen when planning are checked once more immediately before each write, so a plan made against different bytes than it is applied to is refused instead of landing half applied. The input is never modified; the patched bytes are returned. """ @@ -14,10 +14,10 @@ def apply_writes(data: bytes, writes: list[PlannedWrite]) -> bytes: patched = bytearray(data) for write in sorted(writes, key=lambda item: item.file_offset): actual = bytes(patched[write.file_offset:write.end_offset]) - if actual != write.expect_original: + if actual != write.original: raise VerifyError( f"{write.patch_id}: bytes at file offset {write.file_offset:#x} are {actual.hex()}, " - f"expected {write.expect_original.hex()}; nothing was written") + f"expected {write.original.hex()}; nothing was written") patched[write.file_offset:write.end_offset] = write.payload return bytes(patched) diff --git a/tools/src/wtotools/exepatch/assemble.py b/tools/src/wtotools/exepatch/assemble.py index 14aedce..5593b20 100644 --- a/tools/src/wtotools/exepatch/assemble.py +++ b/tools/src/wtotools/exepatch/assemble.py @@ -1,27 +1,35 @@ """Development-side helper: compile a patch's assembly source to machine code. -Patch definitions carry both the assembly source, which is what a reader should look at, -and the compiled bytes, which are what gets written. This module compiles the source so a -development-side check can prove the two agree; an installer only writes the stored bytes -and needs no assembler. +Patch definitions carry both the assembly source, which is what a reader should look at, and the +bytes, which are what gets written. This module compiles the source so a development-side check +can prove the two agree; an installer only writes the stored bytes and needs no assembler. + +Assembly that jumps to existing code names the target as a capture in braces, e.g. +"jmp {spawn_call}", and the stored bytes have a hole there that a fixup fills. Such a source can +only be compiled at a located site: the capture's value is substituted and the code is assembled +at the site's address, then compared with the bytes the planner resolved. """ from __future__ import annotations +import re + from keystone import KS_ARCH_X86, KS_MODE_64, Ks, KsError -from .definition import PatchDefinition +from .definition import PatchVariant from .errors import DefinitionError +from .plan import PlannedWrite _assembler = Ks(KS_ARCH_X86, KS_MODE_64) +_PLACEHOLDER = re.compile(r"\{([a-z][a-z0-9_]*)\}") -def assemble(lines: tuple[str, ...] | list[str]) -> bytes: - """Compile position-independent x86-64 assembly to bytes.""" +def assemble(lines: tuple[str, ...] | list[str], address: int = 0) -> bytes: + """Compile x86-64 assembly to bytes as if placed at `address`.""" source = "; ".join(line.strip() for line in lines if line.strip()) if not source: raise DefinitionError("no assembly source to compile") try: - encoding, _count = _assembler.asm(source) + encoding, _count = _assembler.asm(source, address) except KsError as error: raise DefinitionError(f"could not assemble {source!r}: {error}") from error return bytes(encoding) @@ -38,15 +46,40 @@ def encode_data(data: dict, length: int) -> bytes: return encoded + bytes(length - len(encoded)) -def disagreement(definition: PatchDefinition) -> str | None: - """Why a definition's source (assembly or data text) and stored bytes differ, or None if they agree.""" - if definition.edit.data is not None: - source, compiled = "data text", encode_data(definition.edit.data, len(definition.edit.payload)) - elif definition.edit.asm: - source, compiled = "assembly", assemble(definition.edit.asm) - else: +def needs_site(variant: PatchVariant) -> bool: + """Whether the source names captures, so it can only be checked where the variant applies.""" + return any(_PLACEHOLDER.search(line) for line in variant.edit.asm) + + +def disagreement(variant: PatchVariant, write: PlannedWrite | None = None) -> str | None: + """Why a variant's source (assembly or data text) and its bytes differ, or None if they agree. + + `write` is the variant planned at a site; it is required when the source names captures. + """ + edit = variant.edit + if edit.data is not None: + source, compiled, stored = "data text", encode_data(edit.data, len(edit.payload)), _complete(variant) + elif not edit.asm: return "no assembly source or data text recorded for the stored bytes" - if compiled != definition.edit.payload: - return (f"{source} encodes to {compiled.hex()} but the stored bytes are " - f"{definition.edit.payload.hex()}") + elif needs_site(variant): + if write is None: + raise ValueError("a source naming captures is checked at a located site") + lines = [_PLACEHOLDER.sub(lambda match: _capture(write, match.group(1)), line) for line in edit.asm] + source, compiled, stored = "assembly", assemble(lines, write.rva), write.payload + else: + source, compiled, stored = "assembly", assemble(edit.asm), _complete(variant) + if compiled != stored: + return f"{source} encodes to {compiled.hex()} but the bytes are {stored.hex()}" return None + + +def _complete(variant: PatchVariant) -> bytes: + if not variant.edit.payload.complete: + raise DefinitionError("the bytes have holes but the source names no capture") + return variant.edit.payload.data + + +def _capture(write: PlannedWrite, name: str) -> str: + if name not in write.captures: + raise DefinitionError(f"assembly names {{{name}}}, which is not a capture of this variant") + return hex(write.captures[name]) diff --git a/tools/src/wtotools/exepatch/bytepattern.py b/tools/src/wtotools/exepatch/bytepattern.py new file mode 100644 index 0000000..0a1c06d --- /dev/null +++ b/tools/src/wtotools/exepatch/bytepattern.py @@ -0,0 +1,59 @@ +"""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 (packages/exepatch/src/byte-pattern.ts). + +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.py). +""" +from __future__ import annotations + +import re +from dataclasses import dataclass + +from .errors import DefinitionError + +WILDCARD = "??" + + +@dataclass(frozen=True) +class BytePattern: + data: bytes # 0 where the pattern has a wildcard + fixed: tuple[bool, ...] + + def __len__(self) -> int: + return len(self.data) + + @property + def complete(self) -> bool: + return all(self.fixed) + + def matches(self, actual: bytes) -> bool: + return len(actual) == len(self.data) and all( + not fixed or byte == expected for byte, expected, fixed in zip(actual, self.data, self.fixed)) + + def __str__(self) -> str: + return " ".join(f"{byte:02x}" if fixed else WILDCARD for byte, fixed in zip(self.data, self.fixed)) + + +def parse(text: object, where: str) -> BytePattern: + if not isinstance(text, str): + raise DefinitionError(f"{where} must be a string of hex bytes") + tokens = text.split() + if not tokens: + raise DefinitionError(f"{where} is empty") + data = bytearray() + fixed = [] + for token in tokens: + if token == WILDCARD: + data.append(0) + fixed.append(False) + elif re.fullmatch(r"[0-9a-fA-F]{2}", token): + data.append(int(token, 16)) + fixed.append(True) + else: + raise DefinitionError(f"{where}: token must be a hex byte or {WILDCARD!r}, got {token!r}") + return BytePattern(bytes(data), tuple(fixed)) + + +def spaced(data: bytes) -> str: + return " ".join(f"{byte:02x}" for byte in data) diff --git a/tools/src/wtotools/exepatch/captures.py b/tools/src/wtotools/exepatch/captures.py new file mode 100644 index 0000000..c89a090 --- /dev/null +++ b/tools/src/wtotools/exepatch/captures.py @@ -0,0 +1,73 @@ +"""Values read from the code at a located site (packages/exepatch/src/captures.ts). + +rel32 is a 32-bit displacement captured as the RVA it points to: site + end + displacement, where +`end` is where the instruction holding it ends (default: right after the displacement). The other +types are read as they are, for immediates and displacements such as structure field offsets. +Positions count from the site and must lie inside the bytes the locate method checked. +""" +from __future__ import annotations + +import struct +from dataclasses import dataclass + +from .errors import DefinitionError + +_FORMATS = {"rel32": " int: + return struct.calcsize(_FORMATS[self.type]) + + +def read_specs(raw: object, checked_length: int, where: str) -> tuple[CaptureSpec, ...]: + if raw is None: + return () + if not isinstance(raw, dict): + raise DefinitionError(f"{where}: 'captures' must be an object of named captures") + return tuple(_read_spec(name, value, checked_length, f"{where} capture {name!r}") for name, value in raw.items()) + + +def _read_spec(name: str, raw: object, checked_length: int, where: str) -> CaptureSpec: + if not name or not name[0].islower() or not all(c.islower() or c.isdigit() or c == "_" for c in name): + raise DefinitionError(f"{where}: names are lower case letters, digits and '_'") + if not isinstance(raw, dict): + raise DefinitionError(f"{where} must be an object") + unknown = sorted(set(raw) - _KEYS) + if unknown: + raise DefinitionError(f"{where}: unknown key(s) {', '.join(unknown)}") + kind = raw.get("type") + if kind not in _FORMATS: + raise DefinitionError(f"{where}: 'type' must be one of {', '.join(_FORMATS)}") + offset = _integer(raw.get("offset"), f"{where} offset") + size = struct.calcsize(_FORMATS[kind]) + if offset < 0 or offset + size > checked_length: + raise DefinitionError(f"{where}: bytes {offset}..{offset + size} are outside the {checked_length} checked bytes") + if "end" in raw and kind != "rel32": + raise DefinitionError(f"{where}: 'end' applies to rel32 only") + end = _integer(raw.get("end", offset + size), f"{where} end") + if end < offset + size: + raise DefinitionError(f"{where}: the instruction cannot end before its displacement") + return CaptureSpec(name, offset, kind, end) + + +def read(image, site: int, specs: tuple[CaptureSpec, ...]) -> dict[str, int]: + values = {} + for spec in specs: + (value,) = struct.unpack(_FORMATS[spec.type], image.read(site + spec.offset, spec.size)) + values[spec.name] = site + spec.end + value if spec.type == "rel32" else value + return values + + +def _integer(value: object, where: str) -> int: + if not isinstance(value, int) or isinstance(value, bool): + raise DefinitionError(f"{where} must be an integer") + return value diff --git a/tools/src/wtotools/exepatch/definition.py b/tools/src/wtotools/exepatch/definition.py index bef4e3f..6a48ac7 100644 --- a/tools/src/wtotools/exepatch/definition.py +++ b/tools/src/wtotools/exepatch/definition.py @@ -1,17 +1,15 @@ -"""Patch definitions as they are stored on disk. +"""Exe patch definitions as they are stored on disk (packages/exepatch/src/definition.ts). -One directory per change to the program's behaviour, under patches/exe///: +One directory per change to the program's behaviour, patches/exe///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. - -The engine reads these; it holds no knowledge about any particular patch. Keeping the -definitions as data is what lets the installer report exactly which changes did not apply -and which features are affected. +The engine tries every variant and requires that exactly one applies. Which builds were checked +is recorded per game version in patches/versions/, not here. Unknown keys are rejected so that +explanations stay in comments and in the patch notes. """ from __future__ import annotations @@ -19,31 +17,43 @@ from dataclasses import dataclass from pathlib import Path from .. import jsonc +from . import bytepattern, captures, fixups +from .bytepattern import BytePattern from .errors import DefinitionError +from .locate import signature PATCH_FILE = "patch.jsonc" -LOCATE_FILE = "locate.jsonc" -PATCH_KEYS = frozenset({"id", "title", "features", "requires", "verified_on", "edit"}) -EDIT_KEYS = frozenset({"offset", "asm", "data", "bytes", "expect_original"}) -LOCATE_KEYS = frozenset({"method", "section", "pattern"}) +PATCH_KEYS = frozenset({"id", "title", "features", "requires", "variants"}) +VARIANT_KEYS = frozenset({"written_for", "locate", "edit"}) +EDIT_KEYS = frozenset({"offset", "asm", "data", "bytes", "expect_original", "fixups"}) +LOCATE_KEYS = {signature.METHOD: frozenset({"method", "captures", "section", "pattern"})} + + +@dataclass(frozen=True) +class LocateSpec: + method: str + spec: dict # the method's own keys (pattern, section) + captures: tuple[captures.CaptureSpec, ...] @dataclass(frozen=True) class PatchEdit: """Bytes to write, and the bytes that must already be there.""" offset: int - payload: bytes - expect_original: bytes + payload: BytePattern + expect_original: BytePattern + fixups: tuple[fixups.FixupSpec, ...] asm: tuple[str, ...] # For edits to constant data (strings) instead of code: {"encoding": ..., "text": ...}. # The text, encoded and padded with zero bytes to the edit's length, must equal the payload. data: dict | None = None - def __post_init__(self) -> None: - if len(self.payload) != len(self.expect_original): - raise DefinitionError( - f"payload is {len(self.payload)} bytes but expect_original is " - f"{len(self.expect_original)}; they must cover the same bytes") + +@dataclass(frozen=True) +class PatchVariant: + written_for: str + locate: LocateSpec + edit: PatchEdit @dataclass(frozen=True) @@ -52,15 +62,9 @@ class PatchDefinition: title: str features: tuple[str, ...] requires: tuple[str, ...] - verified_on: tuple[str, ...] - edit: PatchEdit - locate: dict + variants: tuple[PatchVariant, ...] directory: Path | None = None - @property - def locate_method(self) -> str: - return str(self.locate.get("method", "")) - def load_patches(root: Path) -> list[PatchDefinition]: """Read every patch definition under `root`, sorted by identifier.""" @@ -70,59 +74,80 @@ def load_patches(root: Path) -> list[PatchDefinition]: return sorted(definitions, key=lambda item: item.identifier) -def _read(directory: Path) -> PatchDefinition: - patch = _read_json(directory / PATCH_FILE) - locate = _read_json(directory / LOCATE_FILE) - _reject_unknown_keys(patch, PATCH_KEYS, directory / PATCH_FILE) - _reject_unknown_keys(locate, LOCATE_KEYS, directory / LOCATE_FILE) - for key in ("id", "title", "edit"): - if key not in patch: - raise DefinitionError(f"{directory / PATCH_FILE}: missing key {key!r}") - if "method" not in locate: - raise DefinitionError(f"{directory / LOCATE_FILE}: missing key 'method'") - verified_on = tuple(str(item) for item in patch.get("verified_on", ())) - if not verified_on: - raise DefinitionError(f"{directory / PATCH_FILE}: 'verified_on' must name at least one game version") - return PatchDefinition( - identifier=str(patch["id"]), - title=str(patch["title"]), - features=tuple(str(item) for item in patch.get("features", ())), - requires=tuple(str(item) for item in patch.get("requires", ())), - verified_on=verified_on, - edit=_read_edit(directory, patch["edit"]), - locate=locate, - directory=directory, - ) +def read_locate(raw: object, where: str) -> LocateSpec: + if not isinstance(raw, dict): + raise DefinitionError(f"{where} must be an object") + method = raw.get("method") + if method not in LOCATE_KEYS: + raise DefinitionError(f"{where}: unknown locate method {method!r}; known: {', '.join(LOCATE_KEYS)}") + reject_unknown_keys(raw, LOCATE_KEYS[method], where) + spec = {key: value for key, value in raw.items() if key not in ("method", "captures")} + checked = signature.pattern_length(str(spec.get("pattern", ""))) + return LocateSpec(method, spec, captures.read_specs(raw.get("captures"), checked, where)) -def _reject_unknown_keys(data: dict, allowed: frozenset[str], where: Path) -> None: +def reject_unknown_keys(data: dict, allowed: frozenset[str], where: object) -> None: unknown = sorted(set(data) - allowed) if unknown: raise DefinitionError(f"{where}: unknown key(s) {', '.join(unknown)}; " "explanations belong in comments or the patch notes") -def _read_edit(directory: Path, raw: object) -> PatchEdit: - if not isinstance(raw, dict): - raise DefinitionError(f"{directory / PATCH_FILE}: 'edit' must be an object") - _reject_unknown_keys(raw, EDIT_KEYS, directory / PATCH_FILE) - for key in ("bytes", "expect_original"): - if not isinstance(raw.get(key), str): - raise DefinitionError(f"{directory / PATCH_FILE}: edit needs a hex string {key!r}") - return PatchEdit( - offset=int(raw.get("offset", 0)), - payload=_hex(directory, "bytes", raw["bytes"]), - expect_original=_hex(directory, "expect_original", raw["expect_original"]), - asm=tuple(str(line) for line in raw.get("asm", ())), - data=raw.get("data") if isinstance(raw.get("data"), dict) else None, +def variant_objects(raw: object, where: object) -> list[dict]: + """The "variants" list of a definition, each entry an object, written_for names unique.""" + if not isinstance(raw, list) or not raw: + raise DefinitionError(f"{where}: 'variants' must be a non-empty list") + names = [] + for index, item in enumerate(raw): + if not isinstance(item, dict) or not isinstance(item.get("written_for"), str) or not item["written_for"]: + raise DefinitionError(f"{where}: variants[{index}] must be an object with a 'written_for' version") + if item["written_for"] in names: + raise DefinitionError(f"{where}: two variants are written for {item['written_for']}") + names.append(item["written_for"]) + return raw + + +def _read(directory: Path) -> PatchDefinition: + where = directory / PATCH_FILE + patch = _read_json(where) + reject_unknown_keys(patch, PATCH_KEYS, where) + for key in ("id", "title"): + if not isinstance(patch.get(key), str) or not patch[key]: + raise DefinitionError(f"{where}: {key!r} must be a non-empty string") + return PatchDefinition( + identifier=patch["id"], + title=patch["title"], + features=tuple(str(item) for item in patch.get("features", ())), + requires=tuple(str(item) for item in patch.get("requires", ())), + variants=tuple(_read_variant(item, f"{where} variant {item['written_for']}") + for item in variant_objects(patch.get("variants"), where)), + directory=directory, ) -def _hex(directory: Path, key: str, text: str) -> bytes: - try: - return bytes.fromhex(text) - except ValueError as error: - raise DefinitionError(f"{directory / PATCH_FILE}: {key} is not valid hex: {text!r}") from error +def _read_variant(raw: dict, where: str) -> PatchVariant: + reject_unknown_keys(raw, VARIANT_KEYS, where) + locate = read_locate(raw.get("locate"), f"{where} locate") + return PatchVariant(raw["written_for"], locate, _read_edit(raw.get("edit"), locate, f"{where} edit")) + + +def _read_edit(raw: object, locate: LocateSpec, where: str) -> PatchEdit: + if not isinstance(raw, dict): + raise DefinitionError(f"{where} must be an object") + reject_unknown_keys(raw, EDIT_KEYS, where) + payload = bytepattern.parse(raw.get("bytes"), f"{where} bytes") + expect_original = bytepattern.parse(raw.get("expect_original"), f"{where} expect_original") + if len(payload) != len(expect_original): + raise DefinitionError(f"{where}: bytes is {len(payload)} bytes but expect_original is {len(expect_original)}") + names = {capture.name for capture in locate.captures} + return PatchEdit( + offset=int(raw.get("offset", 0)), + payload=payload, + expect_original=expect_original, + fixups=fixups.read_specs(raw.get("fixups"), payload, names, where), + asm=tuple(str(line) for line in raw.get("asm", ())), + data=raw.get("data") if isinstance(raw.get("data"), dict) else None, + ) def _read_json(path: Path) -> dict: diff --git a/tools/src/wtotools/exepatch/fixups.py b/tools/src/wtotools/exepatch/fixups.py new file mode 100644 index 0000000..5fbbbc1 --- /dev/null +++ b/tools/src/wtotools/exepatch/fixups.py @@ -0,0 +1,73 @@ +"""Filling the holes ("??") in the bytes an edit writes (packages/exepatch/src/fixups.ts). + +A rel32 fixup writes the displacement from the end of the written instruction to a captured RVA. +Every hole must be filled by exactly one fixup, and a fixup may only write into holes. +""" +from __future__ import annotations + +import struct +from dataclasses import dataclass + +from .bytepattern import BytePattern +from .errors import DefinitionError + +_KEYS = frozenset({"at", "type", "target", "end"}) +_REL32 = 4 + + +@dataclass(frozen=True) +class FixupSpec: + at: int + type: str + target: str + end: int + + +def read_specs(raw: object, payload: BytePattern, capture_names: set[str], where: str) -> tuple[FixupSpec, ...]: + items = [] if raw is None else raw + if not isinstance(items, list): + raise DefinitionError(f"{where}: 'fixups' must be a list") + fixups = tuple(_read_spec(item, capture_names, f"{where} fixups[{index}]") for index, item in enumerate(items)) + _require_holes_filled_once(payload, fixups, where) + return fixups + + +def _read_spec(raw: object, capture_names: set[str], where: str) -> FixupSpec: + if not isinstance(raw, dict): + raise DefinitionError(f"{where} must be an object") + unknown = sorted(set(raw) - _KEYS) + if unknown: + raise DefinitionError(f"{where}: unknown key(s) {', '.join(unknown)}") + if raw.get("type") != "rel32": + raise DefinitionError(f"{where}: 'type' must be rel32") + if raw.get("target") not in capture_names: + raise DefinitionError(f"{where}: no capture named {raw.get('target')!r} in this variant") + at = raw.get("at") + if not isinstance(at, int): + raise DefinitionError(f"{where}: 'at' must be an integer") + end = raw.get("end", at + _REL32) + if not isinstance(end, int) or end < at + _REL32: + raise DefinitionError(f"{where}: 'end' must be an integer after the displacement") + return FixupSpec(at, "rel32", raw["target"], end) + + +def _require_holes_filled_once(payload: BytePattern, fixups: tuple[FixupSpec, ...], where: str) -> None: + filled = [0] * len(payload) + for fixup in fixups: + for index in range(fixup.at, fixup.at + _REL32): + if index >= len(payload) or payload.fixed[index]: + raise DefinitionError(f"{where}: a fixup at {fixup.at} writes over fixed bytes or past the end") + filled[index] += 1 + for index, count in enumerate(filled): + if not payload.fixed[index] and count != 1: + raise DefinitionError(f"{where}: byte {index} of 'bytes' is a hole that no fixup fills") + + +def resolve(payload: BytePattern, fixups: tuple[FixupSpec, ...], rva: int, captures: dict[str, int]) -> bytes: + data = bytearray(payload.data) + for fixup in fixups: + displacement = captures[fixup.target] - (rva + fixup.end) + if not -0x8000_0000 <= displacement <= 0x7FFF_FFFF: + raise DefinitionError(f"fixup at {fixup.at}: target {captures[fixup.target]:#x} is out of rel32 range") + data[fixup.at:fixup.at + _REL32] = struct.pack(" int: @@ -49,7 +55,7 @@ class PatchPlan: def describe(self) -> str: lines = [f"{len(self.writes)} patch(es) ready, {len(self.failures)} unavailable"] - lines += [f" ready {write.patch_id} at {write.rva:#x}" for write in self.writes] + lines += [f" ready {write.patch_id} at {write.rva:#x} (variant {write.variant.written_for})" for write in self.writes] lines += [f" FAILED {failure.patch_id}: {failure.reason}" for failure in self.failures] if self.failures: lines.append(f" features affected: {', '.join(self.affected_features) or 'none recorded'}") @@ -57,44 +63,48 @@ class PatchPlan: def plan_patches(image, definitions: list[PatchDefinition]) -> PatchPlan: - plan = PatchPlan() + planned: dict[str, PlannedWrite] = {} failed: dict[str, str] = {} - for definition in definitions: try: - plan.writes.append(_plan_one(image, definition)) + _variant, write = choose_variant(definition.variants, lambda item: _plan_variant(image, definition.identifier, item)) + planned[definition.identifier] = write except PatchError as error: failed[definition.identifier] = str(error) _propagate_failures(definitions, failed) + plan = PatchPlan() for definition in definitions: if definition.identifier in failed: - plan.writes = [write for write in plan.writes if write.patch_id != definition.identifier] plan.failures.append(PatchFailure(definition.identifier, definition.features, failed[definition.identifier])) - + else: + plan.writes.append(planned[definition.identifier]) _reject_overlaps(plan.writes) return plan -def _plan_one(image, definition: PatchDefinition) -> PlannedWrite: - spec = {key: value for key, value in definition.locate.items() if key != "method"} - hits = locate_method(definition.locate_method)(image, **spec) +def find_site(image, locate: LocateSpec) -> tuple[int, dict[str, int]]: + """The single place `locate` matches, with its captures; anything else is a LocateError.""" + hits = locate_method(locate.method)(image, **locate.spec) if not hits: raise LocateError("site not found; this game build differs from the verified ones, " "or the executable is already patched") if len(hits) > 1: raise LocateError(f"site found in {len(hits)} places, so it is ambiguous: " f"{', '.join(hex(hit) for hit in hits)}") + return hits[0], captures.read(image, hits[0], locate.captures) - rva = hits[0] + definition.edit.offset - file_offset = image.file_offset(rva) - actual = image.read(rva, len(definition.edit.expect_original)) - if actual != definition.edit.expect_original: - raise VerifyError( - f"bytes at {rva:#x} are {actual.hex()}, expected {definition.edit.expect_original.hex()}" - " (different game build, or already patched)") - return PlannedWrite(definition.identifier, rva, file_offset, - definition.edit.payload, definition.edit.expect_original) + +def _plan_variant(image, patch_id: str, variant: PatchVariant) -> PlannedWrite: + site, values = find_site(image, variant.locate) + edit = variant.edit + rva = site + edit.offset + original = image.read(rva, len(edit.expect_original)) + if not edit.expect_original.matches(original): + raise VerifyError(f"bytes at {rva:#x} are {spaced(original)}, expected {edit.expect_original}" + " (different game build, or already patched)") + payload = fixups.resolve(edit.payload, edit.fixups, rva, values) + return PlannedWrite(patch_id, variant, rva, image.file_offset(rva), payload, original, values) def _propagate_failures(definitions: list[PatchDefinition], failed: dict[str, str]) -> None: @@ -113,8 +123,8 @@ def _propagate_failures(definitions: list[PatchDefinition], failed: dict[str, st def _reject_overlaps(writes: list[PlannedWrite]) -> None: - for earlier, later in zip(sorted(writes, key=lambda w: w.file_offset), - sorted(writes, key=lambda w: w.file_offset)[1:]): + ordered = sorted(writes, key=lambda w: w.file_offset) + for earlier, later in zip(ordered, ordered[1:]): if later.file_offset < earlier.end_offset: raise DefinitionError( f"{earlier.patch_id} and {later.patch_id} write overlapping bytes at " diff --git a/tools/src/wtotools/exepatch/variants.py b/tools/src/wtotools/exepatch/variants.py new file mode 100644 index 0000000..a83173f --- /dev/null +++ b/tools/src/wtotools/exepatch/variants.py @@ -0,0 +1,32 @@ +"""Choosing the variant of a patch that fits the game files at hand (packages/exepatch/src/variants.ts). + +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. +""" +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import TypeVar + +from .errors import LocateError, PatchError + +V = TypeVar("V") +T = TypeVar("T") + + +def choose_variant(variants: Sequence[V], attempt: Callable[[V], T]) -> tuple[V, T]: + """`attempt` returns the variant's result, or raises PatchError saying why it does not apply.""" + applied: list[tuple[V, T]] = [] + reasons: list[str] = [] + for variant in variants: + try: + applied.append((variant, attempt(variant))) + except PatchError as error: + reasons.append(str(error) if len(variants) == 1 else f"variant {variant.written_for}: {error}") + if len(applied) > 1: + names = " and ".join(variant.written_for for variant, _ in applied) + raise LocateError(f"variants {names} all apply, so the choice is ambiguous") + if not applied: + raise LocateError("; ".join(reasons)) + return applied[0] diff --git a/tools/src/wtotools/gui_check.py b/tools/src/wtotools/gui_check.py index 726150b..4a7710a 100644 --- a/tools/src/wtotools/gui_check.py +++ b/tools/src/wtotools/gui_check.py @@ -15,7 +15,8 @@ import tempfile from dataclasses import dataclass from pathlib import Path -from .guipatch import apply, load_gui_patches +from .exepatch.errors import PatchError +from .guipatch import GuiVariant, load_gui_patches, select from .vromfs import Archive, read_archive MOUNT_PREFIXES: tuple[tuple[str, str], ...] = ( @@ -120,19 +121,18 @@ def verify_gui_patches( touched_files: list[str] = [] errors: list[str] = [] + chosen: dict[str, GuiVariant] = {} for patch in patches: - target = patch.file.lower() - if target not in archive.files: - errors.append(f"{patch.identifier}: missing file {target} in gui.vromfs.bin") - continue - if any("`" in edit.replace for edit in patch.edits): - errors.append(f"{patch.identifier}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +") - continue try: - updated = apply(archive.files[target].decode("utf-8"), patch, endpoint) - except ValueError as error: + variant, updated = select(archive.files, patch, endpoint) + except PatchError as error: errors.append(str(error)) continue + if any("`" in edit.replace for edit in variant.edits): + errors.append(f"{patch.identifier}: backtick string syntax is unsupported by the game's Quirrel VM; use $\"...\" or +") + continue + target = variant.file.lower() + chosen[patch.identifier] = variant archive.put(target, updated.encode("utf-8")) if target not in touched_files: touched_files.append(target) @@ -145,12 +145,13 @@ def verify_gui_patches( stock_archive = read_archive(gui_pack_path.read_bytes()) for patch in patches: - target = patch.file.lower() + variant = chosen[patch.identifier] + target = variant.file.lower() stock_src = stock_archive.files[target].decode("utf-8") imp_names, imp_classes = _resolve_file_bindings(stock_src, stock_archive, export_cache, native_syms) reserved = (imp_names | imp_classes) - set(MODULE_BUILTINS) new_locals: set[str] = set() - for edit in patch.edits: + for edit in variant.edits: new_locals |= _declared_locals(edit.replace) - _declared_locals(edit.find) collisions = sorted(new_locals & reserved) if collisions: diff --git a/tools/src/wtotools/guipatch.py b/tools/src/wtotools/guipatch.py index fc2d59a..0e36e55 100644 --- a/tools/src/wtotools/guipatch.py +++ b/tools/src/wtotools/guipatch.py @@ -1,8 +1,11 @@ """GUI script patch definitions, one folder per change under patches/gui///. - patch.jsonc id, title, target script, features, game versions verified on, and the edits; - comments explain the change and why the local server cannot provide it - .nut edit fragments named by `edits`: the stock text to find and its replacement + patch.jsonc id, title, features, and the variants; comments explain the change and why the + local server cannot provide it + .nut edit fragments a variant names: the stock text to find and its replacement + +A variant is the change written for one game build: the target script and its edits. Exactly one +variant must apply (`select`), the same rule as exe patches. 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; `apply` matches regardless of the @@ -15,9 +18,13 @@ from dataclasses import dataclass from pathlib import Path from . import jsonc +from .exepatch.definition import reject_unknown_keys, variant_objects +from .exepatch.errors import PatchError +from .exepatch.variants import choose_variant PATCH_FILE = "patch.jsonc" -ALLOWED_KEYS = frozenset({"id", "title", "file", "features", "verified_on", "edits"}) +PATCH_KEYS = frozenset({"id", "title", "features", "variants"}) +VARIANT_KEYS = frozenset({"written_for", "file", "edits"}) ENDPOINT_PLACEHOLDER = "{{LOCAL_ENDPOINT}}" @@ -27,17 +34,26 @@ class GuiEdit: replace: str +@dataclass(frozen=True) +class GuiVariant: + written_for: str + file: str + edits: tuple[GuiEdit, ...] + + @dataclass(frozen=True) class GuiPatch: identifier: str title: str - file: str features: tuple[str, ...] - verified_on: tuple[str, ...] - edits: tuple[GuiEdit, ...] + variants: tuple[GuiVariant, ...] directory: Path +class GuiPatchMismatch(PatchError): + """The stock text of an edit was not found exactly once, or the target script is missing.""" + + def load_gui_patches(root: Path) -> list[GuiPatch]: patches = [_read(path.parent) for path in sorted(root.rglob(PATCH_FILE))] seen: dict[str, Path] = {} @@ -48,12 +64,27 @@ def load_gui_patches(root: Path) -> list[GuiPatch]: return sorted(patches, key=lambda item: item.identifier) -def apply(text: str, patch: GuiPatch, endpoint: str) -> str: - """`text` with every edit of `patch` applied; raises ValueError when an edit does not match once.""" +def select(files: dict[str, bytes], patch: GuiPatch, endpoint: str) -> tuple[GuiVariant, str]: + """The variant of `patch` that applies to the scripts in `files` (lower-case paths) and its + target script with the edits made; raises PatchError when none or more than one applies.""" + def attempt(variant: GuiVariant) -> str: + target = variant.file.lower() + if target not in files: + raise GuiPatchMismatch(f"the data pack has no script {target}") + return apply(files[target].decode("utf-8"), variant, endpoint) + + try: + return choose_variant(patch.variants, attempt) + except PatchError as error: + raise PatchError(f"{patch.identifier}: {error}") from error + + +def apply(text: str, variant: GuiVariant, endpoint: str) -> str: + """`text` with every edit of `variant` applied; raises GuiPatchMismatch when an edit does not match once.""" newline = "\r\n" if "\r\n" in text else "\n" - for number, edit in enumerate(patch.edits, start=1): + for number, edit in enumerate(variant.edits, start=1): replace = edit.replace.replace("\n", newline).replace(ENDPOINT_PLACEHOLDER, endpoint) - text = _replace_unique(text, edit.find, replace, f"{patch.identifier} edit {number} in {patch.file}") + text = _replace_unique(text, edit.find, replace, f"edit {number} in {variant.file}") return text @@ -77,9 +108,9 @@ def _replace_unique(text: str, find: str, replace: str, label: str) -> str: normalized = "".join(kept) first = normalized.find(find) if first == -1: - raise ValueError(f"{label}: stock text not found") + raise GuiPatchMismatch(f"{label}: stock text not found") if normalized.find(find, first + len(find)) != -1: - raise ValueError(f"{label}: stock text appears more than once") + raise GuiPatchMismatch(f"{label}: stock text appears more than once") return text[:original[first]] + replace + text[original[first + len(find)]:] @@ -93,32 +124,34 @@ def read_fragment(directory: Path, name: str) -> str: def _read(directory: Path) -> GuiPatch: where = directory / PATCH_FILE raw = jsonc.load_object(where) - unknown = sorted(set(raw) - ALLOWED_KEYS) - if unknown: - raise ValueError(f"{where}: unknown key(s) {', '.join(unknown)}; explanations belong in comments or the patch notes") - for key in ("id", "title", "file"): + reject_unknown_keys(raw, PATCH_KEYS, where) + for key in ("id", "title"): if not isinstance(raw.get(key), str) or not raw[key]: raise ValueError(f"{where}: {key!r} must be a non-empty string") - verified_on = tuple(str(item) for item in raw.get("verified_on", ())) - if not verified_on: - raise ValueError(f"{where}: 'verified_on' must name at least one game version") + variants = tuple(_read_variant(directory, item, f"{where} variant {item['written_for']}") + for item in variant_objects(raw.get("variants"), where)) + return GuiPatch( + identifier=raw["id"], + title=raw["title"], + features=tuple(str(item) for item in raw.get("features", ())), + variants=variants, + directory=directory, + ) + + +def _read_variant(directory: Path, raw: dict, where: str) -> GuiVariant: + reject_unknown_keys(raw, VARIANT_KEYS, where) + if not isinstance(raw.get("file"), str) or not raw["file"]: + raise ValueError(f"{where}: 'file' must be a non-empty string") edits_raw = raw.get("edits") if not isinstance(edits_raw, list) or not edits_raw: raise ValueError(f"{where}: 'edits' must be a non-empty list") edits = [] for number, item in enumerate(edits_raw, start=1): - if not isinstance(item, dict) or not isinstance(item.get("find"), str) or not isinstance(item.get("replace"), str): + if not isinstance(item, dict) or set(item) != {"find", "replace"} or not all(isinstance(v, str) for v in item.values()): raise ValueError(f"{where}: edit {number} needs fragment file names 'find' and 'replace'") find = read_fragment(directory, item["find"]) if not find: raise ValueError(f"{where}: edit {number} has an empty 'find' fragment") edits.append(GuiEdit(find=find, replace=read_fragment(directory, item["replace"]))) - return GuiPatch( - identifier=raw["id"], - title=raw["title"], - file=raw["file"], - features=tuple(str(item) for item in raw.get("features", ())), - verified_on=verified_on, - edits=tuple(edits), - directory=directory, - ) + return GuiVariant(written_for=raw["written_for"], file=raw["file"], edits=tuple(edits))