JTAG / SWD with OpenOCD¶
Experimental
hwntools.openocd is tested against a simulated OpenOCD server only so far. Its API may
change in minor releases.
hwntools does not talk to JTAG or SWD adapters directly. You start
OpenOCD with the right interface and target configuration, and
OpenOCD connects to its TCL RPC server (port 6666 by default) to halt the CPU, read
registers and memory, and work with flash banks.
from hwntools import OpenOCD
with OpenOCD("127.0.0.1", 6666) as ocd:
print(ocd.version())
ocd.halt()
print(hex(ocd.reg("pc")))
vectors = ocd.read_memory(0x08000000, 0x100, width=32)
ocd.dump(0x08000000, 0x10000, out="internal-flash.bin")
ocd.resume()
Each command is wrapped in TCL catch, so a failing command raises OpenOCDError with
OpenOCD's message instead of returning an error string. cmd("...") runs any OpenOCD command
with that error check; raw("...") sends it untouched.
Target control¶
| Call | OpenOCD command |
|---|---|
halt(timeout_ms=1000) |
halt |
resume(address=None) |
resume [address] |
step() |
step |
reset("halt") |
reset run, reset halt or reset init |
state() |
<target> curstate (halted, running, ...) |
targets() |
target names |
reg("pc"), reg("r0", 0x1234) |
read, or write then read, a register |
Memory¶
data = ocd.read_memory(0x20000000, 0x400) # 8-bit accesses
words = ocd.read_memory(0x40021000, 0x20, width=32) # 32-bit accesses for MMIO
ocd.write_memory(0x20000000, b"\x00" * 16)
sp = ocd.read_u32(0x08000000)
ocd.write_u32(0x40021018, 0x1)
data = ocd.dump(0x08000000, 0x20000, out="flash.bin", chunk=0x1000)
read_memory() uses OpenOCD's read_memory command (OpenOCD 0.12 and newer) and falls back to
mem2array on older builds. width is the access width in bits (8, 16, 32 or 64) and the size
must be a multiple of it. Values are converted with little-endian byte order. dump() reads a
large region in chunks over RPC with a progress line.
Fast, server-side transfers¶
RPC reads move every byte through the TCL socket. For large regions, let OpenOCD write the file on the machine where OpenOCD runs:
ocd.dump_image("/tmp/sram.bin", 0x20000000, 0x10000) # memory -> file
ocd.flash_read_bank(0, "/tmp/bank0.bin") # whole flash bank -> file
print(ocd.flash_banks())
ocd.load_image("/tmp/stub.bin", 0x20000000) # file -> target RAM
Programming flash¶
flash_write_image() is destructive and needs force=True:
It erases the affected sectors first unless you pass erase=False. Dump the original flash
before you program anything.
A complete script is in
examples/openocd_read_memory.py.