How to duplicate sections in an ELF file

I have a requirement when I need to create a duplicate / copy section of a .data section.

I tried to create a dummy section with the same size of the data section in the linker script and copy the contents of the data section to the dummy section in the init function of my ELF image, but that doesn't match my requirement as I want the copy / duplicate section to be created along with the final ELF image not at runtime.

Below I wanted in my linker script,

SECTIONS {
    .data : { <data section contents> }
    .dummydata : { <copy of .data section> } 
}

      

Can anyone help write a linker script to meet the above requirement?

+3


source to share


1 answer


I don't think it can be done with just ld

a script and linker. Given this line from here :

If a file name matches more than one wildcard pattern, or the file name appears explicitly and also matches a wildcard pattern, the linker will use the first match in the linker script.

It looks like the linker script will only put data (or whatever) in one section.

However, all hope is not lost. You can copy the section with objcopy

and then add the section again withobjcopy

objcopy -O binary --only-section=.data your-file temp.bin
objcopy --add-section .dummydata=temp.bin your-file

      

This will add the section to the last section with VMA / LMA equal to 0. Then you can use objcopy

to move the section to the desired location.

objcopy --change-section-address .dummydata=desired-address your-file

      



Of course, if something already exists, it will be problematic. Luckily, you can create a hole right after the first one .data

with something like:

data_start = .;
.data : { *(.data) }
data_end = .;
. += (data_end - data_start);

      

This should create a hole just after your first data, big enough to put another copy of the data right after it. If that's not exactly where you want it, just add (data_end - data_start)

where you want the hole.

Finally, you can change the flags of the section, again with objcopy

objcopy --set-section-flags .dummydata=the-flags-you-want your-file

      

Not as easy as just duplicating something in the linker script, but it should work.

+3


source







All Articles