[翻译]  Get functions names in a shared library programatically

[CHINESE]  以编程方式在共享库中获取函数名称


Can I get list of all functions names from a shared library (Linux only) programmatically when I am using dl_open()?

当我使用dl_open()时,是否可以通过编程方式从共享库(仅限Linux)获取所有函数名称的列表?

I want something like this:

我想要这样的东西:

std::vector<std::string> list_all_functions(void *dl) { 
   //... what can I do here?
}

int main() {
    void * dl = dl_open("./mylib.so", RTLD_NOW);
    auto functions = list_all_functions(dl);
    //...
    dl_close(dl);
    return 0;
}

Example library (mylib.so)

示例库(mylib.so)

Header (.h):

标题(.h):

extern "C" {
    int sum (int a, int b);
}

Source (.c):

来源(.c):

int sum (int a, int b) { return a + b; }

Dirty hack that I know: use nm or objdump utility

我知道的脏黑客:使用nm或objdump实用程序

1 个解决方案

#1


2  

There is no libc function to do that. However, you can write one yourself (or copy/paste the code from a tool like readelf).

没有libc功能可以做到这一点。但是,您可以自己编写一个(或者从像readelf这样的工具中复制/粘贴代码)。

On Linux, dlopen() returns the address of a link_map structure, which has a member named l_addr that points to the base address of the loaded shared object (assuming your system doesn't randomize shared library placement, and that your library has not been prelinked).

在Linux上,dlopen()返回一个link_map结构的地址,该结构有一个名为l_addr的成员,该成员指向已加载的共享对象的基址(假设您的系统没有随机化共享库放置,并且您的库尚未存在预链接)。

On Linux, a way to find the base address (the address of Elf*_Ehdr) is to use dl_iterate_phdr() after dlopen()ing the library.

在Linux上,找到基址(Elf * _Ehdr的地址)的方法是在dlopen()之后使用dl_iterate_phdr()。

Having the ELF header, you should be able to iterate over a list of exported symbols (the dynamic symbol table), by first locating the Elf*_Phdr of type PT_DYNAMIC, and then locating DT_SYMTAB, DT_STRTAB entries, and iterating over all symbols in the dynamic symbol table. Use /usr/include/elf.h to guide you.

有了ELF头,你应该能够迭代一个导出符号列表(动态符号表),首先找到类型为PT_DYNAMIC的Elf * _Phdr,然后找到DT_SYMTAB,DT_STRTAB条目,并迭代所有符号。动态符号表。使用/usr/include/elf.h来指导您。

Additionally, you could use libelf, that I don't know very well personally.

另外,你可以使用我个人不太了解的libelf。

However, note that you'll get a list of defined functions, but you'll have no idea how to call them.

但请注意,您将获得已定义函数的列表,但您不知道如何调用它们。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号