mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 22:48:43 +00:00
157 lines
6.9 KiB
Python
157 lines
6.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Size the static call tree under each GV100 engine stage body.
|
|
|
|
Starting from the stage bodies in reports/gpu-stage-engine-worklist.json, this
|
|
walks the inferred pseudocode export: direct calls, and calls through an
|
|
engine HAL slot (`param_2 + offset`) resolved with
|
|
reports/gv100-engine-hal-bindings.json. For every stage it reports how many
|
|
functions and bytes of original code are reachable, which BAR0 register
|
|
offsets appear as constant arguments of the register read and write helpers,
|
|
and which HAL slots could not be resolved.
|
|
|
|
Planning evidence only. It is derived from decompiler output, so the tree is
|
|
an estimate: calls through other objects' tables are not followed, a slot is
|
|
resolved as if `param_2` were the stage's own engine object, and a register
|
|
offset computed at run time is not seen.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DEFAULT_ANALYSIS_ROOT = Path("/home/geodd/nvidia-driver/analysis-580.178.04")
|
|
STAGES = ("ConstructEngine", "PreInitLocked", "PreInitUnlocked", "InitLocked", "InitUnlocked",
|
|
"PreLoad", "Load", "PostLoad")
|
|
# Shared services that are not part of an engine's own logic.
|
|
SERVICES = {"_nv047869rm", "_nv047868rm", "_nv047867rm", "_nv046745rm", "_nv046747rm",
|
|
"_nv046751rm", "_nv046752rm", "_nv052687rm", "_nv052701rm", "_nv052705rm",
|
|
"_nv052695rm", "_nv052714rm", "_nv049786rm", "_nv049598rm", "_nv054113rm",
|
|
"_nv054115rm", "_nv054117rm", "_nv030608rm", "_nv030522rm"}
|
|
READ, WRITE = "_nv053907rm", "_nv053912rm"
|
|
|
|
|
|
def find_export_dir(explicit: Path | None = None) -> Path:
|
|
if explicit is not None:
|
|
candidate = explicit
|
|
else:
|
|
analysis = Path(os.environ.get("NV_RS_ANALYSIS_ROOT", str(DEFAULT_ANALYSIS_ROOT)))
|
|
candidate = analysis / "decompiled/kernel-rm-all"
|
|
if not (candidate / "original-symbol-export-map.jsonl").is_file():
|
|
raise SystemExit(
|
|
f"decompiled export map not found under {candidate}; "
|
|
"pass --export-dir or set NV_RS_ANALYSIS_ROOT"
|
|
)
|
|
return candidate
|
|
|
|
|
|
def main(argv=None) -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__,
|
|
formatter_class=argparse.RawTextHelpFormatter)
|
|
parser.add_argument("--depth", type=int, default=8)
|
|
parser.add_argument("--export-dir", type=Path, default=None)
|
|
arguments = parser.parse_args(argv)
|
|
if arguments.depth < 0:
|
|
raise SystemExit("--depth must be >= 0")
|
|
|
|
export_dir = find_export_dir(arguments.export_dir)
|
|
exports = {}
|
|
with (export_dir / "original-symbol-export-map.jsonl").open(encoding="utf-8") as stream:
|
|
for line in stream:
|
|
if not line.strip():
|
|
continue
|
|
row = json.loads(line)
|
|
exports[row["name"]] = (row.get("decompiler_output"), row["ELF_size"])
|
|
worklist = json.loads((ROOT / "reports/gpu-stage-engine-worklist.json").read_text(encoding="utf-8"))
|
|
bindings = {
|
|
entry["class_label"]: entry
|
|
for entry in json.loads(
|
|
(ROOT / "reports/gv100-engine-hal-bindings.json").read_text(encoding="utf-8")
|
|
)["classes"]
|
|
}
|
|
texts = {}
|
|
|
|
def text(name):
|
|
if name not in texts:
|
|
path = exports.get(name, (None, 0))[0]
|
|
texts[name] = (export_dir / path).read_text(encoding="utf-8") if path else ""
|
|
return texts[name]
|
|
|
|
def walk(root, slots, depth):
|
|
seen, registers_read, registers_written, unresolved = {}, set(), set(), set()
|
|
pending = [(root, 0)]
|
|
while pending:
|
|
name, level = pending.pop()
|
|
if name in seen or name in SERVICES or name in (READ, WRITE):
|
|
continue
|
|
seen[name] = exports.get(name, (None, 0))[1]
|
|
body = text(name)
|
|
for helper, found in ((READ, registers_read), (WRITE, registers_written)):
|
|
for match in re.finditer(helper + r"\([^,]+,0,0,(0x[0-9a-f]+|\d+),", body):
|
|
found.add(int(match[1], 0))
|
|
if level >= depth:
|
|
continue
|
|
for callee in re.findall(r"(_nv\d{6}rm)\(", body):
|
|
if callee != name:
|
|
pending.append((callee, level + 1))
|
|
for offset in re.findall(r"\(\*\*\(code \*\*\)\(param_2 \+ (0x[0-9a-f]+|\d+)\)\)", body):
|
|
slot = f"{int(offset, 0):#x}"
|
|
bound = slots.get(slot)
|
|
if bound:
|
|
pending.append((bound["function"], level + 1))
|
|
else:
|
|
unresolved.add(slot)
|
|
return seen, registers_read, registers_written, unresolved
|
|
|
|
classes = {}
|
|
for engine in worklist["engines"]:
|
|
label = engine["class_label"]
|
|
if not engine.get("bodies") or label in classes:
|
|
continue
|
|
slots = bindings.get(label, {}).get("hal_slots", {})
|
|
via_hal = bindings.get(label, {}).get("stage_bodies_via_hal", {})
|
|
stages = {}
|
|
union = {}
|
|
for stage in STAGES:
|
|
body = engine["bodies"].get(stage)
|
|
if not body:
|
|
continue
|
|
root = via_hal.get(stage, {}).get("function") or body["body"]
|
|
seen, reads, writes, unresolved = walk(root, slots, arguments.depth)
|
|
union.update(seen)
|
|
stages[stage] = {
|
|
"root": root,
|
|
"functions": len(seen),
|
|
"bytes": sum(seen.values()),
|
|
"registers_read": [f"{offset:#x}" for offset in sorted(reads)],
|
|
"registers_written": [f"{offset:#x}" for offset in sorted(writes)],
|
|
"unresolved_hal_slots": sorted(unresolved, key=lambda s: int(s, 16)),
|
|
}
|
|
classes[label] = {
|
|
"engine_ordinal0": engine["engine_ordinal0"],
|
|
"load_position0": engine["load_position0"],
|
|
"stages": stages,
|
|
"unique_functions": len(union),
|
|
"unique_bytes": sum(union.values()),
|
|
}
|
|
report = {
|
|
"scope": __doc__.split("\n\n")[2].replace("\n", " "),
|
|
"depth": arguments.depth,
|
|
"shared_services_excluded": sorted(SERVICES),
|
|
"classes": classes,
|
|
}
|
|
out = ROOT / "reports/gv100-engine-call-trees.json"
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")
|
|
for label, entry in sorted(classes.items(), key=lambda item: (item[1]["load_position0"] is None,
|
|
item[1]["load_position0"] or 0)):
|
|
writes = sorted({offset for stage in entry["stages"].values()
|
|
for offset in stage["registers_written"]}, key=lambda s: int(s, 16))
|
|
print(f"{entry['load_position0']!s:>4} {str(label):20} functions={entry['unique_functions']:4} "
|
|
f"bytes={entry['unique_bytes']:7} writes={len(writes):3} {' '.join(writes[:6])}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|