善用backtrace解决大问题

一.用途:
主要用于程序异常退出时寻找错误原因
二.功能:
回溯堆栈,简单的说就是可以列出当前函数调用关系
三.原理:
1. 通过对当前堆栈的分析,找到其上层函数在栈中的帧地址,再分析上层函数的堆栈,再找再上层的帧地址……一直找到最顶层为止,帧地址指的是一块:在栈上存放局部变量,上层返回地址,及寄存器值的空间。
2.  由于不同处理器堆栈方式不同,此功能的具体实现是编译器的内建函数__buildin_frame_address及 __buildin_return_address中,它涉及工具glibc和gcc,  如果编译器不支持此函数,也可自己实现此函数,举例中有arm上的实现
四.方法:
在程序中加入backtrace及相关函数调用
五.举例:
1. 一般backtrace的实现
i. 程序

 
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <execinfo.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <string.h>
  9. #include <unistd.h>
  10. #define PRINT_DEBUG
  11. static void print_reason(int sig, siginfo_t * info, void *secret)
  12. {
  13. void *array[10];
  14. size_t size;
  15. #ifdef PRINT_DEBUG
  16. char **strings;
  17. size_t i;
  18. size = backtrace(array, 10);
  19. strings = backtrace_symbols(array, size);
  20. printf("Obtained %zd stack frames.\n", size);
  21. for (i = 0; i < size; i++)
  22. printf("%s\n", strings);
  23. free(strings);
  24. #else
  25. int fd = open("err.log", O_CREAT | O_WRONLY);
  26. size = backtrace(array, 10);
  27. backtrace_symbols_fd(array, size, fd);
  28. close(fd);
  29. #endif
  30. exit(0);
  31. }
  32. void die()
  33. {
  34. char *test1;
  35. char *test2;
  36. char *test3;
  37. char *test4 = NULL;
  38. strcpy(test4, "ab");
  39. }
  40. void test1()
  41. {
  42. die();
  43. }
  44. int main(int argc, char **argv)
  45. {
  46. struct sigaction myAction;
  47. myAction.sa_sigaction = print_reason;
  48. sigemptyset(&myAction.sa_mask);
  49. myAction.sa_flags = SA_RESTART | SA_SIGINFO;
  50. sigaction(SIGSEGV, &myAction, NULL);
  51. sigaction(SIGUSR1, &myAction, NULL);
  52. sigaction(SIGFPE, &myAction, NULL);
  53. sigaction(SIGILL, &myAction, NULL);
  54. sigaction(SIGBUS, &myAction, NULL);
  55. sigaction(SIGABRT, &myAction, NULL);
  56. sigaction(SIGSYS, &myAction, NULL);
  57. test1();
  58. }

ii. 编译参数
gcc main.c -o test -g -rdynamic

留下评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据