armstm32gnu-toolchainobjcopy

renaming .data to .rodata using objcopy fills output with zeros


Following this helpful guide, I am using objcopy to embed a large data file in my code, like so:

arm-none-eabi-objcopy -I binary -O elf32-littlearm "raw_data.bin" "raw_data.o"

This generates a valid output, but I need it to be stored as a const. I rename the section like so:

arm-none-eabi-objcopy -I binary -O elf32-littlearm --rename-section .data=.rodata,alloc,load,readonly "raw_data.bin" "raw_data.o"

This creates a file of the same size as before, but now all of the data is replaced with zeros. I verify this with objdump:

> arm-none-eabi-objdump -s "raw_data.o"

raw_data.o:     file format elf32-littlearm

Contents of section .rodata:
 00000 00000000 00000000 00000000 00000000  ................
 00010 00000000 00000000 00000000 00000000  ................
 00020 00000000 00000000 00000000 00000000  ................
 00030 00000000 00000000 00000000 00000000  ................
 00040 00000000 00000000 00000000 00000000  ................
 00050 00000000 00000000 00000000 00000000  ................
 00060 00000000 00000000 00000000 00000000  ................
 00070 00000000 00000000 00000000 00000000  ................
 00080 00000000 00000000 00000000 00000000  ................ 

... and so on ...

Solution

  • From objcopy manual:

    --rename-section oldname=newname[,flags]

    Rename a section from oldname to newname, optionally changing the section’s flags to flags in the process. This has the advantage over using a linker script to perform the rename in that the output stays as an object file and does not become a linked executable. This option accepts the same set of flags as the --set-section-flags option.

    This option is particularly helpful when the input format is binary, since this will always create a section called .data. If for example, you wanted instead to create a section called .rodata containing binary data you could use the following command line to achieve it:

       --rename-section .data=.rodata,alloc,load,readonly,data,contents \
       <input_binary_file> <output_object_file>
    

    The contents flag is the key here. You need to keep it in order for objcopy to keep section contents intact.