Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get function address by name?

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.

like image 571
limi Avatar asked Sep 08 '11 17:09

limi


People also ask

How do you find a function address?

We can get the address of a function by just writing the function's name without parentheses. Please refer function pointer in C for details. In C/C++, name of a function can be used to find address of function.

Where are function addresses stored?

June 25, 2021. To point to data, pointers are used. Like normal data pointers, we have function pointers that point to functions . The address of a function is stored in a function pointer.


2 Answers

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.

like image 166
Jason Avatar answered Oct 12 '22 15:10

Jason


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.

like image 41
R.. GitHub STOP HELPING ICE Avatar answered Oct 12 '22 13:10

R.. GitHub STOP HELPING ICE