6

I m constructing a C++ program in which I need to handle SIGSEGV and Signal handler should be able to print the Back Trace. Can any one help in this.

Regards

Ravi Varshney
  • 61
  • 1
  • 2

3 Answers3

6

The best way to get a SIGSEV backtrace is generating a core file more than printing a backtrace. Take care beacause if you handle SIGSEV the system will not call the default core generator.

If you want to handle the SIGSEV anyway (as have been commented before this is system deppendant), see the libc backtrace function [http://www.gnu.org/s/libc/manual/html_node/Backtraces.html ] , it could be useful.

2

Adding to what Jon replied, you basically need a function like this to print backtrace. This function shoudl be called on the SIGSEGV. But I second Jon's point that letting the system generate corefile would be a much better debugging mechanism for you

void print_trace(int nSig)
{
  printf("print_trace: got signal %d\n", nSig);

  void           *array[32];    /* Array to store backtrace symbols */
  size_t          size;     /* To store the exact no of values stored */
  char          **strings;    /* To store functions from the backtrace list in ARRAY */
  size_t          nCnt;

  size = backtrace(array, 32);

  strings = backtrace_symbols(array, size);

  /* prints each string of function names of trace*/
  for (nCnt = 0; nCnt < size; nCnt++)
    fprintf(stderr, "%s\n", strings[nCnt]);


  exit(-1);
}
rajeshnair
  • 1,587
  • 16
  • 32
  • Thanx for replies guys... I used the same technique but it is not printing function name.. What can be the possible reasons. Even it is not printing for the sample code given in following link: http://www.gnu.org/s/libc/manual/html_node/Backtraces.html – Ravi Varshney May 18 '10 at 07:50
  • Please ensure the app is compiled using -g option. This is required to generate the symbols. – rajeshnair Jun 09 '10 at 09:07
  • 1
    not a good idea to call backtrace_symbols because it calles malloc(). – mishmashru May 21 '13 at 20:14
  • It is flat wrong to call async-signal unsafe functions, like `backtrace()`, `backtrace_symbols()`, `printf`-family, in the signal handler. Deadlock might happen. – Leedehai Oct 10 '18 at 16:35
  • As I have mentioned in the answer, this is not recommended. I would edit to answer , should not be used in production. But this function has helped me a lot in test time. – rajeshnair Oct 10 '18 at 17:32
1

Take a look at the sample code here:

C++ Code Snippet - Print Stack Backtrace Programmatically with Demangled Function Names.

You may need to demangle the symbols, that's what the code sample does.

And try two more options:

  • -fno-omit-frame-pointer
  • -rdynamic

The first option keeps frame pointer in generated code thus all the backtrace frames are accessible to the code. The 2nd keeps symbol information in the linked binary. That works on my arm9 build, and no -g is needed.

minghua
  • 5,981
  • 6
  • 45
  • 71