# Binary Patch

Binary patches are used to patch files or programs on a device. It performs find and replace operations using hexadecimal wildcards, supporting both high and low nibble wildcards. For example, `??` represents any byte, and `B?` represents any byte starting with `B`, such as `BA`, `B1`, or `B9`. A wildcard pattern like `49` `BA` `??` `?C` will match any sequence in the file corresponding to `49` `BA` `..` `.C`. The following call will replace all `AA` `BB` `CC` `D[0-9A-F]` byte sequences in `test.bin` with `AA` `BB` `CC` `DD`. The interface returns the number of replacements and their respective offsets.

```python
d.hex_patch("AA BB CC D?", "AA BB CC DD", "/data/test.bin")
```

```python
>>> 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 example only demonstrates a four-byte match and replace, but the interface supports matching and replacing sequences of any length. However, the match pattern must contain at least two valid hexadecimal characters (one byte).
```

To limit the maximum number of replacements, use the `maxreplace` parameter. By default, all occurrences are replaced.

```python
d.hex_patch("AA BB CC D?", "AA BB CC DD", "/data/test.bin", maxreplace=2)
```

A dry run mode is also available. This will only find matching locations in the file without performing any replacement operations.

```python
d.hex_patch("AA BB ?? ??", "AA BB 00 00", "/data/test.bin", dryrun=True)
```

```{hint}
The file path supports wildcard matching (glob). For example, `/data/app/*/test.bin` will find and match `test.bin` files located in any immediate subdirectory under `/data/app`.
```