Function caller in linux kernel

17,234

Solution 1

You can get the caller with __builtin_return_address(0).

The caller's caller is __builtin_return_address(1) and so on.

It's a GCC extension, documented in the gcc manual: http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html

Edit: I should probably point out, that gets you the address of the caller. If you want the function name you can print it with %pS, eg:

printk("Caller is %pS\n", __builtin_return_address(0));

If you don't want to print it, you can use kallsyms_lookup() etc.

Solution 2

You can also print the entire call stack contents by calling dump_stack().

Solution 3

Whether or not frame pointers are needed depends on arch, IIRC. For x86, they are certainly desired to fully exploit these features. Also note that inlining can skew the accuracy of builtin_return_address for this very reason.

If you just want a stack dump to see how some place was reached, better use the dump_stack() function than trying to fiddle around with builtin_return_address.

Share:
17,234
BHS
Author by

BHS

Yocto, Ubuntu expert; Linux Kernel developer

Updated on June 12, 2022

Comments

  • BHS
    BHS almost 2 years

    Is there a way to get function caller in linux kernel? I know __func__ returns the function name which is executing. I am looking for the function which called "__func__"

  • Eric Seppanen
    Eric Seppanen over 13 years
    That's some impressive jujitsu.
  • Jiang
    Jiang over 11 years
    btw: when using __builtin_return_address(0), you cannot replace 0 with a variable such as int i; otherwise, you will get some compiling error. Also, be careful when tracing back too much, such as __builtin_return_address(10). If the call stack is not as deep as 10, the kernel will happily crash.
  • Alok Prasad
    Alok Prasad almost 3 years
    %pF is deprecated and %ps and %pS is preferred way