mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
fix(tools): address all 7 CodeRabbit findings on gpu_stage_engine_worklist
This commit is contained in:
@ -1,4 +1,7 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@ -24,18 +27,28 @@ class TestGpuStageEngineWorklist(unittest.TestCase):
|
||||
mod = _load_mod()
|
||||
self.assertTrue(callable(mod.main))
|
||||
|
||||
def test_wrapper_slot_decoder_via_objdump(self):
|
||||
def test_wrapper_slot_decoder_via_mocked_objdump_and_indexed_load(self):
|
||||
mod = _load_mod()
|
||||
real_check_output = mod.subprocess.check_output
|
||||
objdump_outputs = {
|
||||
bytes.fromhex("488b4030"): " 0:\t48 8b 40 30\tmov rax,QWORD PTR [rax+0x30]\n",
|
||||
bytes.fromhex("488b8080000000"): " 0:\t48 8b 80 80 00 00 00\tmov rax,QWORD PTR [rax+0x80]\n",
|
||||
bytes.fromhex("488b00"): " 0:\t48 8b 00\tmov rax,QWORD PTR [rax]\n",
|
||||
bytes.fromhex("488b4030488b04c8c3"): (
|
||||
" 0:\t48 8b 40 30\tmov rax,QWORD PTR [rax+0x30]\n"
|
||||
" 4:\t48 8b 04 c8\tmov rax,QWORD PTR [rax+rcx*8]\n"
|
||||
" 8:\tc3\tret\n"
|
||||
),
|
||||
}
|
||||
objdump_calls = []
|
||||
|
||||
def spy_check_output(cmd, *args, **kwargs):
|
||||
def fake_check_output(cmd, *args, **kwargs):
|
||||
objdump_calls.append(cmd[0])
|
||||
return real_check_output(cmd, *args, **kwargs)
|
||||
raw = Path(cmd[-1]).read_bytes()
|
||||
return objdump_outputs[raw]
|
||||
|
||||
with (
|
||||
mock.patch.dict(sys.modules, {"capstone": None}),
|
||||
mock.patch.object(mod.subprocess, "check_output", side_effect=spy_check_output),
|
||||
mock.patch.object(mod.subprocess, "check_output", side_effect=fake_check_output),
|
||||
):
|
||||
# mov rax, [rax + 0x30] -> 0x30
|
||||
self.assertEqual(mod._wrapper_slot_from_bytes(bytes.fromhex("488b4030"), 4), 0x30)
|
||||
@ -43,9 +56,116 @@ class TestGpuStageEngineWorklist(unittest.TestCase):
|
||||
self.assertEqual(mod._wrapper_slot_from_bytes(bytes.fromhex("488b8080000000"), 7), 0x80)
|
||||
# mov rax, [rax] (no displacement) -> None
|
||||
self.assertIsNone(mod._wrapper_slot_from_bytes(bytes.fromhex("488b00"), 3))
|
||||
# displacement load + indexed load -> None (matches Capstone behavior)
|
||||
self.assertIsNone(mod._wrapper_slot_from_bytes(bytes.fromhex("488b4030488b04c8c3"), 9))
|
||||
# > 48 bytes -> None (short-circuits before objdump)
|
||||
self.assertIsNone(mod._wrapper_slot_from_bytes(bytes.fromhex("488b4030"), 49))
|
||||
self.assertEqual(objdump_calls, ["objdump", "objdump", "objdump"])
|
||||
self.assertEqual(objdump_calls, ["objdump", "objdump", "objdump", "objdump"])
|
||||
|
||||
def test_check_rejects_json_type_drift_and_writes_atomically(self):
|
||||
mod = _load_mod()
|
||||
fake_report = {
|
||||
"callback_attempts": 1,
|
||||
"unique_callbacks": 1,
|
||||
"engines_with_callbacks": 1,
|
||||
"engine_count": 1,
|
||||
"static_non_default_slots": {},
|
||||
"engines_with_static_slots": 0,
|
||||
"body_kinds": {},
|
||||
"unique_bodies": 0,
|
||||
"engines": [{"engine_ordinal0": 0}],
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = Path(td) / "worklist.json"
|
||||
with mock.patch.object(mod, "build_report", return_value=fake_report):
|
||||
# Atomic write succeeds with no leftover temp files.
|
||||
self.assertEqual(mod.main(["--output", str(out), "--rm-object", td]), 0)
|
||||
self.assertEqual(list(Path(td).iterdir()), [out])
|
||||
# Same values with different whitespace/key order still pass --check.
|
||||
out.write_text(json.dumps(fake_report, sort_keys=True), encoding="utf-8")
|
||||
self.assertEqual(mod.main(["--check", "--output", str(out), "--rm-object", td]), 0)
|
||||
# Replacing int 0 with bool false must fail --check (0 == False in Python).
|
||||
drifted = {**fake_report, "engines": [{"engine_ordinal0": False}]}
|
||||
out.write_text(json.dumps(drifted), encoding="utf-8")
|
||||
with self.assertRaisesRegex(SystemExit, "Stale worklist report"):
|
||||
mod.main(["--check", "--output", str(out), "--rm-object", td])
|
||||
|
||||
def test_build_report_handles_empty_wanted_single_class_default_and_external_path(self):
|
||||
mod = _load_mod()
|
||||
fake_rm = b"fake-rm"
|
||||
fake_digest = hashlib.sha256(fake_rm).hexdigest()
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
t = Path(td)
|
||||
rm_path = t / "nv-kernel.o_binary"
|
||||
rm_path.write_bytes(fake_rm)
|
||||
|
||||
# 1. Empty wanted set (only shared no-op callbacks) + external relative vs absolute path.
|
||||
labels_empty = {
|
||||
"engines": [
|
||||
{
|
||||
"engine_ordinal0": 0,
|
||||
"class_label": "noop",
|
||||
"phase_positions0": {"Load": 0},
|
||||
"callbacks": {"Load": {"symbol": "_nv000001rm", "shared_default_noop": True}},
|
||||
}
|
||||
],
|
||||
"method_catalog": {
|
||||
"_nv000001rm": {"symbol": "_nv000001rm", "shared_default_noop": True, "candidates": []}
|
||||
},
|
||||
}
|
||||
lbl_path = t / "labels_empty.json"
|
||||
lbl_path.write_text(json.dumps(labels_empty), encoding="utf-8")
|
||||
with (
|
||||
mock.patch.object(mod, "DIGEST", fake_digest),
|
||||
mock.patch.object(mod, "_parse_elf64", return_value=(1, b"", [("", 0, 0, 0)], [])),
|
||||
):
|
||||
rep_abs = mod.build_report(lbl_path, rm_path)
|
||||
old_cwd = Path.cwd()
|
||||
try:
|
||||
os.chdir(t)
|
||||
rep_rel = mod.build_report(Path("labels_empty.json"), rm_path)
|
||||
finally:
|
||||
os.chdir(old_cwd)
|
||||
self.assertEqual(rep_abs["source"], rep_rel["source"])
|
||||
self.assertEqual(rep_abs["engines"][0]["static_slots"], None)
|
||||
self.assertEqual(rep_abs["engines_with_static_slots"], 0)
|
||||
|
||||
# 2. Single uniquely identified class whose observed Load callback equals the stage default.
|
||||
labels_one = {
|
||||
"engines": [
|
||||
{
|
||||
"engine_ordinal0": 0,
|
||||
"class_label": "single",
|
||||
"phase_positions0": {"Load": 0},
|
||||
"callbacks": {"Load": {"symbol": "_nv000002rm", "shared_default_noop": False}},
|
||||
}
|
||||
],
|
||||
"method_catalog": {
|
||||
"_nv000002rm": {
|
||||
"symbol": "_nv000002rm",
|
||||
"shared_default_noop": False,
|
||||
"candidates": [
|
||||
{
|
||||
"metadata_engstate_rodata_offset": "0x100",
|
||||
"root_rtti_rodata_offset": "0x200",
|
||||
"engstate_subobject_offset": 0,
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
lbl_one = t / "labels_one.json"
|
||||
lbl_one.write_text(json.dumps(labels_one), encoding="utf-8")
|
||||
syms = [("", 0, 0, 0), ("_nv000002rm", 1, 0, 4)]
|
||||
# Relocation at base (0x100) + Load slot (0x68) -> sym 1 (_nv000002rm)
|
||||
rela = [(0x100 + 0x68, (1 << 32) | 1, 0)]
|
||||
with (
|
||||
mock.patch.object(mod, "DIGEST", fake_digest),
|
||||
mock.patch.object(mod, "_parse_elf64", return_value=(1, b"\xc3\x00\x00\x00", syms, rela)),
|
||||
):
|
||||
rep_one = mod.build_report(lbl_one, rm_path)
|
||||
self.assertEqual(rep_one["engines_with_static_slots"], 1)
|
||||
self.assertEqual(rep_one["static_default_targets"]["Load"], "_nv000002rm")
|
||||
|
||||
def test_missing_rm_object_fails_cleanly_without_touching_output(self):
|
||||
mod = _load_mod()
|
||||
|
||||
@ -39,8 +39,12 @@ SLOTS = {
|
||||
0x90: "StateDestroy",
|
||||
0x98: "IsPresent",
|
||||
}
|
||||
_MOV_RAX_LOAD_RE = re.compile(
|
||||
r"\bmov\s+rax,\s*qword\s+ptr\s+\[rax(?:\s*\+\s*(0x[0-9a-f]+|\d+))?\]",
|
||||
_MOV_RAX_ANY_LOAD_RE = re.compile(
|
||||
r"\bmov\s+rax,\s*qword\s+ptr\s+\[rax[^\]]*\]",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_MOV_RAX_DISP_RE = re.compile(
|
||||
r"\[rax\s*\+\s*(0x[0-9a-f]+|\d+)\]",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
@ -132,13 +136,13 @@ def _wrapper_slot_from_bytes(code: bytes, sym_size: int) -> int | None:
|
||||
|
||||
disassembler = Cs(CS_ARCH_X86, CS_MODE_64)
|
||||
loads = [
|
||||
ins
|
||||
f"{ins.mnemonic} {ins.op_str}"
|
||||
for ins in disassembler.disasm(code, 0)
|
||||
if ins.mnemonic == "mov" and ins.op_str.startswith("rax, qword ptr [rax")
|
||||
if _MOV_RAX_ANY_LOAD_RE.search(f"{ins.mnemonic} {ins.op_str}")
|
||||
]
|
||||
if len(loads) != 1:
|
||||
return None
|
||||
match = re.search(r"\[rax \+ (0x[0-9a-f]+|\d+)\]", loads[0].op_str)
|
||||
match = _MOV_RAX_DISP_RE.search(loads[0])
|
||||
return int(match[1], 0) if match else None
|
||||
except ImportError:
|
||||
pass
|
||||
@ -150,14 +154,15 @@ def _wrapper_slot_from_bytes(code: bytes, sym_size: int) -> int | None:
|
||||
["objdump", "-b", "binary", "-m", "i386:x86-64", "-D", "-M", "intel", tmp.name],
|
||||
text=True,
|
||||
)
|
||||
loads = []
|
||||
for line in out.splitlines():
|
||||
m = _MOV_RAX_LOAD_RE.search(line)
|
||||
if m:
|
||||
loads.append(m.group(1))
|
||||
if len(loads) != 1 or loads[0] is None:
|
||||
loads = [
|
||||
m.group(0)
|
||||
for line in out.splitlines()
|
||||
if (m := _MOV_RAX_ANY_LOAD_RE.search(line)) is not None
|
||||
]
|
||||
if len(loads) != 1:
|
||||
return None
|
||||
return int(loads[0], 0)
|
||||
match = _MOV_RAX_DISP_RE.search(loads[0])
|
||||
return int(match[1], 0) if match else None
|
||||
|
||||
|
||||
def build_report(source_path: Path, rm_object_path: Path) -> dict:
|
||||
@ -188,10 +193,11 @@ def build_report(source_path: Path, rm_object_path: Path) -> dict:
|
||||
"callbacks": callbacks,
|
||||
}
|
||||
)
|
||||
resolved_source = source_path.resolve()
|
||||
try:
|
||||
source_label = source_path.resolve().relative_to(ROOT).as_posix()
|
||||
source_label = resolved_source.relative_to(ROOT).as_posix()
|
||||
except ValueError:
|
||||
source_label = str(source_path)
|
||||
source_label = str(resolved_source)
|
||||
report = {
|
||||
"source": source_label,
|
||||
"source_sha256": hashlib.sha256(raw).hexdigest(),
|
||||
@ -260,10 +266,15 @@ def build_report(source_path: Path, rm_object_path: Path) -> dict:
|
||||
if key is not None:
|
||||
resolved[key] = target_name
|
||||
|
||||
stage_to_slot = {stage: slot for slot, stage in SLOTS.items()}
|
||||
defaults = {}
|
||||
for slot, stage in SLOTS.items():
|
||||
counts = Counter(resolved.get((base, slot)) for base in set(wanted.values()))
|
||||
defaults[stage] = counts.most_common(1)[0][0]
|
||||
if wanted:
|
||||
for slot, stage in SLOTS.items():
|
||||
counts = Counter(resolved.get((base, slot)) for base in set(wanted.values()))
|
||||
defaults[stage] = counts.most_common(1)[0][0]
|
||||
else:
|
||||
for stage in SLOTS.values():
|
||||
defaults[stage] = None
|
||||
|
||||
static_attempts = Counter()
|
||||
for engine in report["engines"]:
|
||||
@ -281,10 +292,17 @@ def build_report(source_path: Path, rm_object_path: Path) -> dict:
|
||||
engine["static_slots"] = slots
|
||||
for stage in STAGES:
|
||||
observed = engine["callbacks"].get(stage)
|
||||
if observed != slots.get(stage):
|
||||
static_target = resolved.get((base, stage_to_slot[stage]))
|
||||
if observed is None:
|
||||
if slots.get(stage) is not None:
|
||||
raise SystemExit(
|
||||
f"Observed/static callback mismatch for engine {engine['engine_ordinal0']} "
|
||||
f"stage {stage}: observed={observed!r}, static={slots.get(stage)!r}"
|
||||
)
|
||||
elif observed != static_target:
|
||||
raise SystemExit(
|
||||
f"Observed/static callback mismatch for engine {engine['engine_ordinal0']} "
|
||||
f"stage {stage}: observed={observed!r}, static={slots.get(stage)!r}"
|
||||
f"stage {stage}: observed={observed!r}, static={static_target!r}"
|
||||
)
|
||||
|
||||
report["static_scope"] = (
|
||||
@ -339,6 +357,35 @@ def build_report(source_path: Path, rm_object_path: Path) -> dict:
|
||||
return report
|
||||
|
||||
|
||||
def _canonical_json(obj: object) -> str:
|
||||
return json.dumps(obj, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def _atomic_write_text(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_name = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=path.parent,
|
||||
prefix=f".{path.name}.",
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as fh:
|
||||
tmp_name = fh.name
|
||||
fh.write(text)
|
||||
fh.flush()
|
||||
os.replace(tmp_name, path)
|
||||
except BaseException:
|
||||
if tmp_name is not None:
|
||||
try:
|
||||
os.unlink(tmp_name)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Derive or verify the per-engine stage callback work list."
|
||||
@ -356,10 +403,10 @@ def main(argv=None) -> int:
|
||||
if args.check:
|
||||
if not args.output.is_file():
|
||||
raise SystemExit(f"Missing worklist report: {args.output}")
|
||||
if json.loads(args.output.read_text()) != report:
|
||||
if _canonical_json(json.loads(args.output.read_text(encoding="utf-8"))) != _canonical_json(report):
|
||||
raise SystemExit(f"Stale worklist report: {args.output}")
|
||||
else:
|
||||
args.output.write_text(encoded)
|
||||
_atomic_write_text(args.output, encoded)
|
||||
|
||||
print(
|
||||
f"{report['callback_attempts']} callback attempts, {report['unique_callbacks']} unique, "
|
||||
|
||||
Reference in New Issue
Block a user