"""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}")