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