#!/usr/bin/env python3 """Emit a ported symbol map: current-build function names -> addresses in a target (e.g. the actually-running) build. Needed because the running firmware (0.49.0.53) is a different build from the one we reverse engineered (0.49.0.54): in SYS_DRV 848/1141 functions MOVED, so every .54 address is wrong on the live part. Output JSON: {"name": {"va": , "size": n, "cls": IDENT|RELOC|MOVED}} Diverged functions are reported separately and deliberately NOT given an address. usage: vport_emit.py """ import json, sys, os, struct from collections import defaultdict from capstone import Cs, CS_ARCH_ARM, CS_MODE_THUMB, CS_MODE_LITTLE_ENDIAN NGRAM = 8 md = Cs(CS_ARCH_ARM, CS_MODE_THUMB | CS_MODE_LITTLE_ENDIAN) md.detail = False def load(p): b = open(p, 'rb').read() ph = struct.unpack('= maxn: break return tuple(out) def main(): new_p, funcs_p, tgt_p, out_p = sys.argv[1:5] nb, noff, nva, _ = load(new_p) ob, ooff, ova, ofsz = load(tgt_p) funcs = json.load(open(funcs_p)) F = sorted(((int(k, 16), v[0], v[1]) for k, v in funcs.items())) idx = defaultdict(list) for va in range(ova, ova + ofsz, 2): fo = va - ova + ooff if fo + 64 > len(ob): continue s = seq(ob[fo:fo + 64], va, NGRAM) if len(s) == NGRAM: idx[s].append(va) out, diverged, tiny = {}, [], [] for st, nm, en in F: size = en - st fs = st - nva + noff if fs < 0 or fs + size > len(nb): continue body = nb[fs:fs + size] s_new = seq(body, st) if len(s_new) < NGRAM: tiny.append(nm) continue hit = None for cand in idx.get(s_new[:NGRAM], ()): co = cand - ova + ooff if co + size > len(ob): continue if seq(ob[co:co + size], cand) == s_new: hit = cand break if hit is None: diverged.append(nm) continue if hit == st: cls = 'IDENT' if ob[st - ova + ooff:st - ova + ooff + size] == body else 'RELOC' else: cls = 'MOVED' out[nm] = {"va": hit, "size": size, "cls": cls} json.dump({"map": out, "diverged": sorted(diverged), "tiny": sorted(tiny), "source": os.path.basename(new_p), "target": os.path.basename(tgt_p)}, open(out_p, 'w'), indent=1) print("%s -> %s : mapped=%d diverged=%d tiny=%d (%s)" % (os.path.basename(new_p), os.path.basename(tgt_p), len(out), len(diverged), len(tiny), out_p)) if __name__ == "__main__": main()