AddressSanitizer (ASan) 使用示例

AddressSanitizer (ASan) 使用示例

环境信息

项目状态
系统Ubuntu 20.04 x86_64
GCC9.4.0
libasanlibasan.so.5 ✅
项目front6.3 / sipgate.exe

一、启用 ASan

编辑 /home/w/c/6.3/front6.3/CMakeLists.txt,找到第 29-30 行,解注释以下两行:

add_compile_options(-fsanitize=address -fno-omit-frame-pointer -fno-common)
add_link_options(-fsanitize=address)

⚠️ 使用完毕后记得重新注释这两行,ASan 会使程序性能下降约 2-3 倍,不适用于生产环境。


二、重新编译

cd /home/w/c/6.3/front6.3/build
cmake ..       # 必须重新 cmake,使新编译选项生效
make -j11

三、运行并收集报告

方式 1:输出到文件(推荐)

报告写入 /home/logs/asan/asan_report.<pid>,程序崩溃后不丢失。

mkdir -p /home/logs/asan
ASAN_OPTIONS="log_path=/home/logs/asan/asan_report:halt_on_error=0:detect_stack_use_after_return=1:detect_leaks=0" \
./sipgate.exe -m cfgfile

方式 2:stderr 重定向

./sipgate.exe -m cfgfile 2>/home/logs/asan/asan_report.log

方式 3:同时输出到控制台和文件

./sipgate.exe -m cfgfile 2>&1 | tee /home/logs/asan/asan_report.log

四、常用 ASAN_OPTIONS 选项

选项说明
log_path=<路径前缀>报告写入 <路径前缀>.<pid> 文件
halt_on_error=0检测到错误后继续运行,可收集更多问题(默认=1立即中止)
halt_on_error=1检测到第一个错误立即终止,适合定位单一问题
detect_stack_use_after_return=1检测栈变量 use-after-return(默认关闭)
detect_leaks=0关闭内存泄漏检测,聚焦堆损坏问题
detect_leaks=1开启内存泄漏检测
print_stats=1程序退出时打印内存使用统计
verbosity=1输出更详细的 ASan 运行信息
abort_on_error=1错误时产生 core dump(结合 gdb 分析)

多个选项用 : 分隔:

ASAN_OPTIONS="log_path=/home/logs/asan/report:halt_on_error=0:detect_leaks=0:detect_stack_use_after_return=1"

五、报告解读

ASan 报告结构如下,可以精确定位首次非法内存操作的位置

==<pid>==ERROR: AddressSanitizer: heap-use-after-free on address 0x...
<错误类型>: READ/WRITE of size N at 0x... thread T3

// 出错时的调用栈(定位使用者)
    #0 0x... in xxx::xxx() File.cpp:50
    #1 0x... in yyy::yyy() File.cpp:30

// 该内存被释放时的调用栈(定位释放者)
freed by thread T1 here:
    #0 0x... in operator delete
    #1 0x... in moduleend JtGbModuleFactory.cpp:67

// 该内存最初被分配时的调用栈
allocated by thread T0 here:
    #0 0x... in operator new
    #1 0x... in GbsPlatform::CreateGetPlatformChnStreamCfgTask GbsPlatform.cpp:86

常见错误类型:

错误类型含义
heap-use-after-free使用已释放的堆内存(最常见)
heap-buffer-overflow堆缓冲区越界写
stack-use-after-return使用已返回函数的栈变量
double-free对同一内存 delete 两次
use-after-poison使用已被标记为不可访问的内存

六、当前项目疑似崩溃位置(供参考)

  • 崩溃信号SIGABRTmalloc_printerr_int_free 触发(堆元数据损坏)
  • 崩溃栈switch_callbackdelete this~lambda(urll)_int_free
  • 疑似根因moduleenddelete subctx 过早执行,或并发 HTTP 请求下 ctx 生命周期管理问题
  • 相关文件
    • gbs/JtGbModuleFactory.cppCreateJtHttpTask lambda 及 moduleend
    • gbs/platform/GbsPlatform.cppCreateGetPlatformChnStreamCfgTask
    • workflow-0.11.7/src/factory/WFTaskFactory.inlswitch_callback / done

ASan 预期会在以下位置报告 heap-use-after-free

gbs/JtGbModuleFactory.cpp:67  (delete subctx)  ← 释放点
gbs/platform/GbsPlatform.cpp:104               ← 或后续访问点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值