Algorithmadvanced
Lock and key temporal checking
Also called CETS, compiler-enforced temporal safety, identifier-based temporal checking.
Gives each allocation a unique key and lock, copies the key with each pointer, and checks that the lock still holds the key at each access.
- Time
- Θ(1) worst
- Space
- Θ(a + s) extra
- Where
- a = the number of live allocations; h = the number of holes in the free list; 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, 2010
Lock and key temporal checking finds every use of a dangling pointer, a pointer to memory that was freed. Each allocation gets a key, a number that is never used again, and a lock, a memory word that holds the key while the allocation is live. Every pointer carries the key of its allocation and the address of its lock. Before an access, the checker compares the lock with the key. Free writes an invalid value into the lock, so every pointer into the allocation, wherever its copies are, fails the next check. The check is a load and a compare, with no search for the copies and no table of live objects. When pointers are stored in memory, their keys and locks go to a disjoint table, as in SoftBound, so the memory layout does not change.
In plain words
When a block of memory is handed out, it gets a fresh ticket number that will never be issued again. The number is written on a small board, the lock, that belongs to the block, and a copy of the number goes with every pointer into the block.
Before using a pointer, the program walks to the board and compares the numbers. If they match, the block is still in use. When the block is given back, the board is wiped. Every old pointer now shows a number that is not on the board, so every use after the free is caught.
Boards can be reused for new blocks, because the new block gets a new number. An old pointer still holds the old number and still fails.
The problem
The input is a C program with ALLOC, FREE, pointer arithmetic, loads and stores, and pointers stored in memory. The goal is temporal memory safety: every access through a pointer whose allocation was freed must be caught, even when the memory was reused by a new allocation, and so is a second free of the same allocation. Checking the address is not enough, because after reuse a dangling pointer points to a valid object, and that object is not the one the pointer was made for. A table of live objects, as in Jones-Kelly, cannot tell the two apart for the same reason.
The algorithm
is an array of lock words. A free lock and a lock of a freed allocation hold the value INVALID, and no key equals INVALID. A pointer in a register is a triple . maps the address of a pointer stored in memory to its key and lock.
ALLOC(n)- 1
b ← a block of n bytes from the allocator - 2
key ← next_key; next_key ← next_key + 1 ▷ never reused - 3
lock ← a free lock location ▷ lock locations are reused - 4
LOCKS[lock] ← key - 5
return (b, key, lock) ADD(p, k)- 6
return (p + k, p.key, p.lock) CHECK(p)- 7
if LOCKS[p.lock] ≠ p.key then - 8
report a temporal error LOAD(p, w) and STORE(p, w, v)- 9
CHECK(p) - 10
read or write the w bytes at p FREE(p)- 11
CHECK(p) ▷ a double free fails here - 12
LOCKS[p.lock] ← INVALID - 13
give back the lock location and the block STOREPTR(loc, q)- 14
CHECK(loc); write q at loc; META[loc] ← (q.key, q.lock) LOADPTR(loc)- 15
CHECK(loc); v ← the value at loc; return (v, META[loc]), or (v, 0, the null lock) if there is no entry
Keys and locks. Line L2 takes the next value of a counter, so two allocations never share a key. Line L3 can reuse a lock location, because what the check compares is the key in it. With 64-bit keys, the counter does not run out in practice.
The check. Line L7 is one load from the lock and one compare. It is correct for every copy of a pointer, because all copies carry the same key and lock address, and they read the same lock.
Free. Line L11 runs the check first, so a free through a dangling pointer, and a second free, are errors. Line L12 kills every pointer to the allocation at once. Compare this with dangling pointer nullification, which must find and change each pointer.
Stack and globals. A stack frame gets a key and a lock when it is entered and the lock is set to INVALID when it returns, so a pointer to a local variable that outlives its frame fails too. Globals share one lock that is never invalidated.
Example
A heap of 64 bytes with first fit; address 0 is not used. Lock location 0 is the null lock, which matches no key.
| step | operation | result |
|---|---|---|
| 1 | ← ALLOC(8) | , |
| 2 | ← ALLOC(4) | , a cell for one pointer |
| 3 | ← ADD(, 4); STOREPTR(, ) | memory at 9 holds 5; |
| 4 | FREE() | $\mathit{LOCKS}[1] = $ INVALID; lock 1 and the block go back |
| 5 | LOAD(, 1) | temporal error: |
| 6 | ← LOADPTR(); LOAD(, 1) | , the copy from memory; temporal error |
| 7 | ← ALLOC(8) | : the same block and the same lock location, key 3 |
| 8 | LOAD(, 1) | temporal error: the lock holds 3, the pointer holds 1 |
| 9 | FREE() | temporal error: a double free |
Step 6 shows that copies stored in memory are caught with no extra work at free. Step 8 shows why the key and not the lock decides: the old pointer reads a valid lock that now belongs to , and the key tells them apart.
Correctness
Every pointer derived from an allocation carries its key and lock address: ALLOC sets them, ADD copies them, and STOREPTR and LOADPTR keep them in . The lock of a live allocation holds its key, because only line L4 writes a key into a lock, and only line L12 writes to the lock of a live allocation. After free, the lock holds INVALID or the key of a later allocation, and both differ from the old key, because keys are never reused. So line L7 passes exactly when the allocation of the pointer is live. The proof, by induction on the operations, is in the correctness proof.
Proof: The lock and key check passes exactly when the allocation is livefull
Setting. The program runs a finite sequence of the operations of the main block. Every pointer it uses comes from ALLOC, ADD or LOADPTR of a location whose metadata entry was written by STOREPTR, and the program cannot write the key or the lock of a pointer. Allocation gets the key in line L2 and the lock location in line L3. A pointer belongs to if ALLOC returned it for , or ADD derived it from a pointer that belongs to , or LOADPTR loaded it from a location where STOREPTR last stored a pointer that belongs to . A pointer with the null lock and key 0 belongs to no allocation; the null lock holds a value that is not a key.
Lemma 1 (invariant K). After each operation:
(a) every pointer that belongs to has key and lock , and every entry written for such a pointer is ;
(b) the keys are distinct and none equals INVALID;
(c) if is live, , and no other live allocation has lock ;
(d) if is freed, is INVALID or the key of an allocation made after was freed.
Proof. By induction on the number of operations. At the start there are no allocations. Assume (a) to (d) before an operation.
- ALLOC, allocation . Line L2 takes the counter, which is larger than every earlier key and is not INVALID, so (b) holds. Line L3 takes a lock location that no live allocation holds, and line L4 writes to it, so (c) holds for and is unchanged for other live allocations. If was the lock of a freed allocation , its new value is the key of an allocation made after was freed, so (d) holds for . Line L5 returns a pointer with , which gives (a).
- ADD copies the key and the lock in line L6, so (a) holds for the result.
- STOREPTR and LOADPTR copy the key and the lock to and from in lines L14 and L15, so (a) holds. They write no lock.
- LOAD and STORE write no lock and no key.
- FREE with belonging to . If line L11 reports an error, nothing changes. Otherwise , and by (b) and (d) a freed could not pass, so is live. Line L12 writes INVALID to , which gives (d) for , and line L13 makes free. No other live allocation had lock by (c), so (c) still holds for them.
Theorem. For a pointer that belongs to allocation , CHECK passes exactly when is live. For a pointer that belongs to no allocation, CHECK fails.
Proof. By Lemma 1(a), and , so line L7 compares with . If is live, they are equal by (c), and the check passes. If was freed, is INVALID, which is not by (b), or the key of an allocation made after was freed, so and by (b). Either way line L8 reports a temporal error. A pointer that belongs to no allocation has the null lock, which holds a value that is not a key, while the pointer's key is 0, so line L7 fails.
Corollary. Every LOAD, STORE, STOREPTR and LOADPTR through a pointer of a freed allocation reports a temporal error, and so does every FREE of such a pointer, which includes every double free. This holds for all copies, in registers and in memory, without any search, and also after the block and the lock location are reused.
Termination. Every operation runs a bounded number of lines, apart from the search of the allocator, which scans a finite list of holes.
Complexity
The check is in the word RAM model: one load and one compare. ALLOC and FREE add to the cost of the allocator: a counter step, and taking or giving back a lock location from a free list of locks. A pointer load or store adds one access to , expected with a hash table. The lock space has one word for each live allocation and stack frame, and one entry for each location that holds a pointer. Each pointer in a register takes two extra words.
The run-time cost of a real system depends on the compiler, the benchmarks and how many checks static analysis can remove. It is a measurement and not a property of the scheme.
Properties
- Complete for temporal errors. Every access through a dangling pointer is caught, including after the memory is reused.
- No search at free. Free writes one word, whatever the number of copies of the pointer.
- Compatible layout. Pointers in memory stay one word; the key and lock live in disjoint metadata.
- Temporal only. A pointer that leaves its object is not caught; combine with SoftBound for spatial safety.
Variants and improvements
- Capability store. Austin, Breach and Sohi kept a capability number in each fat pointer and looked it up in a store of live capabilities. The lock replaces that lookup with a load from a known address.
- With spatial checks. The same metadata table can hold base, bound, key and lock, which gives full memory safety with one table lookup per pointer load or store.
- In hardware. The key and lock check can be done by the processor on each access, with the metadata in a shadow space.
- Probabilistic versions. Memory tagging keeps a small tag, a short key, in the pointer and in the memory itself. It needs no lock load but catches a reuse only with high probability, since tags repeat.
- Nullification. Dangling pointer nullification changes the pointers instead of the lock, so later accesses need no check, but it must track every pointer.
When to use it
Use lock and key checking when you need to catch every use after free and every double free, including after the memory is reused, and you can compile the whole program with the checks. It fits testing and hardened builds of C and C++ code where an exact answer matters more than speed. It needs metadata for every pointer, so code compiled without it, which copies pointers without their keys, produces pointers that fail or are not checked. If a probabilistic answer is enough, memory tagging or the quarantine of AddressSanitizer is cheaper.
Pitfalls
- Reusing keys. If line L2 takes a key from a pool of freed keys, a dangling pointer with the old key matches the lock of a new allocation, and step 8 passes. Keys must come from a counter.
- Checking the lock address instead of the key. If line L7 only tests that the lock location is in use, a pointer whose lock location was reused passes. Compare the value in the lock with the key.
- Free without the check. Without line L11, a double free writes INVALID into a lock that may now belong to another allocation, and that allocation's pointers then fail, far from the bug.
- Losing metadata through memory. If STOREPTR in line L14 does not write , a pointer loaded back in line L15 gets stale or missing metadata. Every store of a pointer, including those in copies of whole structures, must update the table.
- Forgetting the stack. Without a lock per frame, a pointer to a local variable that is used after the function returns is not caught.
Implementations
The Python code runs on a simulated heap, a bytearray with a first-fit allocator, a list of lock words and a dictionary as the metadata table, and never reads real memory. The tests keep all accesses in bounds, so that only temporal errors appear, and compare every check with an oracle that tracks whether the object of each pointer is live. They count uses after free with and without reuse of the memory, and double frees.
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/lock-and-key-temporal-checking/. The authors are listed in prov/NYGPH2.jsonl.
"""Lock and key temporal checking on a simulated heap.
Each allocation gets a key that is never reused and a lock location that holds
the key while the allocation is live. A pointer carries the key and the
address of the lock. An access is allowed only if the lock still holds the
key; free overwrites the lock, so every copy of every pointer into the
allocation fails at once, with no search for the copies. Pointers stored in
memory keep their key and lock in a disjoint table keyed by the address where
the pointer is stored, so the memory layout does not change.
The memory is a Python bytearray, never real memory. This checks temporal
safety only; spatial checks are a separate layer.
"""
from dataclasses import dataclass
WORD = 4 # bytes in a stored pointer
INVALID = 0 # the value free writes to a lock; no key is 0
class AccessError(Exception):
"""An access or a free was refused."""
class TemporalError(AccessError):
"""The allocation of the pointer is no longer live."""
@dataclass(frozen=True)
class KeyedPtr:
"""A pointer in a register with the key of its allocation and the index of its lock."""
value: int
key: int
lock: int
NULL = KeyedPtr(0, 0, 0) # lock 0 holds -1, which matches no key
class LockAndKeyHeap:
"""A first-fit heap with a lock space and a disjoint pointer metadata table.
The check and pointer loads and stores cost O(1); alloc and free cost O(h)
for h holes in the free list, plus O(1) for the lock. Precondition: the
program makes pointers only with alloc, add, load_ptr and int_to_ptr.
"""
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.blocks: dict[int, tuple[int, int]] = {} # base -> (size, lock)
self.locks: list[int] = [-1] # the lock space; lock 0 belongs to no allocation
self.free_locks: list[int] = []
self.next_key = 1
self.meta: dict[int, tuple[int, int]] = {} # address of a stored pointer -> (key, lock)
def alloc(self, n: int) -> KeyedPtr:
"""Allocate n >= 1 zeroed bytes. Return NULL if 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
b = start # @line L1
if length == n:
del self.holes[i]
else:
self.holes[i] = (start + n, length - n)
key = self.next_key # @line L2: never reused
self.next_key += 1
if self.free_locks: # @line L3: lock locations are reused, keys are not
lock = self.free_locks.pop()
else:
lock = len(self.locks)
self.locks.append(INVALID)
self.locks[lock] = key # @line L4
self.blocks[b] = (n, lock)
self.mem[b:b + n] = bytes(n)
return KeyedPtr(b, key, lock) # @line L5
def add(self, p: KeyedPtr, k: int) -> KeyedPtr:
"""Pointer arithmetic: the key and the lock go along."""
return KeyedPtr(p.value + k, p.key, p.lock) # @line L6
def int_to_ptr(self, v: int) -> KeyedPtr:
"""A pointer made from an integer has no valid key."""
return KeyedPtr(v, 0, 0)
def check(self, p: KeyedPtr) -> None:
"""Raise TemporalError unless the allocation of p is live."""
if self.locks[p.lock] != p.key: # @line L7
raise TemporalError(f"key {p.key} does not match lock {p.lock}") # @line L8
def load(self, p: KeyedPtr, w: int) -> int:
self.check(p) # @line L9
return int.from_bytes(self.mem[p.value:p.value + w], "little") # @line L10
def store(self, p: KeyedPtr, w: int, v: int) -> None:
self.check(p) # @line L9
self.mem[p.value:p.value + w] = (v % (1 << (8 * w))).to_bytes(w, "little") # @line L10
def free(self, p: KeyedPtr) -> None:
"""Free the allocation of p; p must be live and point to its start."""
self.check(p) # @line L11: catches a double free
if p.value not in self.blocks or self.blocks[p.value][1] != p.lock:
raise AccessError(f"free of {p.value}, which is not the start of its allocation")
n, lock = self.blocks.pop(p.value)
self.locks[lock] = INVALID # @line L12: every copy of every pointer now fails L7
self.free_locks.append(lock) # @line L13
self._release(p.value, n)
def store_ptr(self, loc: KeyedPtr, q: KeyedPtr) -> None:
"""Store q at loc: the value in memory, the key and lock in the table."""
self.check(loc) # @line L14
self.mem[loc.value:loc.value + WORD] = (q.value % (1 << (8 * WORD))).to_bytes(WORD, "little")
self.meta[loc.value] = (q.key, q.lock)
def load_ptr(self, loc: KeyedPtr) -> KeyedPtr:
"""Load a pointer from loc with the key and lock stored for that address."""
self.check(loc) # @line L15
v = int.from_bytes(self.mem[loc.value:loc.value + WORD], "little")
key, lock = self.meta.get(loc.value, (0, 0))
return KeyedPtr(v, key, lock)
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:
"""Each live block owns one lock that holds a distinct key; free locks hold INVALID."""
owned = [lock for _, lock in self.blocks.values()]
assert len(set(owned)) == len(owned) and 0 not in owned
assert not set(owned) & set(self.free_locks)
keys = [self.locks[lock] for lock in owned]
assert len(set(keys)) == len(keys) and all(0 < k < self.next_key for k in keys)
assert all(self.locks[lock] == INVALID for lock in self.free_locks)
assert self.locks[0] == -1
spans = sorted([(b, b + n) for b, (n, _) in self.blocks.items()] + [(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_lock_and_key_temporal_checking.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lock-and-key-temporal-checking/. The authors are listed in prov/NYGPH2.jsonl.
import random
import pytest
from lock_and_key_temporal_checking import (
NULL,
WORD,
AccessError,
KeyedPtr,
LockAndKeyHeap,
TemporalError,
)
def test_page_example() -> None:
h = LockAndKeyHeap(64)
a = h.alloc(8)
assert a == KeyedPtr(1, 1, 1) and h.locks[1] == 1
cell = h.alloc(4)
assert cell == KeyedPtr(9, 2, 2)
q = h.add(a, 4)
h.store(q, 1, 7)
h.store_ptr(cell, q)
assert h.meta[9] == (1, 1)
h.free(a)
assert h.locks[1] == 0
with pytest.raises(TemporalError):
h.load(q, 1) # a copy in a register
r = h.load_ptr(cell)
assert r == q
with pytest.raises(TemporalError):
h.load(r, 1) # a copy that was stored in memory
c = h.alloc(8)
assert c == KeyedPtr(1, 3, 1) # same block, same lock location, new key
with pytest.raises(TemporalError):
h.load(a, 1) # the lock now holds 3, not 1
with pytest.raises(TemporalError):
h.free(a) # double free
assert h.load(c, 1) == 0
h.check_invariant()
def test_edges() -> None:
h = LockAndKeyHeap(16)
with pytest.raises(TemporalError):
h.load(NULL, 1)
with pytest.raises(TemporalError):
h.load(h.int_to_ptr(3), 1)
a = h.alloc(15)
assert h.alloc(1) == NULL
with pytest.raises(AccessError):
h.free(h.add(a, 2))
other = h.load_ptr(a) # no entry: no valid key
with pytest.raises(TemporalError):
h.load(other, 1)
h.free(a)
h.check_invariant()
with pytest.raises(ValueError):
h.alloc(0)
def test_random_programs_against_object_oracle() -> None:
rng = random.Random(2010)
counts = {"uaf": 0, "reuse": 0, "double": 0, "ok": 0}
for _ in range(600):
h = LockAndKeyHeap(rng.choice([48, 96, 200]))
objs: list[dict] = []
regs: list[KeyedPtr] = []
intent: list[tuple[int, int] | None] = [] # (object, offset) of each register pointer
slots: dict[int, tuple[int, int] | None] = {} # 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 reused(o: dict) -> bool:
return any(x["live"] and x["base"] < o["base"] + o["n"] and o["base"] < x["base"] + x["n"] for x in objs)
for _ in range(rng.randint(5, 50)):
op = rng.random()
if op < 0.2 or not regs:
n = rng.randint(1, 16)
p = h.alloc(n)
if p != NULL:
objs.append({"base": p.value, "n": n, "live": True, "data": bytearray(n)})
regs.append(p)
intent.append((len(objs) - 1, 0))
continue
i = rng.randrange(len(regs))
p, t = regs[i], intent[i]
if t is None: # loaded from a cell an integer store overwrote: not tracked
continue
o = objs[t[0]]
if op < 0.35:
k = rng.randrange(o["n"]) - t[1] # stay in bounds: only temporal errors happen
regs.append(h.add(p, k))
intent.append((t[0], t[1] + k))
elif op < 0.75:
w = rng.choice([1, 2, 4])
off = t[1]
w = min(w, o["n"] - off)
try:
if rng.random() < 0.5:
v = rng.randrange(1 << (8 * w))
h.store(p, w, v)
o["data"][off:off + w] = v.to_bytes(w, "little")
forget(p.value, w)
else:
assert h.load(p, w) == int.from_bytes(o["data"][off:off + w], "little")
ok = True
except TemporalError:
ok = False
assert ok == o["live"]
if not ok:
counts["reuse" if reused(o) else "uaf"] += 1
else:
counts["ok"] += 1
elif op < 0.85 and o["n"] - t[1] >= WORD:
j = rng.randrange(len(regs))
try:
h.store_ptr(p, regs[j])
ok = True
except TemporalError:
ok = False
assert ok == o["live"]
if ok:
o["data"][t[1]:t[1] + WORD] = (regs[j].value % (1 << 32)).to_bytes(WORD, "little")
forget(p.value, WORD)
slots[p.value] = intent[j]
elif op < 0.92 and o["n"] - t[1] >= WORD:
try:
q = h.load_ptr(p)
ok = True
except TemporalError:
ok = False
assert ok == o["live"]
if ok:
regs.append(q)
intent.append(slots.get(p.value))
else:
try:
h.free(p)
got = "ok"
except TemporalError:
got = "temporal"
except AccessError:
got = "interior"
want = "temporal" if not o["live"] else ("ok" if t[1] == 0 else "interior")
assert got == want
if got == "ok":
o["live"] = False
if got == "temporal":
counts["double"] += 1
h.check_invariant()
assert counts["uaf"] > 50 and counts["reuse"] > 50 and counts["double"] > 50 and counts["ok"] > 1000
History
Austin, Breach and Sohi gave each allocation a unique capability in 1994 and checked it against a store of live capabilities. Nagarakatte, Zhao, Martin and Zdancewic presented the lock and key scheme with disjoint metadata at ISMM 2010, as the temporal half of a design whose spatial half is SoftBound, and they showed that it catches all temporal errors at a cost low enough for testing. Later work from the same group and others moved the check into hardware, and memory tagging made a probabilistic version of the idea part of commercial processors.
References
- Santosh Nagarakatte, Jianzhou Zhao, Milo M. K. Martin and Steve Zdancewic, CETS, compiler enforced temporal safety for C, International Symposium on Memory Management (ISMM) 2010, pages 31 to 40, the sections on the key and lock of each allocation, the disjoint metadata for pointers in memory, the stack frames and globals, 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 capability of each allocation and the capability store that the temporal check looks up
- 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 disjoint metadata table that the temporal scheme shares
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 NYGPH2 Edit this page History Report an error Markdown