Skip to content

Instantly share code, notes, and snippets.

@Martoni
Forked from pepijndevos/patch.py
Created July 22, 2022 14:47
Show Gist options
  • Save Martoni/aca9f5459f1d503d1915d2313a131fb7 to your computer and use it in GitHub Desktop.
Save Martoni/aca9f5459f1d503d1915d2313a131fb7 to your computer and use it in GitHub Desktop.
Gowin IDE patcher
#!/usr/bin/python3
import os
import re
import subprocess
import mmap
def patch(filename : str, bytes):
subprocess.run(["cp",filename, filename + '_patched'])
with open(filename + "_patched", "r+b") as f:
mm = mmap.mmap(f.fileno(), 0)
location = mm.find(bytes)
print(" found at offset: ", location, "len = ", len(bytes), "bytes")
patchbytes = bytearray([0x90] * len(bytes)) # NOP
patchbytes[0] = 0x30 # XOR %al %al
patchbytes[1] = 0xC0
patchbytes[2] = 0xFE # INC %al
patchbytes[3] = 0xC0
mm[location:location+len(bytes)] = patchbytes
mm.close()
files = os.listdir(os.getcwd())
# remove all non-executables and directories
files = [filename for filename in files if os.access(filename, os.X_OK) == True]
files = [filename for filename in files if os.path.isdir(filename) == False]
#
files = [filename for filename in files if filename.endswith(tuple([".json", ".ini", ".v", ".xml", ".conf", ".py","_backup", ".vhd"])) == False]
functionName = "_ZN4GLIC15checkoutLicenseEPKc"
reHexByte = "([0-9a-fA-F]{2})"
hexBytes = re.compile(reHexByte)
for filename in files:
print("Processing: ", filename)
result = subprocess.run(["objdump", "--disassemble=main", filename], capture_output=True, text=True, check=True)
if functionName in result.stdout:
print(" patching.. ")
for line in result.stdout.split("\n"):
if (functionName in line):
print(line)
sline = line.split("\t")
if (len(sline) <2):
print("Cannot find bytes!")
else:
bytematch = hexBytes.findall(sline[1])
if (len(bytematch) >= 5):
print("Found bytes: ", sline[1])
searchBytes = bytes([int(x,16) for x in bytematch])
patch(filename, searchBytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment