Programming Search⌘K

Conceptcore

AddressSanitizer

Also called ASan, address sanitizer, -fsanitize=address.

AddressSanitizer (ASan) is a compiler instrumentation that stops a C or C++ program at an out-of-bounds access or a use of freed memory. It marks bad bytes in shadow memory.

Applies to
core-languages

Idea

C and C++ do not check memory accesses. A read past the end of an array, a write through a pointer to freed memory and a write past the end of a stack buffer are undefined behavior. The program does not have to fail. It often prints the right answer in a test and corrupts memory in production. These errors are Out-of-bounds write, Out-of-bounds read and Use after free, and they cause many security holes.

AddressSanitizer (ASan) turns these silent errors into loud ones. The compiler adds a check before each load and store. The check asks one question: may the program touch this byte now? If the answer is no, ASan stops the program and prints a report with the kind of error, the address, the stack of the bad access and the stacks where the memory was allocated and freed.1

The program below writes one byte past the end of a heap buffer. Without ASan, it usually prints alice. With -fsanitize=address, it stops in strcpy with a heap-buffer-overflow report.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char *name = "alice";
    char *copy = malloc(strlen(name)); // no room for the '\0'
    if (copy == NULL) {
        return 1;
    }
    strcpy(copy, name);
    printf("%s\n", copy);
    free(copy);
}

ASan is a test tool. A team builds its tests, its fuzzers and its debug builds with it, and ships a build without it. It finds errors only on the paths that a test runs, so it works together with Unit testing and Fuzz testing.

How it works

ASan has two parts. A compiler pass adds the checks to the code. A run-time library replaces malloc and free, keeps the shadow memory and prints the reports.1

Shadow memory

Allocators return blocks aligned to at least 8 bytes. So each aligned group of 8 bytes, a granule, is in one of 9 states: the first k bytes are addressable and the other 8 − k are not, for k from 0 to 8. One byte can encode this state. ASan keeps one shadow byte for each 8 bytes of application memory, so the shadow uses one eighth of the address space. The address of the shadow byte is a shift and an add:1

shadow address = (address >> 3) + Offset

shadow value    meaning for the 8 bytes of the granule
0               all 8 bytes are addressable
1 to 7          only the first k bytes are addressable
negative        no byte is addressable; the value tells the kind:
                heap redzone, stack redzone, global redzone, freed memory

On 64-bit Linux the paper uses an offset of 2⁴⁴. The offset is fixed for each platform, so the check needs no table lookup.1

The check

For an 8-byte access, the compiler inserts a load of the shadow byte and a test for zero. For a 1-, 2- or 4-byte access, it also compares the position inside the granule with k:1

shadow = *((address >> 3) + Offset)
if (shadow != 0 && (address & 7) + size > shadow)
    report the error and stop

Each access in the original code gets exactly one extra memory read. The pass runs at the end of the LLVM optimization pipeline, so it checks only the accesses that the optimizer keeps.1

Redzones

A check needs poisoned bytes next to each object. These bytes are the redzones.

  • Heap. The run-time library replaces malloc. Blocks of one size class sit in a row, with a redzone between each pair, so n blocks need n + 1 redzones. The left redzone also holds the allocation size, the thread id and the stack of the malloc call. The paper gives a minimum heap redzone of 32 bytes.1
  • Stack. The compiler puts a 32-byte redzone, plus up to 31 bytes for alignment, around each local array in the frame, and poisons it when the function starts.1
  • Globals. The compiler adds redzones after global variables, and the run-time library poisons them at start-up.1

The C example asks the run-time library about each byte near a 13-byte block. The left redzone is poisoned. Bytes 13 to 15 are poisoned through the partial value of the second granule, and the right redzone follows.

buf-2 buf-1 | buf+0 ... buf+12 | buf+13 ... buf+17
  1     1   |   0   ...   0    |   1    ...   1      (1 = poisoned)

Quarantine

free poisons the whole block and puts it in a quarantine, a FIFO queue of freed memory. A later malloc does not get the block until it leaves the queue. A use through a dangling pointer then hits poisoned memory and ASan reports a heap-use-after-free, with the stacks of the allocation, the free and the use.1

What it finds and what it misses

