Let each patch carry variants written for different game builds

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

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

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

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

No files matched your search

+24 -12
View File
@@ -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:
+8 -2
View File
@@ -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",
]
+3 -3
View File
@@ -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)
+51 -18
View File
@@ -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])
@@ -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)
+73
View File
@@ -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": "<i", "u8": "<B", "u16": "<H", "u32": "<I", "i8": "<b", "i16": "<h", "i32": "<i"}
_KEYS = frozenset({"offset", "type", "end"})
@dataclass(frozen=True)
class CaptureSpec:
name: str
offset: int
type: str
end: int
@property
def size(self) -> 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
+96 -71
View File
@@ -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/<domain>/<name>/:
One directory per change to the program's behaviour, patches/exe/<domain>/<name>/patch.jsonc:
patch.jsonc id, title, features, required patches, the game versions it was verified
on, and the bytes to write; comments explain the change and why the local
server cannot provide it
locate.jsonc how to find the site
id, title, features, requires what the patch is; comments explain the change and why the
local server cannot provide it
variants ways to make the change, each written for one game build:
where it goes ("locate") and what to write ("edit")
Unknown keys are rejected so that explanations stay in comments and in the patch notes.
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:
+73
View File
@@ -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("<i", displacement)
return bytes(data)
+36 -26
View File
@@ -1,26 +1,32 @@
"""Work out every write first, then let the caller decide whether to apply it.
Planning does three things per patch: find the site, require that it was found in exactly
one place, and check that the bytes there are the ones the definition expects. A patch
that fails any of these produces a PatchFailure with a reason instead of a write, and so
does any patch that depends on it. Nothing is written during planning.
Per patch: choose the variant that fits (variants.py); 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 that fails produces a PatchFailure with a reason instead
of a write, and so does any patch that depends on it. Nothing is written during planning. Same
rules as packages/exepatch/src/plan.ts.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from .definition import PatchDefinition
from . import captures, fixups
from .bytepattern import spaced
from .definition import LocateSpec, PatchDefinition, PatchVariant
from .errors import DefinitionError, LocateError, PatchError, VerifyError
from .locate import method as locate_method
from .variants import choose_variant
@dataclass(frozen=True)
class PlannedWrite:
patch_id: str
variant: PatchVariant
rva: int
file_offset: int
payload: bytes
expect_original: bytes
original: bytes # the bytes found when planning; writing requires they are still there
captures: dict[str, int]
@property
def end_offset(self) -> 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 "
+32
View File
@@ -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]
+13 -12
View File
@@ -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:
+63 -30
View File
@@ -1,8 +1,11 @@
"""GUI script patch definitions, one folder per change under patches/gui/<domain>/<name>/.
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
<name>.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
<name>.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))