Communitygithub.com

AddressSanitizer (ASan)

在模糊测试中检测 C/C++ 代码的内存错误,如缓冲区溢出和释放后使用。

AddressSanitizer (ASan) 是什么?

AddressSanitizer (ASan) 是一款广泛使用的内存错误检测工具,常用于软件测试,尤其是模糊测试。它通过编译时插桩来跟踪内存分配和访问,在运行时检测非法操作,能发现缓冲区溢出、释放后使用、双重释放和内存泄漏等内存损坏错误。ASan 在 Linux 上支持最佳,macOS 支持有限,Windows 仅为实验性支持。它通常与 libFuzzer、AFL++、cargo-fuzz 和 honggfuzz 等模糊测试工具集成,通过设置相应的编译标志和环境变量启用。ASan 的典型性能开销约为非插桩代码的 2-4 倍,需要约 20TB 虚拟内存,因此使用模糊测试工具时需禁用内存限制。用户可通过 ASAN_OPTIONS 环境变量精细控制其行为,如启用详细输出、禁用泄漏检测或强制异常中止。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/SamuelChien/mega-skills-collection/tree/HEAD/address-sanitizer

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

AddressSanitizer (ASan) 是做什么的?

AddressSanitizer (ASan) 是一款广泛采用的内存错误检测工具,常用于软件测试,尤其是模糊测试。它能帮助检测可能被忽略的内存损坏错误,例如缓冲区溢出、释放后使用以及其他内存安全违规问题。

概述

ASan 是模糊测试中的标准实践,因为它能有效识别内存漏洞。它在编译时对代码进行插桩,以跟踪内存分配和访问,并在运行时检测非法操作。

关键概念

概念描述
插桩ASan 在编译时为内存操作添加运行时检查
影子内存映射 20TB 虚拟内存以跟踪分配状态
性能开销相比非插桩代码大约慢 2-4 倍
检测范围发现缓冲区溢出、释放后使用、双重释放和内存泄漏

何时应用

在以下情况下应用此技术:

  • 对 C/C++ 代码进行模糊测试以查找内存安全漏洞
  • 测试包含 unsafe 块的 Rust 代码
  • 调试与内存损坏相关的崩溃
  • 运行怀疑存在内存错误的单元测试

在以下情况下跳过此技术:

  • 运行生产代码(ASan 可能降低安全性)
  • 平台是 Windows 或 macOS(ASan 支持有限)
  • 性能开销对您的用例不可接受
  • 对没有 FFI 的纯安全语言进行模糊测试(例如纯 Go、纯 Java)

快速参考

任务命令/模式
启用 ASan(Clang/GCC)-fsanitize=address
启用详细输出ASAN_OPTIONS=verbosity=1
禁用泄漏检测ASAN_OPTIONS=detect_leaks=0
出错时强制中止ASAN_OPTIONS=abort_on_error=1
多个选项ASAN_OPTIONS=verbosity=1:abort_on_error=1

分步指南

步骤 1:使用 ASan 编译

使用 -fsanitize=address 标志编译和链接代码:

clang -fsanitize=address -g -o my_program my_program.c

建议使用 -g 标志,以便在 ASan 检测到错误时获得更好的堆栈跟踪。

步骤 2:配置 ASan 选项

设置 ASAN_OPTIONS 环境变量以配置 ASan 行为:

export ASAN_OPTIONS=verbosity=1:abort_on_error=1:detect_leaks=0

步骤 3:运行程序

执行经过 ASan 插桩的二进制文件。检测到内存错误时,ASan 会输出详细报告:

./my_program

步骤 4:调整模糊测试器的内存限制

ASan 需要大约 20TB 的虚拟内存。禁用模糊测试器的内存限制:

  • libFuzzer:-rss_limit_mb=0
  • AFL++:-m none

常见模式

模式:基本 ASan 集成

用例: 使用 ASan 的标准模糊测试设置

之前:

clang -o fuzz_target fuzz_target.c
./fuzz_target

之后:

clang -fsanitize=address -g -o fuzz_target fuzz_target.c
ASAN_OPTIONS=verbosity=1:abort_on_error=1 ./fuzz_target

模式:ASan 与单元测试

用例: 为单元测试套件启用 ASan

之前:

gcc -o test_suite test_suite.c -lcheck
./test_suite

之后:

gcc -fsanitize=address -g -o test_suite test_suite.c -lcheck
ASAN_OPTIONS=detect_leaks=1 ./test_suite

高级用法

提示与技巧

提示为何有用
使用 -g 标志提供详细的堆栈跟踪以便调试
设置 verbosity=1确认 ASan 在程序启动前已启用
在模糊测试期间禁用泄漏检测泄漏检测不会导致立即崩溃,但会干扰输出
启用 abort_on_error=1某些模糊测试器需要 abort() 而不是 _exit()

理解 ASan 报告

当 ASan 检测到内存错误时,它会输出一份详细报告,包括:

  • 错误类型:缓冲区溢出、释放后使用等
  • 堆栈跟踪:错误发生的位置
  • 分配/释放跟踪:内存分配和释放的位置
  • 内存映射:错误附近的影子内存状态

