"""Compare kernel sections of extracted cubin ELF files (cuobjdump -xelf all). usage: cubin_files.py LABEL A_DIR B_DIR"""
import glob, hashlib, json, sys
sys.path.insert(0, "/n/scripts")
import cubin_diff as c

def load(d):
    out = {}
    for f in sorted(glob.glob(d + "/*.cubin")):
        secs, _ = c.elf_sections(open(f, "rb").read())
        for n, data in secs:
            if n.startswith((".text.", ".nv.info.", ".nv.constant", ".nv.shared.")) and data:
                out[n] = hashlib.sha256(data).hexdigest()
    return out

label, a, b = sys.argv[1], load(sys.argv[2]), load(sys.argv[3])
t = lambda ks: [k for k in ks if k.startswith(".text.")]
same = [k for k in a if b.get(k) == a[k]]; differ = [k for k in a if k in b and b[k] != a[k]]
only_a = [k for k in a if k not in b]; only_b = [k for k in b if k not in a]
print(json.dumps({"label": label, "sections_a": len(a), "sections_b": len(b), "kernels_identical": len(t(same)),
                  "kernels_differ": len(t(differ)), "kernels_only_a": len(t(only_a)), "kernels_only_b": len(t(only_b))}))
for kind, ks in (("differ", differ), ("only_a", only_a), ("only_b", only_b)):
    for k in sorted(ks):
        print(json.dumps({"label": label, "kind": kind, "section": k[:300]}))
