How to get function's name from function's pointer in Linux kernel?

CLinux KernelFunction Pointers

C Problem Overview


How to get function's name from function's pointer in C?

Edit: The real case is: I'm writing a linux kernel module and I'm calling kernel functions. Some of these functions are pointers and I want to inspect the code of that function in the kernel source. But I don't know which function it is pointing to. I thought it could be done because, when the system fails (kernel panic) it prints out in the screen the current callstack with function's names. But, I guess I was wrong... am I?

C Solutions


Solution 1 - C

I'm surprised why everybody says it is not possible. It is possible on Linux for non-static functions.

I know at least two ways to achieve this.

There are GNU functions for backtrace printing: backtrace() and backtrace_symbols() (See man). In your case you don't need backtrace() as you already have function pointer, you just pass it to backtrace_symbols().

Example (working code):

#include <stdio.h>
#include <execinfo.h>

void foo(void) {
    printf("foo\n");
}

int main(int argc, char *argv[]) {
    void    *funptr = &foo;

    backtrace_symbols_fd(&funptr, 1, 1);

    return 0;
}

Compile with gcc test.c -rdynamic

Output: ./a.out(foo+0x0)[0x8048634]

It gives you binary name, function name, pointer offset from function start and pointer value so you can parse it.

Another way is to use dladdr() (another extension), I guess print_backtrace() uses dladdr(). dladdr() returns Dl_info structure that has function name in dli_sname field. I don't provide code example here but it is obvious - see man dladdr for details.

NB! Both approaches require function to be non-static!

Well, there is one more way - use debug information using libdwarf but it would require unstripped binary and not very easy to do so I don't recommend it.

Solution 2 - C

That's not directly possible without additional assistance.

You could:

  1. maintain a table in your program mapping function pointers to names

  2. examine the executable's symbol table, if it has one.

The latter, however, is hard, and is not portable. The method will depend on the operating system's binary format (ELF, a.out, .exe, etc), and also on any relocation done by the linker.

EDIT: Since you've now explained what your real use case is, the answer is actually not that hard. The kernel symbol table is available in /proc/kallsyms, and there's an API for accessing it:

#include <linux/kallsyms.h>

const char *kallsyms_lookup(unsigned long addr, unsigned long *symbolsize,
                            unsigned long *ofset, char **modname, char *namebuf)

void print_symbol(const char *fmt, unsigned long addr)

For simple debug purposes the latter will probably do exactly what you need - it takes the address, formats it, and sends it to printk, or you can use printk with the %pF format specifier.

Solution 3 - C

In the Linux kernel, you can use directly "%pF" format of printk !

void *func = &foo;
printk("func: %pF at address: %p\n", func, func);

Solution 4 - C

The following works me on Linux:

  • printf the address of the function using %p
  • Then do an nm <program_path> | grep <address> (without the 0x prefix)
  • It should show you the function name.

It works only if the function in question is in the same program (not in a dynamically linked library or something).

If you can find out the load addresses of the loaded shared libraries, you can subtract the address from the printed number, and use nm on the library to find out the function name.

Solution 5 - C

You can't diectly but you can implement a different approach to this problem if you want. You can make a struct pointer instead pointing to a function as well as a descriptive string you can set to whatever you want. I also added a debugging posebilety since you problably do not want these vars to be printet forever.

// Define it like this
typedef struct
{
  char        *dec_text;
  #ifdef _DEBUG_FUNC
  void        (*action)(char);
  #endif
} func_Struct;

// Initialize it like this
func_Struct func[3]= {
#ifdef _DEBUG_FUNC
{"my_Set(char input)",&my_Set}};
{"my_Get(char input)",&my_Get}};
{"my_Clr(char input)",&my_Clr}};
#else
{&my_Set}};
{&my_Get}};
{&my_Clr}};
#endif 

// And finally you can use it like this
func[0].action( 0x45 );
#ifdef _DEBUG_FUNC
printf("%s",func.dec_text);
#endif

