github/workflows/pycopy-test: Upgrade Pycopy to 3.6.1.
[ScratchABlock.git] / bindata.py
blob78242ecec0cbea7f43915e943a2a1ed036155386
1 "Module to deal with (binary) data of analyzed code."
3 import glob
4 import re
5 from collections import namedtuple
8 AreaTuple = namedtuple("AreaTuple", ["start", "end", "data", "props"])
10 AREAS = []
13 class InvalidAddrException(Exception):
14 "Thrown when dereferencing address which doesn't exist in address space."
15 def __init__(self, addr):
16 self.args = (addr, hex(addr))
19 def init(dir):
20 "Initialize and load binary data structures."
21 for fname in glob.glob(dir + "/*.bin"):
22 m = re.search(r".+/([0-9A-Fa-f]+)-([0-9A-Fa-f]+)(-([A-Za-z]+))?", fname)
23 if not m:
24 continue
25 with open(fname, "rb") as f:
26 data = f.read()
27 start = int(m.group(1), 16)
28 end = int(m.group(2), 16)
29 access = m.group(4).upper()
30 AREAS.append(AreaTuple(start, end, data, {"access": access}))
31 AREAS.sort()
34 def addr2area(addr):
35 for a in AREAS:
36 if a.start <= addr < a.end:
37 return (addr - a.start, a)
38 return (None, None)
41 def get_bytes(addr, sz):
42 off, area = addr2area(addr)
43 if area is None:
44 raise InvalidAddrException(addr)
45 return area.data[off:off + sz]
48 def deref(addr, bits):
49 # TODO: hardcodes little-endian
50 res = 0
51 bcnt = 0
52 for b in get_bytes(addr, bits // 8):
53 res |= b << bcnt
54 bcnt += 8
55 return res
58 if __name__ == "__main__":
59 init(".")
60 print(hex(deref(0x40000054, 32)))