Algorithmadvanced
SoftBound
Also called disjoint metadata bounds checking.
Keeps base and bound for each pointer in a disjoint table indexed by the address where the pointer is stored, for spatial safety in C with no change to memory layout.
- Time
- Θ(1) worst
- Space
- Θ(s) extra
- Where
- s = the number of memory locations that hold a pointer
- Model
- Word RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Santosh Nagarakatte, Jianzhou Zhao, Milo M. K. Martin, Steve Zdancewic, 2009
SoftBound is a compiler transformation for C that gives every pointer its own base and bound, like a fat pointer, but keeps those bounds out of the pointer. In registers a pointer travels with its two bounds. In memory a pointer stays a single word, and its bounds go to a separate table, keyed by the address where the pointer is stored. A store of a pointer writes the table entry, a load of a pointer reads it, and every load and store through a pointer checks the address against the bounds. Because the memory layout does not change, structures, arrays of pointers and the calls to libraries keep their usual form. Because the bounds are per pointer and not per object, SoftBound also catches an overflow from one field of a structure into the next.
In plain words
Each pointer gets a pair of fences: where its object starts and where it ends. While the program works with the pointer, the fences go with it, and every read or write is checked against them.
When the program puts the pointer away in memory, only the bare address goes into the memory cell. The fences are written into a separate notebook, on the line for that memory cell. When the program later takes the pointer out of the cell, the checker reads the fences back from the same line.
Nothing else in memory moves, so other code that does not know about the notebook still sees normal pointers. A pointer that was made from a plain number has no line in the notebook, gets empty fences, and cannot be used.
The problem
The input is a C program. The goal is complete spatial memory safety: no load or store may touch a byte outside the object, or the sub-object, that the pointer was made for. Two other approaches each lose something. A fat pointer changes the size of pointers, so checked code no longer matches the layout of structures in code compiled without checks. Object-based checkers such as Jones-Kelly keep the layout but know only whole objects, so they cannot see an overflow inside a structure, and they need a search to find the object. SoftBound wants the precision of the first and the compatibility of the second.
The algorithm
Each pointer value in a register has two companion values, and , and the object is . The metadata table maps an address to the bounds of the pointer last stored at . A pointer takes bytes in memory.
ALLOC(n)- 1
b ← a new block of n bytes - 2
return (b, b, b + n) ADD(p, k)- 3
return (p + k, p.base, p.bound) ▷ bounds go along, no check FIELD(p, off, size) ▷ &p->field- 4
v ← p + off; return (v, max(v, p.base), min(v + size, p.bound)) CHECK(p, w)- 5
if p < p.base or p + w > p.bound then - 6
report a bounds error LOAD(p, w) and STORE(p, w, v) ▷ integers- 7
CHECK(p, w) - 8
read or write the w bytes at p ▷ META does not change STOREPTR(loc, q) ▷ *loc = q- 9
CHECK(loc, W) - 10
write the value q at loc - 11
META[loc] ← (q.base, q.bound) LOADPTR(loc) ▷ q = *loc- 12
CHECK(loc, W) - 13
v ← the value at loc - 14
(b, e) ← META[loc], or (0, 0) if there is no entry - 15
return (v, b, e) INT-TO-PTR(v)- 16
return (v, 0, 0) ▷ empty bounds
Creating bounds. Lines L1 and L2 give a new object its exact bounds. The same happens for a stack array or a global, with the size known from its type. Line L4 makes a pointer to a field of a structure and narrows the bounds to the field, so a write past the end of one field fails, although it stays inside the whole object.
Propagation. Line L3 copies the bounds through pointer arithmetic, and a copy from one register to another copies them too. The check is at the access, so a pointer may leave its object and come back.
Disjoint metadata. Lines L10 and L11 split a pointer store into two writes: the value goes to its usual place, and the bounds go to . Lines L13 to L15 put them together again on a load. The table is indexed by the address of the location, not by the value of the pointer, so two pointers with the same value can have different bounds. The paper implements either as a hash table or as a shadow space, a large array indexed by the address shifted right, which is a form of shadow memory.
Calls. When a pointer is passed to a function or returned from one, its bounds are passed as extra arguments. A copy of memory with a library function also copies the table entries of any pointers in it.
Example
A memory of 64 bytes and pointers of 4 bytes; addresses below 4 are not used. The struct has a field name of 8 bytes and a field count of 4 bytes.
| step | operation | result |
|---|---|---|
| 1 | ← ALLOC(12) | |
| 2 | ← ALLOC(4) | , a cell for one pointer |
| 3 | ← FIELD(, 0, 8) | : the bounds of the field only |
| 4 | STORE(ADD(, 8), 1, 66) | bounds error: , although byte 12 is in |
| 5 | STORE(ADD(, 8), 4, 3) | allowed: count is in the bounds of |
| 6 | STOREPTR(, ) | memory at 16 holds 4; |
| 7 | ← LOADPTR(); LOAD(ADD(, 8), 1) | ; the load is a bounds error |
| 8 | ← INT-TO-PTR(8); LOAD(, 1) | bounds error: |
Step 4 is an overflow inside one object, which an object table cannot see. Step 7 shows that bounds survive a round trip through memory. Step 8 shows that a pointer forged from an integer is useless, even though address 8 is inside a real object.
Correctness
Call a pair of bounds valid if it is empty or is the range of an allocated object, or a part of one. Lines L2 and L4 make only valid bounds, line L3 copies them, line L16 makes empty bounds, and line L11 stores only bounds that the program held in a register. So, by induction on the steps, every entry of and every pointer in a register has valid bounds. Then line L5 lets an access through only if all its bytes lie inside valid bounds, so every access that succeeds stays inside one object. The proof is in the correctness proof. The paper itself formalizes the scheme for a subset of C and gives a mechanized proof of spatial safety.
Proof: Every access that SoftBound allows stays inside one objectfull
Setting. The program runs a finite sequence of the operations of the main block. It makes pointers only with ALLOC, ADD, FIELD, LOADPTR and INT-TO-PTR, and it cannot write the bounds of a pointer in a register. Objects are never freed, and the allocator returns blocks that do not overlap. A range is valid if (empty) or for the block of some object that ALLOC returned.
Lemma 1 (invariant V). After each operation, (a) every pointer the program holds in a register has valid bounds , and (b) every entry has valid.
Proof. By induction on the number of operations. At the start there are no pointers and is empty. Assume (a) and (b) before an operation.
- ALLOC returns the bounds of its own block in line L2, which is valid.
- ADD copies the bounds of in line L3, valid by (a).
- FIELD in line L4 returns with and . If the range is empty. Otherwise , so the range is a part of , which is valid and not empty, so it lies in one block, and so does the part.
- INT-TO-PTR returns the empty bounds in line L16.
- STOREPTR sets to the bounds of in line L11, valid by (a). Other entries do not change.
- LOADPTR returns the bounds of an entry of in line L14, valid by (b), or the empty bounds.
- LOAD and STORE do not change any bounds or any entry.
Theorem. If LOAD, STORE, STOREPTR or LOADPTR completes, with for the last two, then the bytes lie inside the block of one object.
Proof. Each of these runs CHECK first, in line L7, L9 or L12, and touches memory only after it. CHECK passes only if line L5 is false, that is, and . As , the range is not empty, and by Lemma 1(a) it lies in the block of one object. So .
Corollary (exactness for tracked pointers). Let be made from the block by ALLOC followed by ADD and FIELD steps only, possibly through STOREPTR and LOADPTR at a location whose entry was not overwritten in between. Then the bounds of are the bounds that the same steps compute on without the table, and CHECK passes exactly when the access lies in them.
Proof. ADD and FIELD compute the new bounds from the old ones only. STOREPTR at writes the bounds of to and a later LOADPTR at the same , with no STOREPTR to in between, reads them back in line L14; LOAD and STORE do not change the table. So the bounds of are the computed ones, and CHECK in line L5 is exactly the test that lies in them.
Termination. Every operation runs a bounded number of lines.
Complexity
Each operation is in the word RAM model: two comparisons for a check, and one table access for a pointer load or store, expected with a hash table and worst-case with a shadow space. The table holds one entry per memory location that holds a pointer, space for such locations with a hash table; the shadow space reserves room for every word of memory and uses only the parts that are touched. Registers hold three words per pointer instead of one.
Measured costs depend on the compiler, the benchmarks and the machine. The paper reports an average run-time overhead of 67% for full checking on its benchmarks in 2009, and a much lower overhead when only stores are checked.
Properties
- Complete spatial safety. Every load and store is checked, against bounds that are exact for objects and for fields.
- Compatible layout. Memory holds plain pointers, so the layout of every structure is unchanged.
- Spatial only. A pointer to a freed object keeps valid-looking bounds; temporal safety needs lock and key checking on top.
- Separate compilation. Each function needs only the bounds of its own pointers, passed with the arguments.
Variants and improvements
- Store-only checking. Check only stores, which stops overflows that corrupt memory but not those that read past an object. It is much cheaper.
- Temporal checking. Lock and key temporal checking, from the same group, adds a key and a lock address to the metadata of each pointer and uses the same disjoint table.
- Hardware support. The same design, bounds per pointer in registers and in a table indexed by the address of the pointer, was later built into hardware, with bounds registers and instructions to check them and to load and store table entries.
- Capabilities. CHERI keeps the bounds inside a wider pointer, protected by a tag bit, which gives the precision of SoftBound without a separate table but changes the layout.
When to use it
Use SoftBound when you need exact spatial safety for C, including overflows inside structures, and you must keep the memory layout because the program shares structures with code you cannot recompile. It is a compiler-based tool: all checked code must be compiled with it, and a library that stores pointers without updating the table returns pointers with empty or stale bounds. If you only need to find bugs in testing, AddressSanitizer is cheaper and finds use after free too, but misses overflows that jump over its redzones and overflows inside an object.
Pitfalls
- Keying the table by the pointer value. If line L11 uses instead of as the key, two pointers with the same value share one entry, and a pointer to one past the end of one array gets the bounds of the next object. The key is the address of the location.
- Widening at a field. If line L4 takes without the minimum with , a bad offset gives a field pointer with bounds outside the object. Always intersect with the old bounds.
- Checking at arithmetic. If line L3 rejects a value outside the bounds, programs that form the address one past the end of an array fail. The check is in line L5.
- Unchecked writers of pointers. A library compiled without the pass that writes a pointer into memory does not run line L11. The next LOADPTR from there gets the old entry or the empty bounds of line L14. Wrap such libraries so they update the table.
- Integer stores over a pointer. Line L8 does not change , so a pointer that is overwritten with an integer and loaded again gets its old bounds. This keeps spatial safety, because the old bounds are still valid, but it can hide a bug.
Implementations
The Python code runs on a simulated memory, a bytearray with a bump allocator, with pointers of 4 bytes and a dictionary as the metadata table, and never reads real memory. The tests run random programs that allocate objects, take fields, store pointers in memory and load them back, and overwrite them with integers. An oracle tracks the object and the offset of every pointer. Each check must match the oracle exactly when the oracle knows the pointer, and every access that succeeds must lie inside the bounds of one object.
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/softbound/. The authors are listed in prov/4RX746.jsonl.
"""SoftBound: per-pointer bounds in a disjoint metadata table, on a simulated memory.
A pointer in a register is a triple (value, base, bound). In memory a pointer
is a plain 4-byte word, so the memory layout does not change. Its base and
bound go to a separate table keyed by the address where the pointer is
stored. A pointer store writes the table entry; a pointer load reads it. An
address with no entry gives the empty bounds (0, 0), so the pointer cannot be
used.
The memory is a Python bytearray, never real memory. As in SoftBound itself,
this checks spatial safety only; objects are never freed here.
"""
from dataclasses import dataclass
WORD = 4 # bytes in a stored pointer
class BoundsError(Exception):
"""An access left the bounds of its pointer."""
@dataclass(frozen=True)
class Ptr:
"""A pointer in a register: its value and the bounds [base, bound)."""
value: int
base: int
bound: int
NULL = Ptr(0, 0, 0)
class SoftBoundMemory:
"""A bump-allocated memory with a disjoint metadata table.
Every operation costs O(1) time (one dictionary access for the table,
expected O(1)). The table holds one entry for each address where a pointer
was stored. Precondition: the program makes pointers only with alloc,
add, field, load_ptr and int_to_ptr.
"""
def __init__(self, size: int = 256) -> None:
if size < 2 * WORD:
raise ValueError("size is too small")
self.mem = bytearray(size)
self.top = WORD # addresses below WORD stay unused, so 0 is null
self.meta: dict[int, tuple[int, int]] = {} # address of a stored pointer -> (base, bound)
def alloc(self, n: int) -> Ptr:
"""A new zeroed object of n >= 1 bytes, or NULL when the memory is full."""
if n < 1:
raise ValueError("n must be positive")
if self.top + n > len(self.mem):
return NULL
b = self.top # @line L1
self.top += n
return Ptr(b, b, b + n) # @line L2
def add(self, p: Ptr, k: int) -> Ptr:
"""Pointer arithmetic: the bounds go along unchanged."""
return Ptr(p.value + k, p.base, p.bound) # @line L3
def field(self, p: Ptr, off: int, size: int) -> Ptr:
"""A pointer to the sub-object [p + off, p + off + size), with bounds narrowed to it."""
v = p.value + off # @line L4: never wider than the bounds of p
lo = max(v, p.base)
hi = max(lo, min(v + size, p.bound))
return Ptr(v, lo, hi)
def int_to_ptr(self, v: int) -> Ptr:
"""A pointer made from an integer has empty bounds."""
return Ptr(v, 0, 0) # @line L16
def check(self, p: Ptr, w: int) -> None:
"""Raise BoundsError unless the w bytes at p lie in [p.base, p.bound)."""
if p.value < p.base or p.value + w > p.bound: # @line L5
raise BoundsError(f"access of {w} bytes at {p.value} outside [{p.base}, {p.bound})") # @line L6
def load(self, p: Ptr, w: int) -> int:
"""Read a little-endian integer of w bytes."""
self.check(p, w) # @line L7
return int.from_bytes(self.mem[p.value:p.value + w], "little") # @line L8
def store(self, p: Ptr, w: int, v: int) -> None:
"""Write an integer of w bytes. The metadata table does not change."""
self.check(p, w) # @line L7
self.mem[p.value:p.value + w] = (v % (1 << (8 * w))).to_bytes(w, "little") # @line L8
def store_ptr(self, loc: Ptr, q: Ptr) -> None:
"""Store the pointer q at loc: its value in memory, its bounds in the table."""
self.check(loc, WORD) # @line L9
self.mem[loc.value:loc.value + WORD] = (q.value % (1 << (8 * WORD))).to_bytes(WORD, "little") # @line L10
self.meta[loc.value] = (q.base, q.bound) # @line L11
def load_ptr(self, loc: Ptr) -> Ptr:
"""Load a pointer from loc together with the bounds stored for that address."""
self.check(loc, WORD) # @line L12
v = int.from_bytes(self.mem[loc.value:loc.value + WORD], "little") # @line L13
b, e = self.meta.get(loc.value, (0, 0)) # @line L14: no entry gives empty bounds
return Ptr(v, b, e) # @line L15
test_softbound.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/softbound/. The authors are listed in prov/4RX746.jsonl.
import random
import pytest
from softbound import NULL, WORD, BoundsError, Ptr, SoftBoundMemory
def test_page_example() -> None:
m = SoftBoundMemory(64)
s = m.alloc(12) # a struct: char name[8]; int count;
assert s == Ptr(4, 4, 16)
cell = m.alloc(4) # a cell that holds one pointer
assert cell == Ptr(16, 16, 20)
name = m.field(s, 0, 8)
assert name == Ptr(4, 4, 12)
m.store(m.add(name, 7), 1, 65)
with pytest.raises(BoundsError):
m.store(m.add(name, 8), 1, 66) # into count: caught by the field bounds
m.store(m.add(s, 8), 4, 3) # count itself, through s
m.store_ptr(cell, name)
assert m.meta == {16: (4, 12)}
q = m.load_ptr(cell)
assert q == name
with pytest.raises(BoundsError):
m.load(m.add(q, 8), 1) # the bounds came back from the table
m.store(cell, 4, 4) # an integer store over the pointer leaves the entry
assert m.load_ptr(cell) == Ptr(4, 4, 12)
forged = m.int_to_ptr(8)
with pytest.raises(BoundsError):
m.load(forged, 1)
other = m.alloc(4)
assert m.load_ptr(other) == Ptr(0, 0, 0) # no entry: empty bounds
def test_edges() -> None:
m = SoftBoundMemory(16)
with pytest.raises(BoundsError):
m.load(NULL, 1)
a = m.alloc(12)
assert m.alloc(1) == NULL
with pytest.raises(BoundsError):
m.store_ptr(m.add(a, 9), a) # a 4-byte pointer store needs 4 bytes in bounds
wide = m.field(a, -4, 40)
assert (wide.base, wide.bound) == (a.base, a.bound) # a field never widens the bounds
empty = m.field(a, 20, 4)
assert empty.base == empty.bound
with pytest.raises(ValueError):
m.alloc(0)
def test_random_programs_against_provenance_oracle() -> None:
rng = random.Random(2009)
caught = 0
for _ in range(600):
size = rng.choice([64, 128, 256])
m = SoftBoundMemory(size)
objs: list[tuple[int, int]] = [] # (base, size)
mem = bytearray(size) # the oracle copy of memory
regs: list[Ptr] = []
intent: list[tuple[int, int, int, int] | None] = [] # (object, offset, lo, hi) relative to the base
slots: dict[int, tuple[int, int, int, int]] = {} # address -> intent of the pointer stored there
def forget(a: int, w: int) -> None:
for loc in [x for x in slots if x < a + w and a < x + WORD]:
del slots[loc]
def within_one_object(lo: int, hi: int) -> bool:
return lo == hi or any(b <= lo and hi <= b + n for b, n in objs)
for _ in range(rng.randint(5, 50)):
op = rng.random()
if op < 0.15 or not regs:
n = rng.randint(1, 16)
p = m.alloc(n)
if p != NULL:
objs.append((p.base, n))
regs.append(p)
intent.append((len(objs) - 1, 0, 0, n))
continue
i = rng.randrange(len(regs))
p, t = regs[i], intent[i]
if op < 0.30:
k = rng.randint(-10, 10)
regs.append(m.add(p, k))
intent.append(None if t is None else (t[0], t[1] + k, t[2], t[3]))
continue
if op < 0.38:
off, sz = rng.randint(-2, 10), rng.randint(0, 8)
q = m.field(p, off, sz)
regs.append(q)
if t is None:
intent.append(None)
else:
o = t[1] + off
lo = max(o, t[2])
intent.append((t[0], o, lo, max(lo, min(o + sz, t[3]))))
continue
if op < 0.42:
regs.append(m.int_to_ptr(rng.randrange(size)))
intent.append(None)
continue
w = WORD if op >= 0.75 else rng.choice([1, 2, 4])
if t is not None:
base = objs[t[0]][0]
assert (p.value, p.base, p.bound) == (base + t[1], base + t[2], base + t[3])
want_ok = t[2] <= t[1] and t[1] + w <= t[3]
else:
want_ok = None
try:
if op < 0.60:
v = rng.randrange(1 << (8 * w))
m.store(p, w, v)
mem[p.value:p.value + w] = v.to_bytes(w, "little")
forget(p.value, w)
elif op < 0.75:
assert m.load(p, w) == int.from_bytes(mem[p.value:p.value + w], "little")
elif op < 0.88:
j = rng.randrange(len(regs))
m.store_ptr(p, regs[j])
mem[p.value:p.value + WORD] = (regs[j].value % (1 << 32)).to_bytes(WORD, "little")
forget(p.value, WORD)
if intent[j] is not None and regs[j].value >= 0: # a negative value wraps in memory
slots[p.value] = intent[j]
else:
q = m.load_ptr(p)
assert q.value == int.from_bytes(mem[p.value:p.value + WORD], "little")
assert within_one_object(q.base, q.bound) # bounds always come from one object
regs.append(q)
intent.append(slots.get(p.value))
ok = True
except BoundsError:
ok = False
if want_ok is not None:
assert ok == want_ok
caught += not ok
if ok:
assert within_one_object(p.base, p.bound) and p.base <= p.value and p.value + w <= p.bound
assert caught > 500
History
Austin, Breach and Sohi described per-pointer bounds in 1994 with fat pointers, which change the layout. Nagarakatte, Zhao, Martin and Zdancewic presented SoftBound at PLDI 2009. They kept the per-pointer bounds and moved them into a disjoint table, which keeps the layout, and they formalized the scheme and proved it safe. The same group added temporal checking with locks and keys in 2010. Hardware versions of the design followed.
References
- Santosh Nagarakatte, Jianzhou Zhao, Milo M. K. Martin and Steve Zdancewic, SoftBound, highly compatible and complete spatial memory safety for C, PLDI 2009, pages 245 to 258, the sections on pointer metadata, the disjoint metadata space (hash table and shadow space), the bounds narrowing for structure fields, the formal model and the evaluation
- Todd M. Austin, Scott E. Breach and Gurindar S. Sohi, Efficient detection of all pointer and array access errors, PLDI 1994, pages 290 to 301, the fat-pointer design that SoftBound keeps in registers and moves out of memory
- Laszlo Szekeres, Mathias Payer, Tao Wei and Dawn Song, SoK, eternal war in memory, IEEE Symposium on Security and Privacy 2013, pages 48 to 62, the comparison of pointer-based and object-based spatial safety
Where this leads
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 4RX746 Edit this page History Report an error Markdown