Sanitizer 工具使用方法

Sanitizer 工具使用方法

Sanitizer 是一类由编译器插桩实现的运行时错误检测工具,被 GCC 等编译器广泛支持。在编译阶段向程序中自动插入检查代码,并在运行时结合对应的运行时库,实时监控内存访问、未定义行为和线程同步等操作。

常见的 Sanitizer 包括:

  • ASan(AddressSanitizer):检测堆/栈越界、释放后使用、双重释放等内存错误
  • UBSan(UndefinedBehaviorSanitizer):检测整数溢出、空指针解引用、无效移位等未定义行为
  • TSan(ThreadSanitizer):检测多线程数据竞争和死锁

编译工程修改

ASan & UBSan

编译选项:

-fsanitize=address,undefined -fsanitize-recover=all -O0 -fno-omit-frame-pointer -fno-optimize-sibling-calls

链接选项:

  • 静态链接:
-fsanitize=address,undefined -static-libasan -static-libubsan
  • 动态链接:
-fsanitize=address,undefined

TSan

编译选项:

-fsanitize=thread -O0 -fno-omit-frame-pointer -fno-optimize-sibling-calls

链接选项:

  • 静态链接:
-fsanitize=thread -static-libtsan
  • 动态链接:
-fsanitize=thread

运行环境变量设置

ASan & UBSan

setenv ASAN_OPTIONS 'halt_on_error=0 detect_leaks=1 malloc_context_size=15 alloc_dealloc_mismatch=0 new_delete_type_mismatch=0 check_initialization_order=1 detect_stack_use_after_return=1 detect_stack_use_after_scope=0 log_path=/xx/xxx/asan.log'
setenv UBSAN_OPTIONS 'halt_on_error=0 print_stacktrace=1 report_error_type=1 log_path=/xx/xxx/ubsan.log'

TSan

setenv TSAN_OPTIONS log_path=/xx/xxx/tsan.log
posted @ 2026-09-29 10:06  CJXUNOO  阅读(4)  评论(0)    收藏  举报