Solution 6 - C

If the list of functions that can be pointed to is not too big or if you already suspect of a small group of functions you can print the addresses and compare them to the one used during execution. Ex:

typedef void (*simpleFP)();
typedef struct functionMETA {
    simpleFP funcPtr;
    char * funcName;
} functionMETA;

void f1() {/*do something*/}
void f2() {/*do something*/}
void f3() {/*do something*/}

int main()
{
    void (*funPointer)() = f2; // you ignore this
    funPointer(); // this is all you see

    printf("f1 %p\n", f1);
    printf("f2 %p\n", f2);
    printf("f3 %p\n", f3);

    printf("%p\n", funPointer);

    // if you want to print the name
    struct functionMETA arrFuncPtrs[3] = {{f1, "f1"}, {f2, "f2"} , {f3, "f3"}};
    
    int i;
    for(i=0; i<3; i++) {
        if( funPointer == arrFuncPtrs[i].funcPtr )
            printf("function name: %s\n", arrFuncPtrs[i].funcName);
    }
}

Output:

f1 0x40051b
f2 0x400521
f3 0x400527
0x400521
function name: f2

This approach will work for static functions too.

Solution 7 - C

There is no way how to do it in general.

If you compile the corresponding code into a DLL/Shared Library, you should be able to enlist all entry points and compare with the pointer you've got. Haven't tried it yet, but I've got some experience with DLLs/Shared Libs and would expect it to work. This could even be implemented to work cross-plarform.

Someone else mentioned already to compile with debug symbols, then you could try to find a way to analyse these from the running application, similiar to what a debugger would do. But this is absolutely proprietary and not portable.

Solution 8 - C

  1. Use kallsyms_lookup_name() to find the address of kallsyms_lookup.

  2. Use a function pointer that points to kallsyms_lookup, to call it.

Solution 9 - C

Check out Visual Leak Detector to see how they get their callstack printing working. This assumes you are using Windows, though.

Solution 10 - C

Not exactly what the question is asking for but after reading the answers here I though of this solution to a similar problem of mine:

/**
* search methods */
static int starts(const char *str, const char *c);
static int fuzzy(const char *str, const char *c);

int (*search_method)(const char *, const char *);

/* asign the search_method and do other stuff */
[...]

printf("The search method is %s\n", search_method == starts ? "starts" : "fuzzy")

If your program needs this a lot you could define the method names along with a string in an XMacro and use #define X(name, str) ... #undef X in the code to get the corresponding string from the function name.

Solution 11 - C

Alnitak's answer is very helpful to me when I was looking for a workaround to print out function's name in kernel module. But there is one thing I want to supplyment, which is that you might want to use %pS instead of %pF to print function's name, becasue %pF not works anymore at some newer verions of kernel, for example 5.10.x.

Solution 12 - C

You can't. The function name isn't attached to the function by the time it's compiled and linked. It's all by memory address at that point, not name.

Solution 13 - C

You wouldn't know how you look like without a reflecting mirror. You'll have to use a reflection-capable language like C#.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel SilveiraView Question on Stackoverflow
Solution 1 - CqrdlView Answer on Stackoverflow
Solution 2 - CAlnitakView Answer on Stackoverflow
Solution 3 - CZskdanView Answer on Stackoverflow
Solution 4 - CCalmariusView Answer on Stackoverflow
Solution 5 - Ceaanon01View Answer on Stackoverflow
Solution 6 - CgivanseView Answer on Stackoverflow
Solution 7 - Cmh.View Answer on Stackoverflow
Solution 8 - CWindChaserView Answer on Stackoverflow
Solution 9 - CJim BuckView Answer on Stackoverflow
Solution 10 - CThe GrammView Answer on Stackoverflow
Solution 11 - CRock DengView Answer on Stackoverflow
Solution 12 - CsblundyView Answer on Stackoverflow
Solution 13 - CyogmanView Answer on Stackoverflow