Application examples of BackTrace () series functions in Linux

Source: Internet
Author: User
Tags signal handler

First, Introductionthe BackTrace () series function can be used to output a function call relationship when a code error occurs.

A BackTrace is the series of currently active function calls for the program.

#include <execinfo.h>int backtrace (void **buffer, int size), char **backtrace_symbols (void *const *buffer, int size ) void backtrace_symbols_fd (void *const *buffer, int size, int fd);

Second, example:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> #include < sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <strings.h> #include <string.h > #include <errno.h> #include <signal.h> #include <sys/ioctl.h> #include <execinfo.h> # Define SIZE (+) static sigset_t signals_handled;static void Dbg_backtrace (void) {int I, nline;void *buffer[size];char * * Strings;nline = backtrace (buffer, SIZE);p rintf ("addr:%d = backtrace () \ n", nline); strings = Backtrace_symbols (buffer, nline); if (NULL = = strings) {perror ("backtrace_symbols () \ n"); exit (exit_failure);} for (i = 0; i < nline; i + +) {printf ("Callback:%s\n", Strings[j]);} /* Backtrace_symbols () Internal call malloc function */free (strings);} static void Sig_handler_hup (int sig) {printf ("%s ()%d\n\n", __func__, SIG);} static void Sig_handler_debug (int sig) {printf ("%s ()%d\n\n", __func__, SIG);} static void sig_handler_usr2 (int sig) {printf ("%s ()%d\n\n", __func__, SIG);} static void Sig_handler_fatal (int sig) {printf ("Fatal signal%d\n\n", SIG);d Bg_backtrace (); exit (127);} void Signals_setup (void) {struct sigaction sa;sigemptyset (&signals_handled); Sigaddset (&signals_handled, SIGHUP); Sigaddset (&signals_handled, SIGINT); Sigaddset (&signals_handled, SIGTERM); Sigaddset (&signals_ Handled, SIGUSR2); #define SIGNAL (S, handler) do {Sa.sa_handler = Handler;if (Sigaction (S, &sa, NULL) < 0) printf ("C Ould not set signal handler (%d):%m ", s); } while (0); sa.sa_mask = Signals_handled;sa.sa_flags = 0; SIGNAL (SIGHUP, sig_handler_hup); SIGNAL (SIGUSR1, sig_handler_debug); SIGNAL (SIGUSR2, SIG_HANDLER_USR2); SIGNAL (SIGABRT, sig_handler_fatal); SIGNAL (SIGALRM, sig_handler_fatal); SIGNAL (SIGFPE, sig_handler_fatal); SIGNAL (Sigill, sig_handler_fatal); SIGNAL (Sigpipe, sig_handler_fatal); SIGNAL (Sigquit, sig_handler_fatal); SIGNAL (SIGSEGV, sig_handler_fatal); SIGNAL (Sigpipe, sig_ign);} void Mem_err (void) {char *prt = null;printf ("%s () \ n", __func__); *prt = ' 1 ';} Int Main (int argc, char **argv) {signals_setup (); int i = 0;for (;;) {i ++;if (i >) {Mem_err ();} printf ("I:%d\n", i); sleep (2);} return 0;}

