Created
November 25, 2024 14:43
-
-
Save mrtnvgr/f1c27cfd34a6d77ec8fa34ef477b1614 to your computer and use it in GitHub Desktop.
Binary patcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from io import BytesIO | |
class Patch(): | |
def __init__(self, offset: int, original: str, new: str): | |
self.offset = offset | |
self.original = bytes.fromhex(original) | |
self.new = bytes.fromhex(new) | |
def __str__(self): | |
return f"[\"{self.original.hex()}\" -> \"{self.new.hex()}\" (at {self.offset})]" | |
def apply_patches(data: bytes, patches: list[Patch]): | |
f = BytesIO(data) | |
for patch in patches: | |
f.seek(patch.offset) | |
data = f.read(len(patch.original)) | |
if data != patch.original: | |
raise Exception(f"Failed to apply a patch: {patch}") | |
f.seek(patch.offset) | |
f.write(patch.new) | |
f.seek(0) | |
return f.read() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment