Address Sanitizer


AddressSanitizer (aka ASan) is a memory error detector for C/C++. It finds:
  • Use after free (dangling pointer dereference)
  • Heap buffer overflow
  • Stack buffer overflow
  • Global buffer overflow
  • Use after return
  • Use after scope
  • Initialization order bugs
  • Memory leaks

The tool consists of a compiler instrumentation module (currently, an LLVM pass) and a run-time library which replaces the malloc function.


Clang(發音為/ˈklæŋ/類似英文單字clang[1]) 是一個C、C++、Objective-C和Objective-C++程式語言的編譯器前端。它採用了LLVM作為其後端,而且由LLVM2.6開始,一起釋出新版本。它的目標是提供一個GNU編譯器套裝(GCC)的替代品,支援了GNU編譯器大多數的編譯設定以及非官方語言的擴充功能。

AddressSanitizer is a part of LLVM starting with version 3.1 and a part of GCC starting with version 4.8.

For gcc or clang, the newer version the better, build with the following options to enable address/leak sanitizer.
  • linux build, it does not work on mac osx
  • 
    -ggdb -fsanitize=address -fno-omit-frame-pointer -static-libstdc++ -static-libasan -lrt
    -ggdb -fsanitize=leak -fno-omit-frame-pointer -static-libstdc++ -static-liblsan -lrt
    
    
  • mac osx build option
  • 
    -ggdb -fsanitize=address -fno-omit-frame-pointer -static-libstdc++ -static-libgcc 
    -ggdb -fsanitize=leak -fno-omit-frame-pointer -static-libstdc++ -static-libgcc 
    
Example,

#include 
#include 

int main() {
  char *x = (char*)malloc(10 * sizeof(char*));
  x[10] = 10;
  printf("%d\n", x[100]);
  free(x);
}

Build then get the run-time error:

~$ gcc -ggdb -fsanitize=address -fno-omit-frame-pointer -static-libstdc++ -static-libasan -lrt test.c
~$ ./a.out
=================================================================
==4157==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x607000000084 at pc 0x5622ddc0af4e bp 0x7fffe2216180 sp 0x7fffe2216170
...


留言

熱門文章