Clang lists these errors: out-of-bounds accesses to the heap, the stack and globals, use after free, use after return, use after scope, double free, invalid free, and memory leaks.2 The paper says that ASan has no false positives: the reports that the authors judged undesirable during development were all fixed.1

ASan misses some errors by design:1

  • An unaligned access that is partly out of bounds, for example a 4-byte write at offset 6 of an 8-byte block.
  • An access far past the end of an object, which jumps over the redzone and lands in another valid block. The paper's example is a[500] for a 100-byte a.
  • A use after free when so much memory was freed in between that the block left the quarantine and was reused.

ASan checks only code that the compiler instrumented. A library built without ASan is not checked, although the replaced malloc and the intercepted functions such as strcpy still are. ASan also finds nothing on a path that the tests do not run.

In languages

LanguageVerdictNote
PythonDoes not applyThe interpreter checks every index and frees an object only when no reference to it is left, so Python code cannot reach memory outside an object. Alternative: Build CPython or a C extension with -fsanitize=address to check the C code under it.
C++Library
JavaDoes not applyThe JVM checks every array access and collects garbage, so Java code cannot overflow a buffer or use freed memory. Alternative: JNI code in C or C++ is built with ASan.
CLibrary
C#Does not applyThe runtime checks array and span accesses and collects garbage; only unsafe code with pointers can go out of bounds. Alternative: Native libraries that C# calls through P/Invoke are built with ASan.
JavaScriptDoes not applyThe engine checks every index into a typed array and collects garbage, so script cannot reach freed memory or memory outside a buffer. Alternative: Native addons in C or C++ are built and tested with ASan.
TypeScriptDoes not applyTypeScript runs on a JavaScript engine, which checks bounds and collects garbage.
GoDoes not applyGo checks every index and slice expression and collects garbage. Alternative: Go build -asan links Go code with C code built with ASan through cgo, on linux/arm64, linux/amd64 and linux/loong64 only.
RustLibrary
KotlinDoes not applyOn the JVM, every array access is checked and memory is collected, as in Java; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query does not address memory.
BashDoes not applyBash has no pointers and no manual memory management.
PowerShellDoes not applyPowerShell objects are .NET objects, which are bounds-checked and collected.
HTMLDoes not applyMarkup does not address memory.
CSSDoes not applyStyle rules do not address memory.
Regular expressionsDoes not applyA pattern does not address memory.

The example files show heap and stack overflows in C and C++, and the checks that Rust makes without a sanitizer. The table gives the verdict for each tier 1 language.

Language Verdict Form
C library -fsanitize=address in Clang and GCC, /fsanitize=address in MSVC
C++ library as C; containers can annotate their buffers
Rust library -Zsanitizer=address on a nightly compiler, for unsafe code and foreign code
Go n/a Go code is checked; go build -asan checks C code linked through cgo, on Linux only
Python n/a the interpreter checks each access; ASan is for C extensions and for CPython itself
Java n/a the JVM checks array bounds and collects garbage
C# n/a the runtime checks bounds and collects garbage
JavaScript n/a the engine checks bounds and collects garbage
TypeScript n/a as JavaScript
Kotlin n/a the JVM checks array bounds and collects garbage
PowerShell n/a .NET checks bounds and collects garbage
Bash n/a no pointers and no manual memory
SQL, Regex, HTML, CSS n/a no memory access in the language

Clang and GCC both take -fsanitize=address.23 MSVC takes /fsanitize=address for x86 and x64 targets on Windows.4 The Clang documentation asks for -O1 or higher and -fno-omit-frame-pointer for better stack traces.2 By default, ASan stops at the first error.2

Rust has the flag -Zsanitizer=address. It is unstable, so it needs a nightly compiler, and the documentation recommends a rebuild of the standard library with -Zbuild-std.9 Safe Rust checks indices and rejects dangling references at compile time, so ASan in Rust is for unsafe blocks and for the C and C++ code that Rust calls.

The go command has -asan, which links Go code with C code built with ASan. It works only on linux/arm64, linux/amd64 and linux/loong64.10 Go code itself is bounds-checked and garbage-collected.

The languages with a garbage collector and checked indices do not have these errors in their own code. Their runtimes and native extensions are written in C or C++, and those are built and tested with ASan.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <print>
#include <vector>

int main() {
    std::vector<int> scores = {3, 1, 4};
    int total = 0;
    for (std::size_t i = 0; i <= scores.size(); i++) { // one past the end
        total += scores[i];
    }
    std::println("{}", total);
}

