#!/usr/bin/env python3 """Check the monitor's disassembler and assembler (out/monitor-host, built by build.sh) on random instructions of every kind: - each word disassembles to the same instruction GNU objdump shows (same mnemonic, registers and values), and - the monitor's assembler turns that text back into the same word. python3 test-disasm.py [count per kind] """ import os import random import re import subprocess import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "..", "tools")) HOST = os.path.join(HERE, "out", "monitor-host") N = int(sys.argv[1]) if len(sys.argv) > 1 else 300 random.seed(1) def prefix(): out = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE], capture_output=True, text=True).stdout.strip() return out def r(): return random.randrange(32) def words(): """Random valid RV32IM / Zicsr / system instructions.""" ws = [] csrs = [0x300, 0x301, 0x304, 0x305, 0x340, 0x341, 0x342, 0x343, 0x344, 0x744, 0xB00, 0xC00, 0xC01, 0xC82, 0xF14, 0x7A0, 0x123] for _ in range(N): imm = random.randrange(4096) ws.append(0x37 | r() << 7 | random.randrange(1 << 20) << 12) # lui ws.append(0x17 | r() << 7 | random.randrange(1 << 20) << 12) # auipc j = random.randrange(1 << 20) << 1 # jal v = j ws.append(0x6F | r() << 7 | (v >> 12 & 0xFF) << 12 | (v >> 11 & 1) << 20 | (v >> 1 & 0x3FF) << 21 | (v >> 20 & 1) << 31) ws.append(0x67 | r() << 7 | r() << 15 | imm << 20) # jalr b = random.randrange(1 << 12) << 1 f3 = random.choice([0, 1, 4, 5, 6, 7]) ws.append(0x63 | f3 << 12 | r() << 15 | r() << 20 | (b >> 11 & 1) << 7 | (b >> 1 & 15) << 8 | (b >> 5 & 0x3F) << 25 | (b >> 12 & 1) << 31) ws.append(0x03 | random.choice([0, 1, 2, 4, 5]) << 12 | r() << 7 | r() << 15 | imm << 20) s = random.randrange(4096) ws.append(0x23 | random.choice([0, 1, 2]) << 12 | (s & 31) << 7 | r() << 15 | r() << 20 | (s >> 5) << 25) ws.append(0x13 | random.choice([0, 2, 3, 4, 6, 7]) << 12 | r() << 7 | r() << 15 | imm << 20) ws.append(0x13 | random.choice([(1, 0), (5, 0), (5, 0x20)])[0] << 12 | r() << 7 | r() << 15 | random.randrange(32) << 20) f = random.choice([(0, 0), (0, 0x20), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 0x20), (6, 0), (7, 0)] + [(k, 1) for k in range(8)]) ws.append(0x33 | f[0] << 12 | f[1] << 25 | r() << 7 | r() << 15 | r() << 20) ws.append(0x73 | random.choice([1, 2, 3, 5, 6, 7]) << 12 | r() << 7 | r() << 15 | random.choice(csrs) << 20) # the special cases the disassembler shortens ws.append(0x13 | r() << 7 | 0 << 15 | imm << 20) # li ws.append(0x13 | r() << 7 | r() << 15) # mv ws.append(0x00008067) # ret # F rms = [0, 1, 2, 3, 4, 7] for _ in range(N): imm = random.randrange(4096) ws.append(0x07 | 2 << 12 | r() << 7 | r() << 15 | imm << 20) # flw ws.append(0x27 | 2 << 12 | (imm & 31) << 7 | r() << 15 | r() << 20 | (imm >> 5) << 25) ws.append(random.choice([0x43, 0x47, 0x4B, 0x4F]) | random.choice(rms) << 12 | r() << 7 | r() << 15 | r() << 20 | r() << 27) f5, f3 = random.choice([(0, None), (1, None), (2, None), (3, None), (4, 0), (4, 1), (4, 2), (5, 0), (5, 1), (0x14, 0), (0x14, 1), (0x14, 2)]) ws.append(0x53 | f5 << 27 | (random.choice(rms) if f3 is None else f3) << 12 | r() << 7 | r() << 15 | r() << 20) rr = r() ws.append(0x53 | 4 << 27 | random.randrange(3) << 12 | r() << 7 | rr << 15 | rr << 20) # fmv.s ... ws.append(0x53 | 0x0B << 27 | random.choice(rms) << 12 | r() << 7 | r() << 15) # fsqrt ws.append(0x53 | random.choice([0x18, 0x1A]) << 27 | random.randrange(2) << 20 | random.choice(rms) << 12 | r() << 7 | r() << 15) # fcvt ws.append(0x53 | 0x1C << 27 | random.randrange(2) << 12 | r() << 7 | r() << 15) # fmv.x.w fclass ws.append(0x53 | 0x1E << 27 | r() << 7 | r() << 15) # fmv.w.x ws.append(0x73 | random.choice([1, 2, 3, 5, 6, 7]) << 12 | r() << 7 | r() << 15 | random.choice([1, 2, 3]) << 20) # fcsr ws += [0x13, 0x73, 0x00100073, 0x30200073, 0x70200073, 0x10500073, 0x0FF0000F, 0x100F] return ws def norm_gnu(text, addr): """objdump's operand text -> list of tokens to compare.""" text = re.sub(r"<[^>]*>|#.*", "", text).strip() m = text.split(None, 1) mn = m[0].upper() ops = m[1].split(",") if len(m) > 1 else [] return mn, [o.strip().upper() for o in ops] def val(tok, base10_ok=True): tok = tok.strip() if re.fullmatch(r"-?0X[0-9A-F]+", tok): return int(tok, 16) if re.fullmatch(r"-?[0-9A-F]+H", tok): return int(tok[:-1], 16) if re.fullmatch(r"-?\d+", tok): return int(tok) return None CSRN = {"MSTATUS": 0x300, "MISA": 0x301, "MIE": 0x304, "MTVEC": 0x305, "MSCRATCH": 0x340, "MEPC": 0x341, "MCAUSE": 0x342, "MTVAL": 0x343, "MIP": 0x344, "MNSCRATCH": 0x740, "MNEPC": 0x741, "MNCAUSE": 0x742, "MNSTATUS": 0x744, "TSELECT": 0x7A0, "TDATA1": 0x7A1, "TDATA2": 0x7A2, "TCONTROL": 0x7A5, "MCYCLE": 0xB00, "MINSTRET": 0xB02, "MCYCLEH": 0xB80, "MINSTRETH": 0xB82, "CYCLE": 0xC00, "TIME": 0xC01, "INSTRET": 0xC02, "CYCLEH": 0xC80, "TIMEH": 0xC81, "INSTRETH": 0xC82, "MHARTID": 0xF14, "FFLAGS": 1, "FRM": 2, "FCSR": 3} # objdump's short forms for the float CSRs: read, write, write immediate FCSR_ALIAS = {"FRCSR": ("FCSR", "R"), "FRRM": ("FRM", "R"), "FRFLAGS": ("FFLAGS", "R"), "FSCSR": ("FCSR", ""), "FSRM": ("FRM", ""), "FSFLAGS": ("FFLAGS", ""), "FSRMI": ("FRM", "I"), "FSFLAGSI": ("FFLAGS", "I")} def same(gnu_mn, gnu_ops, our): m = our.split(None, 1) mn = m[0] ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else [] # objdump's other spellings of the same instructions if gnu_mn == "JR" and gnu_ops and "(" in gnu_ops[0]: gnu_mn, gnu_ops = "JALR", ["ZERO"] + gnu_ops elif gnu_mn == "JALR" and len(gnu_ops) == 1 and "(" in gnu_ops[0]: gnu_ops = ["RA"] + gnu_ops elif gnu_mn.startswith("RD") and gnu_mn[2:] in CSRN: gnu_mn, gnu_ops = "CSRR", gnu_ops + [gnu_mn[2:]] elif gnu_mn in FCSR_ALIAS: csr, kind = FCSR_ALIAS[gnu_mn] if kind == "R": gnu_mn, gnu_ops = "CSRR", gnu_ops + [csr] elif len(gnu_ops) == 2: gnu_mn, gnu_ops = "CSRRW" + kind, [gnu_ops[0], csr, gnu_ops[1]] else: gnu_mn, gnu_ops = "CSRW" + kind, [csr] + gnu_ops gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops] ops = [str(CSRN[o]) if o in CSRN else o for o in ops] alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"} if alias.get(gnu_mn, gnu_mn) != mn: return False # objdump writes "fence iorw,iorw" if mn == "FENCE": return True if len(ops) != len(gnu_ops): return False for a, b in zip(gnu_ops, ops): if a == b: continue ma, mb = re.fullmatch(r"(.*)\((\w+)\)", a), re.fullmatch(r"(.*)\((\w+)\)", b) if ma and mb: if ma.group(2) != mb.group(2) or val(ma.group(1) or "0") != val(mb.group(1) or "0"): return False continue va, vb = val(a), val(b) if va is None or vb is None: return False if va & 0xFFFFFFFF != vb & 0xFFFFFFFF: return False return True def main(): pre = prefix() ws = words() tmp = tempfile.mkdtemp() with open(os.path.join(tmp, "w.bin"), "wb") as f: for w in ws: f.write(w.to_bytes(4, "little")) dump = subprocess.run([pre + "objdump", "-D", "-b", "binary", "-m", "riscv:rv32", "-M", "numeric", "--adjust-vma=0x1000", os.path.join(tmp, "w.bin")], capture_output=True, text=True).stdout gnu = {} for line in dump.splitlines(): mm = re.match(r"\s*([0-9a-f]+):\s+([0-9a-f]{8})\s+(.*)", line) if mm and int(mm.group(1), 16) >= 0x1000: gnu[int(mm.group(1), 16) - 0x1000] = mm.group(3) ours = subprocess.run([HOST, "dis"], input="".join("%08X\n" % w for w in ws), capture_output=True, text=True).stdout.splitlines() regn = ["ZERO", "RA", "SP", "GP", "TP", "T0", "T1", "T2", "S0", "S1"] + \ ["A%d" % i for i in range(8)] + ["S%d" % i for i in range(2, 12)] + ["T3", "T4", "T5", "T6"] bad_dis = 0 for i, (w, o) in enumerate(zip(ws, ours)): g = gnu.get(4 * i) if g is None or w == 0x70200073: # (binutils doesn't know MNRET) continue gm, gops = norm_gnu(g, 0x1000) # objdump -M numeric prints x registers: map to ABI names; and its # branch/jump targets are relative to this word (we disassemble at 1000h) gops = [re.sub(r"\bX(\d+)\b", lambda q: regn[int(q.group(1))], t) for t in gops] if gm in ("J", "JAL", "BEQ", "BNE", "BLT", "BGE", "BLTU", "BGEU", "BEQZ", "BNEZ", "BLTZ", "BGEZ", "BLEZ", "BGTZ"): v = val(gops[-1]) if v is not None: gops[-1] = str((v - 4 * i) & 0xFFFFFFFF) if not same(gm, gops, o): bad_dis += 1 if bad_dis <= 15: print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o)) # round trip through the monitor's assembler, one instruction at 1000h each bad_asm = 0 back = subprocess.run([HOST, "asm"], input="".join("ORG 1000H\n%s\n" % o for o in ours), capture_output=True, text=True).stdout.splitlines() for w, o, b in zip(ws, ours, back): want = 0x0FF0000F if (w & 0x707F) == 0x0F else w if b.startswith("ERROR") or int(b, 16) != want: bad_asm += 1 if bad_asm <= 15: print("ASM %08X -> '%s' -> %s" % (w, o, b)) print("%d instructions: %d disassembled differently from objdump, %d assembled back wrong" % (len(ws), bad_dis, bad_asm)) sys.exit(1 if bad_dis or bad_asm else 0) if __name__ == "__main__": main()