Algorithmadvanced
Jones-Kelly bounds checking
Also called object table bounds checking, referent object bounds checking.
Keeps a table of live objects and checks that each pointer arithmetic result stays in the object the operand points to, or one past its end.
- Time
- O(log t) worst · amortized
- Space
- Θ(t) extra
- Where
- h = the number of holes in the free list; t = the number of live objects in the object table
- Model
- Word RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Richard W. M. Jones, Paul H. J. Kelly, 1997
Jones-Kelly bounds checking finds out-of-bounds pointers in C without changing the size or layout of pointers. The checker keeps a table of all live objects, with the base and the size of each. Each time the program computes a pointer by arithmetic, the checker finds the object that the operand points into, its referent object, and checks that the result is still inside that object or exactly one past its end. A result outside that range becomes the special value ILLEGAL, which cannot be used. Because pointers stay plain addresses, checked code and libraries compiled without checks can pass pointers to each other. The cost is a search in the object table on every pointer operation.
In plain words
Every allocated block is written into a register book: where it starts and how long it is. Pointers are left as plain addresses.
When the program moves a pointer, the checker looks the starting address up in the book and finds the block it is in. If the new address is still in that block, or just after its last byte, the move is fine. If it lands anywhere else, even inside some other block, the checker replaces it with a marker that means "bad pointer", and any later use of the marker stops the program.
When the program reads or writes, the checker looks the address up once more and checks that the whole access fits in the block.
Each block gets one spare byte at its end, so the address just after a block never looks like the start of the next one.
The problem
The input is a C program whose pointer operations are the allocation of an object, pointer arithmetic , loads and stores of bytes through a pointer, and free. The goal is to stop every access that leaves the object a pointer was derived from, the spatial part of memory safety, while each pointer stays a single address, so that its size, the layout of structures and the calling conventions do not change. A fat pointer solves the first part and breaks the second. The C standard permits a pointer to the elements of an array and to one past its last element, and nothing else, so a check at arithmetic time matches the language rule.
The algorithm
The checker keeps an object table of the live objects, each a pair of a base and a size, in a search tree keyed by . Every object occupies bytes: the extra pad byte at belongs to the object, so a pointer one past the end is inside and not at the start of the next object. ILLEGAL is a fixed value that is never the address of an object; Jones and Kelly use .
ALLOC(n)- 1
b ← a block of n + 1 bytes from the allocator ▷ one pad byte at b + n - 2
insert (b, n) into the object table T - 3
return b LOOKUP(p)- 4
return the object (b, n) in T with b ≤ p ≤ b + n, or none ADD(p, k)- 5
if p = ILLEGAL then report an error - 6
o ← LOOKUP(p) ▷ the referent object - 7
if o = none then return p + k ▷ unchecked memory: not checked - 8
if o.b ≤ p + k ≤ o.b + o.n then return p + k ▷ one past the end is allowed - 9
return ILLEGAL CHECK(p, w) ▷ before each load or store- 10
if p = ILLEGAL then report an error - 11
o ← LOOKUP(p) - 12
if o = none then report an error ▷ when all memory is in T - 13
if p + w > o.b + o.n then report an error FREE(p)- 14
if no object in T has base p then report an error - 15
delete (p, n) from T; return its n + 1 bytes to the allocator
Allocation. Lines L1 to L3 allocate one extra byte and record the object. Stack and static objects of checked code are recorded the same way when their scope starts and removed when it ends.
Arithmetic. Line L6 finds the referent object of the operand with a search in for the last base that is at most , then a test that . Line L8 accepts a result in , which covers every element and the one-past-the-end pointer. Line L9 marks every other result. Line L7 lets a pointer that is in no checked object, for example a pointer into memory of a library compiled without checks, go through unchecked.
Access. Line L13 checks the last byte of the access, so an access of bytes at the last element, or at the one-past-the-end pointer, is refused. In the original system, a pointer in no checked object is allowed at line L12, because it can point into unchecked memory; in a model where every object is in , as in the Python code, line L12 refuses it.
Free. Line L14 refuses a free of an address that is not the base of a live object, which catches a free of an interior pointer and many double frees.
Example
A heap of 64 bytes; address 0 is not used. The table shows each operation and the result.
| step | operation | result |
|---|---|---|
| 1 | ← ALLOC(8) | ; the object is bytes 1 to 8, the pad byte is 9 |
| 2 | ← ALLOC(4) | ; LOOKUP(9) is and LOOKUP(10) is |
| 3 | ADD(, 8) | 9, one past the end, allowed by line L8 |
| 4 | LOAD(9, 1) | error at line L13: |
| 5 | ADD(, 9) | ILLEGAL: 10 is outside , although it is the base of |
| 6 | ← ADD(, 6); STORE(, 4, 7) | error at line L13: |
| 7 | ADD(ADD(, 12), ) | the inner ADD gives ILLEGAL; the outer one is an error at line L5 |
| 8 | FREE(); LOAD(, 1) | error at line L12: address 1 is in no object |
| 9 | ← ALLOC(8); LOAD(, 1) | ; the old pointer now finds , and the load passes |
Step 5 shows why the check is against the referent object and not against all of memory: address 10 is valid memory, but not memory of the object that points into. Step 7 is a false alarm. C forbids the intermediate pointer, but real programs form it and come back, and they then stop with an error. Step 9 is a missed use after free: the checker knows objects, not allocations, so a dangling pointer into a new object looks valid.
Correctness
Assume that each pointer the program uses comes from ALLOC or ADD, that the objects in with their pad bytes are disjoint, and that the referent object of a pointer stays live while the pointer is used. Then by induction on the ADD steps, each pointer derived from an object is either ILLEGAL or in : ALLOC returns , and line L8 keeps a result only if it is in that range, which by disjointness LOOKUP maps back to the same object. So at an access, LOOKUP finds the object the pointer was derived from, and line L13 refuses exactly the accesses whose last byte is past . Every out-of-bounds access through such a pointer is reported, and every in-bounds access through a pointer that never left passes. The guarantee does not cover a pointer that left and came back, which line L9 marks, or a pointer whose object was freed.
Proof: Jones-Kelly checking catches every out-of-bounds access to a live referent objectfull
Setting. The program runs a finite sequence of ALLOC, ADD, LOAD, STORE and FREE from the main block. Every pointer it uses is the result of ALLOC or of ADD on a pointer it holds. For a pointer that ALLOC returned for allocation , or that ADD derived from such a pointer, we say that is derived from , and we write for its intended offset when ILLEGAL, where is the object of . The allocator returns blocks of bytes that do not overlap any block in use. ILLEGAL is never in a range of an object.
Lemma 1 (the table). After each operation the objects in are exactly the live allocations, and their closed ranges are pairwise disjoint. So LOOKUP returns the unique live object whose closed range holds , or none.
Proof. Line L2 inserts each allocation when it starts and line L15 deletes it when it is freed, so holds the live allocations. The range is the block of bytes that line L1 took, and the allocator gives disjoint blocks. Line L4 searches for that range.
Lemma 2 (derived pointers). Let be derived from allocation , and assume that was live during every ADD in the derivation of . Then $p = $ ILLEGAL or . If moreover every intermediate pointer of the derivation had intended offset in , then ILLEGAL.
Proof. By induction on the number of ADD steps. ALLOC returns in line L3. Now let $q = $ ADD with derived from , and live. If $p = $ ILLEGAL, line L5 reports an error and does not exist. Otherwise by the hypothesis, so by Lemma 1, line L6 returns , and line L7 does not apply. Line L8 returns if it lies in , and line L9 returns ILLEGAL otherwise. Either way the claim holds for . For the second part, if then , so line L8 returns and not ILLEGAL.
Theorem. Let be derived from allocation , let be live at an access of bytes through (it is then live during the whole derivation, since a freed allocation is never live again).
- If the access is out of bounds, that is, $p = $ ILLEGAL or or , then CHECK reports an error.
- If the access is in bounds and the derivation of never left , then CHECK passes.
Proof. (1) If $p = $ ILLEGAL, line L10 reports an error. Otherwise, by Lemma 2, , so and the access is out of bounds only if . By Lemma 1, line L11 returns , and line L13 reports the error.
(2) By Lemma 2, ILLEGAL and , so line L10 passes and line L11 returns , which is not none, so line L12 passes. The access is in bounds, so , and line L13 passes.
What is not claimed. If the derivation left and came back, line L9 made the pointer ILLEGAL and the access is refused although it is in bounds. If was freed and its block was given to a new allocation, LOOKUP finds the new object and the access can pass. Both cases appear in the example on the page.
Termination. Every operation runs a bounded number of lines, each LOOKUP searches a finite table, and the allocator scans a finite list of holes.
Complexity
With the object table in a splay tree, as in the original, each LOOKUP takes amortized time for live objects; a red-black tree gives in the worst case. ADD and CHECK each do one LOOKUP plus work. ALLOC and FREE add an insert or a delete in to the cost of the allocator, for first fit with holes. The table takes space, and each object one extra byte. The Python code keeps the table as a sorted list searched with binary search, so its inserts and deletes cost .
The search on every pointer operation is the main cost, and the reported slowdowns of this class of checker are large. Later work used the table less often, made it smaller, or replaced it with a constant-time lookup.
Properties
- Compatible. Pointers keep their size and meaning, so checked code can call unchecked libraries and the other way round.
- Spatial only. It does not track whether an allocation is live, only whether some live object holds the address.
- Checks arithmetic, not only access. It refuses a pointer as soon as it leaves its object, which is stricter than many programs expect.
- Online and deterministic. Each check uses only the current table.
Variants and improvements
- CRED. Ruwase and Lam replace ILLEGAL with an out-of-bounds object that holds the out-of-bounds address and its referent object. The OOB objects live in their own hash table, not in the object table. Arithmetic and comparisons on such a pointer consult that table, a pointer that comes back into its object becomes normal again, and freeing an object removes the OOB objects that refer to it. This removes the false alarm of step 7. To keep the cost low, CRED checks only string operations by default.
- Pool-based tables. Dhurjati and Adve split the object table into one table per memory pool, found by pointer analysis, so that each search runs on a much smaller tree.
- Baggy bounds. Baggy bounds checking pads each object to a power of two, so the referent object is found in constant time from a table indexed by the address.
- Shadow memory. AddressSanitizer drops the referent object altogether and asks a shadow memory whether each byte is addressable, which finds most but not all overflows in constant time.
- Per-pointer metadata. SoftBound keeps base and bound per pointer in a disjoint table, which handles sub-object bounds that an object table cannot see.
When to use it
Use an object-table checker when the program must stay binary compatible with code compiled without checks and when you want to catch arithmetic that leaves an object, not only accesses that fall in unallocated memory. It is a debugging tool: the cost of a tree search per pointer operation is too high for most production use. It does not find overflows inside an object, from one field of a structure into the next, because the table only knows whole objects. Use baggy bounds or AddressSanitizer when the speed matters more than the exact bounds, and add a temporal checker if you need to find use after free.
Pitfalls
- No pad byte. If line L1 allocates only bytes, the pointer one past the end of an object is the base of the next object, LOOKUP in line L6 returns the wrong object, and a later access through it passes. The pad byte keeps the ranges disjoint.
- Checking only the first byte. If line L13 tests instead of , a 4-byte store at the last byte writes 3 bytes past the object.
- Checking against all memory. If line L8 accepts any result in some live object, step 5 of the example passes and a pointer can move from one object into the next, which is exactly the overflow to stop. The test must use the object of the operand found in line L6.
- Treating ILLEGAL as an address. If line L10 is left out, an ILLEGAL value can fall inside an object in a memory model where it is a valid address, and a bad pointer passes. Pick a value that is never inside an object and test for it first.
- Expecting temporal safety. After a free and a new allocation at the same address, step 9 passes. Do not report the checker as a use-after-free detector.
Implementations
The Python code runs on a simulated heap, a bytearray with a first-fit allocator, and never reads real memory. The object table is a sorted list with binary search in place of the splay tree. The tests compare each result with an oracle that scans all live objects, and check two claims on random programs: every access out of bounds of a live object is caught, and every access through a pointer that never left its object passes.
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/jones-kelly-bounds-checking/. The authors are listed in prov/F1X4NS.jsonl.
"""Jones-Kelly bounds checking with an object table, on a simulated heap.
Pointers stay plain integers. The heap keeps a table of live objects. Pointer
arithmetic looks up the object of the operand and turns a result outside
[base, base + size] into ILLEGAL; a dereference looks up the object again and
checks that the access fits. Each object gets one pad byte, so the pointer one
past the end still belongs to its object.
The memory is a Python bytearray, never real memory. The object table is a
sorted list searched with bisect; the original uses a splay tree.
"""
from bisect import bisect_right, insort
ILLEGAL = -2 # the value that marks an out-of-bounds pointer, as in the original
class BoundsError(Exception):
"""An arithmetic step, an access or a free was refused."""
class JonesKellyHeap:
"""A first-fit heap whose objects are recorded in an object table.
With t live objects and h holes: alloc costs O(h + t) here (O(h + log t)
with a balanced tree), add and the access check cost O(log t), and free
costs O(h + t). Precondition: every pointer the program uses was returned
by alloc or add, or is ILLEGAL.
"""
def __init__(self, size: int = 256) -> None:
if size < 2:
raise ValueError("size must be at least 2")
self.mem = bytearray(size)
self.holes: list[tuple[int, int]] = [(1, size - 1)] # address 0 stays unused
self.bases: list[int] = [] # sorted bases of the live objects
self.size_of: dict[int, int] = {} # base -> size n (without the pad byte)
def alloc(self, n: int) -> int:
"""Allocate n >= 1 zeroed bytes plus one pad byte. Return 0 if nothing fits."""
if n < 1:
raise ValueError("n must be positive")
need = n + 1
for i, (start, length) in enumerate(self.holes):
if length >= need:
break
else:
return 0
b = start # @line L1: first fit, n + 1 bytes
if length == need:
del self.holes[i]
else:
self.holes[i] = (start + need, length - need)
insort(self.bases, b) # @line L2
self.size_of[b] = n
self.mem[b:b + need] = bytes(need)
return b # @line L3
def lookup(self, p: int) -> int | None:
"""The base of the live object [b, b + n] with b <= p <= b + n, or None."""
i = bisect_right(self.bases, p) - 1 # @line L4
if i >= 0 and p <= self.bases[i] + self.size_of[self.bases[i]]:
return self.bases[i]
return None
def add(self, p: int, k: int) -> int:
"""Pointer arithmetic p + k, checked against the object of p."""
if p == ILLEGAL: # @line L5
raise BoundsError("arithmetic on an ILLEGAL pointer")
b = self.lookup(p) # @line L6
if b is None: # @line L7: not in a checked object, so not checked
return p + k
if b <= p + k <= b + self.size_of[b]: # @line L8: one past the end is allowed
return p + k
return ILLEGAL # @line L9
def check(self, p: int, w: int) -> None:
"""Raise BoundsError unless the w bytes at p lie in one live object."""
if p == ILLEGAL: # @line L10
raise BoundsError("dereference of an ILLEGAL pointer")
b = self.lookup(p) # @line L11
if b is None: # @line L12: all simulated memory is checked
raise BoundsError(f"address {p} is in no live object")
if p + w > b + self.size_of[b]: # @line L13
raise BoundsError(f"access of {w} bytes at {p} past the end {b + self.size_of[b]}")
def load(self, p: int, w: int) -> int:
"""Read a little-endian unsigned integer of w bytes at p, after the check."""
self.check(p, w)
return int.from_bytes(self.mem[p:p + w], "little")
def store(self, p: int, w: int, v: int) -> None:
"""Write v modulo 2^(8w) as w little-endian bytes at p, after the check."""
self.check(p, w)
self.mem[p:p + w] = (v % (1 << (8 * w))).to_bytes(w, "little")
def free(self, p: int) -> None:
"""Free the object whose base is p."""
if p not in self.size_of: # @line L14
raise BoundsError(f"free of {p}, which is not the base of a live object")
n = self.size_of.pop(p) # @line L15
self.bases.remove(p)
self._release(p, n + 1)
def _release(self, base: int, n: int) -> None:
holes = sorted(self.holes + [(base, n)])
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:
"""Objects with their pad bytes and the holes tile the memory from address 1."""
assert self.bases == sorted(self.size_of)
spans = sorted([(b, b + self.size_of[b] + 1) for b in self.bases] + [(s, s + l) for s, l in self.holes])
pos = 1
for lo, hi in spans:
assert lo == pos and hi > lo
pos = hi
assert pos == len(self.mem)
test_jones_kelly_bounds_checking.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jones-kelly-bounds-checking/. The authors are listed in prov/F1X4NS.jsonl.
import random
import pytest
from jones_kelly_bounds_checking import ILLEGAL, BoundsError, JonesKellyHeap
def test_page_example() -> None:
h = JonesKellyHeap(64)
a = h.alloc(8)
b = h.alloc(4)
assert (a, b) == (1, 10) # bytes 1 to 8, pad byte 9, then b
assert h.lookup(9) == a and h.lookup(10) == b
end = h.add(a, 8)
assert end == 9 # one past the end: a legal value
with pytest.raises(BoundsError):
h.load(end, 1)
assert h.add(a, 9) == ILLEGAL # would point at b
q = h.add(a, 6)
h.store(q, 2, 0x0102)
with pytest.raises(BoundsError):
h.store(q, 4, 7) # 6 + 4 > 8
with pytest.raises(BoundsError):
h.add(h.add(a, 12), -12) # out and back: a false alarm
h.free(a)
with pytest.raises(BoundsError):
h.load(a, 1) # the address is in no object
c = h.alloc(8)
assert c == a
assert h.load(a, 1) == 0 # the old pointer now finds c: a missed use after free
h.check_invariant()
def test_edges() -> None:
h = JonesKellyHeap(16)
with pytest.raises(BoundsError):
h.load(ILLEGAL, 1)
with pytest.raises(BoundsError):
h.free(3)
a = h.alloc(14)
assert a == 1 and h.alloc(1) == 0
with pytest.raises(BoundsError):
h.free(a + 1)
assert h.add(a, -1) == ILLEGAL
assert h.add(0, 5) == 5 # a pointer outside every object is not checked by add
h.free(a)
with pytest.raises(BoundsError):
h.free(a)
with pytest.raises(ValueError):
h.alloc(0)
h.check_invariant()
def oracle_find(objs: list[dict], p: int) -> dict | None:
"""Linear scan over the live objects; [base, base + size] includes the pad byte."""
for o in objs:
if o["live"] and o["base"] <= p <= o["base"] + o["size"]:
return o
return None
def test_random_programs_against_object_oracle() -> None:
rng = random.Random(1997)
counts = {"caught": 0, "missed_uaf": 0, "false_alarm": 0, "ok": 0}
for _ in range(600):
h = JonesKellyHeap(rng.choice([40, 96, 200]))
objs: list[dict] = []
vals: list[int] = [] # the values the checked program holds
meta: list[tuple[int, int, bool]] = [] # (object, offset, never left [0, size])
for _ in range(rng.randint(5, 40)):
op = rng.random()
if op < 0.25 or not vals:
n = rng.randint(1, 12)
p = h.alloc(n)
if p:
for o in objs:
if o["live"]:
assert p + n + 1 <= o["base"] or o["base"] + o["size"] + 1 <= p
objs.append({"base": p, "size": n, "live": True, "data": bytearray(n)})
vals.append(p)
meta.append((len(objs) - 1, 0, True))
elif op < 0.45:
i = rng.randrange(len(vals))
k = rng.randint(-14, 14)
p = vals[i]
o = None if p == ILLEGAL else oracle_find(objs, p)
if p == ILLEGAL:
want = "error"
elif o is None or o["base"] <= p + k <= o["base"] + o["size"]:
want = p + k
else:
want = ILLEGAL
try:
got: int | str = h.add(p, k)
except BoundsError:
got = "error"
assert got == want
oid, off, _ = meta[i]
if got == "error" and objs[oid]["live"] and 0 <= off + k <= objs[oid]["size"]:
counts["false_alarm"] += 1 # out and back into the object
if got != "error":
oid, off, clean = meta[i]
noff = off + k
vals.append(got)
meta.append((oid, noff, clean and 0 <= noff <= objs[oid]["size"]))
elif op < 0.85:
i = rng.randrange(len(vals))
w = rng.choice([1, 2, 4])
p = vals[i]
o = None if p == ILLEGAL else oracle_find(objs, p)
want_ok = o is not None and p + w <= o["base"] + o["size"]
try:
if rng.random() < 0.5:
v = rng.randrange(1 << (8 * w))
h.store(p, w, v)
off = p - o["base"]
o["data"][off:off + w] = v.to_bytes(w, "little")
else:
got_v = h.load(p, w)
off = p - o["base"]
assert got_v == int.from_bytes(o["data"][off:off + w], "little")
got_ok = True
except BoundsError:
got_ok = False
assert got_ok == want_ok
oid, off, clean = meta[i]
intended = objs[oid]
if intended["live"]:
in_bounds = 0 <= off and off + w <= intended["size"]
if not in_bounds:
assert not got_ok # every spatial error on a live object is caught
counts["caught"] += 1
elif clean:
assert got_ok # no false alarm when the pointer never left
counts["ok"] += 1
elif not got_ok:
counts["false_alarm"] += 1
elif got_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)
got_ok = True
except BoundsError:
got_ok = False
assert got_ok == (o is not None)
if o is not None:
o["live"] = False
h.check_invariant()
assert counts["caught"] > 300 and counts["ok"] > 300
assert counts["false_alarm"] > 0 and counts["missed_uaf"] > 0
History
Jones and Kelly presented the scheme at AADEBUG in 1997 as a patch to GCC, with the goal of checking C programs while keeping the pointer representation, so that checked and unchecked modules could be linked together. Ruwase and Lam built CRED on it in 2004 and removed most false alarms with out-of-bounds objects. Dhurjati and Adve made the table searches faster with pool allocation, and Akritidis and others replaced the tree with a constant-time table in baggy bounds checking in 2009.
References
- Richard W. M. Jones and Paul H. J. Kelly, Backwards-compatible bounds checking for arrays and pointers in C programs, Third International Workshop on Automatic Debugging (AADEBUG) 1997, pages 13 to 25, the object table in a splay tree, the check of each pointer arithmetic result against the object of the operand, the extra byte after each object, and the value ILLEGAL
- Olatunji Ruwase and Monica S. Lam, A practical dynamic buffer overflow detector, NDSS 2004, pages 159 to 169, the out-of-bounds objects of CRED and the four steps for creating, checking and removing them
- Dinakar Dhurjati and Vikram Adve, Backwards-compatible array bounds checking for C with very low overhead, ICSE 2006, the use of automatic pool allocation to split the object table into small per-pool tables
- Periklis Akritidis, Manuel Costa, Miguel Castro and Steven Hand, Baggy bounds checking, USENIX Security Symposium 2009, the description of earlier referent-object schemes and the cost of their splay tree lookups
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 F1X4NS Edit this page History Report an error Markdown