Algorithm Search⌘K

Algorithmadvanced

Baggy bounds checking

Also called baggy bounds.

Pads each allocation to a power of two and stores its log size in a compact table, so that bounds checks need one lookup.

Time
Θ(1) worst
Space
Θ(m / 16) extra
Where
m = the number of bytes of the address space; n = the requested size of an allocation in bytes
Properties
deterministiconlineiterative
Origin
Periklis Akritidis, Manuel Costa, Miguel Castro, Steven Hand, 2009

Baggy bounds checking is a bounds checker for C that finds the object of a pointer in constant time. It pads every allocation to a power of two and aligns it to that size, with a binary buddy allocator. Then the size of an allocation is one small number, its base-two logarithm ee, and the base of the allocation that holds an address pp is pp with its low ee bits cleared. A table with one byte for each 16-byte slot of memory holds ee. Pointer arithmetic checks that the result is in the same padded allocation as the operand with one xor and one shift. Like Jones-Kelly, it keeps pointers as plain addresses, so checked and unchecked code work together. The price is that the checks use the padded size: an access to the padding is not reported.

In plain words

Every allocation is rounded up to a size of 16, 32, 64, 128 bytes and so on, and placed at an address that is a multiple of that size. Because of this, two facts describe an allocation fully: its size, and any address inside it.

The checker keeps a small table with one entry for each 16 bytes of memory. The entry says how big the allocation there is, as a power of two. One table read gives the size, and clearing the low bits of the address gives the start.

When the program moves a pointer, the checker looks at the entry for the old address and asks whether the new address is in the same rounded-up block. If it is just outside, the pointer gets a mark and may come back later. If it is far outside, the program stops.

The problem

The problem is the one of Jones-Kelly bounds checking: stop each pointer computation that leaves the object its operand points into, without changing the size of pointers. The object table of Jones-Kelly finds the object with a search in a splay tree, on every pointer operation, and this search is most of the cost. The goal is a lookup in a constant number of instructions and a table small enough to stay in the cache, at the cost of less exact bounds.

The algorithm

Memory is cut into slots of 16 bytes. The bounds table TT has one byte per slot. For an allocation of padded size 2e2^e at base BB, with BB a multiple of 2e2^e, every slot of [B,B+2e)[B, B + 2^e) has T=eT = e. The slots of memory that the checker did not allocate hold a default value that covers the whole address space, so checks on them always pass; the original uses 31 on 32-bit Windows. A pointer that is at most half a slot outside its allocation is marked by setting a bit above all valid addresses. In the original that is the top bit of a 32-bit address, which points into the kernel half of the address space, so a dereference of a marked pointer faults in hardware.

  1. ALLOC(n)
  2. 1e ← max(4, ⌈log2 n⌉) ▷ padded size 2^e, at least one slot
  3. 2B ← a free block of 2^e bytes, aligned to 2^e ▷ binary buddy allocator
  4. 3for each slot s of [B, B + 2^e) do T[s] ← e
  5. 4clear the 2^e bytes, padding included
  6. 5return B
  7. ADD(p, k)
  8. 6if p is marked then r ← p without the mark; ref ← r - 8 if r is in the low half of its slot, else r + 8
  9. 7else r ← p; ref ← p
  10. 8e ← T[ref >> 4]
  11. 9q ← r + k
  12. 10if (ref xor q) >> e = 0 then return q ▷ in the padded allocation
  13. 11base ← ref with the low e bits cleared
  14. 12if base - 8 ≤ q < base + 2^e + 8 then return q with the mark
  15. 13report a bounds error
  16. CHECK(p, w) ▷ for an access of w bytes
  17. 14if p is marked then fault
  18. 15if (p xor (p + w - 1)) >> T[p >> 4] ≠ 0 then report a bounds error
  19. FREE(p)
  20. 16if p is not the base of an allocation then report an error
  21. 17for each slot of the block do T[s] ← the default; give the block back

The table. Lines L1 to L3 make the bounds a function of the address. One byte per 16 bytes is 1/161/16 of memory, a regular array indexed by the address shifted right by 4, which is a form of shadow memory.

The xor check. Line L10 tests whether qq and refref agree in every bit from bit ee up. Because the block is aligned to 2e2^e, those bits are exactly the base of the block, so the test is true exactly when qq is inside [B,B+2e)[B, B + 2^e). There is no subtraction, no comparison of two bounds and no branch on the size.

Out-of-bounds pointers. C programs often form a pointer just past an array, or just before it, and then come back. Line L12 keeps such a pointer if it is less than half a slot outside the block, and marks it. A marked pointer cannot be used to access memory, but line L6 can still find its allocation. The allocation is at least one slot and ends on a slot boundary, so a pointer past the end lands in the low half of the next slot and a pointer before the base lands in the high half of the previous slot. Moving the address by half a slot back toward the block, as line L6 does, puts it inside the allocation again. A pointer further out is an error at once, in line L13.

Wide accesses. The arithmetic check alone shows that the first byte of an access is in the block. For an access of w>1w > 1 bytes, line L15 also checks the last byte p+w−1p + w - 1. The paper notes that this second check is not needed for accesses that are aligned to their own size, because an aligned access cannot cross a power-of-two boundary of a larger block.

Example

A memory of 256 bytes, so 16 slots; slot 0 is reserved, so 0 is never a valid pointer. The default table value is 8.

step operation result
1 aa ← ALLOC(20) e=5e = 5; a=32a = 32, the block is [32,64)[32, 64); T[2]=T[3]=5T[2] = T[3] = 5
2 bb ← ALLOC(10) e=4e = 4; b=16b = 16, the block is [16,32)[16, 32)
3 STORE(ADD(aa, 25), 1, 9) allowed: byte 57 is padding, inside [32,64)[32, 64)
4 pp ← ADD(aa, 32) q=64q = 64; (32⊕64)≫5=3(32 \oplus 64) \gg 5 = 3; 24≤64<7224 \le 64 < 72, so pp is 64 with the mark
5 LOAD(pp, 1) fault at line L14
6 ADD(pp, −1-1) r=64r = 64 is in the low half, so ref=56ref = 56 and e=5e = 5; q=63q = 63 and (56⊕63)≫5=0(56 \oplus 63) \gg 5 = 0: back in bounds
7 ADD(aa, 40) q=72q = 72 is not below 7272: bounds error at line L13
8 STORE(ADD(aa, 30), 4, 1) the bytes are 62 to 65; (62⊕65)≫5=3(62 \oplus 65) \gg 5 = 3: bounds error at line L15
9 FREE(aa); LOAD(aa, 1) T[2],T[3]T[2], T[3] go back to 8; the load passes

Step 3 shows the lost precision: byte 57 is not part of the 20 bytes the program asked for. Step 6 shows a pointer that leaves and comes back, which Jones-Kelly refuses. Step 9 shows that the scheme has no temporal check.

Correctness

For a live allocation with base BB and padded size P=2eP = 2^e, call a pointer derived from it at offset oo if its address is B+oB + o. The claim, proved in the correctness proof, is an invariant on every such pointer: it is plain if 0≤o<P0 \le o < P, it is marked if −8≤o<0-8 \le o < 0 or P≤o<P+8P \le o < P + 8, and any ADD that would give another offset reports an error. The proof uses two facts. First, the table holds ee in every slot of the block, so line L8 reads the right size. Second, the block is aligned, so the xor test of line L10 is exactly the test B≤q<B+PB \le q < B + P, and line L6 maps a marked pointer back into its own block. From the invariant, CHECK passes exactly when 0≤o0 \le o and o+w≤Po + w \le P. So every access outside the padded block is caught, and no access inside it is refused.

Proof: Baggy bounds checking refuses exactly the accesses outside the padded blockfull

Setting. The memory has 2b2^b bytes and slots of 16 bytes. The mark bit is a bit M>2b+8M > 2^b + 8, a power of two, so every address aa used below has 0≤a<M0 \le a < M and aa with the mark is a+Ma + M. Slot 0 is reserved, so every allocation has base B≥16B \ge 16. The program runs ALLOC, ADD, LOAD, STORE and FREE of the main block, and every pointer it uses is a result of ALLOC or ADD.

Lemma 1 (the table). After each operation, for every live allocation with base BB and padded size P=2eP = 2^e: 16≤P16 \le P, BB is a multiple of PP, the blocks of live allocations are disjoint, and T[s]=eT[s] = e for every slot ss of [B,B+P)[B, B + P).

Proof. Line L1 gives e≥4e \ge 4. The buddy allocator in line L2 gives aligned blocks that are disjoint from all blocks in use. Line L3 writes ee to every slot of the new block, and these slots belong to no other live allocation. Line L17 writes the default only to the slots of the freed block. No other line writes TT. □\square

For a live allocation (B,e)(B, e) with P=2eP = 2^e, define the pointer that baggy bounds must hold at offset oo:

f(o)={B+oif 0≤o<P,(B+o)+Mif −8≤o<0 or P≤o<P+8,noneotherwise.f(o) = \begin{cases} B + o & \text{if } 0 \le o < P, \\ (B + o) + M & \text{if } -8 \le o < 0 \text{ or } P \le o < P + 8, \\ \text{none} & \text{otherwise.} \end{cases}

Lemma 2 (arithmetic). Let the allocation (B,e)(B, e) be live and let p=f(o)≠p = f(o) \ne none. Then ADD(p,k)(p, k) returns f(o+k)f(o + k) if it is not none, and reports a bounds error otherwise.

Proof. First we show that lines L6 and L7 give r=B+or = B + o and an address refref in [B,B+P)[B, B + P).

  • If 0≤o<P0 \le o < P, pp has no mark, and line L7 sets r=ref=B+or = ref = B + o.
  • If P≤o<P+8P \le o < P + 8, write o=P+jo = P + j with 0≤j<80 \le j < 8. Since BB and PP are multiples of 16, r=B+P+jr = B + P + j has r mod 16=j<8r \bmod 16 = j < 8, the low half, so ref=r−8=B+P−8+jref = r - 8 = B + P - 8 + j. As P≥16P \ge 16, this is in [B+P−8,B+P)⊆[B,B+P)[B + P - 8, B + P) \subseteq [B, B + P).
  • If −8≤o<0-8 \le o < 0, write o=−8+jo = -8 + j with 0≤j<80 \le j < 8. Then r mod 16=8+j≥8r \bmod 16 = 8 + j \ge 8, the high half, so ref=r+8=B+j∈[B,B+8)⊆[B,B+P)ref = r + 8 = B + j \in [B, B + 8) \subseteq [B, B + P).

The mark is removed correctly because r<Mr < M. By Lemma 1, line L8 reads T[ref≫4]=eT[ref \gg 4] = e. Line L9 sets q=B+o+kq = B + o + k.

Line L10 tests (ref⊕q)≫e=0(ref \oplus q) \gg e = 0, that is, ⌊ref/P⌋=⌊q/P⌋\lfloor ref / P \rfloor = \lfloor q / P \rfloor for q≥0q \ge 0. As BB is a multiple of PP and ref∈[B,B+P)ref \in [B, B + P), ⌊ref/P⌋=B/P\lfloor ref / P \rfloor = B / P, so the test holds exactly when B≤q<B+PB \le q < B + P, that is, 0≤o+k<P0 \le o + k < P. Then ADD returns q=f(o+k)q = f(o + k).

Otherwise line L11 computes base=Bbase = B, again because ref∈[B,B+P)ref \in [B, B + P) and BB is aligned. Line L12 returns q+M=f(o+k)q + M = f(o + k) exactly when −8≤o+k<P+8-8 \le o + k < P + 8, and line L13 reports an error in the remaining case, where f(o+k)f(o + k) is none. For q<0q < 0 we have o+k<−B≤−16o + k < -B \le -16, so f(o+k)f(o + k) is none, and both tests fail because of the condition q≥0q \ge 0. □\square

Lemma 3 (invariant). While allocation (B,e)(B, e) is live, every pointer derived from it at offset oo equals f(o)f(o).

Proof. By induction on the derivation. ALLOC returns B=f(0)B = f(0) in line L5. ADD keeps the claim by Lemma 2, and a step whose result would be none reports an error and gives no pointer. □\square

Theorem. Let pp be derived from a live allocation (B,e)(B, e) at offset oo, and let w≥1w \ge 1. CHECK(p,w)(p, w) passes exactly when 0≤o0 \le o and o+w≤Po + w \le P, that is, when the ww bytes lie in the padded block [B,B+P)[B, B + P).

Proof. By Lemma 3, p=f(o)p = f(o). If o<0o < 0 or o≥Po \ge P, pp is marked and line L14 faults; in both cases the bytes do not lie in the block. Otherwise p=B+op = B + o with 0≤o<P0 \le o < P, line L14 passes, and line L15 reads T[p≫4]=eT[p \gg 4] = e by Lemma 1. As in Lemma 2, (p⊕(p+w−1))≫e=0(p \oplus (p + w - 1)) \gg e = 0 holds exactly when p+w−1<B+Pp + w - 1 < B + P, that is, o+w≤Po + w \le P. ■\blacksquare

What is not claimed. The theorem is about the padded block, so an access to bytes [B+n,B+P)[B + n, B + P) of the padding passes. It says nothing about a pointer whose allocation was freed: then line L17 has reset the table and the checks use the default or a new allocation.

Termination. Every operation runs a bounded number of lines, plus a loop over the 2e/162^e / 16 slots of one block and a buddy split or merge of at most bb steps.

Complexity

Every check is Θ(1)\Theta(1) in the word RAM model: one table read, one xor, one shift and one compare, plus a second compare for marked pointers. ALLOC and FREE add O(2e/16)O(2^e / 16) table writes to the cost of the buddy allocator, which is O(log⁡m)O(\log m) for an address space of mm bytes. The table takes m/16m / 16 bytes. The padding wastes up to half of each allocation, as internal fragmentation; on average it is much less, because many requests are already close to a power of two.

The measured cost is a property of the implementation and its workload. The paper reports, for its 32-bit Windows implementation in 2009, an 8% decrease of throughput for the Apache web server, and it compares run time on the SPECINT 2000 and Olden benchmarks with earlier checkers.

Properties

  • Backwards compatible. Pointers keep their size, and memory that the checker did not allocate passes every check.
  • Not exact. The bounds are those of the padded block, so an overflow into the padding is allowed. It never reaches another object, because allocations do not overlap.
  • Spatial only. It does not find use after free.
  • Constant-time lookup. The size comes from an array, with no search.

Variants and improvements

  • 64-bit pointers. On a 64-bit machine the paper stores ee in spare high bits of the pointer itself, which removes the table lookup at the cost of masking the pointer before each use.
  • Last-byte check only when needed. Line L15 can be dropped for aligned accesses of built-in types, which leaves one check per pointer computation.
  • Other slot sizes. A larger slot makes the table smaller and the minimum allocation larger. The half-slot rule then allows pointers further out of bounds.
  • Tighter bounds. Later schemes store the exact size elsewhere, or use shadow memory with one entry per small granule, as AddressSanitizer does, to catch the overflows into the padding.

When to use it

Use baggy bounds when you need a spatial checker that is cheap enough for production, that works with libraries compiled without checks, and that stops an overflow from reaching a neighbouring object. It is a hardening technique, not a precise debugging tool: an overflow into the padding goes unseen, and a later access past the padding is reported far from the bug. For finding bugs in testing, a precise checker such as AddressSanitizer reports more of them. For exact per-pointer bounds and sub-object bounds, use SoftBound.

Pitfalls

  • Blocks that are not aligned. If line L2 returns a block that is not aligned to 2e2^e, the xor test of line L10 compares the wrong bits and accepts addresses in the neighbour. The allocator must align every block to its own padded size.
  • A stale table. If line L17 does not reset the slots of a freed block, a later small allocation in that memory gets the old, larger ee for its other slots, and line L10 accepts a range that covers other objects. Reset on free and set again on each allocation.
  • The wrong half. If line L6 moves a marked pointer away from its block, line L8 reads the size of the neighbour, and the pointer is judged against the wrong block. The low half of a slot belongs to the block below.
  • First byte only. Without line L15, an unaligned 8-byte access at the last byte of a block writes 7 bytes into the next block.
  • Uncleared padding. If line L4 clears only the nn requested bytes, a program that reads the padding sees data of an earlier allocation.

Implementations

The Python code runs on a simulated memory of a few hundred bytes with its own buddy allocator and never reads real memory. The mark bit is one bit above the largest address of the simulated memory. The tests run random programs against an oracle that tracks every object, its padded size and the intended offset of every pointer, and they check that the value of each pointer, marked or plain, and the result of each access are exactly what the invariant predicts.

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.

baggy_bounds_checking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baggy-bounds-checking/. The authors are listed in prov/81GP9H.jsonl.

"""Baggy bounds checking on a simulated memory of 2^bits bytes.

Each allocation is padded to a power of two 2^e (at least one slot of 16
bytes) and aligned to it by a binary buddy allocator. A bounds table has one
byte per slot that holds e, so the base and the size of the allocation that
holds an address come from one table read. Pointer arithmetic checks the
result with one xor and one shift. A result less than half a slot out of
bounds gets a mark bit, so it can come back; a result further out is an error.

The memory is a Python bytearray, never real memory. There is no temporal
checking, as in the original.
"""

LOG_SLOT = 4  # slots of 16 bytes
SLOT = 1 << LOG_SLOT
HALF = SLOT // 2


class BoundsError(Exception):
    """An arithmetic result or an access left its padded allocation."""


class BaggyHeap:
    """A buddy heap with a baggy bounds table.

    alloc and free cost O(bits) for the buddy allocator plus O(2^e / 16) to
    write the table entries of the block; add and the access check cost O(1).
    Precondition: pointers come from alloc or add.
    """

    def __init__(self, bits: int = 10) -> None:
        if bits < LOG_SLOT + 1:
            raise ValueError("the memory must hold at least two slots")
        self.bits = bits
        self.mark = 1 << (bits + 1)  # above every address, so a marked pointer is never valid
        self.mem = bytearray(1 << bits)
        self.table = bytearray([bits]) * ((1 << bits) >> LOG_SLOT)  # default: the whole memory
        self.free_blocks: dict[int, set[int]] = {e: set() for e in range(LOG_SLOT, bits + 1)}
        self.free_blocks[bits].add(0)
        self.live: dict[int, tuple[int, int]] = {}  # base -> (e, requested size)
        self.reserved = self._take(LOG_SLOT)  # slot 0 stays unused, so 0 is a null pointer

    def _take(self, e: int) -> int:
        """Remove a free block of 2^e bytes from the buddy lists, splitting a larger one."""
        j = e
        while j <= self.bits and not self.free_blocks[j]:
            j += 1
        if j > self.bits:
            return -1
        b = min(self.free_blocks[j])
        self.free_blocks[j].remove(b)
        while j > e:
            j -= 1
            self.free_blocks[j].add(b + (1 << j))
        return b

    def alloc(self, n: int) -> int:
        """Allocate n >= 1 bytes, padded to a power of two. Return 0 if nothing fits."""
        if n < 1:
            raise ValueError("n must be positive")
        e = max(LOG_SLOT, (n - 1).bit_length())  # @line L1: the padded size is 2^e
        if e > self.bits:
            return 0
        b = self._take(e)  # @line L2: aligned to 2^e
        if b < 0:
            return 0
        for s in range(b >> LOG_SLOT, (b + (1 << e)) >> LOG_SLOT):  # @line L3
            self.table[s] = e
        self.mem[b:b + (1 << e)] = bytes(1 << e)  # @line L4: the padding is cleared too
        self.live[b] = (e, n)
        return b  # @line L5

    def is_marked(self, p: int) -> bool:
        return bool(p & self.mark)

    def add(self, p: int, k: int) -> int:
        """Checked pointer arithmetic p + k."""
        if p & self.mark:  # @line L6: find the referent from the half of the slot
            r = p & ~self.mark
            ref = r - HALF if r % SLOT < HALF else r + HALF
        else:
            r = ref = p  # @line L7
        e = self.table[ref >> LOG_SLOT]  # @line L8
        q = r + k  # @line L9
        if q >= 0 and (ref ^ q) >> e == 0:  # @line L10: inside the padded allocation
            return q
        base = ref & ~((1 << e) - 1)  # @line L11
        if q >= 0 and base - HALF <= q < base + (1 << e) + HALF:  # @line L12
            return q | self.mark
        raise BoundsError(f"{r} + {k} is far outside the allocation [{base}, {base + (1 << e)})")  # @line L13

    def check_access(self, p: int, w: int) -> None:
        """The check for an access of w bytes at p: unmarked, and the last byte in the block."""
        if p & self.mark:  # @line L14: a marked pointer faults
            raise BoundsError(f"access through an out-of-bounds pointer {p & ~self.mark}")
        e = self.table[p >> LOG_SLOT]
        if (p ^ (p + w - 1)) >> e != 0:  # @line L15
            raise BoundsError(f"access of {w} bytes at {p} crosses the end of its allocation")

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

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

    def free(self, p: int) -> None:
        """Free the allocation with base p and give its slots the default entry."""
        if p not in self.live:  # @line L16
            raise BoundsError(f"free of {p}, which is not the base of an allocation")
        e, _ = self.live.pop(p)
        for s in range(p >> LOG_SLOT, (p + (1 << e)) >> LOG_SLOT):  # @line L17
            self.table[s] = self.bits
        while e < self.bits and (p ^ (1 << e)) in self.free_blocks[e]:  # buddy merge
            self.free_blocks[e].remove(p ^ (1 << e))
            p = min(p, p ^ (1 << e))
            e += 1
        self.free_blocks[e].add(p)

    def check_invariant(self) -> None:
        """Blocks tile the memory, are aligned, and the table matches the live blocks."""
        spans = [(self.reserved, LOG_SLOT)] + [(b, e) for b, (e, _) in self.live.items()]
        spans += [(b, e) for e, s in self.free_blocks.items() for b in s]
        spans.sort()
        pos = 0
        for b, e in spans:
            assert b == pos and b % (1 << e) == 0
            pos = b + (1 << e)
        assert pos == len(self.mem)
        want = bytearray([self.bits]) * len(self.table)
        for b, (e, _) in self.live.items():
            for s in range(b >> LOG_SLOT, (b + (1 << e)) >> LOG_SLOT):
                want[s] = e
        assert self.table == want
test_baggy_bounds_checking.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baggy-bounds-checking/. The authors are listed in prov/81GP9H.jsonl.

import random

import pytest
from baggy_bounds_checking import HALF, SLOT, BaggyHeap, BoundsError


def test_page_example() -> None:
    h = BaggyHeap(8)  # 256 bytes, 16 slots; slot 0 is reserved
    a = h.alloc(20)
    assert a == 32  # padded to 32 bytes, aligned to 32
    assert list(h.table[2:4]) == [5, 5] and h.table[1] == 8
    b = h.alloc(10)
    assert b == 16  # padded to one slot
    h.store(h.add(a, 19), 1, 7)  # the last requested byte
    h.store(h.add(a, 25), 1, 9)  # in the padding: allowed
    end = h.add(a, 32)
    assert h.is_marked(end) and end & ~h.mark == 64
    with pytest.raises(BoundsError):
        h.load(end, 1)
    back = h.add(end, -1)
    assert back == 63 and h.load(back, 1) == 0
    with pytest.raises(BoundsError):
        h.add(a, 40)  # 8 or more bytes past the padded end
    low = h.add(a, -3)
    assert h.is_marked(low)
    with pytest.raises(BoundsError):
        h.store(h.add(a, 30), 4, 1)  # bytes 62 to 65 cross the end
    h.free(a)
    assert h.load(a, 1) == 0  # no temporal checking
    h.check_invariant()


def test_edges() -> None:
    h = BaggyHeap(6)  # 64 bytes
    with pytest.raises(BoundsError):
        h.free(0)
    a = h.alloc(32)
    assert a == 32 and h.alloc(17) == 0
    c = h.alloc(16)
    assert c == 16 and h.alloc(1) == 0
    with pytest.raises(BoundsError):
        h.free(a + 1)
    h.free(a)
    with pytest.raises(BoundsError):
        h.free(a)
    h.free(c)
    h.check_invariant()
    assert h.alloc(32) == 32
    with pytest.raises(ValueError):
        h.alloc(0)


def expected_value(h: BaggyHeap, base: int, padded: int, off: int) -> int | None:
    """The pointer that baggy bounds must hold for a live object, or None for an error."""
    if 0 <= off < padded:
        return base + off
    if -HALF <= off < padded + HALF:
        return (base + off) | h.mark
    return None


def test_random_programs_against_object_oracle() -> None:
    rng = random.Random(2009)
    counts = {"caught": 0, "padding": 0, "far": 0, "missed_uaf": 0}
    for _ in range(500):
        h = BaggyHeap(rng.choice([8, 9, 10]))
        objs: list[dict] = []
        vals: list[int] = []
        meta: list[tuple[int, int]] = []  # (object, intended offset)
        for _ in range(rng.randint(5, 40)):
            op = rng.random()
            if op < 0.25 or not vals:
                n = rng.randint(1, 70)
                p = h.alloc(n)
                if p:
                    padded = max(SLOT, 1 << (n - 1).bit_length())
                    assert p % padded == 0
                    for o in objs:
                        if o["live"]:
                            assert p + padded <= o["base"] or o["base"] + o["padded"] <= p
                    objs.append({"base": p, "n": n, "padded": padded, "live": True, "data": bytearray(padded)})
                    vals.append(p)
                    meta.append((len(objs) - 1, 0))
            elif op < 0.45:
                i = rng.randrange(len(vals))
                k = rng.randint(-20, 20)
                oid, off = meta[i]
                o = objs[oid]
                try:
                    got: int | None = h.add(vals[i], k)
                except BoundsError:
                    got = None
                if o["live"]:
                    want = expected_value(h, o["base"], o["padded"], off + k)
                    assert got == want
                    if want is None:
                        counts["far"] += 1
                if got is not None:
                    vals.append(got)
                    meta.append((oid, off + k))
            elif op < 0.85:
                i = rng.randrange(len(vals))
                w = rng.choice([1, 2, 4, 8])
                oid, off = meta[i]
                o = objs[oid]
                p = vals[i]
                try:
                    if rng.random() < 0.5:
                        v = rng.randrange(1 << (8 * w))
                        h.store(p, w, v)
                        for j, byte in enumerate(v.to_bytes(w, "little")):
                            for x in objs:  # a dangling store lands in whatever object holds the byte
                                if x["live"] and x["base"] <= p + j < x["base"] + x["padded"]:
                                    x["data"][p + j - x["base"]] = byte
                        ok, loaded = True, None
                    else:
                        ok, loaded = True, h.load(p, w)
                except BoundsError:
                    ok, loaded = False, None
                if o["live"]:
                    in_padded = 0 <= off and off + w <= o["padded"]
                    assert ok == in_padded
                    if loaded is not None:
                        assert loaded == int.from_bytes(o["data"][off:off + w], "little")
                    if not in_padded:
                        counts["caught"] += 1
                    elif off + w > o["n"]:
                        counts["padding"] += 1
                elif ok:
                    counts["missed_uaf"] += 1
            else:
                i = rng.randrange(len(vals))
                p = vals[i]
                o = next((x for x in objs if x["live"] and x["base"] == p), None)
                try:
                    h.free(p)
                    ok = True
                except BoundsError:
                    ok = False
                assert ok == (o is not None)
                if o is not None:
                    o["live"] = False
            h.check_invariant()
    assert counts["caught"] > 100 and counts["padding"] > 50
    assert counts["far"] > 30 and counts["missed_uaf"] > 10

History

Akritidis, Costa, Castro and Hand presented baggy bounds checking in 2009, after Jones-Kelly (1997), CRED (2004) and the pool-based tables of Dhurjati and Adve (2006). They kept the referent-object approach and the backwards compatibility of that line of work, and replaced the tree with an array lookup made possible by padding and alignment. The same idea, in which an allocator layout makes the metadata a function of the address, appears in later hardening allocators and in hardware with bounds in pointer bits.

References

  1. Periklis Akritidis, Manuel Costa, Miguel Castro and Steven Hand, Baggy bounds checking, an efficient and backwards-compatible defense against out-of-bounds errors, USENIX Security Symposium 2009, the sections on the bounds table with one byte per 16-byte slot, the xor check, out-of-bounds pointers within half a slot and the mark bit, the binary buddy allocator, the 64-bit variant and the evaluation
  2. Richard W. M. Jones and Paul H. J. Kelly, Backwards-compatible bounds checking for arrays and pointers in C programs, AADEBUG 1997, pages 13 to 25, the referent-object approach and the object table that baggy bounds replaces
  3. Olatunji Ruwase and Monica S. Lam, A practical dynamic buffer overflow detector, NDSS 2004, pages 159 to 169, the out-of-bounds objects that the mark bit of baggy bounds replaces for pointers close to their object

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
  • a scene preset for the example