Data structurecore
Shadow memory
Also called memory shadowing.
A scaled copy of the address space that holds metadata for each byte or word, found from the address by a shift and an add.
- Time
- Θ(1) worst
- Space
- Θ(n / 2^k) extra
- Where
- c = log2 of the size of a chunk in the two-level table; k = log2 of the granule size, so one metadata byte covers 2^k bytes; n = the number of bytes of the application address space
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
Shadow memory is a second, smaller copy of the address space that holds metadata about the first. Each granule of application bytes has one metadata byte, and the address of that byte comes from the application address by a shift right by and an add of a fixed offset. A checker reads the shadow byte before each load or store and learns, in a constant number of instructions, whether the bytes are allocated, initialized, tagged or poisoned. AddressSanitizer, Valgrind's Memcheck, baggy bounds checking and many race and taint detectors are built on it. When the address space is large and sparse, a two-level table with shared read-only chunks takes the place of one flat region.
In plain words
Think of a large building with numbered rooms, and a small notebook at the front desk. Each line of the notebook is about a block of rooms, for example eight rooms in a row. To find the line about a room, you divide the room number by eight and look at that line. No search is needed.
The notebook line says what the checker needs to know about those rooms: whether anyone is allowed in, or how many of the rooms are open. A guard looks at the line before letting anyone through a door.
If the building is huge and most floors are empty, a full notebook wastes paper. Then there is one page per floor, and all empty floors share one pre-printed page. A floor gets its own page only when something on it changes.
The abstract type
Shadow memory is a total map from granules of the application address space to metadata values, here bytes from 0 to 255. Granule is the range , and the granule of address is . The operations are GET, the value of the granule of ; SET, which sets that value; and SETRANGE, which sets every granule in for granule-aligned and . Before any SET, every granule has a default value. The contract is that of an array indexed by granule: GET returns the value of the last SET that covered the granule, or the default.
Representation
Direct map. The application bytes are and the shadow bytes are in the same address space. The shadow byte of address is at . The region must not overlap the application region, and application code must never write to it; real systems reserve it and make it unreachable for normal code. In the Python code the whole space is one bytearray and .
Two-level table. For an address space of bytes, a primary table has entries, one for each chunk of application bytes. Each entry refers to a secondary chunk of metadata bytes. A distinguished chunk for a value is a read-only chunk in which every byte is ; many entries may share it. A private chunk belongs to one entry and may be written.
Invariant (S). For every granule , the stored byte for is the value of the map at : in the direct map it is the byte at ; in the two-level table it is byte of the chunk in entry . In addition, each distinguished chunk of value holds only .
Operations
SHADOW-ADDR(a) ▷ direct map- 1
return (a >> k) + off ▷ one shift and one add GET(a)- 2
return M[SHADOW-ADDR(a)] SET(a, v)- 3
M[SHADOW-ADDR(a)] ← v SETRANGE(lo, hi, v)- 4
for a ← lo, lo + 2^k, ..., hi - 2^k do - 5
SET(a, v) TWO-LEVEL GET(a) and SET(a, v)- 6
i ← a >> c ▷ the high bits pick the chunk - 7
j ← (a mod 2^c) >> k ▷ the low bits pick the byte GET returns P[i][j]; SET goes on:- 8
if P[i] is a distinguished chunk then ▷ never write a shared chunk - 9
P[i] ← a private copy of P[i] ▷ copy on write; skip if P[i][j] = v - 10
P[i][j] ← v TWO-LEVEL SETRANGE(lo, hi, v)- 11
for each whole chunk i inside [lo, hi) do - 12
P[i] ← the distinguished chunk of v ▷ drop the private copy - 13
for each granule left at the two ends do SET(a, v)
Direct map. Line L1 is the whole point of the structure: a shift and an add, with no branch and no memory access. GET and SET then touch one byte. SETRANGE runs lines L4 and L5 once per granule, which is how an allocator poisons or unpoisons a block.
Two-level GET and SET. Lines L6 and L7 split the address: the high bits index the primary table, and the next bits index the chunk. GET is two memory reads. SET first checks whether the chunk is shared. Line L9 copies it before the first write that changes a byte, so the other entries that share it still see the default. A write of the value already there needs no copy.
Two-level SETRANGE. Line L12 sets a whole chunk by pointing its entry at a distinguished chunk, in time, and this also gives back the private copy. Line L13 handles the partial chunks at the two ends granule by granule.
Example
Direct map, , , , default 0. The shadow is the 8 bytes .
| step | operation | result |
|---|---|---|
| 1 | SHADOW-ADDR(37) | |
| 2 | SETRANGE(16, 40, 5) | granules 2, 3 and 4 are set; bytes are 0 0 5 5 5 0 0 0 |
| 3 | GET(15), GET(16), GET(39), GET(40) | 0, 5, 5, 0 |
| 4 | the program writes 99 to address 20 | the shadow does not change; GET(20) is still 5 |
Two-level table, , , , default 1. The primary table has 256 entries, each chunk has 32 bytes, and at the start all 256 entries share the distinguished chunk of 1.
| step | operation | result |
|---|---|---|
| 1 | GET(0x1234) | , ; the value is 1 |
| 2 | SET(0x1234, 1) | the value is already 1, so no copy; 0 private chunks |
| 3 | SET(0x1234, 7) | entry 0x12 gets a private copy and byte 6 becomes 7; 1 private chunk |
| 4 | GET(0x1230), GET(0x1238) | 7 (the same granule), 1 (the next granule) |
| 5 | SETRANGE(0x1200, 0x1300, 1) | a whole chunk: entry 0x12 points at the distinguished chunk again; 0 private chunks |
Correctness
Each operation keeps invariant (S). In the direct map, is one to one, so SET of one granule changes the stored byte of that granule only, and the application region does not overlap the shadow, so no application write changes a stored byte. In the two-level table, line L9 makes the chunk private before line L10 writes it, so no distinguished chunk is ever written, and the other entries that shared it keep their values. Line L12 sets every granule of a whole chunk to at once. Then GET reads the stored byte of the granule, which by (S) is the value of the map. The proof is in the correctness proof.
Proof: Shadow memory returns the last value set for each granulefull
Setting. Let . The abstract state is a map from granules to bytes, with for every at the start, where is the default. SET changes to . SETRANGE, for multiples of , sets for every with . GET must return . Application writes go to addresses in and do not change .
Lemma 1 (direct map). Let . Before and after each operation, for every granule .
Proof. By induction on the number of operations. At the start the constructor writes to every byte of , so the claim holds. The map is one to one, and its image is disjoint from because .
- SET writes in lines L1 and L3. That is the stored byte of and of no other granule, so after the write the claim holds for with value and is unchanged for every other .
- SETRANGE runs SET in line L5 for , whose granules are exactly the with . Each step keeps the claim by the case above.
- GET writes nothing.
- An application write changes a byte in , which is not a stored byte.
Lemma 2 (two-level table). Let and . Before and after each operation: (a) for every distinguished chunk , every byte of is ; (b) for every granule , ; (c) no two entries of refer to the same private chunk.
Proof. By induction. At the start every entry refers to , which holds only , so (a), (b) and (c) hold. For an address , lines L6 and L7 compute and . With we have and , so is the position of in (b), and distinct granules have distinct positions.
- SET. If is distinguished and , nothing changes and was already by (b). If is distinguished and , line L9 puts a new private copy in ; the copy has the same bytes, so (b) still holds, no distinguished chunk changes, and the copy is referred to by only, so (c) holds. Now is private, and line L10 writes byte of it. By (c), this changes position and no position of another entry, so (b) holds with and is unchanged elsewhere. A distinguished chunk is never written, so (a) holds.
- SETRANGE. Line L12 makes entry of each chunk inside the range refer to . By (a), every position of entry then holds , which is the new on all granules of that chunk. The private chunk it referred to, if any, is no longer referred to, so (c) holds. Line L13 handles the other granules of the range by SET, which keeps (a), (b) and (c) by the case above. Every granule of the range is covered once, by line L12 or by line L13, and no granule outside it is touched.
- GET writes nothing.
Theorem. In both representations, GET returns : the value of the last SET or SETRANGE that covered the granule of , or the default if there was none.
Proof. In the direct map, line L2 returns , which is by Lemma 1. In the two-level table, GET returns , which is by Lemma 2(b) and the computation of . By the definition of SET and SETRANGE on , that value is the one of the last operation that covered the granule, or .
Termination. Every operation is a bounded number of steps, except SETRANGE, which runs once per granule or chunk of the finite range, and the copy in line L9, which copies bytes.
Complexity
The costs are in the word RAM model.
| operation | direct map | two-level table |
|---|---|---|
| GET | : a shift, an add and a read | : two reads |
| SET | , or for the first change of a shared chunk | |
| SETRANGE over granules |
Space: the direct map reserves bytes, one eighth of the address space for , whether the memory is used or not. Real systems reserve this range of virtual addresses and let the operating system give physical pages only to the parts that are touched. The two-level table uses entries plus bytes for each changed chunk. The run-time cost of a checker built on shadow memory is a measurement of that checker on its benchmarks, and it is not a property of the structure.
Variants
- Granule size. With the shadow has one byte per byte, which can say exactly which bytes are addressable. With , AddressSanitizer stores in one byte how many of the first bytes of an 8-byte granule are addressable, which works because its allocator aligns blocks to 8 bytes. A larger granule saves space and loses precision at the ends of objects.
- Several bits per byte. Memcheck keeps an addressable bit for each byte and a defined bit for each bit of memory, and it compresses the common cases into 2 bits per byte in its shadow.
- A table per slot. Baggy bounds checking keeps one byte per 16-byte slot, holding the log of the size of the allocation that covers the slot.
- Tags in hardware. Memory tagging keeps a small tag for each 16-byte granule in storage that the hardware manages, and compares it with a tag in the pointer on each access.
- Multi-level tables. The two-level table is a two-level radix tree on the address bits. A 64-bit space needs more levels, or a hash table of chunks.
- Shadow for registers. Dynamic binary instrumentation frameworks also shadow each register, so that metadata follows a value through computation.
When to use it
Use shadow memory when a checker needs a few bits of state for every byte or word of memory and must find them on every access, with no search. It fits dynamic checkers and sanitizers that run in testing, where the program can reserve a large range of addresses. Use the direct map when you control the layout of the address space and can reserve the shadow region, and the two-level table when you cannot, or when most of the space is never used. If the metadata is per object rather than per byte, an object table such as the one of Jones-Kelly can be smaller, and if it is per pointer, a table keyed by the address of the pointer, as in SoftBound, is more precise.
Pitfalls
- An offset that lets the shadow overlap the application. If is too small, line L1 maps some application addresses into the shadow region itself, and a program write can change metadata. Choose so that and are disjoint.
- Writing a shared chunk. If line L8 is left out, line L10 writes the distinguished chunk, and every entry that shares it changes at once. The test in line L8 and the copy in line L9 must come before every write.
- An unaligned range. SETRANGE with or inside a granule sets the whole granule, so a few bytes outside the range get the new value. Line L4 assumes aligned ends; for an unaligned end, use a value that encodes the partial granule, as AddressSanitizer does.
- A multi-byte access across granules. One GET for the first byte of an access of bytes says nothing about a second granule. Check both granules, or align accesses so they stay inside one.
- Mixing up the shift. With and swapped in line L7, or with used as the index inside a chunk, the code reads the wrong byte and still passes on default values. Test with values that differ from the default.
Implementations
The Python code keeps both representations on a simulated address space, a bytearray for the direct map and a list of byte chunks for the two-level table, and never reads real memory. The tests compare both with a dictionary model on random sequences of SET and SETRANGE, and they also check that the number of private chunks stays at most the number of chunks that were changed.
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/shadow-memory/. The authors are listed in prov/ZD4SXZ.jsonl.
"""Shadow memory on a simulated address space.
Two representations of the same abstract type: a map from each granule of
2^k bytes of application memory to one metadata byte.
- DirectShadow: the shadow lives in the same simulated memory, at
(a >> k) + offset, as in AddressSanitizer.
- TwoLevelShadow: a primary table of chunk references; every chunk starts as a
shared, read-only distinguished chunk and is copied on the first write that
changes it, as in Valgrind's Memcheck.
Nothing here touches real memory: the address space is a Python bytearray.
"""
class DirectShadow:
"""Application bytes [0, size) and their shadow at [offset, offset + size >> k).
Every operation costs O(1) per granule; the space is size / 2^k bytes.
"""
def __init__(self, size: int, k: int, default: int = 0) -> None:
if k < 0 or size < 1 or size % (1 << k):
raise ValueError("size must be a positive multiple of 2^k")
self.size = size
self.k = k
self.offset = size # the shadow region starts right after the application region
self.mem = bytearray(size + (size >> k)) # one simulated address space
for g in range(size >> k):
self.mem[self.offset + g] = default
def shadow_addr(self, a: int) -> int:
"""The address of the metadata byte of application address a."""
if not 0 <= a < self.size:
raise IndexError(f"address {a} is not an application address")
return (a >> self.k) + self.offset # @line L1: one shift and one add
def get(self, a: int) -> int:
"""The metadata of the granule that holds a."""
return self.mem[self.shadow_addr(a)] # @line L2
def set(self, a: int, v: int) -> None:
"""Set the metadata of the granule that holds a to v (0 to 255)."""
self.mem[self.shadow_addr(a)] = v # @line L3
def set_range(self, lo: int, hi: int, v: int) -> None:
"""Set the metadata of every granule of [lo, hi); lo and hi are multiples of 2^k."""
g = 1 << self.k
if lo % g or hi % g or lo > hi:
raise ValueError("the range must be granule aligned")
for a in range(lo, hi, g): # @line L4
self.set(a, v) # @line L5
class TwoLevelShadow:
"""A sparse shadow for an address space of 2^bits bytes.
The primary table has 2^(bits - c) entries, one for each chunk of 2^c
application bytes. A chunk holds 2^(c - k) metadata bytes. get costs O(1);
set costs O(1), or O(2^(c - k)) when it copies a distinguished chunk.
Space: the primary table plus one chunk for each chunk that was changed.
"""
def __init__(self, bits: int, c: int, k: int, default: int = 0) -> None:
if not 0 <= k <= c <= bits:
raise ValueError("need 0 <= k <= c <= bits")
self.bits, self.c, self.k = bits, c, k
self.per_chunk = 1 << (c - k)
self.dsm: dict[int, bytes] = {} # distinguished chunks, shared and read-only
self.primary: list[bytes | bytearray] = [self._distinguished(default)] * (1 << (bits - c))
def _distinguished(self, v: int) -> bytes:
if v not in self.dsm:
self.dsm[v] = bytes([v]) * self.per_chunk
return self.dsm[v]
def get(self, a: int) -> int:
"""The metadata of the granule that holds a, 0 <= a < 2^bits."""
chunk = self.primary[a >> self.c] # @line L6: the high bits pick the chunk
return chunk[(a & ((1 << self.c) - 1)) >> self.k] # @line L7: the low bits pick the byte
def set(self, a: int, v: int) -> None:
"""Set the metadata of the granule that holds a."""
i = a >> self.c # @line L6
chunk = self.primary[i]
j = (a & ((1 << self.c) - 1)) >> self.k # @line L7
if isinstance(chunk, bytes): # @line L8: a distinguished chunk is never written
if chunk[j] == v:
return
chunk = bytearray(chunk) # @line L9: copy on write
self.primary[i] = chunk
chunk[j] = v # @line L10
def set_range(self, lo: int, hi: int, v: int) -> None:
"""Set every granule of [lo, hi); lo and hi are multiples of 2^k.
A whole chunk inside the range goes back to the distinguished chunk of
v, which frees its private copy.
"""
g, cs = 1 << self.k, 1 << self.c
if lo % g or hi % g or lo > hi:
raise ValueError("the range must be granule aligned")
a = lo
while a < hi:
if a % cs == 0 and a + cs <= hi: # @line L11
self.primary[a >> self.c] = self._distinguished(v) # @line L12
a += cs
else:
self.set(a, v) # @line L13
a += g
def private_chunks(self) -> int:
"""The number of chunks that hold a private copy."""
return sum(1 for ch in self.primary if isinstance(ch, bytearray))
def check_invariant(self) -> None:
"""Distinguished chunks still hold only their own value."""
for v, ch in self.dsm.items():
assert isinstance(ch, bytes) and ch == bytes([v]) * self.per_chunk
for ch in self.primary:
assert len(ch) == self.per_chunk
test_shadow_memory.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shadow-memory/. The authors are listed in prov/ZD4SXZ.jsonl.
import random
import pytest
from shadow_memory import DirectShadow, TwoLevelShadow
def test_page_example_direct() -> None:
s = DirectShadow(64, 3)
assert s.offset == 64 and len(s.mem) == 72
assert s.shadow_addr(37) == 68
assert s.shadow_addr(0) == 64 and s.shadow_addr(63) == 71
s.set_range(16, 40, 5)
assert [s.get(a) for a in (15, 16, 39, 40)] == [0, 5, 5, 0]
assert list(s.mem[64:72]) == [0, 0, 5, 5, 5, 0, 0, 0]
s.mem[20] = 99 # an application write does not touch the shadow
assert s.get(20) == 5
def test_page_example_two_level() -> None:
t = TwoLevelShadow(bits=16, c=8, k=3, default=1)
assert len(t.primary) == 256 and t.per_chunk == 32
assert t.get(0x1234) == 1 and t.private_chunks() == 0
t.set(0x1234, 1) # the same value: no copy
assert t.private_chunks() == 0
t.set(0x1234, 7)
assert t.private_chunks() == 1 and t.get(0x1234) == 7 and t.get(0x1238) == 1
assert t.get(0x1230) == 7 # same granule of 8 bytes
t.set_range(0x1200, 0x1300, 1)
assert t.private_chunks() == 0 and t.get(0x1234) == 1
t.check_invariant()
def test_edges() -> None:
with pytest.raises(ValueError):
DirectShadow(60, 3)
s = DirectShadow(8, 0)
s.set(7, 255)
assert s.get(7) == 255 and s.shadow_addr(7) == 15
with pytest.raises(IndexError):
s.get(8)
with pytest.raises(ValueError):
DirectShadow(64, 3).set_range(3, 16, 1)
t = TwoLevelShadow(bits=4, c=4, k=0)
t.set_range(0, 16, 9)
assert all(t.get(a) == 9 for a in range(16)) and t.private_chunks() == 0
def test_random_against_dict_model() -> None:
rng = random.Random(2007)
for _ in range(500):
k = rng.randint(0, 3)
c = rng.randint(k, 6)
bits = rng.randint(c, 8)
size = 1 << bits
default = rng.randint(0, 3)
d = DirectShadow(size, k, default)
t = TwoLevelShadow(bits, c, k, default)
model: dict[int, int] = {}
for _ in range(rng.randint(1, 30)):
if rng.random() < 0.6:
a = rng.randrange(size)
v = rng.randint(0, 3)
d.set(a, v)
t.set(a, v)
model[a >> k] = v
else:
g = 1 << k
lo = rng.randrange(0, size // g + 1) * g
hi = rng.randrange(lo // g, size // g + 1) * g
v = rng.randint(0, 3)
d.set_range(lo, hi, v)
t.set_range(lo, hi, v)
for a in range(lo, hi, g):
model[a >> k] = v
t.check_invariant()
for a in range(size):
want = model.get(a >> k, default)
assert d.get(a) == want
assert t.get(a) == want
assert d.mem[:size] == bytearray(size)
assert t.private_chunks() <= len({g >> (c - k) for g in model})
History
Shadow values go back to the early dynamic checkers for memory errors, such as Purify in the early 1990s, which kept state bits for each byte of memory. Nethercote and Seward described the two-level table of Valgrind's Memcheck, with its distinguished secondary maps, in 2007. Serebryany and others made the direct map with one byte per 8 bytes and a fixed offset the core of AddressSanitizer in 2012, which made a shadow check cheap enough to run in large test suites. The same layout now holds the metadata of many sanitizers for races, uninitialized reads and type errors.
References
- Nicholas Nethercote and Julian Seward, How to shadow every byte of memory used by a program, VEE 2007, pages 65 to 74, the two-level shadow table of Memcheck, the distinguished secondary maps and their copy on write
- Konstantin Serebryany, Derek Bruening, Alexander Potapenko and Dmitry Vyukov, AddressSanitizer, a fast address sanity checker, USENIX Annual Technical Conference 2012, pages 309 to 318, the section on the shadow memory (one shadow byte for 8 application bytes, at the address shifted right by 3 plus an offset)
- Nicholas Nethercote and Julian Seward, Valgrind, a framework for heavyweight dynamic binary instrumentation, PLDI 2007, the shadow values that the framework keeps for registers and memory
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 ZD4SXZ Edit this page History Report an error Markdown