Algorithm Search⌘K

Algorithmcore

AddressSanitizer

Also called ASan, redzone checking.

Puts poisoned redzones around objects and a quarantine for freed memory, and checks each access against shadow memory to find overflows and use after free.

Time
Θ(1) worst
Space
Θ(m / 8) extra
Where
m = the size of the application memory in bytes; n = the size of an object in bytes
Properties
deterministiconlineiterative
Origin
Konstantin Serebryany, Derek Bruening, Alexander Potapenko, Dmitry Vyukov, 2012

AddressSanitizer finds out-of-bounds accesses and uses after free in C and C++ programs. Its allocator puts a redzone of memory that the program must not touch on each side of every heap object, and it does not reuse freed memory at once but keeps it in a quarantine. One byte of shadow memory describes each aligned granule of 8 bytes: whether all of it, only a prefix of it, or none of it may be accessed. The compiler adds a few instructions before each load and store that read the shadow byte and report an error if the access touches a byte that is not addressable. An overflow that steps into a redzone and a use of memory that is still in the quarantine are reported at the faulting access. The tool is meant for testing, not for production, since it slows the program down and uses much more memory.

In plain words

Picture a car park where every car gets a row of painted no-parking spaces at each end. A guard has a small notebook with one line for each group of eight spaces, saying how many of them are in use.

Before anyone parks, the guard looks up the line for that group. If the space is a no-parking space, or a space nobody has rented, the guard stops the driver at once.

When a car leaves, its spaces are not rented again straight away. They stay marked as "recently left" for a while, so a driver who comes back to the old space is caught. Only when enough newer spaces have been freed does the oldest group go back up for rent.

The problem

The input is a program with heap objects, and the goal is to report the first load or store that touches a byte outside every live object: past the end of an object or before its start, or in an object that was freed. The check must be cheap enough to run on large programs and in fuzzing, so it must take constant time and must not change the layout of pointers. Exact per-pointer bounds, as in SoftBound, or a lookup of the object, as in Jones and Kelly bounds checking, cost more. AddressSanitizer instead asks a simpler question about the address only: is this byte inside some live object?

The algorithm

The heap is split into granules of 8 bytes, and objects start on granule boundaries. The shadow byte of a granule is 0 if all 8 bytes are addressable, kk in 1 to 7 if only the first kk are, and a negative value if none are. Different negative values mark a redzone and a freed object, so that a report can say which it was. OFFSET is the start of the shadow region; real systems fix it for each platform. An access of ww bytes, with ww in {1,2,4,8}\{1, 2, 4, 8\}, is aligned to ww, so it lies in one granule. RZ is the redzone size, a multiple of 8.

  1. SHADOW(a)
  2. 1return M[(a >> 3) + OFFSET]
  3. CHECK(a, w) ▷ before each load or store of w bytes at a
  4. 2k ← SHADOW(a), as a signed byte
  5. 3if k ≠ 0 and (a & 7) + w - 1 ≥ k then report an error at a
  6. MALLOC(n)
  7. 4c ← a free chunk of RZ + ⌈n/8⌉·8 + RZ bytes; b ← c + RZ
  8. 5poison the shadow of [c, b) and of [b + ⌈n/8⌉·8, c + the chunk length) as a redzone
  9. 6set the shadow of the ⌊n/8⌋ full granules at b to 0, and of the next granule to n mod 8 if it is not 0
  10. 7return b
  11. FREE(p)
  12. 8if p is not the start of a live object then report a double or bad free
  13. 9poison the shadow of the ⌈n/8⌉ granules at p as freed
  14. 10append the chunk to the end of the FIFO quarantine Q
  15. 11while the total size of Q exceeds its limit do
  16. 12remove the oldest chunk from Q and give it back to the allocator

The check. Line L3 is one comparison in the common case: most shadow bytes are 0, and then the access is allowed. If kk is between 1 and 7, the access is allowed when its last byte, at position (a&7)+w−1(a \mathbin{\&} 7) + w - 1 inside the granule, is below kk. If kk is negative, the comparison is true for every access, since the left side is never negative. For w=8w = 8 the access covers the whole granule, so any nonzero kk is an error, and the formula gives this too.

