Data structurecore
Fat pointer
Also called bounded pointer, safe pointer.
A pointer that carries the base and bound of its object, so that each dereference can be checked against them.
- Time
- Θ(1) worst
- Space
- Θ(1) extra
- Where
- h = the number of holes in the free list of the allocator
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A fat pointer is a pointer that carries the bounds of its object with it: the address, the base and the end of the block it was made from, and often a number that says which allocation it belongs to. Each load and store through the pointer first checks the address against the bounds, so an out-of-bounds access is caught at the access, and with the allocation number a use after free is caught too. This gives spatial memory safety at the cost of a larger pointer, which breaks the memory layout that unchecked C code expects. Austin, Breach and Sohi (1994) called it a safe pointer; CCured, Cyclone, the slices of Rust and Go, and CHERI capabilities are all fat pointers of some kind.
In plain words
A plain pointer is a street address. It says where to go and nothing else, so nothing stops a program from walking past the end of its own plot into the next one.
A fat pointer is the address plus the two ends of the plot it belongs to, written on the same card. Before each read or write, the program looks at the card and checks that the address is still inside the plot. If it is not, the program stops before it touches the neighbour.
The card can also carry a ticket number for the plot. When the plot is given back, its ticket is cancelled. A later visit with an old card shows a cancelled ticket and is refused, even if a new owner has moved onto the same land.
The abstract type
A fat pointer implements a pointer with checked access. The operations are ALLOC, which returns a pointer to a new block of bytes; ADD, pointer arithmetic; LOAD and STORE, which read or write bytes at ; and FREE. The contract is the one of memory safety: a LOAD or STORE succeeds exactly when the bytes lie inside a live block that was derived from, and otherwise it reports a spatial error (outside the block) or a temporal error (the block was freed). ADD is not checked: forming an out-of-bounds address is allowed, using it is not.
Representation
A fat pointer is a record . The field is the address. The block is the half-open range . The field is a capability number, unique to one allocation and never reused. The heap keeps a capability store , a map from the number of each live allocation to its range. The null pointer is , and the number 0 is never issued.
Invariant (F). For each fat pointer that the program holds, is the block of the allocation with number , or is null. If , that block is still allocated, and the live blocks are pairwise disjoint.
The program can copy a fat pointer and change its value by ADD. It cannot write the other three fields. This is the point of the design: the bounds come from the allocator, not from the program.
Operations
ALLOC(n)- 1
base ← the first hole of at least n bytes ▷ first fit; split the hole - 2
cap ← a new capability number ▷ never reused - 3
LIVE[cap] ← [base, base + n) - 4
return (base, base, base + n, cap) ADD(p, k)- 5
return (p.value + k, p.base, p.bound, p.cap) ▷ no check here CHECK(p, w)- 6
if p.value < p.base or p.value + w > p.bound then - 7
report a spatial error - 8
if p.cap is not in LIVE then - 9
report a temporal error LOAD(p, w) and STORE(p, w, v)- 10
CHECK(p, w) - 11
read or write the w bytes at p.value FREE(p)- 12
if p.value ≠ p.base then report a spatial error ▷ not the start of a block - 13
if p.cap is not in LIVE then report a temporal error ▷ double free - 14
delete LIVE[p.cap] - 15
return the block [p.base, p.bound) to the allocator
ALLOC. Lines L1 to L4 take a block from the allocator, here first fit, and give the pointer the bounds of exactly that block. A fresh capability number goes into the store. The cost is the search of the allocator, for holes; the fat pointer itself adds .
ADD. Line L5 moves the address and copies the three other fields. The pointer may leave its block and come back; the bounds do not change, so the final access is judged against the right block. The cost is .
CHECK, LOAD and STORE. Lines L6 and L7 are the spatial check: two comparisons. Lines L8 and L9 are the temporal check: one lookup in the store, expected with a hash table. The spatial check comes first, so a null pointer and a far-off pointer report a spatial error.
FREE. Lines L12 and L13 refuse a free of an interior pointer and a second free. Line L14 cancels the capability. Every copy of the pointer, wherever the program keeps it, now fails line L8, with no search for the copies.
Example
A heap of 64 bytes; address 0 is never used, so the first block starts at 1. The table shows each operation and the result.
| step | operation | result |
|---|---|---|
| 1 | ← ALLOC(8) | |
| 2 | ← ALLOC(4) | , the next block |
| 3 | ← ADD(, 6); STORE(, 2, 0x0102) | bytes 7 and 8 written; |
| 4 | LOAD(ADD(, 7), 1) | 0x01, the high byte |
| 5 | STORE(, 4, 7) | spatial error: , so the store would reach |
| 6 | ← ADD(, 8); LOAD(, 1) | is formed; the load is a spatial error |
| 7 | FREE() | capability 1 leaves the store |
| 8 | ← ALLOC(8) | , the same block, a new number |
| 9 | LOAD(, 1) | temporal error: the bounds pass, capability 1 is dead |
| 10 | LOAD(, 1) | 0, a new block is zeroed |
Step 5 is the buffer overflow that the structure exists to stop: a plain pointer would write two bytes of . Step 6 shows that the address one past the end is a legal value and an illegal target. Step 9 shows why the bounds alone are not enough: after the block is reused, the old pointer's bounds describe the new object, and only the capability tells the two apart.
Correctness
ALLOC sets the fields from the block it returns, ADD changes only the value, and nothing else makes a fat pointer, so invariant (F) holds for every pointer the program holds. Then line L6 passes exactly when the bytes lie inside the block of the allocation, and line L8 passes exactly when that allocation is live. So a LOAD or a STORE succeeds exactly when it is memory safe, and reports the kind of error otherwise. The full proof, by induction on the number of operations, is in the correctness proof.
Proof: A fat pointer check passes exactly on memory-safe accessesfull
Setting. The program runs a finite sequence of the operations ALLOC, ADD, LOAD, STORE and FREE of the main block, on a heap whose allocator returns disjoint blocks: a block it returns does not overlap any block that is allocated and not freed. Each allocation has a block and a capability number ; the numbers come from a counter, so they are distinct. Every pointer the program holds was returned by ALLOC or by ADD; the program cannot write the fields , or . For a pointer that ALLOC returned in allocation , or that ADD derived from such a pointer, we say that belongs to . The null pointer belongs to no allocation.
An access of bytes through is memory safe if belongs to an allocation , the bytes lie in , and is live (not yet freed). It is a spatial error if is null or the bytes do not lie in , and a temporal error if they lie in and was freed.
Lemma 1 (invariant (F)). After each operation: (a) every non-null pointer that belongs to allocation has , and ; (b) exactly when for an allocation that is live, and then .
Proof. By induction on the number of operations. Before the first one there is no pointer and is empty, so (a) and (b) hold. Assume both hold before an operation.
- ALLOC, allocation . Line L1 picks . Line L2 picks a number that was never issued, so it is not in and it is distinct from the numbers of all other allocations. Line L3 adds , which keeps (b), and line L4 returns , which satisfies (a). Old pointers do not change.
- ADD. If belongs to , line L5 returns a pointer that belongs to and copies the three fields of , which are those of by the hypothesis, so (a) holds for it. If is null, the result has the null fields and belongs to no allocation. does not change.
- LOAD and STORE change no pointer and do not change .
- FREE. If line L12 or line L13 reports an error, nothing changes. Otherwise and . By (b), for a live , and by (a) and the distinct numbers, belongs to that . Line L14 deletes and allocation is now freed, so (b) holds again. No pointer field changes, so (a) holds.
Theorem. LOAD and STORE succeed exactly when the access is memory safe. Otherwise CHECK reports a spatial error for a spatial error and a temporal error for a temporal error.
Proof. Both operations run CHECK in line L10 before they touch memory in line L11.
If is null, then , and for either or , so line L6 is true and line L7 reports a spatial error.
If belongs to , Lemma 1(a) gives . Line L6 is false exactly when and , that is, exactly when the bytes lie in . So line L7 reports a spatial error exactly in the spatial case. If the bytes lie in , line L8 tests , which by Lemma 1(b) holds exactly when is live. So line L9 reports a temporal error exactly in the temporal case, and otherwise CHECK returns and line L11 runs.
Corollary (FREE). FREE succeeds exactly when belongs to a live allocation and . A second FREE of any copy of reports a temporal error.
Proof. Line L12 passes exactly when , which by Lemma 1(a) is for the allocation of . Line L13 passes exactly when , which by Lemma 1(b) holds exactly when is live. After a successful FREE, is not in and is never issued again, so a second FREE of any pointer that belongs to fails line L13.
Termination. Every operation runs a bounded number of lines, except the search of the allocator in line L1, which scans a finite list of holes once.
Complexity
The costs are in the word RAM model.
| operation | time | notes |
|---|---|---|
| ALLOC | plus | the allocator's search dominates; the fat pointer adds a store insert |
| ADD | one addition and three copies | |
| CHECK, LOAD, STORE | two comparisons and one lookup in a hash table, expected | |
| FREE | plus | one delete from the store |
Space: each pointer takes four words instead of one, and the store takes words for each live allocation. The extra words in every pointer are the real cost. They raise cache and memory traffic, and they change the size of every structure that holds a pointer. The slowdown of a real system with fat pointers is a measurement of that system, its compiler and its benchmarks, not a property of the structure.
Variants
- Base and size, or base and bound. Austin, Breach and Sohi store the base and the size, plus a storage class and the capability. Bound and size are equivalent; the bound saves an addition in the check.
- Spatial only. Drop the capability and keep . This is the slice of Rust (a pointer and a length) and of Go (a pointer, a length and a capacity), where the type system handles the temporal side.
- Kinds of pointers. CCured infers for each pointer one of three kinds: SAFE (no arithmetic, a null check only), SEQ (a fat pointer with bounds) and WILD (bounds plus run-time type tags). Most pointers end up SAFE, which removes most of the cost. Cyclone lets the programmer pick fat, thin and never-null pointers in the types.
- Disjoint metadata. SoftBound keeps the same base and bound, but in a table beside memory, so the pointer keeps its size and the memory layout does not change.
- Lock and key. Lock and key temporal checking replaces the capability store with a lock word per allocation that the check reads directly.
- Hardware capabilities. CHERI makes the fat pointer a register type with a tag bit, so the hardware checks the bounds and the program cannot forge them.
- Object-based checking. Jones-Kelly and baggy bounds keep the bounds per object, not per pointer, and keep plain pointers.
When to use it
Use fat pointers when you control the language or the whole program, so that every pointer can change its layout: a safe dialect of C, a new language, an interpreter, or a capability machine. They give exact bounds per pointer, they handle pointers that leave their block and return, and with a capability or a key they also find use after free. Do not use them when checked code must share pointers and structures with libraries compiled without the checks, because the layouts differ; then keep the metadata outside the pointer, as in SoftBound, or per object, as in Jones-Kelly.
Pitfalls
- Checking at ADD instead of at the access. If line L5 refuses an address outside the block, common C loops that form the address one past the end, or that step outside and come back, are refused. The check belongs in line L6, at the access.
- Checking only the first byte. The test lets a 4-byte store at the last byte of a block write 3 bytes of the next block. Line L6 must test .
- Bounds that the program can write. If a fat pointer is stored in memory as plain bytes, and the program can write those bytes as integers, it can forge the bounds. The fields must be written only by the allocator and by ADD, as CCured enforces with its kinds and CHERI with a tag bit.
- Bounds without a temporal check. After FREE and a new ALLOC of the same block, the old pointer's bounds fit the new object. Without line L8, step 9 of the example reads another object's data.
- A cast from an integer. A pointer made from an integer has no block. Give it null bounds, so every access fails, not the bounds of the whole memory.
Implementations
The Python code runs on a simulated heap of a few hundred bytes, a bytearray with a first-fit allocator, and never on real memory. The tests run random programs of allocations, arithmetic, loads, stores and frees, and compare every verdict with an oracle that tracks each object and the offset of each pointer.
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/fat-pointer/. The authors are listed in prov/QJJ3SE.jsonl.
"""Fat pointers with a base, a bound and a capability, on a simulated heap.
This is the safe pointer of Austin, Breach and Sohi (PLDI 1994) in a small
model. The memory is a Python bytearray, never real memory. Each pointer
carries the base and the bound of its block and the capability number of the
allocation. A load or a store checks the bounds and then asks the capability
store whether the allocation is still live.
"""
from dataclasses import dataclass
class AccessError(Exception):
"""A checked access, free or arithmetic step was refused."""
class SpatialError(AccessError):
"""The access is outside the bounds that the pointer carries."""
class TemporalError(AccessError):
"""The allocation of the pointer was freed."""
@dataclass(frozen=True)
class FatPointer:
"""A pointer value with the bounds [base, bound) and a capability number.
The capability 0 is never issued, so the null pointer (0, 0, 0, 0) fails
every check.
"""
value: int
base: int
bound: int
cap: int
NULL = FatPointer(0, 0, 0, 0)
class FatPointerHeap:
"""A first-fit heap of size bytes whose pointers are fat pointers.
alloc costs O(h) for h holes in the free list; add, load and store cost
O(1) plus one lookup in the capability store (a Python set, O(1)
expected); free costs O(h) for the coalescing.
"""
def __init__(self, size: int = 256) -> None:
if size < 1:
raise ValueError("size must be positive")
self.mem = bytearray(size)
self.holes: list[tuple[int, int]] = [(1, size - 1)] # address 0 stays unused
self.live: dict[int, tuple[int, int]] = {} # capability -> (base, bound)
self.next_cap = 1
def alloc(self, n: int) -> FatPointer:
"""Allocate n >= 1 bytes, zeroed. Return NULL when no hole is large enough."""
if n < 1:
raise ValueError("n must be positive")
for i, (start, length) in enumerate(self.holes):
if length >= n:
break
else:
return NULL
base = start # @line L1: first fit
if length == n:
del self.holes[i]
else:
self.holes[i] = (start + n, length - n)
cap = self.next_cap # @line L2: a fresh capability, never reused
self.next_cap += 1
self.live[cap] = (base, base + n) # @line L3
self.mem[base:base + n] = bytes(n)
return FatPointer(base, base, base + n, cap) # @line L4
def add(self, p: FatPointer, k: int) -> FatPointer:
"""Pointer arithmetic p + k. It is not checked; the bounds go along."""
return FatPointer(p.value + k, p.base, p.bound, p.cap) # @line L5
def check(self, p: FatPointer, w: int) -> None:
"""Raise SpatialError or TemporalError unless p may access w bytes."""
if p.value < p.base or p.value + w > p.bound: # @line L6
raise SpatialError(f"access of {w} bytes at {p.value} outside [{p.base}, {p.bound})") # @line L7
if p.cap not in self.live: # @line L8
raise TemporalError(f"capability {p.cap} is not live") # @line L9
def load(self, p: FatPointer, w: int) -> int:
"""Read a little-endian unsigned integer of w bytes at p, after the check."""
self.check(p, w) # @line L10
return int.from_bytes(self.mem[p.value:p.value + w], "little") # @line L11
def store(self, p: FatPointer, w: int, v: int) -> None:
"""Write v (taken modulo 2^(8w)) as w little-endian bytes at p, after the check."""
self.check(p, w) # @line L10
self.mem[p.value:p.value + w] = (v % (1 << (8 * w))).to_bytes(w, "little") # @line L11
def free(self, p: FatPointer) -> None:
"""Free the block of p. p must point to the start of a live block."""
if p.value != p.base or p.bound <= p.base: # @line L12
raise SpatialError(f"free of {p.value}, which is not the start of a block")
if p.cap not in self.live: # @line L13
raise TemporalError(f"double free of capability {p.cap}")
del self.live[p.cap] # @line L14: every copy of p now fails line L8
self._release(p.base, p.bound - p.base) # @line L15
def _release(self, base: int, n: int) -> None:
"""Put [base, base + n) back into the sorted hole list and merge neighbours."""
holes = self.holes + [(base, n)]
holes.sort()
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:
"""Live blocks and holes are disjoint, inside the memory, and cover it."""
spans = sorted(list(self.live.values()) + [(s, s + l) for s, l in self.holes])
pos = 1
for lo, hi in spans:
assert lo == pos and hi > lo, (lo, hi, pos)
pos = hi
assert pos == len(self.mem)
assert all(c < self.next_cap and c > 0 for c in self.live)
test_fat_pointer.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fat-pointer/. The authors are listed in prov/QJJ3SE.jsonl.
import random
import pytest
from fat_pointer import NULL, FatPointer, FatPointerHeap, SpatialError, TemporalError
def test_page_example() -> None:
h = FatPointerHeap(64)
a = h.alloc(8)
assert a == FatPointer(1, 1, 9, 1)
b = h.alloc(4)
assert b == FatPointer(9, 9, 13, 2)
q = h.add(a, 6)
h.store(q, 2, 0x0102)
assert h.load(h.add(a, 7), 1) == 0x01
with pytest.raises(SpatialError):
h.store(q, 4, 7) # bytes 7 to 10, past the bound 9
r = h.add(a, 8) # one past the end: legal to form, not to use
with pytest.raises(SpatialError):
h.load(r, 1)
h.free(a)
c = h.alloc(8) # first fit reuses the block of a
assert c.base == a.base and c.cap == 3
with pytest.raises(TemporalError):
h.load(a, 1) # in bounds of the new block, but the capability is dead
assert h.load(c, 1) == 0
h.check_invariant()
def test_edges() -> None:
h = FatPointerHeap(16)
with pytest.raises(SpatialError):
h.load(NULL, 1)
with pytest.raises(SpatialError):
h.free(NULL)
a = h.alloc(15)
assert a.bound == 16
assert h.alloc(1) == NULL
with pytest.raises(SpatialError):
h.free(h.add(a, 1))
back = h.add(h.add(a, 40), -40) # far out and back: the bounds never changed
h.store(back, 1, 255)
assert h.load(a, 1) == 255
with pytest.raises(SpatialError):
h.load(h.add(a, -1), 1)
h.free(a)
with pytest.raises(TemporalError):
h.free(a)
h.check_invariant()
with pytest.raises(ValueError):
h.alloc(0)
def outcome(fn) -> str:
try:
fn()
except SpatialError:
return "spatial"
except TemporalError:
return "temporal"
return "ok"
def test_random_programs_against_object_oracle() -> None:
rng = random.Random(1994)
caught = {"spatial": 0, "temporal": 0}
for _ in range(600):
h = FatPointerHeap(rng.choice([48, 96, 256]))
objs: list[dict] = [] # the oracle: size, live flag and bytes of each object
fat: list[FatPointer] = []
ref: list[tuple[int | None, int]] = [] # the oracle pointer: (object, offset)
for _ in range(rng.randint(5, 40)):
op = rng.random()
if op < 0.25 or not fat:
n = rng.randint(1, 16)
p = h.alloc(n)
if p == NULL:
fat.append(p)
ref.append((None, 0))
else:
objs.append({"size": n, "live": True, "data": bytearray(n)})
fat.append(p)
ref.append((len(objs) - 1, 0))
elif op < 0.45:
i = rng.randrange(len(fat))
k = rng.randint(-20, 20)
fat.append(h.add(fat[i], k))
ref.append((ref[i][0], ref[i][1] + k))
elif op < 0.85:
i = rng.randrange(len(fat))
w = rng.choice([1, 2, 4])
oid, off = ref[i]
if oid is None or off < 0 or off + w > objs[oid]["size"]:
want = "spatial"
elif not objs[oid]["live"]:
want = "temporal"
else:
want = "ok"
if rng.random() < 0.5:
v = rng.randrange(1 << (8 * w))
got = outcome(lambda: h.store(fat[i], w, v))
if want == "ok":
objs[oid]["data"][off:off + w] = v.to_bytes(w, "little")
else:
box: list[int] = []
got = outcome(lambda: box.append(h.load(fat[i], w)))
if want == "ok":
assert box[0] == int.from_bytes(objs[oid]["data"][off:off + w], "little")
assert got == want
if want != "ok":
caught[want] += 1
else:
i = rng.randrange(len(fat))
oid, off = ref[i]
if oid is None or off != 0:
want = "spatial"
elif not objs[oid]["live"]:
want = "temporal"
else:
want = "ok"
got = outcome(lambda: h.free(fat[i]))
assert got == want
if want == "ok":
objs[oid]["live"] = False
h.check_invariant()
assert caught["spatial"] > 200 and caught["temporal"] > 50
History
Austin, Breach and Sohi described the safe pointer in 1994, with a spatial check against base and size and a temporal check against a capability store, and they called the result the detection of all pointer and array access errors. CCured (Necula, McPeak and Weimer, 2002) and Cyclone (Jim and others, 2002) put fat pointers into the types of a C-like language, and they reduced the cost by using thin pointers wherever the analysis or the programmer could show that no arithmetic happens. Later work moved the metadata out of the pointer to keep the memory layout (SoftBound, 2009) and into hardware (CHERI, 2014).
References
- 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, Section 3 (the safe pointer with value, base, size, storage class and capability, the spatial and the temporal check, and the capability store)
- George C. Necula, Scott McPeak and Westley Weimer, CCured, type-safe retrofitting of legacy code, POPL 2002, the SAFE, SEQ and WILD pointer kinds, and the inference that gives most pointers the cheap SAFE kind
- Trevor Jim, Greg Morrisett, Dan Grossman, Michael Hicks, James Cheney and Yanling Wang, Cyclone, a safe dialect of C, USENIX Annual Technical Conference 2002, the fat pointer type with bounds, and the never-null and thin pointer types beside it
- 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, Section on spatial safety (pointer-based bounds checking, fat pointers and the compatibility cost of a changed pointer layout)
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 | W4 complete |
|
Tag QJJ3SE Edit this page History Report an error Markdown