7. SPI flash and JTAG¶
These use stand-ins
The built-in simulator has no SPI programmer and no debug port. In this lesson,
hwntools talks to two small stand-ins for the external programs it normally drives:
a fake flashrom executable and a fake OpenOCD server. The hwntools calls are the real
ones; what comes back is canned. On real hardware you replace only the stand-in line.
SPI flash with Flashrom¶
Dumping over md.b is slow and needs a working U-Boot. The faster, more reliable way is to
read the chip itself: clip a programmer such as a CH341A onto the 8-pin flash chip (board
powered off) and run flashrom. Flashrom wraps that program,
parses the detected chip, and reads the chip twice, comparing both reads, because a
badly seated clip gives you corrupted data that looks fine.
The stand-in prints what flashrom prints and "reads" the chip by copying your flash.bin
(POSIX only, because it is a script with a #! line):
import stat
import sys
from pathlib import Path
from hwntools import Flashrom
# A stand-in for the flashrom program: it prints what flashrom prints and "reads"
# the chip by copying flash.bin. Real flashrom would talk to a CH341A clip instead.
fake = Path("fake-flashrom")
fake.write_text(f"""#!{sys.executable}
import shutil, sys
print('Found Winbond flash chip "W25Q128.V" (16384 kB, SPI) on ch341a_spi.')
if "-r" in sys.argv:
shutil.copy("flash.bin", sys.argv[sys.argv.index("-r") + 1])
print("Reading flash... done.")
""")
fake.chmod(fake.stat().st_mode | stat.S_IEXEC)
fr = Flashrom("ch341a_spi", flashrom=str(fake.resolve()))
print(fr.detect())
image = fr.read("spi-dump.bin") # reads twice and compares
print(len(image), image == Path("flash.bin").read_bytes())
[+] Detected Winbond W25Q128.V (16384 KiB)
[FlashChip(vendor='Winbond', name='W25Q128.V', size=16777216, bus='SPI')]
[*] Reading flash (attempt 1/3)
[+] Two reads match (sha256 7ef5b7f225393bbd)
32768 True
On real hardware: pip install hwntools, install flashrom, and write
Flashrom("ch341a_spi"). The real read returns the whole 16 MiB chip, not just the 32 KiB
image.
JTAG and SWD with OpenOCD¶
JTAG (and SWD on ARM microcontrollers) is the CPU's debug port: you can stop the CPU, read
and write registers and memory, and often read out the internal flash. The usual tool is
OpenOCD, which you start with config files for your debugger and
target. It then listens for commands on TCP port 6666, and hwntools' OpenOCD class talks
to that port.
lab.OpenOCDStandIn answers a handful of commands like OpenOCD would for a small
Cortex-M chip. A classic first read is the vector table at the start of flash: the
initial stack pointer and the address of the reset handler, which tells you where the
firmware's code starts.
from hwntools import OpenOCD
from hwntools.learn.lab import OpenOCDStandIn
with OpenOCDStandIn() as server: # real life: `openocd -f interface/... -f target/...`
ocd = OpenOCD(port=server.port)
print(ocd.version())
ocd.halt()
print(hex(ocd.reg("pc")))
sp, reset = ocd.read_u32(0x08000000), ocd.read_u32(0x08000004)
print(f"initial SP {sp:#x}, reset handler {reset:#x}")
print(ocd.read_memory(0x08000008, 8).hex())
ocd.close()
Open On-Chip Debugger 0.12.0 (lab stand-in)
0x8000134
initial SP 0x20005000, reset handler 0x8000135
0001020304050607
The reset handler address is odd (...135) because Cortex-M marks Thumb code with the
lowest bit; the code itself is at 0x8000134, where the program counter stopped.
On real hardware: run e.g. openocd -f interface/stlink.cfg -f target/stm32f1x.cfg and use
OpenOCD() with the default port. ocd.dump(addr, size, out=...) reads large regions, and
flash_read_bank() reads internal flash on the OpenOCD side, which is much faster. Many
production chips have readout protection enabled; then these reads fail, and that is a
finding too (a good one, for the vendor).
Try it¶
Try it
Using the same stand-in, try to write flash.bin back to the chip with fr.write().
What does hwntools do?
Solution
from pathlib import Path
from hwntools import Flashrom, SafetyError
fr = Flashrom("ch341a_spi", flashrom=str(Path("fake-flashrom").resolve()))
try:
fr.write("flash.bin")
except SafetyError as exc:
print("refused:", exc)
Like saveenv() in lesson 3, write() and erase() raise SafetyError unless you
pass force=True. With force=True, write() also verifies the chip afterwards.