Malloc. Lines L4 to L6 make exactly the nn bytes of the object addressable and poison everything else in the chunk. The bytes between b+nb + n and the end of the last granule are covered by the partial value n mod 8n \bmod 8, so an overflow by one byte is caught even when nn is not a multiple of 8.

Free and the quarantine. Line L9 marks the object as freed, so that any later access reports a use after free. Lines L10 to L12 delay the reuse of the chunk: it goes back to the allocator only after enough other memory has been freed after it. While the chunk is in the quarantine, every stale pointer into it is caught.

Example

A memory of 256 bytes, redzones of 16 bytes and a quarantine limit of 64 bytes. The shadow values FA\mathtt{FA} (a redzone) and FD\mathtt{FD} (freed) are negative as signed bytes.

step operation result
1 pp ← MALLOC(13) chunk [0,48)[0, 48), p=16p = 16; the shadow of the six granules is FA, FA, 0, 5, FA, FA
2 qq ← MALLOC(8) chunk [48,88)[48, 88), q=64q = 64
3 LOAD(p+12p + 12, 1) granule 3 has k=5k = 5; 4+0<54 + 0 < 5: allowed
4 LOAD(p+13p + 13, 1) 5+0≥55 + 0 \ge 5: heap buffer overflow
5 LOAD(p+12p + 12, 4) 4+3≥54 + 3 \ge 5: heap buffer overflow, one byte in bounds is not enough
6 LOAD(p−8p - 8, 8) kk is FA: overflow into the left redzone
7 FREE(pp) the object granules become FD; the quarantine holds 48 bytes
8 LOAD(pp, 1) kk is FD: heap use after free
9 FREE(pp) pp is not live but is in the quarantine: double free
10 FREE(qq) the quarantine would hold 88 bytes, so the chunk of pp leaves it
11 rr ← MALLOC(13) first fit gives the chunk at 0 again: r=16=pr = 16 = p
12 LOAD(pp, 1) allowed: the stale pointer now reads the new object

Step 12 shows the limit of the design: once a chunk leaves the quarantine and is reused, a dangling pointer to it is no longer reported.

Correctness

The check decides a property of the address, not of the pointer. Invariant S: for every granule, the shadow byte is 0 if all 8 bytes lie in live objects, kk in 1 to 7 if exactly the first kk do, and negative if none do. Objects start on granule boundaries and redzones are at least one granule, so these are the only cases. MALLOC sets the shadow of its chunk to match, and FREE poisons the object it frees; no other operation changes which bytes are live. Under S, line L3 reports an aligned access of w≤8w \le 8 bytes exactly when one of its bytes is outside every live object. So every overflow that ends in a redzone or in free memory is reported, and every use of an object whose chunk is still in the quarantine is reported, with no false reports. An access that leaves its object and lands inside another live object is not reported. The proof is in the correctness proof.

Proof: The shadow check reports an aligned access exactly when it touches a byte outside every live objectfull

Setting. Memory is split into granules of 8 bytes. A chunk consists of a redzone of RZ bytes, the object of n≥1n \ge 1 bytes padded to ⌈n/8⌉⋅8\lceil n/8 \rceil \cdot 8 bytes, and another redzone of RZ bytes, where RZ is a positive multiple of 8. Chunks start on granule boundaries, so every object starts on one. Chunks are live, in the quarantine, or part of the free memory, and the allocator only hands out free memory. At the start the whole shadow holds the redzone value, which is negative. A byte is live if it lies in a live object. An access of w∈{1,2,4,8}w \in \{1, 2, 4, 8\} bytes at aa has a mod w=0a \bmod w = 0, so all its bytes lie in the granule ⌊a/8⌋\lfloor a/8 \rfloor, at positions a&7a \mathbin{\&} 7 to (a&7)+w−1(a \mathbin{\&} 7) + w - 1.

Lemma 1. In every granule, the live bytes form a prefix: positions 00 to j−1j - 1 for some jj in 0 to 8.

Proof. Objects do not overlap, each starts on a granule boundary and is followed by a redzone of at least one granule. So a granule meets at most one object, and that object starts at or before the granule's start. Its bytes in the granule are positions 00 to j−1j - 1. □\square

