Enumerate all ELF sections of all shared objects currently loaded
Asked Answered
G

3

5

I am looking for a nice way of enumerating all ELF sections and their addresses of the current binary and all shared objects the current process might have loaded.

I know about the existance of dl_iterate_phdr() which gives me an easy to use list of ELF segments, but I am looking for ELF sections, so it's not the right call for me.

I don't care about portability, as long as it works on Linux with ELF I am happy!

Any hint appreciated!

Gowk answered 1/2, 2012 at 23:1 Comment(1)
Oh and yes, I am looking for a some C API/code that is suitable for introspecting the process it runs in.Gowk
B
3

I assume you're trying to programmatically access this information from a C/C++ program. I suspect you should be able to do what you want with the GNU Binary File Descriptor library (BFD), which is used to implement the GNU linker, objdump, etc. (it also has a Wikipedia article). See in particular section 2.6 of the manual, which is all about sections. BFD creates a linked list of "struct bfd_section", accessed through the "sections" member of struct bfd. I think you should be able to open the current binary by using bfd_fopen on argv[0]. BFD ships with binutils.

Broadside answered 1/2, 2012 at 23:44 Comment(0)
E
3

This sounds like a really bad idea, but if you have a legitimate use for it, I would just parse /proc/self/maps and open the referenced files. There is no reason to believe that section headers are even mapped into memory; in all likelihood, they're located immediately after .data on disk and thus will be overwritten with zeros for .bss when the shared object is mapped into memory.

Once you have the files open, you could use libbfd, but I would just use elf.h directly. It's easy to follow the Ehdr to the Shdr table.

Excitant answered 2/2, 2012 at 1:36 Comment(0)
B
1

The readelf command can do this e.g., readelf -s

This not trivial, so posting a link to source code for readelf seems like a best choice. One reason for this is the large number of macros required to process header and section structs.

http://rpm5.org/docs/api/readelf_8c-source.html

Bertha answered 1/2, 2012 at 23:48 Comment(2)
That code is vastly complicated by the fact that it's supporting non-native ELF files and thus has to deal with endian and 32/64-bit issues. If you only need to process native ELF files (as in OP's case) the code becomes trivial. Iterating the section headers shouldn't take more than 10-15 lines.Excitant
On my system, the correct command to show sections is readelf -S [filename]Girt

© 2022 - 2024 — McMap. All rights reserved.