How can I find the dynamic libraries required by an ELF Binary in C++?

时光毁灭记忆、已成空白 提交于 2019-12-09 12:21:36

问题


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:

  1. Parse the ELF header, check that the file is a dynamic executable (ET_EXEC or ET_DYN).
  2. Get the offset and count of the program headers (e_phoff/e_phnum/e_phentsize), check that they're non-zero and valid.
  3. parse the program headers, looking for the PT_DYNAMIC one. Also remember virtual address -> file offset mappings for the PT_LOAD segments.
  4. Once found, parse the dynamic section. Look for the DT_NEEDED and DT_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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!