AddressSanitizer初探


参考文档

简介

AddressSanitizer是一种快速内存错误检测器。它由一个编译器检测模块和一个运行时库组成。该工具可以检测以下类型的错误:

  • Out-of-bounds accesses to heap, stack and globals
  • Use-after-free
  • Use-after-return (runtime flag ASAN_OPTIONS=detect_stack_use_after_return=1)
  • Use-after-scope (clang flag -fsanitize-address-use-after-scope)
  • Double-free, invalid free
  • Memory leaks (experimental)

用法

Simply compile and link your program with -fsanitize=address flag. The AddressSanitizer run-time library should be linked to the final executable, so make sure to use clang (not ld) for the final link step. When linking shared libraries, the AddressSanitizer run-time is not linked, so -Wl,-z,defs may cause link errors (don’t use it with AddressSanitizer). To get a reasonable performance add -O1 or higher. To get nicer stack traces in error messages add -fno-omit-frame-pointer. To get perfect stack traces you may need to disable inlining (just use -O1) and tail call elimination (-fno-optimize-sibling-calls).

% cat example_UseAfterFree.cc
int main(int argc, char **argv) {
  int *array = new int[100];
  delete [] array;
  return array[argc];  // BOOM
}

# Compile and link
% clang++ -O1 -g -fsanitize=address -fno-omit-frame-pointer example_UseAfterFree.cc

局限性

  • 与本地运行相比,AddressSanitizer使用的实际内存更多。确切的开销取决于分配大小。您进行的分配越小,开销就越大。
  • AddressSanitizer使用更多的堆栈内存。我们看到增长了3倍。
  • 在64位平台上,AddressSanitizer映射(但不保留)16+ TB的虚拟地址空间。这意味着类似之类的工具ulimit可能无法正常使用。
  • 不支持可执行文件的静态链接。

文章作者: Mr.Pan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Mr.Pan !
  目录