以编程方式获取共享库中的函数名称 [英] Get functions names in a shared library programmatically
问题描述
使用dl_open()
时可以通过编程方式从共享库(仅Linux)中获取所有函数名称的列表吗?
Can I get list of all functions names from a shared library (Linux only) programmatically when I am using dl_open()
?
我想要这样的东西:
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;
}
示例库(mylib.so)
Example library (mylib.so)
标题(.h):
extern "C" {
int sum (int a, int b);
}
来源(.c):
int sum (int a, int b) { return a + b; }
我知道的肮脏黑客:使用nm
或objdump
实用程序
Dirty hack that I know: use nm
or objdump
utility
推荐答案
没有libc函数可以执行此操作.但是,您可以自己编写(或从诸如readelf之类的工具中复制/粘贴代码).
There is no libc function to do that. However, you can write one yourself (or copy/paste the code from a tool like readelf).
在Linux上,dlopen()
返回link_map
结构的地址,该结构具有名为l_addr
的成员,该成员指向已加载的共享库的基址(假设您的系统没有随机分配共享库的位置,并且您的媒体库尚未预链接).
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上,找到基地址(Elf*_Ehdr
的地址)的一种方法是在dlopen()
库之后使用dl_iterate_phdr()
.
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.
具有ELF标头,通过首先找到类型PT_DYNAMIC
的Elf*_Phdr
,然后找到DT_SYMTAB
,DT_STRTAB
,您应该能够遍历导出的符号列表(动态符号表).条目,并遍历动态符号表中的所有符号.使用/usr/include/elf.h
指导您.
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.
此外,您可以使用 libelf ,因为我个人不太了解
Additionally, you could use libelf, that I don't know very well personally.
但是,请注意,您将获得已定义函数的列表,但是您不知道如何调用它们.
However, note that you'll get a list of defined functions, but you'll have no idea how to call them.
这篇关于以编程方式获取共享库中的函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!