LuisABOL LuisABOL - 6 months ago 13
Linux Question

How to get a pointer to an specific section of a dynamic library (Linux ELF)?

As can be seen in the second answer for this question , it's quite simple to get a pointer to an specific section of a program from within itself, using the section's name. With

libelf
, just open the program's own file, loop over all sections (which are represented by
Elf64_Shdr
structs) in it, stop when the section name matches the one you want and use the pointer stored in the
sh_addr
element of the
Elf64_Shdr
struct. In this case, it's very simple to get the wanted pointer because it is defined in the ELF executable file.

But, imagine you have a program that uses a dynamic library and you need to get a pointer to a section of that dynamic library. Since the addresses of its sections are defined in runtime, how is it possible to get pointers to sections of a dynamic library?

By the way, both the dynamic library and the main program itself have, each one, a section with the same name (which is the one I need to get a pointer to). So, in this case, is it possible that these two sections with the same name are stored adjacently in memory, so that I just need to get a pointer to the main file's section (as I explained in the first paragraph) and add an offset to reach the dynamic library section?

Answer

it's quite simple to get a pointer to an specific section of a program from within itself

Not necessarily. The section table is not actually needed at runtime, and can be completely stripped (only segments matter, not sections).

Since the addresses of its sections are defined in runtime, how is it possible to get pointers to sections of a dynamic library?

The library is not at all different from the main executable. The main difference is that the library is usually linked at address 0 (the main executable is not), and relocated by the runtime loader to some other constant offset.

Once you know that offset, just add it to the section start (which you can find from readelf -S foo.so or from libelf), and voila: you've got the runtime address of the section.

So how can you find the relocation for a given shared library?

Inelegant solution (already suggested by Nick) is to parse /proc/self/maps.

A better solution is to use (glibc-specific) dl_iterate_phdr. Documentation here. You'll want to use dlpi_addr .