This blog is under construction

Saturday, 2 February 2013

backtrace_symbols example in C


Header file:
    execinfo.h

Synopsis:
     char ** backtrace_symbols(void *const *buffer, int size);

Description:
     backtrace() function gives us set of backtrace symbols(set of addresses).  And those address can be translated to an array of strings using backtrace_symbols.  Argument buffer indicates the set of address(backtrace symbols) from backtrace() and size indicates the number of entries in the array.  And the return value of this function is the memory(pointer to a memory location) obtained via malloc and its user's responsibility to free the dynamically allocated block.


backtrace_symbols function C example


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

  void func5() {
        void *array[12];
        int size, i;
        char **str;
        size = backtrace(array, 12);  // gets backtrace symbols in array
        printf("Backtrace:\n");
        for (i = 0; i < size; i++) {
                printf("0x%08x\n", (int)array[i]);
        }

        printf("\nBacktrace symbols:\n");
        str = backtrace_symbols(array, size);  // address to string conversion

        for (i = 0; i < size; i++)
                printf("%s\n", str[i]);
        printf("No of level in backtrace:%d\n", size);
        free(str);
  }

  void func4() {
        func5();
  }

  void func3() {
        func4();
  }

  void func2() {
        func3();
  }

  void func1() {
        func2();
  }


  int main() {
        func1();
        return 0;
  }



  Output:
  jp@jp-VirtualBox:$ gcc -rdynamic backtrace_symbols.c 
  jp@jp-VirtualBox:$ ./a.out
  Backtrace:
  0x080486dd
  0x08048785
  0x08048792
  0x0804879f
  0x080487ac
  0x080487b9
  0x00126ce7
  0x08048631

  Backtrace symbols:
  ./a.out(func5+0x19) [0x80486dd]
  ./a.out(func4+0xb) [0x8048785]
  ./a.out(func3+0xb) [0x8048792]
  ./a.out(func2+0xb) [0x804879f]
  ./a.out(func1+0xb) [0x80487ac]
  ./a.out(main+0xb) [0x80487b9]
  /lib/libc.so.6(__libc_start_main+0xe7) [0x126ce7]
  ./a.out() [0x8048631]
  No of level in backtrace:8

Note:
why rdynamic option?
Eg: gcc -rdynamic backtrace_symbols.c
rdynamic is the linker option that makes the function names available to the program. Basically, it instructs the linker to add all the symbols to the dynamic symbol table.


No comments:

Post a Comment