operator[] does not check the index. The vector holds exactly three elements on the heap, so scores[3] reads the right redzone of that block, and ASan reports a heap-buffer-overflow.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <print>
#include <string>
#include <string_view>

std::string greeting(const std::string &name) {
    return "hello, " + name + ", and welcome to the system";
}

int main() {
    std::string_view view = greeting("alice"); // the string dies here
    std::println("{}", view);
}

The temporary std::string is destroyed at the end of the full expression, and its heap buffer is freed. The view still points to it. ASan reports a heap-use-after-free, the error of Use after free. The text is longer than the small-string buffer of the library, so the characters are on the heap.

#include <print>
#include <stdexcept>
#include <string>
#include <vector>

std::string greeting(const std::string &name) {
    return "hello, " + name + ", and welcome to the system";
}

int main() {
    std::vector<int> scores = {3, 1, 4};
    try {
        std::println("{}", scores.at(3));
    } catch (const std::out_of_range &) {
        std::println("index 3 is out of range");
    }
    std::string text = greeting("alice"); // owns its characters
    std::println("{}", text);
}
Output
index 3 is out of range
hello, alice, and welcome to the system
  • Verdict: library. ASan is a part of Clang, GCC and MSVC (/fsanitize=address), not of the C++ language.
  • at checks the index and throws std::out_of_range. operator[], iterators and raw pointers do not check, so ASan is the check for them in a test build.
  • A view type such as std::string_view or std::span does not own its data. When the owner frees heap data, ASan finds the next use through the view, because the freed block stays poisoned in the quarantine.
  • A container library can call into the ASan runtime to mark the unused part of its buffer. ASan then reports a container-overflow for an access between size() and capacity(). The Clang documentation warns that this check can give false positives when only a part of the program is built with ASan.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Copies a name into a new buffer. The size forgets the terminating '\0'.
char *copy_name(const char *name) {
    char *copy = malloc(strlen(name));
    if (copy != NULL) {
        strcpy(copy, name); // writes one byte past the end
    }
    return copy;
}

int main(void) {
    char *name = copy_name("alice");
    if (name == NULL) {
        return 1;
    }
    printf("%s\n", name);
    free(name);
}

The buffer has 5 bytes, and strcpy writes 6. AddressSanitizer reports a heap-buffer-overflow in strcpy, called from copy_name. Without the sanitizer, the program usually prints alice, because the extra byte lands in padding that the allocator does not use.

#include <sanitizer/asan_interface.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char *buf = malloc(13);
    if (buf == NULL) {
        return 1;
    }
    // One digit for each byte from buf - 2 to buf + 17: 1 means poisoned.
    for (int i = -2; i < 18; i++) {
        printf("%d", __asan_address_is_poisoned(buf + i));
    }
    printf("\n");
    free(buf);
}
Output
11000000000000011111

The run asks the ASan runtime which bytes it treats as unaddressable. The two bytes before the block are the left redzone. The 13 bytes of the block are addressable. The bytes from buf + 13 on are poisoned: three bytes at the end of the second 8-byte granule, then the right redzone.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

int sum(const int *values, int count) {
    int total = 0;
    for (int i = 0; i <= count; i++) { // <= reads one element too many
        total += values[i];
    }
    return total;
}

int main(void) {
    int scores[4] = {3, 1, 4, 1};
    printf("%d\n", sum(scores, 4));
}

The compiler puts redzones around scores in the stack frame of main. The read of values[4] hits the right redzone, and ASan reports a stack-buffer-overflow.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Copies a name into a new buffer, with room for the terminating '\0'.
char *copy_name(const char *name) {
    size_t size = strlen(name) + 1;
    char *copy = malloc(size);
    if (copy != NULL) {
        memcpy(copy, name, size);
    }
    return copy;
}

int sum(const int *values, int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += values[i];
    }
    return total;
}

int main(void) {
    char *name = copy_name("alice");
    if (name == NULL) {
        return 1;
    }
    int scores[4] = {3, 1, 4, 1};
    printf("%s %d\n", name, sum(scores, 4));
    free(name);
}
Output
alice 9

This code has a memory error, on purpose, and the sanitizer reports it.