Lemma 2 (invariant S). After each operation, the shadow byte of every granule gg is 0 if j(g)=8j(g) = 8, is j(g)j(g) if 1≤j(g)≤71 \le j(g) \le 7, and is negative if j(g)=0j(g) = 0.

Proof. By induction on the number of operations. At the start no byte is live, and every shadow byte is negative. Loads and stores change no shadow byte and no live byte.

  • MALLOC(n)(n). The chunk [c,c+ℓ)[c, c + \ell) comes from free memory, so before the call it held no live byte, and after the call its only live bytes are [b,b+n)[b, b + n). Line L5 makes the granules of both redzones negative; they hold no live byte. Line L6 sets the ⌊n/8⌋\lfloor n/8 \rfloor granules that [b,b+n)[b, b + n) fills to 0, and if n mod 8≠0n \bmod 8 \ne 0, sets the next granule, which holds the first n mod 8n \bmod 8 bytes of the object and then padding, to n mod 8n \bmod 8. These are all the granules of the chunk. Granules outside it do not change, and neither do their live bytes.
  • FREE(p)(p). If line L8 reports an error, nothing changes. Otherwise the object [p,p+n)[p, p + n) stops being live, and line L9 makes its ⌈n/8⌉\lceil n/8 \rceil granules negative. The redzones stay negative. Lines L10 to L12 move chunks between the quarantine and free memory, which changes no shadow byte and no live byte. □\square

Theorem. CHECK(a,w)(a, w) reports an error if and only if some byte of [a,a+w)[a, a + w) is not live.

Proof. Let gg be the granule of aa, kk its shadow byte, j=j(g)j = j(g), and e=(a&7)+w−1e = (a \mathbin{\&} 7) + w - 1, the position of the last byte of the access; 0≤e≤70 \le e \le 7. By Lemma 1 the access touches a byte that is not live exactly when e≥je \ge j. By Lemma 2 there are three cases. If j=8j = 8, then k=0k = 0, line L3 does not report, and e≤7<je \le 7 < j. If 1≤j≤71 \le j \le 7, then k=j≠0k = j \ne 0, and line L3 reports exactly when e≥je \ge j. If j=0j = 0, then k<0≤ek < 0 \le e, so line L3 reports, and the access touches only bytes that are not live. ■\blacksquare

Corollary. An access through a pointer derived from an object oo is reported if it leaves oo and touches a byte that is in a redzone, in free memory or in the quarantine. An access after FREE(o)(o) is reported while the chunk of oo is in the quarantine, because none of its bytes is then live. The access is not reported if all its bytes lie in another live object, for example after an overflow longer than the redzone, or after the chunk of oo left the quarantine and was reused.

Termination. CHECK runs two lines. MALLOC and FREE write a finite number of shadow bytes, and the loop of lines L11 and L12 removes one chunk from the finite quarantine in each round.

Complexity

In the word RAM model the check takes Θ(1)\Theta(1) time: one shift, one add, one load and at most two comparisons. MALLOC and FREE write Θ(n/8)\Theta(n / 8) shadow bytes for an object of nn bytes, plus the cost of the allocator. The shadow takes Θ(m/8)\Theta(m / 8) bytes for mm bytes of memory; redzones add 2⋅RZ2 \cdot \mathrm{RZ} bytes per object, and the quarantine keeps up to its limit of freed memory out of use.

The paper reports, in 2012, an average slowdown of 73% on SPEC CPU2006 on 64-bit x86 Linux, and more than 300 bugs found in the Chromium browser.

Properties

  • No false reports for aligned accesses of 1, 2, 4 or 8 bytes: a report always means a byte outside every live object.
  • Not complete. An overflow that jumps over the redzone into another object, and a use after free after the chunk is reused, are missed.
  • Address based. The check needs no metadata in pointers, so code compiled without it can share pointers with code compiled with it.
  • Deterministic. For the same program and input, the same accesses are reported.

