How to fix st-flash ERROR common.c: stlink_flash_loader_run(0x8000000) failed! == -1

Problem:

While flashing an STM32 using st-flash using a command like

st-flash write build/firmware.bin 0x8000000

you see an error message like

2022-02-12T01:31:34 ERROR flash_loader.c: flash loader run error
2022-02-12T01:31:34 ERROR common.c: stlink_flash_loader_run(0x8000000) failed! == -1

See below for a full error log

Solution

Most likely your STM32 is locked (readout protection). Use OpenOCD to unlock it, see How to unlock STM32F0x using OpenOCD for an example. Adjust to your STM32 family as needed.

Full st-flash log

st-flash 1.6.1
2022-02-12T01:31:34 INFO common.c: F0xx small: 4 KiB SRAM, 16 KiB flash in at least 1 KiB pages.
file build/mom.bin md5 checksum: da211df7131de9de15f3b6c7a96176dd, stlink checksum: 0x000d0d03
2022-02-12T01:31:34 INFO common.c: Attempting to write 11108 (0x2b64) bytes to stm32 address: 134217728 (0x8000000)
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08000000 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08000400 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08000800 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08000c00 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08001000 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08001400 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08001800 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08001c00 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08002000 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08002400 erased
2022-02-12T01:31:34 INFO common.c: Flash page at addr: 0x08002800 erased
2022-02-12T01:31:34 INFO common.c: Finished erasing 11 pages of 1024 (0x400) bytes
2022-02-12T01:31:34 INFO common.c: Starting Flash write for VL/F0/F3/F1_XL core id
2022-02-12T01:31:34 INFO flash_loader.c: Successfully loaded flash loader in sram
2022-02-12T01:31:34 ERROR flash_loader.c: flash loader run error
2022-02-12T01:31:34 ERROR common.c: stlink_flash_loader_run(0x8000000) failed! == -1
stlink_fwrite_flash() == -1