问题
How can I get a list of all the dynamic libraries that is required by an elf binary in linux using C++?
Once I've managed to extract the information (filename?) from the binary I can find the actual file by searching through the PATH
, but I haven't been able to find any information regarding extracting unmangled information from the ELF binary.
Thoughts?
回答1:
The list of required shared objects is stored in the so-called dynamic section of the executable. The rough algorithm of getting the necessary info would be something like this:
- Parse the ELF header, check that the file is a dynamic executable (
ET_EXEC
orET_DYN
). - Get the offset and count of the program headers (
e_phoff/e_phnum/e_phentsize
), check that they're non-zero and valid. - parse the program headers, looking for the
PT_DYNAMIC
one. Also remember virtual address -> file offset mappings for thePT_LOAD
segments. - Once found, parse the dynamic section. Look for the
DT_NEEDED
andDT_STRTAB
entries.
The d_val
field of the DT_NEEDED
entries is the offset into the DT_STRTAB
's string table, which will be the SONAME of the required libraries. Note that since DT_STRTAB
entry is the run-time address and not the offset of the string table, you'll need to map it back to a file offset using information stored at step 3.
回答2:
You can call "readelf -d" program and parse the output:
readelf -d /usr/bin/readelf | grep NEEDED
0x0000000000000001 (NEEDED) Shared library: [libz.so.1]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
来源:https://stackoverflow.com/questions/22612735/how-can-i-find-the-dynamic-libraries-required-by-an-elf-binary-in-c