asan 内存越界检查

介绍

AddressSanitizer (or ASan) is an open source programming tool by Google that detects memory corruption bugs such as buffer overflows or accesses to a dangling pointer (use-after-free). AddressSanitizer is based on compiler instrumentation and directly-mapped shadow memory. AddressSanitizer is currently implemented in Clang (starting from version 3.1) , GCC (starting from version 4.8) and Xcode (starting from version 7.0) . On average, the instrumentation increases processing time by about 73% and memory usage by 240%. – 摘自 wiki

wiki 里面讲的很详细,还包括了 example
下面主要是尝试使用的记录

安装

centos: sudo yum install libasan 或者 sudo yum install devtoolset-3-libasan-devel
或者: https://github.com/google/sanitizers 编译安装

使用

  • 编译参数: -fsanitize=address -fno-omit-frame-pointer -g
  • 连接参数:-lasan
  • 环境变量:export ASAN_OPTIONS=log_path=/home/jianglei/asan.log 指定输出错误日志文件路径
  • 测试代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>

    int main() {

    char* ptr = new char[10];
    memset(ptr, 0, 11);

    while (true) {
    sleep(1);
    }
    return 0;
    }

结果

  • libasan 会把程序在哪一行访问越界多少字节,越界的内存地址清楚的标记出来
  • libasan 会立即终止程序(不过一般内存都踩坏了,程序继续运行也可能会有更大的事故)
  • 开发期间尽量包在编译选项,并且指向到日志
  • 如果 gcc -O 的关系无法看到具体出错的地方,可以用 addr2line -e ./asan -f 0x4007d7 | c++filt 定位,
    具体参考 addr2line
------ 本文结束 ------
------ 版权声明:转载请注明出处 ------