segmentation|segmentation fault分析方法

相信写c/c++程序的coder, segmentation fault的问题碰到不少,趁最近有时间总结一下分析此类错误的方法。
1. 段错误是什么 一句话来说,段错误是指访问的内存超出了系统给这个程序所设定的内存空间,例如访问了不存在的内存地址、访问了系统保护的内存地址、访问了只读的内存地址等等情况。这里贴一个对于“段错误”的准确定义(https://en.wikipedia.org/wiki/Segmentation_fault):

In computing, a segmentation fault (often shortened to segfault) or access violation is a fault, or failure condition, raised by hardware with memory protection, notifying an operating system (OS) the software has attempted to access a restricted area of memory (a memory access violation). On standard x86 computers, this is a form of general protection fault. The OS kernel will, in response, usually perform some corrective action, generally passing the fault on to the offending process by sending the process a signal. Processes can in some cases install a custom signal handler, allowing them to recover on their own,[1] but otherwise the OS default signal handler is used, generally causing abnormal termination of the process (a program crash), and sometimes a core dump.
2. 段错误产生的原因
  • 访问不存在的内存地址
  • 访问系统保护的内存地址
  • 访问只读的内存地址
  • 栈溢出
3. 分析段错误的方法 Item 1: log大法 最简单粗暴的方法,也确实很有效,但有时log也看不出什么。
为了方便使用这种方法,可以使用条件编译指令#ifdef DEBUG和#endif把printf函数包起来。这样在程序编译时,如果加上-DDEBUG参数就能查看调试信息;否则不加该参数就不会显示调试信息。
Item 2: 自定义segv handler和添加backtrace()
  • 示例代码
#include #include #include #include #include #include int *result = 0; void add(int a, int b) { *result = a + b; }void subtract(int a, int b) { *result = a - b; }void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); }int main() { signal(SIGSEGV, handler); // install our handlerint ret; int pagesize; // 获取操作系统一个页的大小, 一般是 4KB == 4096 pagesize = sysconf(_SC_PAGE_SIZE); printf("pagesize is: %d Byte\n", pagesize); if (pagesize == -1) { perror("sysconf"); return -1; }// 按页对齐来申请一页内存, result会是一个可以被页(0x1000 == 4096)整除的地址 ret = posix_memalign((void**)&result, pagesize, pagesize); printf("posix_memalign mem %p\n", result); if (ret != 0) { // posix_memalign 返回失败不会设置系统的errno, 不能用perror输出错误 printf("posix_memalign fail, ret %u\n", ret); return -1; }add(1, 1); // 结果写入 *result printf("the result is %d\n", *result); // 保护result指向的内存, 权限设为只读 ret = mprotect(result, pagesize, PROT_READ); if (ret == -1) { perror("mprotect"); return -1; }subtract(1, 1); // 结果写入 *result, 但是 *result 只读, 引发segment fault printf("the result is %d\n", *result); free(result); return 0; }

  • 编译,需加-g选项
g++ -g-o mproject_test mproject_test.cc

  • 运行命令
./mproject_test 2>&1 |cut -d '[' -f 2|grep -o '0x[0-9a-z].*' | xargs addr2line -Cfe mproject_test

运行结果
handler(int) ??:0 ?? ??:0 subtract(int, int) ??:0 main ??:0 ?? ??:0 _start ??:0 ?? ??:0

可以看到在函数subtract出崩溃了。
由于捕获了segv信号,所以不会产生core文件,也不会有dmesg记录,其中addr2line可以将出错的地址转换为对应的函数和代码地址(在ubuntu上始终没看到代码的行数,在centos上可以)。
Item 3: dmesg + objdump 注释掉C代码中的signal(SIGSEGV, handler); ,程序中则不会处理SIGSEGV信号,执行时会在dmesg中留下记录,此时可以用objdump -d解析出汇编代码,找到发生crash时的地址(注意不要用-O优化,否则编译器优化了汇编)。
  • dmesg查看段错误信息
dmesg | tail [257215.924911] e1000: eth0 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: RX [257526.392613] e1000: eth0 NIC Link is Down [257528.397505] e1000: eth0 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: RX [257669.623324] mproject_test[29542]: segfault at 180c000 ip 000000000040083c sp 00007fffcb1018e0 error 7 in mproject_test[400000+1000]

出错的地址是000000000040083c
  • 使用objdump反汇编
objdump -d mproject_test > mproject_test.dump

  • 在反汇编文件中分析
$ vi mproject_test.dump 0000000000400825 <_Z8subtractii>: 400825:55push%rbp 400826:48 89 e5mov%rsp,%rbp 400829:89 7d fcmov%edi,-0x4(%rbp) 40082c:89 75 f8mov%esi,-0x8(%rbp) 40082f:48 8b 05 42 08 20 00mov0x200842(%rip),%rax# 601078 400836:8b 55 fcmov-0x4(%rbp),%edx 400839:2b 55 f8sub-0x8(%rbp),%edx 40083f:c3retq

可以看到出错的地方在subtract函数
Item4: 使用catchsegv catchsegv命令专门用来扑获段错误,它通过动态加载器(ld-linux.so)的预加载机制(PRELOAD)把一个事先写好的库(/lib/libSegFault.so)加载上,用于捕捉断错误的出错信息。
$ catchsegv ./mproject_testBacktrace: ??:0(_Z8subtractii)[0x40083c] ??:0(main)[0x4009ab] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7ff4721747ed] ??:0(_start)[0x400719]

Item 5: gdb + core 【segmentation|segmentation fault分析方法】这种方式也很常用,找到发生segv或异常的地方,然后bt,就能发现引起crash的codepath。这种方法需要core文件足够大,在这里就不说了
参考文献
  • https://www.cnblogs.com/panfeng412/category/367117.html
  • https://zhuanlan.zhihu.com/p/37571803

    推荐阅读