tools/address_guard: match runtime 48-bit wraparound spans and header last_module field

Support 48-bit spans crossing 0 (both signed negative and unsigned 48-bit two's complement)
using chunk-level bit-range marking matching runtime/src/address_guard.h, add optional
last_module parameter to header(), and add unit + semantic regression tests verified with
address_guard_test and RTX 3060 run_address_guard_gpu_test.py.

AI-assisted: Antigravity gemini-4-neon.
This commit is contained in:
andretuta
2026-11-26 22:11:37 -03:00
parent d1dff7949b
commit 1524a0913a
3 changed files with 181 additions and 13 deletions

View File

@ -142,6 +142,9 @@ class TableModel(unittest.TestCase):
self.assertFalse(ag.passes(words, 0x80000, 0x6_0000_0000, 4)) # another chunk, nothing backed
self.assertTrue(ag.passes(words, 0x80000, 0x7fffc, 4)) # the arena, no lookup
self.assertFalse(ag.passes(words, 0x80000, 0x7fffc, 8)) # past the arena, page 0x80 unbacked
self.assertTrue(ag.passes(words, 0x80000, -0x2000, 4)) # third span: ends at 0 (wraps 2^48)
self.assertTrue(ag.passes(words, 0x80000, -0x1000, 4))
self.assertFalse(ag.passes(words, 0x80000, -0x3000, 4))
def test_negative_offsets(self):
"""A buffer below the arena (LEONIDA_IMPORT_BELOW_ARENA=1): its 48-bit offset, sign-extended."""
@ -150,6 +153,18 @@ class TableModel(unittest.TestCase):
self.assertFalse(ag.passes(words, 0x80000, (-0x1000) & ag.MASK48, 4))
self.assertFalse(ag.passes(words, 0x80000, (-4) & ag.MASK48, 8)) # wraps through 0: not the arena
def test_wrapping_spans_match_runtime(self):
"""Spans crossing 0 (negative signed or 48-bit unsigned) back both sides, matching AddressGuardTable::assign."""
for span in (((-0x1000) & ag.MASK48, 0x1000), (-0x1000, 0x1000)):
with self.subTest(span=span):
words = ag.table_words([span])
self.assertTrue(ag.page_backed(words, -0x1000))
self.assertTrue(ag.page_backed(words, 0))
self.assertFalse(ag.page_backed(words, -0x2000))
self.assertFalse(ag.page_backed(words, 0x1000))
self.assertTrue(ag.passes(words, 0x80000, -4, 8))
self.assertFalse(ag.passes(words, 0x80000, -0x1004, 8))
def test_full_block_when_out_of_room(self):
words = ag.table_words([(1 << 32, (1 << 32) + 1), (2 << 32, (2 << 32) + 1)], max_blocks=1)
self.assertTrue(ag.passes(words, 0x80000, 1 << 32, 4))

119
tests/test_address_guard.py Normal file
View File

@ -0,0 +1,119 @@
"""Unit tests for tools/address_guard.py parity with runtime/src/address_guard.h.
Standard library only; no GPU, no LLVM, no game files.
"""
import contextlib
import io
import os
import struct
import sys
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.join(ROOT, "tools")
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
import address_guard as ag # noqa: E402
GIB = 1 << 30
LIMIT = ag.RESERVED_END
class AddressGuardOracleTest(unittest.TestCase):
def test_header_layout_and_last_module(self):
raw_default = ag.header(LIMIT, 0x100000)
self.assertEqual(len(raw_default), 64)
self.assertEqual(struct.unpack("<QQQIIQ", raw_default[:40]), (ag.MAGIC, LIMIT, 0x100000, 0, 0, 0))
self.assertEqual(raw_default[40:], bytes(24))
raw_full = ag.header(LIMIT, -0x2000, refused=7, last=0xA0000, last_module=0x12345678)
self.assertEqual(
struct.unpack("<QQQIIQ", raw_full[:40]),
(ag.MAGIC, LIMIT, (-0x2000) & ((1 << 64) - 1), 7, 0x12345678, 0xA0000),
)
def test_empty_spans_produce_only_empty_and_full_blocks(self):
words = ag.table_words([(0x1000, 0x1000), (0, 0), (-0x2000, (-0x2000) & ag.MASK48)])
self.assertEqual(len(words), ag.L1 + 2 * ag.BLOCK_WORDS)
self.assertFalse(ag.page_backed(words, 0x1000))
self.assertFalse(ag.page_backed(words, -0x2000))
def test_signed_and_unsigned_wraparound_spans_match_cpp(self):
"""Matches runtime/test/address_guard_test.cpp::negative_and_wide."""
below = (-0x2000) & ag.MASK48
wrap = (-0x1000) & ag.MASK48
wide = 8 * GIB + 0x10000
for spans in (
[(below, below + 0x1000), (wrap, 0x1000), (wide, wide + 6 * GIB)],
[(-0x2000, -0x1000), (-0x1000, 0x1000), (wide, wide + 6 * GIB)],
):
with self.subTest(spans=spans):
words = ag.table_words(spans)
allocated = (len(words) - ag.L1) // ag.BLOCK_WORDS - 2
self.assertEqual(allocated, 4) # chunks 0, 2, 3, and 0xffff
self.assertTrue(ag.passes(words, LIMIT, below, 4))
self.assertTrue(ag.passes(words, LIMIT, -0x2000, 4))
self.assertTrue(ag.passes(words, LIMIT, -4, 8))
self.assertFalse(ag.passes(words, LIMIT, -0x3000, 4))
self.assertTrue(ag.passes(words, LIMIT, wide, 4))
self.assertTrue(ag.passes(words, LIMIT, wide + 4 * GIB, 4))
self.assertTrue(ag.passes(words, LIMIT, wide + 6 * GIB - 4, 4))
self.assertFalse(ag.passes(words, LIMIT, wide + 6 * GIB, 4))
self.assertFalse(ag.passes(words, LIMIT, wide - 4, 8))
def test_span_ending_at_zero_and_single_byte_below_zero(self):
words = ag.table_words([((-0x2000) & ag.MASK48, 0)])
self.assertTrue(ag.page_backed(words, -0x2000))
self.assertTrue(ag.page_backed(words, -1))
self.assertFalse(ag.page_backed(words, -0x3000))
self.assertFalse(ag.page_backed(words, 0))
one_byte = ag.table_words([(-1, 0)])
self.assertTrue(ag.page_backed(one_byte, -0x1000))
self.assertTrue(ag.page_backed(one_byte, -1))
self.assertFalse(ag.page_backed(one_byte, -0x2000))
self.assertFalse(ag.page_backed(one_byte, 0))
def test_word_boundary_bit_marking(self):
"""Exercise partial low word, full interior words, and partial high word inside one chunk."""
start = 0x1000 * 31 # page 31 (last bit of word 0)
end = 0x1000 * (64 + 2) # through page 65 (first 2 bits of word 2), covering all 32 bits of word 1
words = ag.table_words([(start, end)])
self.assertFalse(ag.page_backed(words, 0x1000 * 30))
for page in range(31, 66):
self.assertTrue(ag.page_backed(words, 0x1000 * page), f"page {page}")
self.assertFalse(ag.page_backed(words, 0x1000 * 66))
def test_max_blocks_overflow_gives_full_block(self):
words = ag.table_words([(4 * GIB, 4 * GIB + 1), (8 * GIB, 8 * GIB + 1)], max_blocks=1)
self.assertEqual(words[1], 2)
self.assertEqual(words[2], ag.FULL_BLOCK)
self.assertTrue(ag.passes(words, LIMIT, 4 * GIB, 4))
self.assertFalse(ag.passes(words, LIMIT, 4 * GIB + 0x1000, 4))
self.assertTrue(ag.passes(words, LIMIT, 8 * GIB + 0x5000, 4))
def test_cli_reports_wrapped_and_unbacked_checks(self):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = ag.main([
"0xfffffffff000:0x1000",
"--check", "-4", "8",
"--check", "0xffffffffe000", "4",
])
self.assertEqual(rc, 0)
out = buf.getvalue()
self.assertIn("2 level-2 block(s)", out)
self.assertIn("-0x4 +8: passes", out)
self.assertIn("0xffffffffe000 +4: refused", out)
buf2 = io.StringIO()
with contextlib.redirect_stdout(buf2):
rc2 = ag.main(["--check", "-4", "8", "--", "-0x1000:0x1000"])
self.assertEqual(rc2, 0)
self.assertIn("-0x4 +8: passes", buf2.getvalue())
if __name__ == "__main__":
unittest.main()

View File

@ -26,33 +26,67 @@ MASK48 = (1 << 48) - 1
EMPTY_BLOCK, FULL_BLOCK = 0, 1 # every table has them; allocated blocks start at 2
def header(limit, table_offset, refused=0, last=0):
def header(limit, table_offset, refused=0, last=0, last_module=0):
"""The 64-byte header: magic, arena size (offsets below it pass without a lookup), the table's address minus
heap_base (mod 2^64), the refusal count and the last refused offset, which the shaders write."""
return struct.pack("<QQQIIQ24x", MAGIC, limit, table_offset & ((1 << 64) - 1), refused, 0, last)
heap_base (mod 2^64), the refusal count, the last refusing module id, and the last refused offset, which the
shaders write."""
return struct.pack(
"<QQQIIQ24x",
MAGIC,
limit,
table_offset & ((1 << 64) - 1),
refused & 0xFFFFFFFF,
last_module & 0xFFFFFFFF,
last & ((1 << 64) - 1),
)
def _mark_pages(chunks, first, last):
"""Set the page bits for inclusive 48-bit page range [first, last] in per-chunk level-2 bitmaps."""
for chunk in range(first >> 20, (last >> 20) + 1):
bits = chunks.get(chunk)
if bits is None:
bits = [0] * BLOCK_WORDS
chunks[chunk] = bits
lo = max(first, chunk << 20) & 0xFFFFF
hi = min(last, (chunk << 20) | 0xFFFFF) & 0xFFFFF
w_lo, b_lo = lo >> 5, lo & 31
w_hi, b_hi = hi >> 5, hi & 31
if w_lo == w_hi:
bits[w_lo] |= ((1 << (b_hi - b_lo + 1)) - 1) << b_lo
else:
bits[w_lo] |= (0xFFFFFFFF << b_lo) & 0xFFFFFFFF
for w in range(w_lo + 1, w_hi):
bits[w] = 0xFFFFFFFF
bits[w_hi] |= (1 << (b_hi + 1)) - 1
def table_words(spans, max_blocks=None):
"""The table's words for backed [start, end) heap offset spans: level 1, then the level-2 blocks. A page is
backed when any byte of it is (a GPU page is mapped whole). Past `max_blocks` allocated blocks a chunk gets the
full block: everything in it passes, as the runtime does when it runs out of room (and logs it)."""
"""The table's words for backed [start, end) heap offset spans: level 1, then the level-2 blocks. Spans are
48-bit heap offsets and may wrap through 2^48 (for a negative offset below the arena, matching
runtime/src/address_guard.h). A page is backed when any byte of it is (a GPU page is mapped whole). Past
`max_blocks` allocated blocks a chunk gets the full block: everything in it passes, as the runtime does when
it runs out of room (and logs it)."""
chunks = {}
max_page = MASK48 >> 12
for start, end in spans:
if end <= start:
if ((end - start) & MASK48) == 0:
continue
for page in range((start & MASK48) >> 12, (((end - 1) & MASK48) >> 12) + 1):
chunks.setdefault(page >> 20, set()).add(page & 0xFFFFF)
first = (start & MASK48) >> 12
last = ((end - 1) & MASK48) >> 12
if first <= last:
_mark_pages(chunks, first, last)
else: # wraps through 2^48: two runs (runtime/src/address_guard.h)
_mark_pages(chunks, first, max_page)
_mark_pages(chunks, 0, last)
level1 = [EMPTY_BLOCK] * L1
blocks = []
for chunk in sorted(chunks):
if max_blocks is not None and len(blocks) >= max_blocks:
level1[chunk] = FULL_BLOCK
continue
bits = [0] * BLOCK_WORDS
for page in chunks[chunk]:
bits[page >> 5] |= 1 << (page & 31)
level1[chunk] = 2 + len(blocks)
blocks.append(bits)
blocks.append(chunks[chunk])
words = level1 + [0] * BLOCK_WORDS + [0xFFFFFFFF] * BLOCK_WORDS
for bits in blocks:
words += bits