nvdisasm-re / builder.py
ejschwartz's picture
Add an instruction builder for random legal instructions
02fd83a
Raw History Blame Contribute Delete
3.16 kB
"""Random legal instructions of one opcode, optionally restricted to an md class and pinned modifiers."""
import random
from functools import cache
from sass import synth
from sass.assemble import assemble_instruction
from sass.assemble.encoding import encode_environment
from sass.decode import ir, pydecode
HIDDEN = {"REUSE", "EXP_DESC"} # scheduling hints and descriptor switches, not semantics
TRIES = 256
# Alternate classes are pseudo-op spellings (IADD, LOP, FADD32I) that decode as another class.
def decodable(arch): return [k for k in ir.load(arch).classes if not k.alternate]
@cache
def opcodes(arch): return sorted({k.mnemonic for k in decodable(arch)})
def classes(arch, opcode, form=None):
return [k for k in decodable(arch) if k.mnemonic == opcode and form in (None, k.name)]
def forms(arch, opcode): return [k.name for k in classes(arch, opcode)]
def mods(k): return [a for a in k.format if a.kind == "mod" and a.type not in HIDDEN]
def members(md, a):
"""Spellings of a modifier's values, as the decoder renders them, default first."""
names = md.rev_enums[a.type]
default = names.get(md.enums[a.type].get(a.default))
return sorted((n for n in dict.fromkeys(names.values()) if not n.startswith("INVALID")), key=lambda n: n != default)
def modifiers(arch, opcode, form=None):
"""Modifiers with a choice to make, by name: the first form's spellings win."""
md = ir.load(arch)
found = {a.name: members(md, a) for k in reversed(classes(arch, opcode, form)) for a in mods(k)}
return {n: m for n, m in found.items() if len(m) > 1}
def pinned(md, k, pins):
"""Field values for `pins` ({modifier: spelling}) in class k, or None when k cannot express them."""
types = {a.name: a.type for a in mods(k)}
if all(n in types and m in md.enums[types[n]] for n, m in pins.items()):
return {n: md.enums[types[n]][m] for n, m in pins.items()}
def unguarded(md, k):
return {key: v for a in k.format if a.kind == "guard" for key, v in ((a.name, md.enums[a.type][a.default]), ((a.name, "not"), 0))}
def build(arch, opcode, form=None, pins={}, predicated=False, rng=None):
"""Instruction text: a random legal word of a matching class, re-encoded with the pins applied."""
md, rng = ir.load(arch), rng or random.Random()
pool = [(k, values | ({} if predicated else unguarded(md, k)))
for k in classes(arch, opcode, form) if (values := pinned(md, k, pins)) is not None]
for _ in range(TRIES if pool else 0):
k, values = rng.choice(pool)
try:
env = pydecode.decode(arch, synth.legal_word(md, k, rng, rng.random())).env
d = pydecode.decode(arch, encode_environment(md, k, values, base=env)[0])
if d.klass.name == k.name and all(d.env.get(n) == v for n, v in values.items()):
assemble_instruction(arch, d.text)
return d.text
except (ValueError, pydecode.NoMatch):
continue
raise ValueError(f"no legal {'.'.join([opcode, *pins.values()])} found"
+ (f" in {form}" if form else "") + ("" if pool else ": no form has these modifiers"))