ASan 报告示例:

==12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000eff4 at pc 0x00000048e6a3
READ of size 4 at 0x60300000eff4 thread T0
    #0 0x48e6a2 in main /path/to/file.c:42

组合使用消毒剂

ASan 可以与其他消毒剂组合使用,实现全面检测:

clang -fsanitize=address,undefined -g -o fuzz_target fuzz_target.c

平台特定注意事项

Linux:完全支持 ASan,性能最佳 macOS:支持有限,某些功能可能无法使用 Windows:实验性支持,不推荐用于生产环境的模糊测试

反模式

反模式问题正确做法
在生产环境中使用 ASan可能降低应用程序安全性仅在测试中使用 ASan
不禁用内存限制模糊测试器可能因 20TB 虚拟内存而终止进程设置 -rss_limit_mb=0 或 -m none
忽略泄漏报告内存泄漏表明资源管理问题在模糊测试活动结束时审查泄漏报告

工具特定指导

libFuzzer

同时使用模糊测试器和地址消毒剂编译:

clang++ -fsanitize=fuzzer,address -g harness.cc -o fuzz

使用无限 RSS 运行:

./fuzz -rss_limit_mb=0

集成提示:

  • 始终将 -fsanitize=fuzzer 与 -fsanitize=address 结合使用
  • 使用 -g 获取崩溃报告中的详细堆栈跟踪
  • 考虑使用 ASAN_OPTIONS=abort_on_error=1 以便更好地处理崩溃

参见:libFuzzer: AddressSanitizer

AFL++

使用 AFL_USE_ASAN 环境变量:

AFL_USE_ASAN=1 afl-clang-fast++ -g harness.cc -o fuzz

使用无限内存运行:

afl-fuzz -m none -i input_dir -o output_dir ./fuzz

集成提示:

  • AFL_USE_ASAN=1 会自动添加正确的编译标志
  • 使用 -m none 禁用 AFL++ 的内存限制
  • 对于具有大覆盖率映射的程序,考虑使用 AFL_MAP_SIZE

参见:AFL++: AddressSanitizer

cargo-fuzz (Rust)

使用 --sanitizer=address 标志:

cargo fuzz run fuzz_target --sanitizer=address

或者在 fuzz/Cargo.toml 中配置:

[profile.release]
opt-level = 3
debug = true

集成提示:

  • ASan 对模糊测试不安全的 Rust 代码或 FFI 边界很有用
  • 安全的 Rust 代码可能受益不大(编译器已防止许多错误)
  • 重点关注 unsafe 块、裸指针和 C 库绑定

参见:cargo-fuzz: AddressSanitizer

honggfuzz

使用 ASan 编译并与 honggfuzz 链接:

honggfuzz -i input_dir -o output_dir -- ./fuzz_target_asan

编译目标:

hfuzz-clang -fsanitize=address -g target.c -o fuzz_target_asan

集成提示:

  • honggfuzz 开箱即可与 ASan 良好配合
  • 使用反馈驱动模式,结合消毒剂获得更好的覆盖率
  • 监控内存使用情况,因为 ASan 会增加内存占用

故障排除

问题原因解决方案
模糊测试器立即终止进程内存限制过低,无法满足 ASan 的 20TB 虚拟内存要求使用 -rss_limit_mb=0(libFuzzer)或 -m none(AFL++)
“ASan runtime not initialized”链接顺序错误或缺少运行时库确保在编译和链接时都使用 -fsanitize=address
泄漏报告干扰输出LeakSanitizer 默认启用设置 ASAN_OPTIONS=detect_leaks=0
性能不佳(>4 倍减速)调试模式或非优化构建与 -fsanitize=address 一起使用 -O2 或 -O3
ASan 未检测到明显错误二进制文件未插桩使用 ASAN_OPTIONS=verbosity=1 检查 ASan 是否输出启动信息
误报拦截器冲突查看 ASan FAQ 了解与特定库的已知问题

相关技能

使用此技术的工具

技能如何应用
libfuzzer使用 -fsanitize=fuzzer,address 编译,实现集成模糊测试与内存错误检测
aflpp在编译期间使用 AFL_USE_ASAN=1 环境变量
cargo-fuzz使用 --sanitizer=address 标志为 Rust 模糊测试目标启用 ASan
honggfuzz使用 -fsanitize=address 编译目标,进行 ASan 插桩的模糊测试

相关技术

技能关系
未定义行为消毒剂常与 ASan 一起使用,实现全面错误检测(未定义行为 + 内存错误)
模糊测试用例编写测试用例必须设计为处理 ASan 检测到的崩溃,并避免误报
覆盖率分析覆盖率引导的模糊测试有助于触发代码路径,使 ASan 能够检测内存错误

资源

关键外部资源

AddressSanitizer on Google Sanitizers Wiki

官方 ASan 文档涵盖:

  • 算法和实现细节
  • 检测到的错误类型完整列表
  • 性能特征和开销
  • 平台特定行为
  • 已知限制和不兼容性

