There are four ways to get the function call stack for Linux, see called Stack TRACE GENERATION.
Here is a brief list of the four scenarios mentioned in this article:
Method 1 gcc built-in function __builtin_return_address
Method 2 BackTrace function in glibc
Method 3 The enhanced BackTrace implemented by Jeff Muizelaar , in addition to the function name, can also get the code line number
Method 4 Libunwind
This method 2 and Method 4 have tried, Method 2 of the BackTrace function is to read the operating system of a global information area, in multi-threaded concurrent calls, will cause serious lock conflict.
The Libunwind of Method 4 also has a large overhead problem.
Finally, the following scenario is used:
#define Stackcall __attribute__ ((Regparm (1), noinline)) void * * Stackcall getebp (void) {void **ebp=null;__asm__ __volatile__ (" mov%%rbp,%0;\n\t ":" =m "(EBP)/* Output */:/* Input */:" Memory "); /* Non-affected register */return (void * *) (*EBP);} int my_backtrace (void **buffer,int size) {int frame=0;void * * ebp;void **ret=null;unsigned Long Long func_frame_distance= 0;if (buffer!=null && size >0) {ebp=getebp (); func_frame_distance= (unsigned long Long) (*EBP)-(unsigned long Long) Ebp;while (ebp&& frame<size&& (func_frame_distance< (1ull<<24))//assume function EBP more than 16m&& (func_frame_distance>0)) {ret=ebp+1;buffer[frame++]=*ret;ebp= (void**) (*EBP); func_ frame_distance= (unsigned long) (*EBP)-(unsigned long long) EBP;}} return frame;}
My_backtrace returns the same content as the glibc backtrace, you can get a readable call stack using the method in the call address of the dynamic link library using BackTrace .
Limitations:
If the source code compiles with the-o1 or-O2 optimization option, the executable code uses the EBP/RBP/RSP register as a normal register, resulting in backtrace failure. To prevent this from happening, you can use -o2-fno-omit-frame-pointer or -og at compile time to avoid using the above registers in optimizations.
The realization of my_backtrace in this paper is mainly attributed to Wangpeng students.
Reference documents
Http://blog.chinaunix.net/uid-24774106-id-3457205.html
Http://www.linuxidc.com/Linux/2011-08/41641.htm
Efficient method for obtaining/backtrace of Linux function call stacks