Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move bunch source file code in specific section of linker script

I have learned that using __attribute__ ((section(".section_name"))), I can move function or variable at specific section as per defined in linker script. But I have a bunch of C source files for which I wish to move all of that code in a specific section with a simple method instead of writing the above command for each of the function/variable declarations.

The same way I have some mode C files for which I need to move them into other defined sections.

Writing __attribute__ ((section(".section_name"))) For every function and Variable will be time consuming and complex process. Can anyone have an alternate method to apply a specific section for the whole file instead of every function?

like image 265
Logan859 Avatar asked May 14 '26 02:05

Logan859


2 Answers

Are you exaggerating when you say "writing __attribute__ ((section(".section_name"))) for every function and Variable will be time consuming and complex process"?

Ctx's proposal is a viable solution. But when you revisit your code in half a year's time, you will have a hard time remembering why and how it works. And it will add a lot of extra effort when you move to a different build system.

A more pragmatic solution would be to use a macro:

#define MY_SECTION __attribute__ ((section(".section_name")))

Using the macro creates easy to read and understandable code with no hidden linker magic:

int variable MY_SECTION = 10;

int sqr(int n1) MY_SECTION;
like image 159
Codo Avatar answered May 16 '26 20:05

Codo


You can use a linker script for this. First, fetch the default linker script:

$ ld --verbose

There is a SECTIONS section included, which you have to modify:

SECTIONS
{
  /* Read-only sections, merged into text segment: */
  PROVIDE (__executable_start = SEGMENT_START("text-segment", 0x400000)); . = SEGMENT_START("text-segment", 0x400000) + SIZEOF_HEADERS;
  .interp         : { *(.interp) }
  .note.gnu.build-id : { *(.note.gnu.build-id) }
  .hash           : { *(.hash) }
  .gnu.hash       : { *(.gnu.hash) }
  .dynsym         : { *(.dynsym) }
  .dynstr         : { *(.dynstr) }
  .gnu.version    : { *(.gnu.version) }
...

Now, at the location where you want your new section to appear, place the following command:

.mysection : { obj1.o obj2.o }

This places all symbols of the specified object files into the specified section. You can also restrict this to specific input sections, for example

.mysection : { obj1.o(.text) obj2.o(.data) }

You can also use wildcards for the file name specification:

.mysection : { sdk/files_*.o }

For further details you can consult the GNU ld manual

like image 40
Ctx Avatar answered May 16 '26 20:05

Ctx