Skip to content

SPI flash with flashrom

Experimental

hwntools.spiflash is tested against a fake flashrom script only so far, not real programmers. Its API may change in minor releases.

Flashrom drives the flashrom command-line tool with a fixed programmer. Reading is the main use: a full, verified copy of the SPI flash is the starting point of almost every firmware assessment. flashrom must be installed and on PATH (ToolNotFoundError otherwise).

from hwntools import Flashrom

fr = Flashrom("ch341a_spi")          # or "linux_spi:dev=/dev/spidev0.0", "ft2232_spi:type=232H", ...
chips = fr.detect()                   # [FlashChip(vendor='Winbond', name='W25Q128.V', size=16777216, bus='SPI')]
image = fr.read("dump.bin")           # reads twice and compares

Detect the chip

detect() runs flashrom without an operation and parses the Found <vendor> flash chip "<name>" lines into FlashChip(vendor, name, size, bus) objects (size in bytes). When several chip definitions match, which is common for clones, flashrom needs to be told which one to use. Pass one of the returned names:

fr = Flashrom("ch341a_spi", chip="W25Q128.V")

Extra flashrom arguments go in extra_args=[...]; the per-call timeout defaults to 30 minutes.

Read, verified

image = fr.read("dump.bin")                # verify=True, tries=3
image = fr.read(verify=False)              # one read, nothing written to disk

With verify=True the chip is read twice and both reads must be identical. On a mismatch (a loose clip, marginal wiring, a back-powered SoC interfering) another pair of reads is attempted, up to tries pairs, before FlashromError is raised. Keep the verified image and its hash before doing anything else.

Write and erase

Both are destructive and refuse to run without force=True:

fr.write("patched.bin")                    # raises SafetyError
fr.write("patched.bin", force=True)        # flashrom -w, verified by flashrom
fr.erase(force=True)                       # flashrom -E
fr.verify("dump.bin")                      # True if the chip matches the file (flashrom -v)

Take and verify a backup with read() first, and keep it somewhere safe.

In-circuit reads

Clipping onto a flash chip on a board can back-power the SoC through the chip's VCC. If reads are unstable or the board heats up, stop: hold the SoC in reset or desolder the chip. See Safety.

No programmer? Use U-Boot

If the board has a U-Boot console, you can copy the flash without touching the chip: sf probe; sf read into RAM, then UBoot.dump().