Add the executable patch engine and local archive compatibility
Keep patch definitions and dependencies separate from the patch engine. Resolve all patches before writing, verify expected bytes, and refuse to overwrite the input executable. Include a read-only check command for comparing definitions with their assembly source. Allow locally rebuilt script archives to load in the offline client. Verify the patch against the 2.61.0.37 executable and confirm that the patched copy remains readable as PE.
This commit is contained in:
1 parent
c9e10b0db7
commit
8fa50b7804
12 files changed
+701
No files matched your search
@@ -0,0 +1,90 @@
|
||||
"""Command line entry point for the development-side tools.
|
||||
|
||||
wtotools check-patches --exe <aces.exe> [--patches exe-patches]
|
||||
wtotools patch-exe --exe <aces.exe> --out <aces.exe> [--patches exe-patches]
|
||||
|
||||
The input executable is only ever read. `patch-exe` refuses to write over its input and
|
||||
refuses an existing output unless --force is given, so it cannot modify a game install by
|
||||
accident.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .exepatch import apply_writes, changed_ranges, load_patches, plan_patches
|
||||
from .exepatch.assemble import disagreement
|
||||
from .pe import PeImage
|
||||
|
||||
DEFAULT_PATCHES = Path("exe-patches")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="wtotools", description=__doc__)
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
check = commands.add_parser("check-patches", help="locate and verify every patch, write nothing")
|
||||
_add_common(check)
|
||||
check.set_defaults(handler=_check_patches)
|
||||
|
||||
patch = commands.add_parser("patch-exe", help="apply every patch to a copy of the executable")
|
||||
_add_common(patch)
|
||||
patch.add_argument("--out", type=Path, required=True, help="where to write the patched copy")
|
||||
patch.add_argument("--force", action="store_true", help="overwrite an existing output file")
|
||||
patch.set_defaults(handler=_patch_exe)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
return args.handler(args)
|
||||
|
||||
|
||||
def _add_common(parser: argparse.ArgumentParser) -> None:
|
||||
parser.add_argument("--exe", type=Path, required=True, help="the game executable to read")
|
||||
parser.add_argument("--patches", type=Path, default=DEFAULT_PATCHES, help="patch definition directory")
|
||||
|
||||
|
||||
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" assembly disagrees with stored bytes: {definition.identifier}: {problem}")
|
||||
if not mismatched:
|
||||
print(" every patch's assembly source compiles to its stored bytes")
|
||||
|
||||
plan = plan_patches(PeImage(args.exe.read_bytes()), definitions)
|
||||
print(plan.describe())
|
||||
return 0 if plan.complete and not mismatched else 1
|
||||
|
||||
|
||||
def _patch_exe(args: argparse.Namespace) -> int:
|
||||
if args.out.resolve() == args.exe.resolve():
|
||||
print("refusing to write over the input executable; choose a different --out", file=sys.stderr)
|
||||
return 2
|
||||
if args.out.exists() and not args.force:
|
||||
print(f"{args.out} already exists; pass --force to overwrite", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
original = args.exe.read_bytes()
|
||||
plan = plan_patches(PeImage(original), load_patches(args.patches))
|
||||
print(plan.describe())
|
||||
if not plan.complete:
|
||||
print("some patches are unavailable; nothing was written", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
patched = apply_writes(original, plan.writes)
|
||||
for start, end in changed_ranges(original, patched):
|
||||
print(f" changed {end - start} byte(s) at file offset {start:#x}: "
|
||||
f"{original[start:end].hex()} -> {patched[start:end].hex()}")
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.out.write_bytes(patched)
|
||||
print(f"wrote {args.out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Locate and apply the declared changes to aces.exe.
|
||||
|
||||
The patches themselves live as data under exe-patches/; this package is only the engine.
|
||||
Order of work, and the reason for it: find every site and verify every original byte first
|
||||
(plan), then write (apply). A site that is missing or ambiguous is reported, never guessed,
|
||||
so a game update produces a list of unavailable patches and the features they cover rather
|
||||
than a broken executable.
|
||||
|
||||
`authoring` and `assemble` are development-side only: they need a disassembler and an
|
||||
assembler, and are imported explicitly rather than from here.
|
||||
"""
|
||||
from .apply import apply_writes, changed_ranges
|
||||
from .definition import PatchDefinition, PatchEdit, load_patches
|
||||
from .errors import DefinitionError, LocateError, PatchError, VerifyError
|
||||
from .plan import PatchFailure, PatchPlan, PlannedWrite, plan_patches
|
||||
|
||||
__all__ = [
|
||||
"DefinitionError",
|
||||
"LocateError",
|
||||
"PatchDefinition",
|
||||
"PatchEdit",
|
||||
"PatchError",
|
||||
"PatchFailure",
|
||||
"PatchPlan",
|
||||
"PlannedWrite",
|
||||
"VerifyError",
|
||||
"apply_writes",
|
||||
"changed_ranges",
|
||||
"load_patches",
|
||||
"plan_patches",
|
||||
]
|
||||
@@ -0,0 +1,39 @@
|
||||
"""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
|
||||
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.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .errors import VerifyError
|
||||
from .plan import PlannedWrite
|
||||
|
||||
|
||||
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:
|
||||
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")
|
||||
patched[write.file_offset:write.end_offset] = write.payload
|
||||
return bytes(patched)
|
||||
|
||||
|
||||
def changed_ranges(original: bytes, patched: bytes) -> list[tuple[int, int]]:
|
||||
"""Byte ranges that differ, for confirming a patched file changed only what was planned."""
|
||||
if len(original) != len(patched):
|
||||
raise VerifyError(f"size changed from {len(original)} to {len(patched)} bytes")
|
||||
ranges: list[tuple[int, int]] = []
|
||||
start = None
|
||||
for index, (left, right) in enumerate(zip(original, patched)):
|
||||
if left != right and start is None:
|
||||
start = index
|
||||
elif left == right and start is not None:
|
||||
ranges.append((start, index))
|
||||
start = None
|
||||
if start is not None:
|
||||
ranges.append((start, len(original)))
|
||||
return ranges
|
||||
@@ -0,0 +1,38 @@
|
||||
"""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.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from keystone import KS_ARCH_X86, KS_MODE_64, Ks, KsError
|
||||
|
||||
from .definition import PatchDefinition
|
||||
from .errors import DefinitionError
|
||||
|
||||
_assembler = Ks(KS_ARCH_X86, KS_MODE_64)
|
||||
|
||||
|
||||
def assemble(lines: tuple[str, ...] | list[str]) -> bytes:
|
||||
"""Compile position-independent x86-64 assembly to bytes."""
|
||||
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)
|
||||
except KsError as error:
|
||||
raise DefinitionError(f"could not assemble {source!r}: {error}") from error
|
||||
return bytes(encoding)
|
||||
|
||||
|
||||
def disagreement(definition: PatchDefinition) -> str | None:
|
||||
"""Why a definition's assembly source and stored bytes differ, or None if they agree."""
|
||||
if not definition.edit.asm:
|
||||
return "no assembly source recorded for the stored bytes"
|
||||
compiled = assemble(definition.edit.asm)
|
||||
if compiled != definition.edit.payload:
|
||||
return (f"assembly compiles to {compiled.hex()} but the stored bytes are "
|
||||
f"{definition.edit.payload.hex()}")
|
||||
return None
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Development-side helper: turn a known code range into a stored signature pattern.
|
||||
|
||||
This is where a disassembler is needed, so it is deliberately separate from the matching
|
||||
code in locate/signature.py. Patterns produced here are committed into patch definitions;
|
||||
an installer never runs this module.
|
||||
|
||||
Masking rule: keep the bytes that describe what the code does, wildcard the bytes that
|
||||
hold an address. Those are the displacement of a rip-relative operand and the target of a
|
||||
relative call or jump, both of which shift when unrelated code moves.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from capstone import CS_ARCH_X86, CS_MODE_64, Cs
|
||||
from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_REG_RIP
|
||||
|
||||
from .errors import DefinitionError
|
||||
from .locate import signature
|
||||
|
||||
_disassembler = Cs(CS_ARCH_X86, CS_MODE_64)
|
||||
_disassembler.detail = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatternDraft:
|
||||
pattern: str
|
||||
byte_length: int
|
||||
instruction_count: int
|
||||
hits: list[int]
|
||||
|
||||
@property
|
||||
def unique(self) -> bool:
|
||||
return len(self.hits) == 1
|
||||
|
||||
|
||||
def build_pattern(image, rva: int, length: int) -> str:
|
||||
"""Masked pattern for `length` bytes of code starting at `rva`."""
|
||||
tokens: list[str] = []
|
||||
consumed = 0
|
||||
for instruction in _disassembler.disasm(image.read(rva, length), rva):
|
||||
tokens.extend(_instruction_tokens(instruction))
|
||||
consumed += instruction.size
|
||||
if consumed == 0:
|
||||
raise DefinitionError(f"could not disassemble any instruction at {rva:#x}")
|
||||
return " ".join(tokens)
|
||||
|
||||
|
||||
def draft_for_function(reference, target, rva: int, length: int | None = None) -> PatternDraft:
|
||||
"""Build a pattern from `reference` at `rva` and report where it matches in `target`.
|
||||
|
||||
`length` defaults to the whole function containing `rva`, which is what makes a generic
|
||||
function prologue identifiable; pass a smaller value when the function is very large.
|
||||
"""
|
||||
bounds = reference.function_containing(rva)
|
||||
if length is None:
|
||||
if bounds is None:
|
||||
raise DefinitionError(f"{rva:#x} is not inside a known function; pass an explicit length")
|
||||
length = bounds[1] - rva
|
||||
pattern = build_pattern(reference, rva, length)
|
||||
return PatternDraft(
|
||||
pattern=pattern,
|
||||
byte_length=signature.pattern_length(pattern),
|
||||
instruction_count=sum(1 for _ in _disassembler.disasm(reference.read(rva, length), rva)),
|
||||
hits=signature.locate(target, pattern=pattern),
|
||||
)
|
||||
|
||||
|
||||
def _instruction_tokens(instruction) -> list[str]:
|
||||
raw = instruction.bytes
|
||||
masked = bytearray(len(raw)) # 1 marks a wildcard
|
||||
for start, size in _address_fields(instruction):
|
||||
masked[start:start + size] = b"\1" * size
|
||||
return [signature.WILDCARD if flag else f"{byte:02x}" for byte, flag in zip(raw, masked)]
|
||||
|
||||
|
||||
def _address_fields(instruction) -> list[tuple[int, int]]:
|
||||
fields = []
|
||||
for operand in instruction.operands:
|
||||
if operand.type == X86_OP_MEM and operand.mem.base == X86_REG_RIP:
|
||||
fields.append((instruction.disp_offset, instruction.disp_size))
|
||||
elif operand.type == X86_OP_IMM and _is_relative_branch(instruction):
|
||||
fields.append((instruction.imm_offset, instruction.imm_size))
|
||||
return [(start, size) for start, size in fields if size]
|
||||
|
||||
|
||||
def _is_relative_branch(instruction) -> bool:
|
||||
return instruction.mnemonic == "call" or instruction.mnemonic.startswith("j")
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Patch definitions as they are stored on disk.
|
||||
|
||||
One directory per change to the program's behaviour, under exe-patches/<domain>/<name>/:
|
||||
|
||||
patch.json what the program does now, what it does after the patch, why the
|
||||
executable has to change at all, which features depend on it, and the
|
||||
bytes to write
|
||||
locate.json how to find the site, and how that was established
|
||||
|
||||
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.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import DefinitionError
|
||||
|
||||
PATCH_FILE = "patch.json"
|
||||
LOCATE_FILE = "locate.json"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatchEdit:
|
||||
"""Bytes to write, and the bytes that must already be there."""
|
||||
offset: int
|
||||
payload: bytes
|
||||
expect_original: bytes
|
||||
asm: tuple[str, ...]
|
||||
|
||||
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 PatchDefinition:
|
||||
identifier: str
|
||||
title: str
|
||||
features: tuple[str, ...]
|
||||
requires: tuple[str, ...]
|
||||
edit: PatchEdit
|
||||
locate: dict
|
||||
directory: Path | None = None
|
||||
notes: dict = field(default_factory=dict)
|
||||
|
||||
@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."""
|
||||
definitions = [_read(path.parent) for path in sorted(root.rglob(PATCH_FILE))]
|
||||
_reject_duplicate_ids(definitions)
|
||||
_reject_unknown_requirements(definitions)
|
||||
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)
|
||||
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'")
|
||||
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", ())),
|
||||
edit=_read_edit(directory, patch["edit"]),
|
||||
locate=locate,
|
||||
directory=directory,
|
||||
notes={key: value for key, value in patch.items()
|
||||
if key not in ("id", "title", "features", "requires", "edit")},
|
||||
)
|
||||
|
||||
|
||||
def _read_edit(directory: Path, raw: object) -> PatchEdit:
|
||||
if not isinstance(raw, dict):
|
||||
raise DefinitionError(f"{directory / PATCH_FILE}: 'edit' must be an object")
|
||||
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", ())),
|
||||
)
|
||||
|
||||
|
||||
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_json(path: Path) -> dict:
|
||||
if not path.is_file():
|
||||
raise DefinitionError(f"{path}: file not found")
|
||||
try:
|
||||
data = json.loads(path.read_text("utf-8"))
|
||||
except json.JSONDecodeError as error:
|
||||
raise DefinitionError(f"{path}: invalid JSON: {error}") from error
|
||||
if not isinstance(data, dict):
|
||||
raise DefinitionError(f"{path}: expected a JSON object")
|
||||
return data
|
||||
|
||||
|
||||
def _reject_duplicate_ids(definitions: list[PatchDefinition]) -> None:
|
||||
seen: dict[str, Path | None] = {}
|
||||
for definition in definitions:
|
||||
if definition.identifier in seen:
|
||||
raise DefinitionError(f"two definitions use id {definition.identifier!r}: "
|
||||
f"{seen[definition.identifier]} and {definition.directory}")
|
||||
seen[definition.identifier] = definition.directory
|
||||
|
||||
|
||||
def _reject_unknown_requirements(definitions: list[PatchDefinition]) -> None:
|
||||
known = {definition.identifier for definition in definitions}
|
||||
for definition in definitions:
|
||||
unknown = [item for item in definition.requires if item not in known]
|
||||
if unknown:
|
||||
raise DefinitionError(f"{definition.identifier} requires unknown patch(es): {', '.join(unknown)}")
|
||||
@@ -0,0 +1,22 @@
|
||||
class PatchError(Exception):
|
||||
"""A patch cannot be applied, so nothing was written."""
|
||||
|
||||
|
||||
class DefinitionError(PatchError):
|
||||
"""A patch definition on disk is malformed."""
|
||||
|
||||
|
||||
class LocateError(PatchError):
|
||||
"""A patch site could not be found, or was found in more than one place.
|
||||
|
||||
The caller reports which patches are affected and which features depend on them;
|
||||
it never falls back to a guessed address.
|
||||
"""
|
||||
|
||||
|
||||
class VerifyError(PatchError):
|
||||
"""The bytes at a located site are not what the definition expects.
|
||||
|
||||
Either the game version differs more than the signature could detect, or the
|
||||
executable is already patched.
|
||||
"""
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Ways to find a patch site in an executable.
|
||||
|
||||
One method per module, each exposing `locate(image, spec) -> list[int]` returning the
|
||||
RVAs it matched. A method never picks a winner among several matches; the caller
|
||||
requires exactly one and refuses otherwise.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
|
||||
from ..errors import DefinitionError
|
||||
from . import signature
|
||||
|
||||
Locator = Callable[..., list[int]]
|
||||
|
||||
_METHODS: Mapping[str, Locator] = {
|
||||
signature.METHOD: signature.locate,
|
||||
}
|
||||
|
||||
|
||||
def method(name: str) -> Locator:
|
||||
if name not in _METHODS:
|
||||
raise DefinitionError(f"unknown locate method {name!r}; known methods: {', '.join(sorted(_METHODS))}")
|
||||
return _METHODS[name]
|
||||
|
||||
|
||||
__all__ = ["Locator", "method", "signature"]
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Find a patch site by scanning for a byte pattern with wildcards.
|
||||
|
||||
A pattern is a hex string where "??" stands for any byte, for example:
|
||||
|
||||
"41 57 41 56 48 81 ec ?? ?? ?? ??"
|
||||
|
||||
Wildcards cover the bytes that legitimately differ between builds: addresses inside
|
||||
rip-relative operands and the targets of relative calls and jumps. What is left is the
|
||||
shape of the code, which is what identifies the function across versions.
|
||||
|
||||
This module only matches patterns; it needs no disassembler, which is why it is the part
|
||||
that runs on the player's machine. Patterns are generated once on the development side
|
||||
(see authoring.py) and stored in the patch definition.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ..errors import DefinitionError
|
||||
|
||||
METHOD = "signature"
|
||||
WILDCARD = "??"
|
||||
|
||||
|
||||
def locate(image, *, pattern: str, section: str = ".text", limit: int = 8, **_unused) -> list[int]:
|
||||
"""RVAs in `section` where `pattern` matches, at most `limit` of them."""
|
||||
expression = compile_pattern(pattern)
|
||||
data = image.section_bytes(section)
|
||||
base = image.section(section).rva
|
||||
hits = []
|
||||
for match in expression.finditer(data):
|
||||
hits.append(base + match.start())
|
||||
if len(hits) >= limit:
|
||||
break
|
||||
return hits
|
||||
|
||||
|
||||
def compile_pattern(pattern: str) -> re.Pattern[bytes]:
|
||||
return re.compile(b"".join(_token_to_regex(token) for token in _tokens(pattern)), re.DOTALL)
|
||||
|
||||
|
||||
def pattern_length(pattern: str) -> int:
|
||||
return len(_tokens(pattern))
|
||||
|
||||
|
||||
def _tokens(pattern: str) -> list[str]:
|
||||
tokens = pattern.split()
|
||||
if not tokens:
|
||||
raise DefinitionError("signature pattern is empty")
|
||||
for token in tokens:
|
||||
if token != WILDCARD and not re.fullmatch(r"[0-9a-fA-F]{2}", token):
|
||||
raise DefinitionError(f"signature pattern token must be a hex byte or {WILDCARD!r}, got {token!r}")
|
||||
return tokens
|
||||
|
||||
|
||||
def _token_to_regex(token: str) -> bytes:
|
||||
return b"." if token == WILDCARD else re.escape(bytes.fromhex(token))
|
||||
@@ -0,0 +1,121 @@
|
||||
"""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.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .definition import PatchDefinition
|
||||
from .errors import DefinitionError, LocateError, PatchError, VerifyError
|
||||
from .locate import method as locate_method
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlannedWrite:
|
||||
patch_id: str
|
||||
rva: int
|
||||
file_offset: int
|
||||
payload: bytes
|
||||
expect_original: bytes
|
||||
|
||||
@property
|
||||
def end_offset(self) -> int:
|
||||
return self.file_offset + len(self.payload)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatchFailure:
|
||||
patch_id: str
|
||||
features: tuple[str, ...]
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class PatchPlan:
|
||||
writes: list[PlannedWrite] = field(default_factory=list)
|
||||
failures: list[PatchFailure] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def complete(self) -> bool:
|
||||
return not self.failures
|
||||
|
||||
@property
|
||||
def affected_features(self) -> list[str]:
|
||||
return sorted({feature for failure in self.failures for feature in failure.features})
|
||||
|
||||
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" 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'}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def plan_patches(image, definitions: list[PatchDefinition]) -> PatchPlan:
|
||||
plan = PatchPlan()
|
||||
failed: dict[str, str] = {}
|
||||
|
||||
for definition in definitions:
|
||||
try:
|
||||
plan.writes.append(_plan_one(image, definition))
|
||||
except PatchError as error:
|
||||
failed[definition.identifier] = str(error)
|
||||
|
||||
_propagate_failures(definitions, failed)
|
||||
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]))
|
||||
|
||||
_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)
|
||||
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)}")
|
||||
|
||||
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 _propagate_failures(definitions: list[PatchDefinition], failed: dict[str, str]) -> None:
|
||||
"""A patch whose prerequisite is unavailable cannot be applied either."""
|
||||
requirements = {definition.identifier: definition.requires for definition in definitions}
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for identifier, requires in requirements.items():
|
||||
if identifier in failed:
|
||||
continue
|
||||
blocking = [item for item in requires if item in failed]
|
||||
if blocking:
|
||||
failed[identifier] = f"depends on unavailable patch(es): {', '.join(blocking)}"
|
||||
changed = True
|
||||
|
||||
|
||||
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:]):
|
||||
if later.file_offset < earlier.end_offset:
|
||||
raise DefinitionError(
|
||||
f"{earlier.patch_id} and {later.patch_id} write overlapping bytes at "
|
||||
f"{earlier.rva:#x} and {later.rva:#x}")
|
||||
Reference in new issue
Block a user