mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:38:37 +00:00
Merge pull request #1712 from Tortoche/feat/shader-disasm-auto-fallback
tools: add auto fallback to python disassembler in shader_disasm and shader_library
This commit is contained in:
@ -12,6 +12,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = os.path.join(ROOT, "tools", "shader_disasm.py")
|
||||
@ -502,5 +503,46 @@ class DisasmOutputCollisionTest(unittest.TestCase):
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.dir, "foo.s")))
|
||||
|
||||
|
||||
class DisasmAutoBackendTest(unittest.TestCase):
|
||||
@staticmethod
|
||||
def _import_shader_disasm():
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
try:
|
||||
import shader_disasm
|
||||
return shader_disasm
|
||||
finally:
|
||||
sys.path.pop(0)
|
||||
|
||||
def test_auto_backend_falls_back_to_python_on_invalid_words(self):
|
||||
shader_disasm = self._import_shader_disasm()
|
||||
code = bytes.fromhex("02 1a 28 f4 00 00 00 fa") + b"\x00\x00\x81\xbf"
|
||||
with mock.patch.object(
|
||||
shader_disasm,
|
||||
"run_mc",
|
||||
return_value=("\ts_endpgm\n", 2, "<stdin>:1:1: warning: invalid instruction encoding\n"),
|
||||
):
|
||||
asm, bad, err = shader_disasm.disasm(code, "gfx1013", backend="auto", wave32=True)
|
||||
self.assertEqual(bad, 0)
|
||||
self.assertEqual(err, "")
|
||||
self.assertIn("[s104,s105,vcc_lo,vcc_hi]", asm)
|
||||
self.assertIn("s_endpgm", asm)
|
||||
|
||||
def test_auto_backend_preserves_clean_llvm_mc_output(self):
|
||||
shader_disasm = self._import_shader_disasm()
|
||||
with mock.patch.object(shader_disasm, "run_mc", return_value=(ASM, 0, "")), \
|
||||
mock.patch.object(shader_disasm.rdna2_decode, "disasm_bytes") as py_disasm:
|
||||
asm, bad, err = shader_disasm.disasm(CODE, "gfx1013", backend="auto", wave32=True)
|
||||
self.assertEqual((asm, bad, err), (ASM, 0, ""))
|
||||
py_disasm.assert_not_called()
|
||||
|
||||
def test_auto_backend_keeps_llvm_mc_when_python_not_better(self):
|
||||
shader_disasm = self._import_shader_disasm()
|
||||
mc_result = ("\ts_nop 0\n", 1, "warning: invalid instruction encoding\n")
|
||||
with mock.patch.object(shader_disasm, "run_mc", return_value=mc_result), \
|
||||
mock.patch.object(shader_disasm.rdna2_decode, "disasm_bytes", return_value=("\ts_nop 0\n", 1)):
|
||||
asm, bad, err = shader_disasm.disasm(CODE, "gfx1013", backend="auto", wave32=True)
|
||||
self.assertEqual((asm, bad, err), mc_result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -13,11 +13,13 @@ import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import zlib
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
|
||||
import shader_disasm # noqa: E402
|
||||
import shader_library as sl # noqa: E402
|
||||
import shader_meta # noqa: E402
|
||||
|
||||
@ -713,6 +715,45 @@ class Main(unittest.TestCase):
|
||||
"1 unreadable/corrupt container\n", stdout.getvalue())
|
||||
self.assertEqual(stderr.getvalue().splitlines(), ["carve: ZERO.dxbc: not a DXBC container"])
|
||||
|
||||
def test_disasm_auto_falls_back_per_program_without_regressing_clean_programs(self):
|
||||
ps_prog = prog(0x11112222)
|
||||
vs_body = bytes.fromhex("02 1a 28 f4 00 00 00 fa") + ENDPGM
|
||||
vs_code = prologue(0x33334444) + vs_body
|
||||
vs_prog = vs_code + CODE_END * ((-len(vs_code)) % 256 // 4)
|
||||
blobs = [layout_blob(2, D_PS), layout_blob(2, D_VS)]
|
||||
graphics = [(NONE, NONE, {0: (0, 0), 1: (1, 1)})]
|
||||
lib_bytes = build(graphics, [], blobs, [ps_prog, vs_prog])
|
||||
|
||||
def fake_run_mc(code, mcpu, wave32=True):
|
||||
if code == V_MOV * 2 + ENDPGM:
|
||||
return "\t; mocked llvm-mc ps\n\ts_endpgm\n", 0, ""
|
||||
return "\ts_endpgm\n", 2, "<stdin>:1:1: warning: invalid instruction encoding\n"
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = os.path.join(tmp, "lib.bin")
|
||||
with open(src, "wb") as f:
|
||||
f.write(lib_bytes)
|
||||
out = os.path.join(tmp, "out")
|
||||
with mock.patch.object(shader_disasm, "probe") as probe_mock, \
|
||||
mock.patch.object(shader_disasm, "run_mc", side_effect=fake_run_mc):
|
||||
rc, _ = self.run_main(src, "--out", out, "--disasm", "--jobs", "1")
|
||||
self.assertEqual(rc, 0)
|
||||
probe_mock.assert_called_once_with("gfx1013")
|
||||
with open(os.path.join(out, "disasm", "lib_ps_00000.s"), encoding="utf-8") as f:
|
||||
ps_text = f.read()
|
||||
self.assertIn("; mocked llvm-mc ps", ps_text)
|
||||
self.assertIn("0 invalid words", ps_text)
|
||||
self.assertNotIn("; --- llvm-mc messages ---", ps_text)
|
||||
with open(os.path.join(out, "disasm", "lib_vs_00001.s"), encoding="utf-8") as f:
|
||||
vs_text = f.read()
|
||||
self.assertIn("0 invalid words", vs_text)
|
||||
self.assertIn("[s104,s105,vcc_lo,vcc_hi]", vs_text)
|
||||
self.assertNotIn("; --- llvm-mc messages ---", vs_text)
|
||||
with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
|
||||
by = {e["file"]: e for e in json.load(f)}
|
||||
self.assertEqual(by["lib_ps_00000.dxbc"]["invalid_words"], 0)
|
||||
self.assertEqual(by["lib_vs_00001.dxbc"]["invalid_words"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -95,6 +95,14 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True
|
||||
the second (0xFA......) as an 8-byte EXP and the rest of the listing goes out of step (gfx1013 and gfx1030 alike).
|
||||
In 749 of the 2,684 library programs of 1.0.2.1 that refused 945 programs ('fall-through into undecodable
|
||||
words'). tools/rdna2_decode.py decodes them; such a program takes its listing when it has fewer invalid words."""
|
||||
if backend == "auto":
|
||||
asm, bad, err = disasm(code, mcpu, backend="llvm-mc", wave32=wave32)
|
||||
if bad == 0 and asm.strip():
|
||||
return asm, bad, err
|
||||
py_asm, py_bad, _ = disasm(code, mcpu, backend="python", wave32=wave32)
|
||||
if py_asm.strip() and (not asm.strip() or py_bad < bad):
|
||||
return py_asm, py_bad, ""
|
||||
return asm, bad, err
|
||||
if compute and backend != "python":
|
||||
asm, bad, err = disasm(code, mcpu, backend=backend, wave32=wave32)
|
||||
if bad:
|
||||
@ -346,8 +354,8 @@ def main():
|
||||
ap.add_argument("--out")
|
||||
ap.add_argument("--skip-existing", action="store_true", help="reuse complete listings from a matching run")
|
||||
ap.add_argument("--mcpu", default="gfx1013")
|
||||
ap.add_argument("--backend", choices=("llvm-mc", "python"), default="llvm-mc",
|
||||
help="disassembler backend: llvm-mc (default) or pure-Python RDNA2 decoder (#1901)")
|
||||
ap.add_argument("--backend", choices=("llvm-mc", "python", "auto"), default="llvm-mc",
|
||||
help="disassembler backend: llvm-mc (default), pure-Python RDNA2 decoder (#1901), or auto")
|
||||
ap.add_argument("--limit", type=positive_int)
|
||||
ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2))
|
||||
a = ap.parse_args()
|
||||
@ -399,6 +407,11 @@ def main():
|
||||
if files:
|
||||
if a.backend == "llvm-mc":
|
||||
probe(a.mcpu)
|
||||
elif a.backend == "auto":
|
||||
try:
|
||||
probe(a.mcpu)
|
||||
except SystemExit:
|
||||
a.backend = "python"
|
||||
with ThreadPoolExecutor(a.jobs) as ex:
|
||||
res.update(ex.map(lambda p: one(p, out, a.mcpu, backend=a.backend), files))
|
||||
print(f"{total} shaders -> {os.path.abspath(out)}: {dict(res)}")
|
||||
|
||||
@ -294,6 +294,9 @@ def main(argv=None) -> int:
|
||||
help="extract only compute programs with these kind-6 SHA-256 hashes, one per line")
|
||||
ap.add_argument("--disasm", action="store_true", help="also write disasm/<name>.s (needs llvm-mc, see LLVM_MC)")
|
||||
ap.add_argument("--mcpu", default="gfx1013", help="llvm-mc CPU for --disasm (default gfx1013)")
|
||||
ap.add_argument("--backend", choices=("auto", "llvm-mc", "python"), default="auto",
|
||||
help="disassembler backend for --disasm: auto (default, llvm-mc with python fallback), "
|
||||
"llvm-mc, or python")
|
||||
ap.add_argument("--carve", help="a tools/shader_carve.py output folder: name each program's source shader by the "
|
||||
"digest its resource-layout blob ends with (the container's HASH part), and "
|
||||
"copy that container to <name>.dxbc for the translator's signature reads")
|
||||
@ -439,7 +442,7 @@ def main(argv=None) -> int:
|
||||
|
||||
def one(job):
|
||||
entry, name, code, start, end = job
|
||||
asm, invalid, err = disasm.disasm(code, a.mcpu, wave32=entry.get("wave32", True), compute=True)
|
||||
asm, invalid, err = disasm.disasm(code, a.mcpu, backend=a.backend, wave32=entry.get("wave32", True), compute=True)
|
||||
entry["invalid_words"] = invalid
|
||||
with open(os.path.join(disasm_dir, name + ".s"), "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n")
|
||||
@ -448,6 +451,13 @@ def main(argv=None) -> int:
|
||||
f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n")
|
||||
|
||||
if work:
|
||||
if a.backend == "llvm-mc":
|
||||
disasm.probe(a.mcpu)
|
||||
elif a.backend == "auto":
|
||||
try:
|
||||
disasm.probe(a.mcpu)
|
||||
except SystemExit:
|
||||
a.backend = "python"
|
||||
with ThreadPoolExecutor(a.jobs) as ex: # each job waits on its own llvm-mc process
|
||||
list(ex.map(one, work))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user