1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
#!/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": <target VA>, "size": n, "cls": IDENT|RELOC|MOVED}}
Diverged functions are reported separately and deliberately NOT given an address.
usage: vport_emit.py <new.elf> <funcs.json> <target.elf> <out.json>
"""
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('<I', b[28:32])[0]
t, off, va, pa, fsz, msz, fl, al = struct.unpack('<IIIIIIII', b[ph:ph + 32])
return b, off, va, fsz
def seq(buf, va, maxn=None):
out = []
for ins in md.disasm(buf, va):
out.append(ins.mnemonic)
if maxn and len(out) >= 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()
|