mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:08:38 +00:00
psocache_inspect: guard --entry bounds, zero-meta references, and header string slots
This commit is contained in:
@ -270,6 +270,115 @@ class PsocacheInspectTest(unittest.TestCase):
|
||||
self.assertEqual(p.returncode, 2)
|
||||
self.assertNotIn("Traceback", p.stderr)
|
||||
|
||||
def test_entry_pointing_past_meta_blob_does_not_crash_or_read_code_blob(self):
|
||||
meta_index_off = HEADER + GRAPHICS * 0x70 + COMPUTE * 0x18
|
||||
meta_off = meta_index_off + META_INDEX * 8 + SHADER_INDEX * 8
|
||||
code_off = meta_off + META_SIZE
|
||||
|
||||
# Subtest 1: entry pointing past EOF must report an out-of-range span, not raise struct.error.
|
||||
oob_eof = bytearray(build())
|
||||
struct.pack_into("<2I", oob_eof, meta_index_off, 0xFFFFFFFF, 32)
|
||||
p_eof = os.path.join(self.tmp.name, "oob_eof.cache")
|
||||
with open(p_eof, "wb") as f:
|
||||
f.write(oob_eof)
|
||||
r_eof = psocache_inspect.inspect(p_eof, with_meta=True, entry=0)
|
||||
self.assertEqual(r_eof["verdict"], "disagrees with the model")
|
||||
self.assertEqual(len(r_eof["meta_entry"]), 1)
|
||||
self.assertIn("points past", r_eof["meta_entry"][0])
|
||||
cli = run(p_eof, "--meta", "--entry", "0")
|
||||
self.assertEqual(cli.returncode, 1, cli.stderr)
|
||||
self.assertIn("points past", cli.stdout)
|
||||
self.assertNotIn("Traceback", cli.stderr)
|
||||
|
||||
# Subtest 2: entry spilling across meta_blob into code_blob must not decode code bytes as chunks.
|
||||
oob_spill = bytearray(build())
|
||||
struct.pack_into("<8I", oob_spill, code_off, 0x41, 0x300, 0, 0, 0, 0, 0, 0)
|
||||
struct.pack_into("<2I", oob_spill, meta_index_off + 8, META_SIZE, 32)
|
||||
p_spill = os.path.join(self.tmp.name, "oob_spill.cache")
|
||||
with open(p_spill, "wb") as f:
|
||||
f.write(oob_spill)
|
||||
r_spill = psocache_inspect.inspect(p_spill, with_meta=True, entry=1)
|
||||
self.assertIn("points past", r_spill["meta_entry"][0])
|
||||
self.assertFalse(any("0x41 kind=0x300" in line for line in r_spill["meta_entry"]))
|
||||
|
||||
def test_entry_rejected_when_meta_truncated_or_bad_arguments(self):
|
||||
with open(self.path, "r+b") as f:
|
||||
f.truncate(HEADER + GRAPHICS * 0x70 + COMPUTE * 0x18 + 8)
|
||||
with self.assertRaisesRegex(ValueError, "meta_index or meta_blob does not fit"):
|
||||
psocache_inspect.inspect(self.path, entry=0)
|
||||
cli = run(self.path, "--entry", "0")
|
||||
self.assertEqual(cli.returncode, 2)
|
||||
self.assertNotIn("Traceback", cli.stderr)
|
||||
|
||||
for kwargs in ({"entry": -1}, {"entry": True}, {"limit": True}, {"limit": False}):
|
||||
with self.subTest(kwargs=kwargs):
|
||||
with self.assertRaises(ValueError):
|
||||
psocache_inspect.inspect(self.path, **kwargs)
|
||||
|
||||
def test_references_checked_when_meta_index_is_empty(self):
|
||||
# 1 graphics + 1 compute record referencing meta index 0 while meta_index count is 0.
|
||||
size = HEADER + 0x70 + 0x18
|
||||
data = bytearray(size)
|
||||
data[0:4] = b"PS\x00\x09"
|
||||
data[0x04:0x09] = b"test\x00"
|
||||
data[0x24:0x27] = b"v1\x00"
|
||||
struct.pack_into("<4I", data, 0x50, 1, 1, 0, 0)
|
||||
struct.pack_into("<2I", data, 0x60, 0, 0)
|
||||
# Graphics record: one non-hole reference (0 at +8), five 0xFFFFFFFF holes.
|
||||
struct.pack_into("<2I", data, HEADER + 8, 0, 0xFFFFFFFF)
|
||||
struct.pack_into("<4I", data, HEADER + 0x50, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)
|
||||
# Compute record: four references to 0 (all out of range for a 0-entry meta index).
|
||||
p_bad = os.path.join(self.tmp.name, "zero_meta_bad.cache")
|
||||
with open(p_bad, "wb") as f:
|
||||
f.write(data)
|
||||
r = psocache_inspect.inspect(p_bad)
|
||||
self.assertEqual(
|
||||
r["references"],
|
||||
{"limit": 0, "graphics_out_of_range": 1, "compute_out_of_range": 4},
|
||||
)
|
||||
self.assertEqual(r["verdict"], "disagrees with the model")
|
||||
self.assertEqual(run(p_bad).returncode, 1)
|
||||
|
||||
# Graphics record with only 0xFFFFFFFF holes and 0 compute records holds even with 0 meta entries.
|
||||
hole_data = bytearray(HEADER + 0x70)
|
||||
hole_data[0:4] = b"PS\x00\x09"
|
||||
hole_data[0x04:0x09] = b"test\x00"
|
||||
hole_data[0x24:0x27] = b"v1\x00"
|
||||
struct.pack_into("<4I", hole_data, 0x50, 1, 0, 0, 0)
|
||||
struct.pack_into("<2I", hole_data, 0x60, 0, 0)
|
||||
struct.pack_into("<2I", hole_data, HEADER + 8, 0xFFFFFFFF, 0xFFFFFFFF)
|
||||
struct.pack_into("<4I", hole_data, HEADER + 0x50, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)
|
||||
p_ok = os.path.join(self.tmp.name, "zero_meta_holes.cache")
|
||||
with open(p_ok, "wb") as f:
|
||||
f.write(hole_data)
|
||||
r_ok = psocache_inspect.inspect(p_ok)
|
||||
self.assertEqual(
|
||||
r_ok["references"],
|
||||
{"limit": 0, "graphics_out_of_range": 0, "compute_out_of_range": 0},
|
||||
)
|
||||
self.assertEqual(r_ok["verdict"], "model holds")
|
||||
|
||||
def test_unterminated_header_strings_bounded_to_slots(self):
|
||||
for off, stop, fill in ((0x04, 0x24, b"A"), (0x24, 0x48, b"B")):
|
||||
with self.subTest(offset=hex(off)):
|
||||
data = bytearray(build())
|
||||
data[off:stop] = fill * (stop - off)
|
||||
path = os.path.join(self.tmp.name, f"unterm_{off:x}.cache")
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
r = psocache_inspect.inspect(path)
|
||||
entry = next(s for s in r["header_strings"] if s["offset"] == off)
|
||||
self.assertEqual(entry["length"], 0)
|
||||
self.assertEqual(r["verdict"], "disagrees with the model")
|
||||
self.assertTrue(any(f"0x{off:x}" in prob and "NUL" in prob for prob in r["problems"]))
|
||||
|
||||
def test_parse_chunks_rejects_out_of_bounds_span(self):
|
||||
buf = struct.pack("<8I", 0x41, 0x300, 0, 0, 0, 0, 0, 0)
|
||||
self.assertEqual(psocache_inspect.parse_chunks(buf, 0, 0, 64), (None, None))
|
||||
self.assertEqual(psocache_inspect.parse_chunks(buf, 0, -4, 32), (None, None))
|
||||
self.assertEqual(psocache_inspect.parse_chunks(buf, -1, 0, 32), (None, None))
|
||||
self.assertIsNone(psocache_inspect.entry_chunks(buf, 0, 0, 64))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -56,6 +56,7 @@ S_END_PGM = b"\x00\x00\x81\xbf" # s_endpgm, 0xBF810000 little-endian
|
||||
S_CODE_END = b"\x00\x00\x9f\xbf" # s_code_end, 0xBF9F0000 little-endian
|
||||
HASH_OFF = 0x48
|
||||
STRING_OFFS = (0x04, 0x24)
|
||||
STRING_BOUNDS = ((0x04, 0x24), (0x24, HASH_OFF))
|
||||
COUNT_OFFS = (0x50, 0x54, 0x58, 0x5C)
|
||||
SIZE_OFFS = (0x60, 0x64)
|
||||
|
||||
@ -97,6 +98,8 @@ def parse_chunks(m, base, start, size):
|
||||
The first header length, in 4-byte steps, that covers the entry exactly with 32-byte chunks all of type
|
||||
0x41/0x42/0x43 wins. Returns ``(header_size, [(tag, word1), ...])`` or ``(None, None)`` when no length fits.
|
||||
"""
|
||||
if base < 0 or start < 0 or size < 0 or base + start + size > len(m):
|
||||
return None, None
|
||||
for header in range(0, ENTRY_HEADER_MAX + 1, 4):
|
||||
if size < header or (size - header) % CHUNK_SIZE:
|
||||
continue
|
||||
@ -267,8 +270,10 @@ def decode_meta(m, base, spans, limit=None):
|
||||
|
||||
def inspect(path, with_meta=False, entry=None, limit=None):
|
||||
"""Read ``path`` and return the report as a dict. Raises OSError/ValueError on unusable input."""
|
||||
if limit is not None and limit < 1:
|
||||
if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1):
|
||||
raise ValueError("--limit must be at least 1")
|
||||
if entry is not None and (isinstance(entry, bool) or not isinstance(entry, int) or entry < 0):
|
||||
raise ValueError("--entry must be 0 or more")
|
||||
with open(path, "rb") as fh:
|
||||
size = os.fstat(fh.fileno()).st_size
|
||||
if size < HEADER_SIZE:
|
||||
@ -297,12 +302,17 @@ def inspect(path, with_meta=False, entry=None, limit=None):
|
||||
report["sizes"] = sizes
|
||||
report["header_hash"] = m[HASH_OFF : HASH_OFF + 8].hex()
|
||||
report["header_strings"] = []
|
||||
for off in STRING_OFFS:
|
||||
end = m.find(b"\x00", off, HEADER_SIZE)
|
||||
report["header_strings"].append(
|
||||
{"offset": off, "length": (end - off) if end >= 0 else 0}
|
||||
)
|
||||
problems = []
|
||||
for off, stop in STRING_BOUNDS:
|
||||
end = m.find(b"\x00", off, stop)
|
||||
if end < 0:
|
||||
report["header_strings"].append({"offset": off, "length": 0})
|
||||
problems.append(
|
||||
"header string at 0x%x has no NUL terminator before 0x%x"
|
||||
% (off, stop)
|
||||
)
|
||||
else:
|
||||
report["header_strings"].append({"offset": off, "length": end - off})
|
||||
if any(
|
||||
m[off : off + 4] != b"\x00\x00\x00\x00"
|
||||
for off in range(0x68, HEADER_SIZE, 4)
|
||||
@ -355,7 +365,7 @@ def inspect(path, with_meta=False, entry=None, limit=None):
|
||||
if (
|
||||
regions["graphics"]["fits"]
|
||||
and regions["compute"]["fits"]
|
||||
and counts["meta_index"]
|
||||
and (counts["meta_index"] or counts["graphics"] or counts["compute"])
|
||||
):
|
||||
meta_limit = counts["meta_index"]
|
||||
bad_graphics = 0
|
||||
@ -471,7 +481,19 @@ def inspect(path, with_meta=False, entry=None, limit=None):
|
||||
"--entry %d is outside the %d-entry meta index"
|
||||
% (entry, len(entries))
|
||||
)
|
||||
report["meta_entry"] = describe_entry(m, meta_off, *entries[entry])
|
||||
a, b = entries[entry]
|
||||
if a + b > meta_size:
|
||||
report["meta_entry"] = [
|
||||
"entry offset 0x%x size %d: points past the 0x%x-byte meta blob"
|
||||
% (a, b, meta_size)
|
||||
]
|
||||
else:
|
||||
report["meta_entry"] = describe_entry(m, meta_off, a, b)
|
||||
elif entry is not None:
|
||||
raise ValueError(
|
||||
"--entry %d cannot be read because meta_index or meta_blob does not fit in the file"
|
||||
% entry
|
||||
)
|
||||
|
||||
# Shader index: (offset, size) pairs inside the code blob, in ascending offset order.
|
||||
if regions["shader_index"]["fits"] and regions["code_blob"]["fits"]:
|
||||
|
||||
Reference in New Issue
Block a user