Binary Patching¶
Binary patching is used to modify files or programs on a device. It performs search-and-replace operations using hexadecimal wildcards, supporting both high and low bit wildcard matching. For example:
??represents any single byte,B?represents any byte starting withB, such asBA,B1, orB9.The wildcard pattern
49 BA ?? ?Cwill match any sequence in the file that fits49 BA .. .C.
The following call replaces all occurrences of the byte sequence AA BB CC D[0-9A-F] in test.bin with AA BB CC DD. The interface returns the number of replacements made and the offsets where replacements occurred.
d.hex_patch("AA BB CC D?", "AA BB CC DD", "/data/test.bin")
>>> result = d.hex_patch("AA BB CC D?", "AA BB CC DD", "/data/test.bin")
>>> print(result.count)
1
>>> print(result.replaces[0].offset)
8123
Note
The demonstration shows only four-byte matching and replacement, but the interface supports matching and replacing sequences of any length, provided there are at least two valid bytes for matching.
To limit the maximum number of replacements, use the maxreplace parameter. By default, all matches are replaced.
d.hex_patch("AA BB CC D?", "AA BB CC DD", "/data/test.bin", maxreplace=2)
There is also a dry-run mode, which only locates matching positions in the file without performing actual replacements.
d.hex_patch("AA BB ?? ??", "AA BB 00 00", "/data/test.bin", dryrun=True)
Hint
File paths support glob-style wildcards. For example, /data/app/*/test.bin will find and match the file test.bin in any first-level subdirectory under /data/app.