Sanitizers
compiler-rt carries the sanitizers' runtimes for each target, and the targets with ASan an ASan build of libc++ (the ASan libc++), which ASan programs link. MemorySanitizer comes with the runtimes from source. libFuzzer is there for the glibc Linux, macOS and x64 MSVC targets.
| target | ASan | LSan | TSan | UBSan | MSan |
|---|---|---|---|---|---|
x86_64-unknown-linux-gnu | yes | yes | yes | yes | with the runtimes from source |
aarch64-unknown-linux-gnu | yes | yes | yes | yes | with the runtimes from source |
x86_64-w64-mingw32 | yes | yes | |||
aarch64-w64-mingw32 | yes | ||||
aarch64-apple-darwin | yes | yes | yes | yes | |
x86_64-apple-darwin | yes | yes | yes | yes | |
x86_64-unknown-linux-musl | yes | ||||
aarch64-unknown-linux-musl | yes | ||||
x86_64-pc-windows-msvc | yes | yes | |||
aarch64-pc-windows-msvc | yes |
How each family differs: MinGW Targets, MSVC Targets, musl Targets, MemorySanitizer.
Usage
The examples are in examples/sanitizers. The CMake and plain clang++ commands below run in that directory inside pixi shell after pixi install, on a Linux or macOS host.
overflow.cpp reads past the end of a std::string, within its allocated capacity:
#include <cstdio>
#include <string>
int main(int argc, char**) {
std::string s(40, 'x');
s.reserve(100);
// Past size(), within capacity(): only an instrumented libc++ annotates it.
volatile char c = s.data()[40 + argc];
(void)c;
std::puts("no report");
}race.cpp has a data race between two threads:
#include <chrono>
#include <thread>
int shared;
int main() {
std::thread t([] { shared++; });
// The thread's write first, then the main thread's, which races with
// it: in this order TSan reports the race every time.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
shared++;
t.join();
}fuzz.cpp is a libFuzzer target:
#include <cstddef>
#include <cstdint>
#include <fuzzer/FuzzedDataProvider.h>
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
FuzzedDataProvider input(data, size);
if (input.ConsumeIntegral<char>() == 'x') {
volatile int sum = input.ConsumeIntegral<int>();
(void)sum;
}
return 0;
}CMake
With xclang's toolchain file (--toolchain $XCLANG/lib/cmake/xclang/toolchain.cmake), pass -DXCLANG_SANITIZER=address, thread, undefined or leak (or memory with -DXCLANG_RUNTIMES=source; see MemorySanitizer). XCLANG_SANITIZER adds the corresponding -fsanitize= flag to every compile and link in the build, and for address automatically switches to the prebuilt ASan libc++ (or builds an instrumented libc++ when XCLANG_RUNTIMES=source is set).
Without the toolchain file, pass -fsanitize=address and the ASan libc++ flags in CMAKE_CXX_FLAGS and CMAKE_EXE_LINKER_FLAGS, where asan=$(dirname "$(clang++ -print-library-module-manifest-path)")/asan (Plain Clang):
cmake_minimum_required(VERSION 3.28)
project(sanitizers LANGUAGES CXX)
add_executable(overflow overflow.cpp)cmake -G Ninja -B build-asan -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
"-DCMAKE_CXX_FLAGS=-fsanitize=address -isystem $asan/include" \
"-DCMAKE_EXE_LINKER_FLAGS=-fsanitize=address -nostdlib++ $asan/libc++.a"
cmake --build build-asan./build-asan/overflow reports the container-overflow. Because xclang::std is compiled with CMAKE_CXX_FLAGS, a project that uses import std compiles the std module with matching sanitizer flags (C++20 modules).
Bazel
Enable a sanitizer across the whole build with --features=asan, --features=tsan, --features=ubsan or --features=lsan:
load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
cc_binary(
name = "overflow",
srcs = ["overflow.cpp"],
)
cc_binary(
name = "race",
srcs = ["race.cpp"],
)MODULE.bazel and .bazelrc
module(name = "sanitizers")
bazel_dep(name = "rules_cc", version = "0.2.25")
bazel_dep(name = "xclang", version = "23.1.3.4")common --registry=https://bazel.clice.io/
common --registry=https://bcr.bazel.build/
# The C++ toolchain is xclang's; rules_cc's detection of another is off.
common --repo_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1bazel run -c dbg --features=asan //:overflow
bazel run -c dbg --features=tsan //:raceThe first command reports the container-overflow and the second the data race; both exit with the sanitizer's non-zero exit code.
--features=asancompiles and links every C++ target against the ASanlibc++.- Requesting a sanitizer that the target platform does not support stops the build immediately at analysis time with an error naming the target and sanitizer.
- On
x86_64Windows targets,--features=asancopies the ASan runtime DLL beside every binary inbazel-binand in its runfiles sobazel runandbazel testcan start it (MinGW Targets). - Adding
--@xclang//runtimes:sourcecompileslibc++,libc++abiandlibunwindfrom source with the build's sanitizer features, and enables--features=msanon the glibc Linux targets (MemorySanitizer, runtimes from source).
Plain Clang
On Linux, macOS and MinGW targets, the ASan libc++ sits in the asan directory next to libc++.modules.json (usr/lib/asan in the sysroot on Linux, lib/asan on macOS and MinGW):
asan=$(dirname "$(clang++ -print-library-module-manifest-path)")/asan
clang++ -fsanitize=address -g -O1 overflow.cpp -o overflow-plain
clang++ -fsanitize=address -isystem "$asan/include" -nostdlib++ "$asan/libc++.a" -g -O1 overflow.cpp -o overflow
clang++ -fsanitize=thread -g -O1 race.cpp -o race
clang++ -fsanitize=fuzzer -g -O1 fuzz.cpp -o fuzz| command | prints | exit code |
|---|---|---|
./overflow-plain | no report | 0 |
./overflow | ERROR: AddressSanitizer: container-overflow in main, overflow.cpp:8 | 1 |
./race | WARNING: ThreadSanitizer: data race | 66 |
./fuzz -runs=1000 | Done 1000 runs | 0 |
overflow-plain links the normal libc++, which does not annotate the std::string buffer, so ASan does not detect the out-of-bounds read. On macOS, a sanitizer report aborts the process, so the shell reports exit code 134.
Options
| Plain Clang | CMake (toolchain file) | Bazel | |
|---|---|---|---|
| AddressSanitizer | -fsanitize=address + ASan libc++ | -DXCLANG_SANITIZER=address | --features=asan |
| ThreadSanitizer | -fsanitize=thread | -DXCLANG_SANITIZER=thread | --features=tsan |
| UBSan | -fsanitize=undefined | -DXCLANG_SANITIZER=undefined | --features=ubsan |
| LeakSanitizer | -fsanitize=leak | -DXCLANG_SANITIZER=leak | --features=lsan |
| libFuzzer | -fsanitize=fuzzer | -fsanitize=fuzzer in compile/link flags | |
| MemorySanitizer | -DXCLANG_RUNTIMES=source -DXCLANG_SANITIZER=memory | --@xclang//runtimes:source --features=msan | |
ASan libc++ flags | compile: -isystem $asan/include; link: -nostdlib++ $asan/libc++.a (MSVC: compile flag only) | included in XCLANG_SANITIZER=address | included in --features=asan |
Full option lists are in the CMake API and the Bazel API.
Behavior
- Every C++ library in an ASan program must use the ASan
libc++:libc++annotates its containers (std::vector,std::string) so ASan knows which portion of the allocated buffer is withinsize()and reports accesses betweensize()andcapacity()ascontainer-overflow. Mixing code built against the ASanlibc++and the uninstrumentedlibc++produces falsecontainer-overflowreports (below). - Other sanitizers use the normal
libc++: TSan, UBSan and LSan builds link the standard prebuiltlibc++unless runtimes from source are requested. - Dynamic sanitizer runtimes on macOS and Windows: on macOS, sanitizer runtimes are
.dylibfiles such aslibclang_rt.asan_osx_dynamic.dylib, loaded from the toolchain's resource directory or the binary's directory. On Windows, thex86_64ASan runtime is a DLL. Because sanitizer builds are used for testing rather than shipping, loading these dynamic runtimes is an exception to hermeticity. In Bazel on macOS hosts, the sanitizer features add the toolchain's resource directory as anrpath; binaries cross-compiled on Linux or Windows look for the.dylibin their own directory. - ASan build of
libclang: for Linuxx86_64and macOSarm64hosts, xclang provides an ASan-instrumented build oflibclangcompiled against the ASanlibc++(libclang). - No ASan build of the platform's C++ library: with
XCLANG_STDLIB=platform,XCLANG_SANITIZER=addresslinks no ASan C++ library, and on the MSVC targets the STL's containers under ASan needstl_asan.lib, whichxclang sdk fetch windowsdoes not fetch.
Why an ASan libc++
Container annotations are written by whichever copy of a container method runs, and checked on every element access. When a program compiled with -fsanitize=address links an uninstrumented libc++.a, two versions of the same container methods exist in the binary: inline functions in the program are compiled with ASan and update container annotations, while functions and template instantiations compiled into libc++.a are not.
When the linker keeps one copy of a template instantiated in both places, and picks the uninstrumented one from libc++.a, vector growth no longer updates the ASan shadow memory and later reads report a false container-overflow. That is what catter's macOS tests hit, with std::vector<std::string_view>::push_back inside std::filesystem::relative.
xclang therefore ships an ASan-instrumented libc++ alongside the normal one. It consists of a libc++.a (or libc++asan-x86_64.lib on MSVC) compiled with -fsanitize=address and a __config_site header that defines _LIBCPP_INSTRUMENTED_WITH_ASAN, which also turns on container annotations for std::string. Compiling with -isystem $asan/include and linking the ASan libc++ instruments the program and the standard library identically.
MinGW Targets
The MinGW targets carry UBSan on x86_64 and aarch64 and ASan with the ASan libc++ on x86_64, matching what compiler-rt and llvm-mingw support on Windows. clang selects the runtime libraries from lib/clang/<major>/lib/<arch>-w64-windows-gnu when -fsanitize= is passed.
- ASan's runtime is a DLL: Windows has no static ASan runtime, so ASan programs link
libclang_rt.asan_dynamic.dll.aand loadlibclang_rt.asan_dynamic.dllat startup from their own directory orPATH. On thex86_64Windows host, a copy of the DLL sits in the toolchain'sbin/directory, whichpixiorcondaactivation places onPATH; on other machines, copy the DLL next to the.exe. In Bazel,--features=asanplaces the DLL beside every binary inbazel-binand in its runfiles. Unlikellvm-mingw's ASan DLL, xclang linkslibc++andlibunwindinto the DLL statically so it depends only on Windows system DLLs and UCRT. - The ASan
libc++is inx86_64-w64-mingw32/lib/asan($asanbelow): pass-isystem $asan/includewhen compiling and-nostdlib++ $asan/libc++.awhen linking, or use CMake's-DXCLANG_SANITIZER=addressor Bazel's--features=asan. - Native
x86_64Windows only: anx86_64ASan program must run onx86_64Windows; underarm64Windows'x86_64emulator, ASan cannot intercept the C runtime's functions. - Unsupported sanitizers:
compiler-rthas no TSan, LeakSanitizer, MemorySanitizer or libFuzzer for MinGW, and no ASan foraarch64Windows. CMake and Bazel reject those sanitizers for MinGW targets.
ubsan.cpp, in examples/sanitizers, triggers a signed integer overflow:
#include <climits>
#include <cstdio>
int main(int argc, char**) {
int n = INT_MAX;
// A signed overflow: UBSan reports it, and the program goes on.
n += argc;
std::printf("%d\n", n);
}Cross-compile both examples from any host:
asan=$(dirname "$(clang++ --target=x86_64-w64-mingw32 -print-library-module-manifest-path)")/asan
clang++ --target=x86_64-w64-mingw32 -fsanitize=address -isystem "$asan/include" -nostdlib++ "$asan/libc++.a" \
-g -O1 overflow.cpp -o overflow.exe
clang++ --target=aarch64-w64-mingw32 -fsanitize=undefined -O1 ubsan.cpp -o ubsan.exeOn an x86_64 Windows machine with libclang_rt.asan_dynamic.dll beside it or on PATH, overflow.exe reports the container-overflow. On arm64 Windows, ubsan.exe reports runtime error: signed integer overflow and prints -2147483648.
With Bazel on an x86_64 Windows host, --features=asan places the DLL beside the executable and runs it:
bazel run -c dbg --features=asan //:overflowIt reports the container-overflow and exits with code 1.
MSVC Targets
The MSVC targets carry UBSan on x86_64 and aarch64, and ASan and libFuzzer on x86_64. clang selects their libraries from lib/clang/<major>/lib/windows when -fsanitize= is passed.
- The
x86_64ASanlibc++islib/clang/<major>/lib/windows/libc++asan-x86_64.lib, with its__config_sitein$XCLANG/x86_64-pc-windows-msvc/lib/asan/include. Pass-isystem $XCLANG/x86_64-pc-windows-msvc/lib/asan/includewhen compiling: its__config_siteembeds#pragma comment(lib, "libc++asan-x86_64.lib")in every object file in place oflibc++-x86_64.lib, so the link step needs no extra library flag and works with the hybrid CRT,/MDand the static CRT alike. CMake's-DXCLANG_SANITIZER=addressand Bazel's--features=asanpass this include path automatically. - ASan's runtime is a DLL,
clang_rt.asan_dynamic-x86_64.dll, even when linking the static CRT. Thex86_64Windows host toolchain includes a copy inbin/; on other machines, copy it beside the executable (Bazel's--features=asancopies it automatically). Becausecompiler-rtlinks this DLL against the dynamic VC runtime, it loadsvcruntime140.dllat run time. - Not compatible with
-stdlib=platformcontainers: when compiling against Microsoft's STL (-stdlib=platform), STL containers under ASan referencestl_asan.lib, whichxclang sdk fetch windowsdoes not fetch. - No
aarch64ASan or libFuzzer: LLVM 23 does not support ASan or libFuzzer onarm64Windows.
With the Windows SDK fetched, cross-compile from any host using ubsan.cpp from MinGW Targets:
clang++ --target=x86_64-pc-windows-msvc -fsanitize=address -isystem "$XCLANG/x86_64-pc-windows-msvc/lib/asan/include" \
-g -O1 overflow.cpp -o overflow.exe
clang++ --target=aarch64-pc-windows-msvc -fsanitize=undefined -O1 ubsan.cpp -o ubsan.exeWith clang_rt.asan_dynamic-x86_64.dll beside it, overflow.exe reports the container-overflow; ubsan.exe reports runtime error: signed integer overflow and prints -2147483648.
musl Targets
The musl targets link statically, and only UBSan works in a statically linked executable: its standalone runtime (-fsanitize=undefined, -DXCLANG_SANITIZER=undefined in CMake, --features=ubsan in Bazel), its minimal runtime (-fsanitize-minimal-runtime), or trapping mode (-fsanitize-trap=undefined).
ASan, TSan and LSan intercept C library functions and look up the underlying symbols via dlsym, which a static musl binary does not have; linking their runtimes into a static binary fails with undefined hidden symbol: _DYNAMIC, and libFuzzer fails at its first sigaction call. Those runtimes are therefore not built for musl. Build for the glibc target of the same architecture to run ASan, TSan, LSan or libFuzzer; a dynamically linked musl target variant for them is considered.
clang++ --target=x86_64-unknown-linux-musl -fsanitize=undefined -O1 ubsan.cpp -o ubsanubsan is a static executable that runs on any Linux x86_64 machine.
MemorySanitizer
MemorySanitizer (MSan) requires every library in the program, including libc++ and libc++abi, to be compiled with -fsanitize=memory, along with compiler-rt's MSan runtime. Because prebuilt archives do not include an MSan-instrumented libc++ or MSan runtime, xclang builds both on demand on the glibc Linux targets (x86_64 and aarch64) when runtimes from source are enabled:
- CMake: pass
-DXCLANG_RUNTIMES=source -DXCLANG_SANITIZER=memorywith the toolchain file. - Bazel: pass
--@xclang//runtimes:source --features=msan.
Enabling runtimes from source with TSan or ASan also compiles libc++ and libc++abi from source with that sanitizer's instrumentation.
