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
- Model
- Word RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , and the base of the allocation that holds an address is with its low bits cleared. A table with one byte for each 16-byte slot of memory holds . 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 has one byte per slot. For an allocation of padded size at base , with a multiple of , every slot of has . 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.
ALLOC(n)- 1
e ← max(4, ⌈log2 n⌉) ▷ padded size 2^e, at least one slot - 2
B ← a free block of 2^e bytes, aligned to 2^e ▷ binary buddy allocator - 3
for each slot s of [B, B + 2^e) do T[s] ← e - 4
clear the 2^e bytes, padding included - 5
return B ADD(p, k)- 6
if 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 - 7
else r ← p; ref ← p - 8
e ← T[ref >> 4] - 9
q ← r + k - 10
if (ref xor q) >> e = 0 then return q ▷ in the padded allocation - 11
base ← ref with the low e bits cleared - 12
if base - 8 ≤ q < base + 2^e + 8 then return q with the mark - 13
report a bounds error CHECK(p, w) ▷ for an access of w bytes- 14
if p is marked then fault - 15
if (p xor (p + w - 1)) >> T[p >> 4] ≠ 0 then report a bounds error FREE(p)- 16
if p is not the base of an allocation then report an error - 17
for 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 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 and agree in every bit from bit up. Because the block is aligned to , those bits are exactly the base of the block, so the test is true exactly when is inside . 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 bytes, line L15 also checks the last byte . 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 | ← ALLOC(20) | ; , the block is ; |
| 2 | ← ALLOC(10) | ; , the block is |
| 3 | STORE(ADD(, 25), 1, 9) | allowed: byte 57 is padding, inside |
| 4 | ← ADD(, 32) | ; ; , so is 64 with the mark |
| 5 | LOAD(, 1) | fault at line L14 |
| 6 | ADD(, ) | is in the low half, so and ; and : back in bounds |
| 7 | ADD(, 40) | is not below : bounds error at line L13 |
| 8 | STORE(ADD(, 30), 4, 1) | the bytes are 62 to 65; : bounds error at line L15 |
| 9 | FREE(); LOAD(, 1) | 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 and padded size , call a pointer derived from it at offset if its address is . The claim, proved in the correctness proof, is an invariant on every such pointer: it is plain if , it is marked if or , and any ADD that would give another offset reports an error. The proof uses two facts. First, the table holds 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 , and line L6 maps a marked pointer back into its own block. From the invariant, CHECK passes exactly when and . 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 bytes and slots of 16 bytes. The mark bit is a bit , a power of two, so every address used below has and with the mark is . Slot 0 is reserved, so every allocation has base . 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 and padded size : , is a multiple of , the blocks of live allocations are disjoint, and for every slot of .
Proof. Line L1 gives . The buddy allocator in line L2 gives aligned blocks that are disjoint from all blocks in use. Line L3 writes 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 .
For a live allocation with , define the pointer that baggy bounds must hold at offset :
Lemma 2 (arithmetic). Let the allocation be live and let none. Then ADD returns if it is not none, and reports a bounds error otherwise.
Proof. First we show that lines L6 and L7 give and an address in .
- If , has no mark, and line L7 sets .
- If , write with . Since and are multiples of 16, has , the low half, so . As , this is in .
- If , write with . Then , the high half, so .
The mark is removed correctly because . By Lemma 1, line L8 reads . Line L9 sets .
Line L10 tests , that is, for . As is a multiple of and , , so the test holds exactly when , that is, . Then ADD returns .
Otherwise line L11 computes , again because and is aligned. Line L12 returns exactly when , and line L13 reports an error in the remaining case, where is none. For we have , so is none, and both tests fail because of the condition .
Lemma 3 (invariant). While allocation is live, every pointer derived from it at offset equals .
Proof. By induction on the derivation. ALLOC returns 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.
Theorem. Let be derived from a live allocation at offset , and let . CHECK passes exactly when and , that is, when the bytes lie in the padded block .
Proof. By Lemma 3, . If or , is marked and line L14 faults; in both cases the bytes do not lie in the block. Otherwise with , line L14 passes, and line L15 reads by Lemma 1. As in Lemma 2, holds exactly when , that is, .
What is not claimed. The theorem is about the padded block, so an access to bytes 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 slots of one block and a buddy split or merge of at most steps.
Complexity
Every check is 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 table writes to the cost of the buddy allocator, which is for an address space of bytes. The table takes 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 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 , 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 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 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 81GP9H Edit this page History Report an error Markdown