@ 前记:
最近查一个线上项目的crash,review代码无果,crash几率低,不可在本地环境重现。之后在线上好几个服务器跑valgrind就不crash了。个人猜测可能是跑valgrind后性能下降的比较严重,导致crash那个点触发不到了。
gcc从4.8开始支持address sanitizer,也比较好用,文章最后会简单分析下用法。
另我的环境是ubuntu13.04+gcc4.7.3,目标是升级到4.9.0。
@ 编译gcc4.9.0
$wget ftp://mirrors.kernel.org/gnu/gcc/gcc-4.9.0/gcc-4.9.0.tar.gz
$tar zxvf gcc-4.9..tar.gz
$cd gcc-4.9.
$./contrib/download_prerequisites
$cd ..
$mkdir gcc-build-4.9.
$cd gcc-build-4.9.
$../gcc-4.9./configure --enable-checking=release --enable-languages=c,c++ --disable-multilib
$make -j4
$make install
$gcc -v
补充:我这边编译出来的lib都在路径/usr/local/lib64
@ 用法
#include <stdio.h> int main()
{
int *p = new int;
delete p;
*p = 10;
return 0;
}
这是个访问野指针的程序,但是用gcc编译(不管加不加-g)后运行却不会coredump。有了address sanitize,我们可以这样
$g++ test.cc -fsanitize=address -g
$export LD_LIBRARY_PATH=/usr/local/lib64/
$./a.out
我摘一部分运行信息贴出来
==25380==ERROR: AddressSanitizer: heap-use-after-free on address 0x60200000eff0 at pc 0x4007d1 bp 0x7ffffbe70890 sp 0x7ffffbe70888
WRITE of size 4 at 0x60200000eff0 thread T0
#0 0x4007d0 in main /home/parallels/sss/cc/test/test.cc:7
#1 0x7f6454635ea4 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21ea4)
#2 0x4006a8 (/home/parallels/sss/cc/test/a.out+0x4006a8) 0x60200000eff0 is located 0 bytes inside of 4-byte region [0x60200000eff0,0x60200000eff4)
freed by thread T0 here:
#0 0x7f645525a3e7 in operator delete(void*) ../../../../gcc-4.9.0/libsanitizer/asan/asan_new_delete.cc:81
#1 0x400799 in main /home/parallels/sss/cc/test/test.cc:6
#2 0x7f6454635ea4 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21ea4) previously allocated by thread T0 here:
#0 0x7f6455259f6f in operator new(unsigned long) ../../../../gcc-4.9.0/libsanitizer/asan/asan_new_delete.cc:50
#1 0x400789 in main /home/parallels/sss/cc/test/test.cc:5
#2 0x7f6454635ea4 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21ea4)
这信息够清楚了吧。
@ 后记
我暂时还没有测它对性能的影响,希望上线后能帮助定位到bug。
@ 补充
@ ubuntu 14.04LTS+gcc4.8.2,使用sanitize信息不全,定位不到具体行号,动态库好像还用不了
@ sanitize起作用后,貌似不会再有core产生。
@ 新机器需要先apt-get gcc g++ make