Printing a stack trace from a signal handler

I need to print a stack trace from a 64-bit mutli-threaded C ++ handler, an application running on Linux. Although I found some sample code, none of them compile. My blocking point gets the caller (the point where the signal was generated) the address from the ucontext_t structure. All the information I could find points to the EIP register as ucontext.gregs [REG_EIP] or ucontext.eip. Both appear to be x86-specific. I need 64-bit compatible code for Intel and AMD processors. Can anyone help?

+6
source share
2 answers

there is a glibc backtrace function. An example call is shown on the manual page:

#define SIZE 100 void myfunc3(void) { int j, nptrs; void *buffer[100]; char **strings; nptrs = backtrace(buffer, SIZE); printf("backtrace() returned %d addresses\n", nptrs); /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO) would produce similar output to the following: */ strings = backtrace_symbols(buffer, nptrs); if (strings == NULL) { perror("backtrace_symbols"); exit(EXIT_FAILURE); } for (j = 0; j < nptrs; j++) printf("%s\n", strings[j]); free(strings); } 

See the man page for more context.

itโ€™s hard to determine if this really works from a signal handler, since posix lists only a few return functions that are guaranteed to work. Remember: a signal handler can be called while the rest of your process is right in the middle of a malloc call.

I suppose this usually works, but it may fail from time to time. This may be enough for debugging.

+4
source

The usual way to get the stack trace is to take the address of a local variable, then add some magic number to it, depending on how the compiler generates the code (which may depend on the optimization parameters used to compile the code), and work from there. Everything is very system dependent, but doable if you know what you are doing.

If this works in a signal handler, this is another question. I donโ€™t know about the platform you are describing, but many systems set up a separate stack for signal handlers, without reference to the interrupted stack in user-accessible memory.

+1
source

Source: https://habr.com/ru/post/908019/


All Articles