Binary Patching¶
Binary patching is used to patch files or programs on devices. It employs hexadecimal wildcards for find and replace operations, supporting high/low nibble wildcards. For example, ?? represents any single byte, B? represents any byte with B as the high nibble (i.e., B0-BF), such as BA, B1, B9. The pattern 49 BA ?? ?C will match any byte sequence in the file that conforms to the pattern. The following call will replace all byte sequences matching AA BB CC D? in test.bin with AA BB CC DD, and the interface returns the count of replacements and the offset of each replacement.
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 a four-byte match and replacement, but the interface actually supports multi-byte matching and replacement of arbitrary length, provided the match pattern contains at least two valid hex characters (i.e., at least one non-wildcard byte).
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)
You can also enable dry-run mode with the dryrun parameter, which will only locate the 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 pattern matching. For example, /data/app/*/test.bin will match the test.bin file in any single-level subdirectory under /data/app.