"""Machine code of the grouped MMA arms, main against the branch's three-block arms (.text.<kernel> of each cubin)."""
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])
# main: <B,C,NT,P,LEAN,SIZED>; branch: <B,C,NT,P,LEAN,FOUR,SIZED>. Drop the branch's FOUR=false to match names.
norm = lambda n: re.sub(r"(Li\d+ELi\d+ELi\d+ELi\d+ELb[01]E)Lb0E(Lb[01]E)", r"\1\2", n)
three = {norm(k): v for k, v in b.items() if re.search(r"Li\d+ELi\d+ELi\d+ELi\d+ELb[01]ELb0ELb[01]E", k)}
same = [k for k in a if three.get(k) == a[k]]; diff = [k for k in a if k in three and three[k] != a[k]]; miss = [k for k in a if k not in three]
print(f"grouped kernels: main {len(a)}, branch {len(b)} ({len(three)} at FOUR=false); identical machine code {len(same)}, different {len(diff)}, unmatched {len(miss)}")
for k in diff: print("DIFF", k[:80], a[k], three[k])
for k in miss[:5]: print("MISS", k[:80])