Operation Result:
Mem_err ()Fatal Signal
addr:7 = BackTrace ()callback:./sig_setup () [0x804867b]callback:./sig_setup () [0x8048791]callback: [0xb77af400]callback:./sig_setup () [0x8048ae7]callback:./sig_setup () [0x8048b13]callback:/lib/i386-linux-gnu/i686/cmov/libc.so.6 (__libc_start_main+0xe6) [0xb764ce66]callback:./sig_setup () [0x8048591]
three, BackTrace () series function meaning:
int backtrace (void **buffer, int size);
BackTrace () returns the BackTrace information for the program call, with the result (that is, address from the corresponding stack frame) stored in the array that the buffer pointer points to. The size parameter specifies the maximum number of results that can be saved by the array to which buffer points, and if the number of results is greater than size, the array will hold those recently executed function calls.
The return value represents the number of actual elements in the array that buffer points to.
Char **backtrace_symbols (void *const *buffer, int size);
BackTrace () returns an array in which the result is the address value, and backtrace_symbols () translates the addresses into corresponding strings.
each element (string) contains the function name corresponding to the address value (which does not exist if it cannot be obtained), the offset address of the internal statement relative to the function (hexadecimal), and the actual address of the statement (hexadecimal). such as:./prog (MYFUNC3+0X5C) [0x80487f0]The Backtrace_symbols () function has a malloc operation inside, so the caller must have free memory.
operation execution failure returns NULL.
void backtrace_symbols_fd (void *const *buffer, int size, int fd);
function is the same as the Backtrace_symbols () function, except that it writes the returned results by line to the file of the FD representative. There is no malloc operation inside the BACKTRACE_SYMBOLS_FD function!
Iv. Analysis of the results:Perform disassembly first: objdump-d Test > Dump.txt
Callback:./sig_setup () [0x804867b]:0804865c <dbg_backtrace>: 804865c:55 push%ebp 804865d:89 e5 MOV%esp,%ebp 804865f:81 EC B8 (XX) sub $0x1b8,%esp 8048665:c7-XX movl $0x64 , 0x4 (%ESP) 804866c:00 804866d:8d 5c FE FF FF LEA-0X1A4 (%EBP),%eax 8048673:89, mov%eax, (%es P) 8048676:e8 e5 fe ff FF call 8048560 <[email protected]> 804867b:89 F0 mov%eax,-0x Ten (%EBP) callback:./sig_setup () [0x8048791]08048773 <sig_handler_fatal>: 8048773:55 push%EBP 80 48774:89 e5 mov%esp,%ebp 8048776:83 EC (sub $0x18,%esp 8048779:8b) mo V 0x8 (%EBP),%eax 804877c:89, mov%eax,0x4 (%ESP) 8048780:c7 8c movl $0x8048c15, (%es p) 8048787:e8-FD FF FF call 80484a0 <[email protected]> 804878C:E8 CB FE FF FF call 804865c <dbg_backtrace> 8048791:c7 7f xx movl $0x7f, (%ESP) callback:./sig_setup () [0x8048ae7]08048ac3 <mem_err>: 8048ac3:55 Push%ebp 8048ac4:89 e5 mov%esp,%ebp 8048ac6:83 EC Sub $0x28,%esp 804 8ac9:c7 f4 xx movl $0x0,-0xc (%EBP) 8048ad0:c7 5b 8c Movl $0x8048c5b,0x4 (%ESP) 8048ad7:08 8048 Ad8:c7 4e 8c movl $0x8048c4e, (%esp) 8048adf:e8 BC F9 FF FF call 80484a0 &LT;[EMAIL&NBSP;PROTECTED]&G T 8048ae4:8b f4 mov-0xc (%EBP),%eax 8048ae7:c6 xx movb $0x31, (%EAX)
At this point, the function calls here, resulting in illegal memory operations.
Five, BackTrace () series function considerations:These three functions assume that the return address of a function is stored on the stack in the way it thinks it should, so be aware of it when used:
1, the frame pointer (frame pointers) shielding/ignoring may cause the above hypothesis to fail2. The function described by the inline keyword does not have a stack frame (stack frames)3, Tail call (Tail-call) optimization causes one stack frame to be replaced by another4, for a specific compiler, you should specify the link option, otherwise the function name field may be invalid; For systems using the GNU linker, use the-rdynamic link item5. The function described by the static keyword is not displayed, and won ' t is available in the BackTrace
PS:stack frame (stack frames):in the computer science, a stack frame was a memory management strategy used to create and destroy temporary (auto Matic) variables in some programming languages. Stack frames only exist at run-time.in computer science, stack frames are a memory management strategy that is used in some programming languages to create/destroy temporary (automatic) variables. Stack frames exist only at run time. tail Call (Tail-call):in computer science, a tail call was a subroutine call performed as the final action of a procedure. in computer science, a tail call refers to the case where the last action in a function is a function call: that is, the return value of the call is directly returned by the current function.
References:frame pointer (frame pointers): Http://stackoverflow.com/questions/579262/what-is-the-purpose-of-the-frame-pointerhttp://blog.chinaunix.net/uid-25871104-id-2938389.htmlstack frame (stack frames): Http://en.citizendium.org/wiki/Stack_frametail Call (Tail-call): Http://en.wikipedia.org/wiki/Tail_call

Application examples of BackTrace () series functions in Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.