Printing stack trace from a signal handler

ぃ、小莉子 提交于 2019-11-30 14:10:56

there is a glibc function backtrace. The man page lists an example the the call:

#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 difficult to tell if this really is guaranteed to work from a signal handler, since posix lists only a few reentrant functions that are guaranteed to work. Remember: a signal handler may be called while the rest of your process is right in the middle of an malloc call.

My guess is, that this usually works, but it may fail from time to time. For debugging this may be good enough.

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

Whether this works in a signal handler is another question. I don't know about the platform you describe, but a lot of systems install a separate stack for the signal handlers, with no link back to the interrupted stack in user accessible memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!