Variants and improvements

  • Stack and globals. The compiler also puts redzones between local arrays and between global objects and poisons them in the shadow, so overflows of the stack and of globals are caught the same way.
  • Unaligned and larger accesses. An access that crosses a granule, or is longer than 8 bytes, checks the shadow of its first and last bytes, or of every granule it covers.
  • Use after return and use after scope. Locals can be moved to a heap-like area or poisoned when their scope ends, so that a pointer to a dead local is caught.
  • Tagging instead of redzones. Memory tagging stores a small tag in each pointer and in each granule and checks that they match, which also catches overflows that jump far and uses after reuse, with a probability set by the tag width.
  • Exact bounds. Baggy bounds checking and SoftBound check the bounds of the object that the pointer came from, so a jump into another object is caught.

When to use it

Use AddressSanitizer in testing and in fuzz testing of C and C++ code: it finds most heap, stack and global overflows and many uses after free at the faulting access, with a small change to the build and a moderate cost. In coverage-guided fuzzing it turns silent memory errors into crashes that the fuzzer can see. Do not use it as a production defense: the redzones and the quarantine use much memory, and the misses above mean it gives no guarantee. When every access must be checked against the bounds of the right object, use a bounds checker; when every use after free must be caught, use lock and key checking.

Pitfalls

  • A small redzone. An overflow by more than the redzone can land inside the next object and is not reported. Larger redzones catch more and cost more memory.
  • A small quarantine. Once a freed chunk is reused, a stale pointer to it reads the new object without a report. A larger quarantine delays reuse longer.
  • Forgetting the partial granule. If MALLOC sets the last granule to 0 when nn is not a multiple of 8, overflows of up to 7 bytes are missed.
  • Treating the shadow byte as unsigned. The test in line L3 relies on poisoned values being negative. As unsigned bytes they are large, and an access to a poisoned granule passes.
  • Unaligned accesses. An unaligned access can cross into the next granule, and checking only the shadow of its first byte misses the second granule.
  • Code without instrumentation. Accesses made by libraries compiled without the check are not checked, though their allocations still get redzones if they use the same allocator.

Implementations

The Python code runs on a simulated memory, a bytearray that holds the application bytes and the shadow bytes after them, and never reads real memory. The shadow offset is the size of the simulated memory, not the value used on any real system. The allocator is first fit with redzones of 16 bytes and a FIFO quarantine with a limit in bytes. The tests compare every report of random programs with an oracle that tracks each object and checks every byte of each access against the live objects, and they count the overflows and the uses after free that land in other live objects and are not reported.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

addresssanitizer.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/addresssanitizer/. The authors are listed in prov/B574DH.jsonl.

"""AddressSanitizer on a simulated memory.

One shadow byte describes each granule of 8 bytes of application memory:
0 means all 8 bytes are addressable, k in 1..7 means only the first k are,
and a negative value (as a signed byte) means none are. The allocator puts a
poisoned redzone on each side of every object and keeps freed chunks in a
FIFO quarantine before it reuses them. Each load and store checks the shadow
byte of its address first.

The memory is a Python bytearray, never real memory. The shadow region sits
after the application bytes in the same array, at a symbolic offset.
"""

from collections import deque

GRANULE = 8
LOG_GRANULE = 3
REDZONE = 16  # bytes on each side of an object, a multiple of GRANULE
HEAP_REDZONE = 0xFA  # negative as a signed byte: a redzone or memory never allocated
FREED = 0xFD  # negative as a signed byte: a freed object


class ASanError(Exception):
    """A report: kind is heap-buffer-overflow, heap-use-after-free, double-free or bad-free."""

    def __init__(self, kind: str, addr: int) -> None:
        super().__init__(f"{kind} at {addr}")
        self.kind = kind
        self.addr = addr


def _signed(b: int) -> int:
    return b - 256 if b >= 128 else b


def round_up(n: int) -> int:
    """n rounded up to a multiple of GRANULE."""
    return (n + GRANULE - 1) & ~(GRANULE - 1)


