Flashing of ELF file using OpenOcd causes the ELF header to be written to Flash

Viewed 883

I use OpenOcd to flash the Elf image of a STM32 ARM Cmake project.

In the mem.ld script the origin address of the FLASH sector is assigned with an address offset to 0x08020200.

If the Elf file is written to the Flash using OpenOCD and the write_image command it seems like the ELF header is written to the FLASH at 0x08020000.

enter image description here

The application binary is correctly written to the flash at 0x08020200 (the first four bytes at 0x08020200 reflect the stack pointer value)

Since 0x08020200 is a address within the flash sector 5 (0x08020000 - 0x0803FFFF) i would expect the auto erase feature of the OpenOcd write_image command to erase the entire sector 5 (because only full sectors can be erased)

What could cause the ELF header to be written to flash at address 0x08020000 ?

I performed the following steps:

  • Manually erased the entire flash memory
  • Dumped the entire flash content with the OpenOcd dump_image command
  • Checked the dumped image represents a clear flash (all bytes 0xFF)
  • Flashed the test.elf file with the OpenOcd write_image command
  • Dumped the entire flash content with the OpenOcd dump_image command again
  • Checked the first four bytes at 0x08020200 reflect the stack pointer value
  • Checked content of flash at 0x08020000 -> ELF header was written to flash
2 Answers

This is a problem with PT_LOAD section alignment in the elf file. OpenOCD has no way of knowing where to write the image as the elf header is bundled into the section with the actual firmware payload offset from a 64KiB boundary.

The fix I found for this is to use --nmagic on ld (linker). It will force the alignment to 4 bytes and eliminate the elf header from being inadvertently written to the target. Use 'readelf -l the.elf' to see the differences.

I have the same problem when ELF header is programmed at the start of flash, but I have this problem with "stm32 programmer CLI" (not openOCD) and I fixed it by means HEX. If I use hex file instead ELF beginning of flash isn't corrupted.

Related