SanitizerCommonFlags

所有消毒剂共享的通用配置标志:

  • verbosity:控制诊断输出级别
  • log_path:将消毒剂输出重定向到文件
  • symbolize:启用/禁用报告中的符号解析
  • external_symbolizer_path:使用自定义符号解析器

AddressSanitizerFlags

ASan 特定配置选项:

  • detect_leaks:控制内存泄漏检测
  • abort_on_error:出错时调用 abort() 与 _exit()
  • detect_stack_use_after_return:检测栈上释放后使用错误
  • check_initialization_order:查找初始化顺序错误

AddressSanitizer FAQ

常见陷阱和解决方案:

  • 链接顺序问题
  • 与其他工具的冲突
  • 平台特定问题
  • 性能调优提示

Clang AddressSanitizer Documentation

Clang 特定指南:

  • 编译标志和选项
  • 与其他 Clang 功能的交互
  • 支持的平台和架构

GCC Instrumentation Options

GCC 特定 ASan 文档:

  • GCC 特定标志和行为
  • 与 Clang 实现的差异
  • GCC 中的平台支持

AddressSanitizer: A Fast Address Sanity Checker (USENIX Paper)

包含技术细节的原始研究论文:

  • 影子内存算法
  • 虚拟内存需求(历史上为 16TB,现在约 20TB)
  • 性能基准
  • 设计决策和权衡

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

SamuelChien/mega-skills-collection

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

SamuelChien/mega-skills-collection

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

SamuelChien/mega-skills-collection

Ingeniero de Sistemas de Andru.ia. Diseña, redacta y despliega nuevas habilidades (skills) dentro del repositorio siguiendo el Estándar de Diamante.

SamuelChien/mega-skills-collection

Estratega de Inteligencia de Dominio de Andru.ia. Analiza el nicho específico de un proyecto para inyectar conocimientos, regulaciones y estándares únicos del sector. Actívalo tras definir el nicho.

SamuelChien/mega-skills-collection

2D game development principles. Sprites, tilemaps, physics, camera.

SamuelChien/mega-skills-collection

3D game development principles. Rendering, shaders, physics, cameras.

SamuelChien/mega-skills-collection

Expert in building 3D experiences for the web - Three.js, React Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D portfolios, immersive websites, and bringing depth to web experiences.

SamuelChien/mega-skills-collection

Accessibility audit skill for scanning, fixing, and verifying WCAG 2.2 Level A and AA compliance across React, Next.js, Vue, Angular, Svelte, and plain HTML codebases. Use when auditing accessibility, fixing a11y violations, checking color contrast, generating compliance reports, or integrating accessibility checks into CI/CD pipelines.

SamuelChien/mega-skills-collection

Ab Test Analyzer - Auto-activating skill for Data Analytics. Triggers on: ab test analyzer, ab test analyzer Part of the Data Analytics skill category.

SamuelChien/mega-skills-collection

A B Test Config Creator - Auto-activating skill for ML Deployment. Triggers on: a b test config creator, a b test config creator Part of the ML Deployment skill category.

SamuelChien/mega-skills-collection

When the user wants to plan, design, or implement an A/B test or experiment. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "conversion experiment," "statistical significance," or "test this." For tracking implementation, see analytics-tracking.

SamuelChien/mega-skills-collection

Acceptance Criteria Creator - Auto-activating skill for Enterprise Workflows. Triggers on: acceptance criteria creator, acceptance criteria creator Part of the Enterprise Workflows skill category.

SamuelChien/mega-skills-collection

Use when a coding task should be driven end-to-end from issue intake through implementation, review, deployment, and acceptance verification with minimal human re-intervention.

SamuelChien/mega-skills-collection

Accessibility Audit Runner - Auto-activating skill for Frontend Development. Triggers on: accessibility audit runner, accessibility audit runner Part of the Frontend Development skill category.

SamuelChien/mega-skills-collection

You are an accessibility expert specializing in WCAG compliance, inclusive design, and assistive technology compatibility. Conduct audits, identify barriers, and provide remediation guidance.

SamuelChien/mega-skills-collection

Web accessibility patterns for WCAG 2.2 compliance including ARIA, keyboard navigation, screen readers, and testing

SamuelChien/mega-skills-collection

Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed, or change policy for the Discord channel.

SamuelChien/mega-skills-collection

Create unified specification packages across Business, Development, and Design teams. Staged elaboration (L0 Vision → L1 Requirements → L2 Team Detail → L3 Acceptance Criteria) to build shared understanding. Does not write code.

SamuelChien/mega-skills-collection

Research a company or person and get actionable sales intel. Works standalone with web search, supercharged when you connect enrichment tools or your CRM. Trigger with "research [company]", "look up [person]", "intel on [prospect]", "who is [name] at [company]", or "tell me about [company]".

SamuelChien/mega-skills-collection

Validate messaging consistency across website, GitHub repos, and local documentation generating read-only discrepancy reports. Use when checking content alignment or finding mixed messaging. Trigger with phrases like "check consistency", "validate documentation", or "audit messaging".

相关技能