#include <limits.h>
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main(void) {
    printf("%d\n", add(INT_MAX, 1));
}

UndefinedBehaviorSanitizer reports signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'. ASan does not check arithmetic, so this needs -fsanitize=undefined.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <pthread.h>
#include <stdio.h>

static long counter = 0;

static void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < 1000; i++) {
        counter++; // two threads write without a lock
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, work, NULL);
    pthread_create(&b, NULL, work, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("%ld\n", counter);
}

ThreadSanitizer reports a data race on the global counter, with the stacks of the two writes. ASan and TSan cannot be in the same build, so a project builds and tests twice.

  • Verdict: library. ASan is a part of Clang and GCC, not of the C language. -fsanitize=address adds the checks at compile time and links the runtime library.
  • C has no bounds check of its own, so ASan finds errors that the language leaves as undefined behavior. See Out-of-bounds write and Out-of-bounds read.
  • <sanitizer/asan_interface.h> lets a program poison and unpoison its own memory. A custom allocator uses ASAN_POISON_MEMORY_REGION to mark free blocks, and the macro does nothing in a build without ASan.
  • Leak detection (LSan) is not supported by the Apple toolchain that recorded these examples, so this file has no leak example. See Memory leak.
RustGitHub

This code panics, on purpose.

fn main() {
    let scores = vec![3, 1, 4];
    let mut total = 0;
    for i in 0..=scores.len() {
        total += scores[i]; // index 3 is out of bounds
    }
    println!("{total}");
}

Safe Rust checks each index. The read of scores[3] stops the program with a panic before it touches memory outside the vector. This is the check that ASan adds to C.

This code does not compile, on purpose.

fn main() {
    let view: &str;
    {
        let name = String::from("alice");
        view = &name;
    }
    println!("{view}");
}
Error output
error[E0597]: `name` does not live long enough
 --> main.rs:5:16
  |
4 |         let name = String::from("alice");
  |             ---- binding `name` declared here
5 |         view = &name;
  |                ^^^^^ borrowed value does not live long enough
6 |     }
  |     - `name` dropped here while still borrowed
