"""Compare the machine code of every MMA kernel between two objects (cubin .text.<kernel> sections).
Usage (in the image): python textcmp.py base.o new.o  -- names are normalised for the extra `SIZED = false` template bool."""
import hashlib, os, re, struct, subprocess, sys, tempfile
def texts(obj):
    d = tempfile.mkdtemp()
    subprocess.run(["cuobjdump", "-xelf", "all", os.path.abspath(obj)], cwd=d, check=True, capture_output=True)
    out = {}
    for f in os.listdir(d):
        b = open(os.path.join(d, f), "rb").read()
        if b[:4] != b"\x7fELF": continue
        shoff, = struct.unpack_from("<Q", b, 0x28); shentsize, shnum, shstrndx = struct.unpack_from("<HHH", b, 0x3A)
        secs = [struct.unpack_from("<IIQQQQIIQQ", b, shoff + i * shentsize) for i in range(shnum)]
        stro = secs[shstrndx][4]
        for s in secs:
            name = b[stro + s[0]: b.index(b"\0", stro + s[0])].decode()
            if name.startswith(".text."):
                out[name[6:]] = hashlib.sha256(b[s[4]: s[4] + s[5]]).hexdigest()[:16] + f":{s[5]}"
    return out
a, b = texts(sys.argv[1]), texts(sys.argv[2])
norm = lambda n: re.sub(r"(ELb[01])ELb0E", r"\1E", n)
bn = {norm(k): v for k, v in b.items()}
same = [k for k in a if bn.get(k) == a[k]]; diff = [k for k in a if k in bn and bn[k] != a[k]]; miss = [k for k in a if k not in bn]
print(f"kernels: base {len(a)}, new {len(b)}; identical machine code {len(same)}, different {len(diff)}, unmatched {len(miss)}")
for k in diff[:10]: print("DIFF", k[:110], a[k], bn[k])
for k in miss[:5]: print("MISS", k[:110])
