IT技术博客大学习 共学习 共进步

善用backtrace解决大问题

PHPor 的blog 2011-09-21 13:38:36 累计浏览 2,663 次
本机暂存
一.用途:
主要用于程序异常退出时寻找错误原因
二.功能:
回溯堆栈,简单的说就是可以列出当前函数调用关系
三.原理:
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[i]);
  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

建议继续学习

  1. Java程序员应该知道的10个eclipse调试技巧 (累计阅读 7,901)
  2. 使用gdb调试运行时的程序小技巧 (累计阅读 7,161)
  3. 程序员最怕的事 (累计阅读 6,863)
  4. 使用GDB调试多进程程序 (累计阅读 6,301)
  5. 一个程序员的血泪史 (累计阅读 6,181)
  6. 为什么C语言需要函数声明 (累计阅读 5,662)
  7. php调试利器之phpdbg (累计阅读 5,621)
  8. 程序员应该是什么样的 (累计阅读 5,028)
  9. overflow:hidden真的失效了吗 (累计阅读 4,940)
  10. 当程序出问题时程序员最喜欢说的20句话 (累计阅读 4,642)