Question

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?

Was it helpful?

Solution

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 .

OTHER TIPS

It is very simple, herein an example:

#include <stdio.h>

int i __attribute__((section("my_section"))) = 2;
int j __attribute__((section("my_section"))) = 3;
int k __attribute__((section("my_section"))) = 5;

extern int __start_my_section;
extern int __stop_my_section;

int main(void)
{
    int *p = &__start_my_section;

    printf("%d\n", *p++); /* print k value */
    printf("%d\n", *p++); /* print j value */
    printf("%d\n", *p);   /* print i value */

   return 0;
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top