How to get function address by name?

夙愿已清 提交于 2021-02-18 12:11:16

问题


I'd like to get function's address by name.

For example, currently I am using dlsym:

unsigned long get_func_addr(const char *func_name)
{
     return (unsigned long)dlsym(NULL, func_name);
}

However, dlsym only works for extern function. It won't work for static function. I know there could multiple static functions with same name in different files. But I need to at least get one static function's address with the name. Sometime static function will be inlned. But it's OK if C file is compiled with debug. I think with -g, the symbol table of static functions is present, but how can I access it?

I don't want to created a table for mapping the string to function address. I need to find a way to do it dynamically.


回答1:


This isn't really possible without somehow creating some external file that can be used for a look-up ... for instance, as you mentioned, a symbol table of static functions is present, but that is generated at compile/link time ... it is not something accessible from a non-compiled code module.

So basically you could generate and export the symbol table as an external file from your compiled and linked executable, and then have a function that dynamically looks up the function name in the external file which would provide the information necessary to get the address of the function where the complier and linker compiled/linked it to.




回答2:


A static function need not even exist in the binary, so there's no way to get its address. Even if it does exist, it might have been modified by the compiler based on the knowledge that certain arguments can only take particular values, or it might have had the calling convention adjusted such that it's not externally callable, etc. The only way you can be sure a "real" version of a static function exists is if its address is made visible to other modules via a function pointer.




回答3:


If the required function you want to lookup is in a DLL, you could use the Windows API getprocaddress(), which takes the name of the function and the name of the DLL as parameters.

If you want to find user defined functions, I would recommend using a lookup table as the names of those functions are not stored.

For user defined functions, you could force that every function export its name to another function at its start. i.e.:

void my_func()
{
    register(my_func,"my_func");// the address and the name
    // ...
}

Thus you could lookup the function later by name.



来源:https://stackoverflow.com/questions/7352100/how-to-get-function-address-by-name

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