Sunday, June 5, 2022

[SOLVED] GCC - Relocate data section of a shared library to specific memory location

Issue

I am searching to find a way to relocate/load a user defined data section of a shared library to specific virtual memory of a C program.

Initially, i was using only static libraries (.a) to link the whole program. some of these libraries (2 of them, let call libdata1.a and libdata2.a) are just a collection of initialized structs. A kind of "C based database files".
for some compatibility reasons, the "data section" of these libraries need to be loaded at a specific memory location in the final program.

in the static case, I just modify the ld script to add a rule to achieve that, and all work fine.

  .usrdata1 0x04200000 : { *(.usrdata1 ) }   /* data1 is the renamed data section of libdata1  */
  .usrdata2 0x04300000 : { *(.usrdata2 ) }   /* data2 is the renamed data section of libdata2  */

However now, I need a solution to load these two libs (or the data section that they embed) in a dynamic fashion. So the libs will be dissociated from the final binary. I thought on using shared libraries (.so), however the dynamic linker will just load the two libraries at any virtual memory, and I don't know a mean to force a specific memory location.

Do you have any idea of any applicable solution please ?

If this is not valuable, is it possible to find the memory location where the two "usrdata" sections were loaded in the running binary by the dynamic linker ? If so, this can be sufficient for me, because I can also change some memory references in the inner C code to make it work.

Thanks in advance


Solution

some of these libraries (2 of them, let call libdata1.a and libdata2.a) are just a collection of initialized structs.
However now, I need a solution to load these two libs (or the data section that they embed) in a dynamic fashion.

The easiest solution is to save the raw initialized structs into a file (file1.data, file2.data) and mmap() them at the address you need with MAP_FIXED flag.

Involving the dynamic loader in this endeavor is counter-productive -- you'll just fight it.

is it possible to find the memory location where the two "usrdata" sections were loaded in the running binary by the dynamic linker ?

That is trivial to do using dladdr.



Answered By - Employed Russian
Answer Checked By - Candace Johnson (WPSolving Volunteer)