class ASanHeap:
    """A first-fit heap with redzones, a quarantine and shadow checks.

    A check costs O(1). Malloc and free cost O(n / 8) shadow writes for an
    object of n bytes, plus the first-fit search over the holes. The shadow
    takes size / 8 bytes. Precondition: accesses have a width of 1, 2, 4 or 8
    bytes, are aligned to their width and lie inside the application memory.
    """

    def __init__(self, size: int = 512, quarantine_limit: int = 64) -> None:
        if size <= 0 or size % GRANULE:
            raise ValueError("size must be a positive multiple of 8")
        self.size = size
        self.offset = size  # the shadow follows the application bytes
        self.mem = bytearray(size + size // GRANULE)
        self.mem[self.offset:] = bytes([HEAP_REDZONE]) * (size // GRANULE)
        self.holes: list[tuple[int, int]] = [(0, size)]
        self.live: dict[int, tuple[int, int, int]] = {}  # base -> (chunk, chunk length, n)
        self.quarantine: deque[tuple[int, int]] = deque()  # (chunk, chunk length), oldest first
        self.quarantine_bytes = 0
        self.quarantine_limit = quarantine_limit

    def shadow_addr(self, a: int) -> int:
        """The address of the shadow byte of the granule that holds a."""
        return (a >> LOG_GRANULE) + self.offset  # @line L1

    def check(self, a: int, w: int) -> None:
        """Raise ASanError if any of the w bytes at a is not addressable."""
        if w not in (1, 2, 4, 8) or a % w or a < 0 or a + w > self.size:
            raise ValueError("an access must be aligned, of width 1, 2, 4 or 8, and in memory")
        k = _signed(self.mem[self.shadow_addr(a)])  # @line L2
        if k != 0 and (a & (GRANULE - 1)) + w - 1 >= k:  # @line L3
            kind = "heap-use-after-free" if k == _signed(FREED) else "heap-buffer-overflow"
            raise ASanError(kind, a)

    def _poison(self, lo: int, hi: int, value: int) -> None:
        for g in range(lo >> LOG_GRANULE, hi >> LOG_GRANULE):
            self.mem[self.offset + g] = value

    def malloc(self, n: int) -> int:
        """Allocate n >= 1 bytes between two redzones. Return 0 if no hole fits."""
        if n < 1:
            raise ValueError("n must be positive")
        length = REDZONE + round_up(n) + REDZONE
        for i, (start, hole) in enumerate(self.holes):
            if hole >= length:
                break
        else:
            return 0
        if hole == length:
            del self.holes[i]
        else:
            self.holes[i] = (start + length, hole - length)
        c = start
        b = c + REDZONE  # @line L4
        self._poison(c, b, HEAP_REDZONE)  # @line L5
        self._poison(b + round_up(n), c + length, HEAP_REDZONE)
        full = n >> LOG_GRANULE  # @line L6
        self._poison(b, b + full * GRANULE, 0)
        if n & (GRANULE - 1):
            self.mem[self.shadow_addr(b) + full] = n & (GRANULE - 1)
        self.live[b] = (c, length, n)
        return b  # @line L7

    def free(self, p: int) -> None:
        """Free the object at p, poison it and put its chunk in the quarantine."""
        if p not in self.live:  # @line L8
            if any(c + REDZONE == p for c, _ in self.quarantine):
                raise ASanError("double-free", p)
            raise ASanError("bad-free", p)
        c, length, n = self.live.pop(p)
        self._poison(p, p + round_up(n), FREED)  # @line L9
        self.quarantine.append((c, length))  # @line L10
        self.quarantine_bytes += length
        while self.quarantine_bytes > self.quarantine_limit:  # @line L11
            c0, l0 = self.quarantine.popleft()  # @line L12
            self.quarantine_bytes -= l0
            self._release(c0, l0)

    def load(self, a: int, w: int) -> int:
        self.check(a, w)
        return int.from_bytes(self.mem[a:a + w], "little")

    def store(self, a: int, w: int, v: int) -> None:
        self.check(a, w)
        self.mem[a:a + w] = (v % (1 << (8 * w))).to_bytes(w, "little")

    def _release(self, start: int, length: int) -> None:
        holes = sorted(self.holes + [(start, length)])
        merged: list[tuple[int, int]] = []
        for s, l in holes:
            if merged and merged[-1][0] + merged[-1][1] == s:
                merged[-1] = (merged[-1][0], merged[-1][1] + l)
            else:
                merged.append((s, l))
        self.holes = merged

    def check_invariant(self) -> None:
        """Chunks and holes tile the memory, and every shadow byte has its expected value."""
        pieces = sorted(
            [(c, l) for c, l, _ in self.live.values()] + list(self.quarantine) + self.holes
        )
        pos = 0
        for s, l in pieces:
            assert s == pos and l > 0 and s % GRANULE == 0 and l % GRANULE == 0
            pos += l
        assert pos == self.size
        assert self.quarantine_bytes == sum(l for _, l in self.quarantine)
        assert self.quarantine_bytes <= self.quarantine_limit
        expect = [None] * (self.size // GRANULE)
        for b, (c, l, n) in self.live.items():
            assert b == c + REDZONE and l == 2 * REDZONE + round_up(n)
            for g in range(c // GRANULE, (c + l) // GRANULE):
                expect[g] = HEAP_REDZONE
            for i in range(round_up(n) // GRANULE):
                left = n - i * GRANULE
                expect[b // GRANULE + i] = 0 if left >= GRANULE else left
        for c, l in self.quarantine:
            for g in range(c // GRANULE, (c + l) // GRANULE):
                inside = c + REDZONE <= g * GRANULE < c + l - REDZONE
                expect[g] = FREED if inside else HEAP_REDZONE
        for g, e in enumerate(expect):
            v = self.mem[self.offset + g]
            if e is None:
                assert _signed(v) < 0  # quarantined and free memory is poisoned
            else:
                assert v == e
test_addresssanitizer.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/addresssanitizer/. The authors are listed in prov/B574DH.jsonl.

import random
from collections import deque

import pytest
from addresssanitizer import REDZONE, ASanError, ASanHeap, round_up


def test_page_example() -> None:
    h = ASanHeap(256, quarantine_limit=64)
    p = h.malloc(13)  # chunk [0, 48): redzone, 16 bytes for the object, redzone
    q = h.malloc(8)  # chunk [48, 88)
    assert (p, q) == (16, 64)
    assert [h.mem[h.shadow_addr(a)] for a in range(0, 48, 8)] == [0xFA, 0xFA, 0, 5, 0xFA, 0xFA]
    h.store(p + 12, 1, 7)
    assert h.load(p + 12, 1) == 7 and h.load(p + 8, 4) == 0
    for a, w in [(p + 13, 1), (p + 12, 4), (p - 8, 8), (p + 16, 1)]:
        with pytest.raises(ASanError) as e:
            h.load(a, w)
        assert e.value.kind == "heap-buffer-overflow"
    h.free(p)  # the chunk of 48 bytes goes into the quarantine
    with pytest.raises(ASanError) as e:
        h.load(p, 1)
    assert e.value.kind == "heap-use-after-free"
    with pytest.raises(ASanError) as e:
        h.free(p)
    assert e.value.kind == "double-free"
    h.free(q)  # 88 bytes in the quarantine: the chunk of p leaves it
    r = h.malloc(13)
    assert r == p  # the memory of p is reused
    assert h.load(p, 1) == 0  # so the stale pointer p is not reported
    with pytest.raises(ASanError):
        h.load(q, 1)  # q is still in the quarantine
    h.check_invariant()


def test_edges() -> None:
    h = ASanHeap(128, quarantine_limit=0)
    with pytest.raises(ValueError):
        h.malloc(0)
    with pytest.raises(ValueError):
        ASanHeap(100)
    p = h.malloc(16)
    h.store(p + 8, 8, -1)
    assert h.load(p + 8, 8) == (1 << 64) - 1
    with pytest.raises(ValueError):
        h.load(p + 2, 4)  # not aligned
    with pytest.raises(ValueError):
        h.load(p, 3)
    with pytest.raises(ASanError) as e:
        h.free(p + 8)
    assert e.value.kind == "bad-free"
    assert h.malloc(100) == 0  # no hole is large enough
    h.free(p)  # a quarantine of 0 bytes reuses the chunk at once
    assert h.malloc(16) == p
    h.check_invariant()


def test_random_programs_against_byte_oracle() -> None:
    rng = random.Random(2012)
    counts = {"caught": 0, "overflow_missed": 0, "uaf_missed": 0, "uaf_caught": 0}
    for _ in range(500):
        size = rng.choice([256, 512])
        limit = rng.choice([0, 64, 256])
        h = ASanHeap(size, quarantine_limit=limit)
        data = bytearray(size)
        objs: list[dict] = []
        quarantine: deque[tuple[int, int]] = deque()  # (chunk start, chunk length)
        held = 0

        def addressable(a: int) -> bool:
            return any(o["live"] and o["base"] <= a < o["base"] + o["n"] for o in objs)

        for _ in range(rng.randint(10, 60)):
            op = rng.random()
            if op < 0.25:
                n = rng.randint(1, 40)
                b = h.malloc(n)
                if b:
                    lo, hi = b - REDZONE, b + round_up(n) + REDZONE
                    for o in objs:  # disjoint from every live chunk
                        if o["live"]:
                            assert hi <= o["base"] - REDZONE or o["base"] + round_up(o["n"]) + REDZONE <= lo
                    for c, l in quarantine:  # and from every chunk in the quarantine
                        assert hi <= c or c + l <= lo
                    objs.append({"base": b, "n": n, "live": True})
            elif op < 0.37:
                if not objs:
                    continue
                o = rng.choice(objs)
                same = [x for x in objs if x["live"] and x["base"] == o["base"]]
                if same:  # a stale base that was reused frees the new object
                    o = same[0]
                    h.free(o["base"])
                    o["live"] = False
                    length = 2 * REDZONE + round_up(o["n"])
                    quarantine.append((o["base"] - REDZONE, length))
                    held += length
                    while held > limit:
                        held -= quarantine.popleft()[1]
                else:
                    with pytest.raises(ASanError):
                        h.free(o["base"])
            elif objs:
                o = rng.choice(objs)
                w = rng.choice([1, 2, 4, 8])
                a = o["base"] + rng.randint(-40, o["n"] + 40)
                a -= a % w
                if a < 0 or a + w > size:
                    continue
                bad = not all(addressable(x) for x in range(a, a + w))
                real_bug = not o["live"] or a < o["base"] or a + w > o["base"] + o["n"]
                assert not bad or real_bug  # an access inside a live object is never a bug
                try:
                    if op < 0.7:
                        v = rng.randrange(1 << (8 * w))
                        h.store(a, w, v)
                        data[a:a + w] = v.to_bytes(w, "little")
                    else:
                        assert h.load(a, w) == int.from_bytes(data[a:a + w], "little")
                    reported = False
                except ASanError:
                    reported = True
                assert reported == bad  # exact for aligned accesses
                if real_bug and reported:
                    counts["caught"] += 1
                    counts["uaf_caught"] += not o["live"]
                elif real_bug:
                    counts["uaf_missed" if not o["live"] else "overflow_missed"] += 1
            assert h.mem[:size] == data
            h.check_invariant()
    assert counts["caught"] > 1000 and counts["uaf_caught"] > 200
    assert counts["overflow_missed"] > 20 and counts["uaf_missed"] > 20

History

Checking each access against a map of the state of memory goes back to tools such as Purify in the early 1990s and Valgrind's Memcheck in the 2000s, which used binary instrumentation and were slow. Serebryany, Bruening, Potapenko and Vyukov designed AddressSanitizer at Google and presented it at USENIX ATC 2012. It moved the checks into the compiler and used a compact shadow of one byte per 8 bytes, which made it fast enough to run on large programs and in continuous fuzzing. It became part of LLVM and GCC, and its design led to the later work on hardware-assisted and memory-tagging sanitizers.

References

  1. Konstantin Serebryany, Derek Bruening, Alexander Potapenko and Dmitry Vyukov, AddressSanitizer: a fast address sanity checker, USENIX ATC 2012, pages 309-318, Section 3 (the shadow mapping, the instrumentation of 1, 2, 4 and 8 byte accesses, the redzones and the quarantine) and Section 4 (the evaluation)
  2. Nicholas Nethercote and Julian Seward, How to shadow every byte of memory used by a program, VEE 2007, pages 65-74, the layout of shadow memory and the cost of its lookups

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example