How to use asan in linux

1. 安装编译工具

ASan 是 GCC 和 Clang 内建的功能,无需额外安装 ASan,只需要你的编译器支持即可。GCC ≥ 4.8 / Clang ≥ 3.1 就支持 ASan

1
2
3
4
5
6
7
8
9
10
11
root@lavm-bar1guved6:~# clang --version
Ubuntu clang version 14.0.0-1ubuntu1.1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

root@lavm-bar1guved6:~# gcc --version
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

2. how to use

使用gcc

1
gcc -fsanitize=address -g your_file.c -o your_program

使用cmake

1
2
3
4
5
6
7
8
9
10
11
12
13
# 编译阶段(C/C++)加 ASan 插桩
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fno-omit-frame-pointer -g")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fno-omit-frame-pointer -g")

# 链接阶段链接 libasan
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address")

#or
cmake -DCMAKE_C_FLAGS="-fsanitize=address -fno-omit-frame-pointer -g" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address" \
-DCMAKE_BUILD_TYPE=Debug \
......

使用 Makefile

可以在 CFLAGS 中添加:

1
2
CFLAGS += -fsanitize=address -g -fno-omit-frame-pointer
LDFLAGS += -fsanitize=address

使用 LSAN(泄漏检测)

GCC 和 Clang 中 ASan 自动包含 LeakSanitizer(LSan),但某些情况下要确保:

1
-fsanitize=address -fno-omit-frame-pointer

加上 -fno-omit-frame-pointer 可以让调用栈更完整。

3. 运行程序

编译好的程序可以直接运行:

1
./your_program

4. 设置环境变量

1
export ASAN_OPTIONS=detect_leaks=1:halt_on_error=0:symbolize=1:quarantine_size=1024:log_path=/home/postgres/asan/asan.log

5. Example

1
2
3
4
5
6
7
8
9
=================================================================
==791265==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1024 byte(s) in 1 object(s) allocated from:
#0 0x7f6fcee65887 in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
#1 0x55adcdfee87a in main /home/postgres/codes/sample/epoll_server.c:54
#2 0x7f6fcebb1d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58

SUMMARY: AddressSanitizer: 1024 byte(s) leaked in 1 allocation(s).