7 |     println!("{view}");
  |                ---- borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0597`.

The borrow checker rejects the program at compile time. view would outlive name, so the program cannot read freed memory, and there is nothing for ASan to find.

fn main() {
    let scores = vec![3, 1, 4];
    match scores.get(3) {
        Some(value) => println!("{value}"),
        None => println!("index 3 is out of range"),
    }
    let total: i32 = scores.iter().sum();
    println!("{total}");
}
Output
index 3 is out of range
8
  • Verdict: library. rustc -Zsanitizer=address builds a program with ASan. The flag is unstable, so it needs a nightly compiler, and the Rust documentation recommends a rebuild of the standard library with -Zbuild-std.
  • Safe Rust has bounds checks and the borrow checker, so ASan is for unsafe code and for C or C++ code that Rust calls.
  • get returns an Option, so the caller must handle an index that is out of range.

ASan is one of a family of sanitizers in Clang and GCC. Each one has its own shadow encoding and its own run-time library.

  • UndefinedBehaviorSanitizer (UBSan) finds undefined behavior such as signed Integer overflow or wraparound, misaligned and null pointers, shifts out of range and array indices out of bounds. Clang says that it has a small run-time cost and no effect on the address space layout or the ABI.5 It can be in the same build as ASan, as in the fixed C example (-fsanitize=address,undefined).
  • ThreadSanitizer (TSan) finds Data race. Clang gives a typical slowdown of 5x to 15x and a memory overhead of 5x to 10x.6 It cannot be in the same build as ASan.3
  • MemorySanitizer (MSan) finds reads of uninitialized memory. Clang gives a typical slowdown of 3x. It needs all the code of the program, the C library included, to be instrumented, and it runs on Linux, NetBSD and FreeBSD only.7
  • LeakSanitizer (LSan) finds Memory leak. It runs at the end of the process and reports blocks that no pointer reaches. It is part of ASan, and it also runs alone with -fsanitize=leak.8 Clang turns it on by default with ASan on Linux.2 The Apple toolchain that recorded the examples does not support it.
  • Manual poisoning. A program can poison its own memory through <sanitizer/asan_interface.h>. A pool allocator marks free blocks with ASAN_POISON_MEMORY_REGION, so a use of a free block is reported as if the system allocator had freed it. The macros do nothing in a build without ASan.11 Container libraries use the same interface to poison the unused capacity of a vector.2
  • Valgrind Memcheck finds similar errors by binary translation, with no recompilation. The paper reports slowdowns of about 20x for Valgrind and 10x for Dr. Memory on SPEC CPU2006, against 73% for ASan. These tools also find uninitialized reads and leaks, but they miss most overflows of stack and global arrays.1

Pitfalls

A clean run does not prove the code is correct

ASan reports only the errors that happen in the run. A buffer overflow on a path that no test takes stays hidden. A far out-of-bounds access can land in another valid block and pass.1 Use ASan with tests that reach the edge cases, and with a fuzzer that generates inputs.

Mixing sanitizers in one build

-fsanitize=address and -fsanitize=thread cannot be combined, and GCC says the same for thread and leak.3 A project that wants both runs its tests twice, once with ASan and UBSan, and once with TSan. The C example file shows a data race that only the TSan build reports.

Shipping an ASan build

ASan replaces the allocator, maps a large shadow region and keeps freed memory in a quarantine. These are test features. The Clang documentation lists the extra memory, up to 3 times more stack, and more than 16 terabytes of mapped virtual address space as limits.2 Ship the build without the sanitizer.

Errors in code that ASan does not see

Memory that a custom allocator hands out from one large malloc block has no redzones between the small objects. An overflow from one object into the next is not reported. The allocator must poison its free blocks and gaps by hand.11

Cost

The paper measured SPEC CPU2006 with Clang -O2:1

  • Time. The average slowdown was 73%. The largest were 2.60x for perlbench and 2.67x for xalancbmk. With only writes checked, the average slowdown was 26%.
  • Memory. The average memory use grew 3.37 times, mostly because of the heap redzones. The quarantine adds a fixed amount on top.
  • Defaults. The paper's run-time defaults were a stack depth of 30 frames for malloc and free, a 256 MB quarantine and 128-byte heap redzones.

The Clang documentation gives a typical slowdown of 2x.2 The numbers differ because the workloads and the settings differ. A larger quarantine finds more uses after free and costs memory, not time.1

History

  • 2011. The AddressSanitizer team released the tool in May 2011. In the first 10 months it found over 300 bugs in Chromium: 210 heap uses after free, 73 heap buffer overflows, 8 global buffer overflows, 7 stack buffer overflows and 1 overlap of memcpy arguments.1
  • 2012. Serebryany, Bruening, Potapenko and Vyukov published the design at USENIX ATC 2012. The paper describes the shadow encoding, the allocator with redzones and quarantine, and the measurements above.1

References

  1. Konstantin Serebryany, Derek Bruening, Alexander Potapenko and Dmitry Vyukov, AddressSanitizer, A Fast Address Sanity Checker, USENIX ATC 2012, Abstract; 1 Introduction; 3.1 Shadow Memory; 3.2 Instrumentation; 3.3 Run-time Library; 3.4 Stack And Globals; 3.5 False Negatives; 3.6 False Positives; 4 Evaluation; 4.1 Comparison; 4.2 AddressSanitizer Deployment; 4.3 Tuning
  2. Clang documentation, AddressSanitizer, Introduction; Usage; Container Overflow Detection; Limitations; Supported Platforms
  3. Using the GNU Compiler Collection, Program Instrumentation Options, -fsanitize=address and -fsanitize=thread
  4. Microsoft C++ documentation, AddressSanitizer, the overview (the /fsanitize=address option and the supported targets)
  5. Clang documentation, UndefinedBehaviorSanitizer, Introduction; Available checks
  6. Clang documentation, ThreadSanitizer, Introduction
  7. Clang documentation, MemorySanitizer, Introduction; Supported Platforms; Limitations
  8. Clang documentation, LeakSanitizer, Introduction; Usage; Supported Platforms
  9. The Rust Unstable Book, sanitizer, the introduction (-Zsanitizer and the supported targets) and AddressSanitizer
  10. Command go, Compile packages and dependencies, the build flags -asan and -race
  11. LLVM compiler-rt, sanitizer/asan_interface.h, __asan_poison_memory_region, __asan_address_is_poisoned, ASAN_POISON_MEMORY_REGION

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/41NX54/text.yaml