Search code examples
c++linkerarmgnuld

Is there a way to prevent an added .o file section of being removed from gnu linker garbage collection?


I have an asymmetric dual core (ARM) controller (A5 core and M4 core). I want to create ONE binary which I can write into the RAM/ROM of the controller and then execute code for both cores. I include the M4 code as a .o file in the A5 linker ld. The section is garbage collected because of the option --gc-sections. Is there a way how I can keep this section but still use the option --gc-sections for all the other sections?

More detailed:

I built the m4 code and from the binary output I create a .o file.

COMMAND arm-none-eabi-objcopy.exe -O binary --gap-fill 0xff m4_tester.elf m4_tester.bin
COMMAND arm-none-eabi-objcopy.exe -I binary -O elf32-littlearm -B arm m4_tester.bin m4_tester.o

This file I included in the A5 project linker .ld file as a section:

    SECTIONS
    {  
      .m4stuff : { 
        . = ALIGN(4);
        m4_tester.o
        KEEP(*(.m4stuff))
        . = ALIGN(4);
        } > m4code

    ...
    }

So far this works all fine and looks like this in the map file:

.m4stuff        0x3f4e0000      0xd68
                0x3f4e0000                . = ALIGN (0x4)
 m4_tester.o()
 .data          0x3f4e0000      0xd68 m4_tester.o
                0x3f4e0000                _binary_m4_tester_bin_start
                0x3f4e0d68                _binary_m4_tester_bin_end
 *(.m4stuff)
                0x3f4e0d68                . = ALIGN (0x4)

Now I would also like to use the linker option --gc-sections. By its definition the m4stuff section is now garbage collected:

.m4stuff        0x3f4e0000        0x0
                0x3f4e0000                . = ALIGN (0x4)
 m4_tester.o()
 *(.m4stuff)
                0x3f4e0000                . = ALIGN (0x4)

Is there a way how I can keep this section but still use the option --gc-sections for all the other sections?


Solution

  • In principle the KEEP command in your command file should do this.

    From the GNU ld manual:

    3.6.4.4 Input Section and Garbage Collection

    When link-time garbage collection is in use (‘--gc-sections’), it is often useful to mark sections that should not be eliminated. This is accomplished by surrounding an input section’s wildcard entry with KEEP(), as in KEEP((.init)) or KEEP(SORT_BY_NAME()(.ctors)).

    This SO answer contains an example of KEEP use that might help.