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:
N0VAN0M4LY committed 2026-11-23 13:32:36 +08:00
1 parent c9e10b0db7
commit 8fa50b7804
12 files changed
+701

No files matched your search

+133
View File
@@ -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)}")