elf_mem_map 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. #!/usr/bin/env python3
  2. import argparse
  3. import elftools.elf.elffile
  4. import elftools.dwarf.descriptions
  5. from collections import namedtuple
  6. from struct import unpack
  7. import re
  8. SRAM_START = 0x200
  9. SRAM_OFFSET = 0x800000
  10. EEPROM_OFFSET = 0x810000
  11. FILL_BYTE = b'\0'
  12. Entry = namedtuple('Entry', ['name', 'loc', 'size', 'declpos'])
  13. Member = namedtuple('Member', ['name', 'off', 'size'])
  14. def array_inc(loc, dim, idx=0):
  15. if idx == len(dim):
  16. return True
  17. loc[idx] += 1
  18. if loc[idx] == dim[idx]:
  19. loc[idx] = 0
  20. return array_inc(loc, dim, idx+1)
  21. return False
  22. def get_type_size(type_DIE):
  23. while True:
  24. if 'DW_AT_byte_size' in type_DIE.attributes:
  25. return type_DIE, type_DIE.attributes.get('DW_AT_byte_size').value
  26. if 'DW_AT_type' not in type_DIE.attributes:
  27. return None
  28. type_DIE = type_DIE.get_DIE_from_attribute('DW_AT_type')
  29. def get_type_arrsize(type_DIE):
  30. size = get_type_size(type_DIE)
  31. if size is None:
  32. return None
  33. byte_size = size[1]
  34. if size[0].tag != 'DW_TAG_pointer_type':
  35. array_DIE = get_type_def(type_DIE, 'DW_TAG_array_type')
  36. if array_DIE is not None:
  37. for range_DIE in array_DIE.iter_children():
  38. if range_DIE.tag == 'DW_TAG_subrange_type' and \
  39. 'DW_AT_upper_bound' in range_DIE.attributes:
  40. dim = range_DIE.attributes['DW_AT_upper_bound'].value + 1
  41. byte_size *= dim
  42. return byte_size
  43. def get_type_def(type_DIE, type_tag):
  44. while True:
  45. if type_DIE.tag == type_tag:
  46. return type_DIE
  47. if 'DW_AT_type' not in type_DIE.attributes:
  48. return None
  49. type_DIE = type_DIE.get_DIE_from_attribute('DW_AT_type')
  50. def get_FORM_block1(attr):
  51. if attr.form != 'DW_FORM_block1':
  52. return None
  53. if attr.value[0] == 3: # OP_addr
  54. return int.from_bytes(attr.value[1:], 'little')
  55. if attr.value[0] == 35: # OP_plus_uconst (ULEB128)
  56. v = 0
  57. s = 0
  58. for b in attr.value[1:]:
  59. v |= (b & 0x7f) << s
  60. if b & 0x80 == 0:
  61. break
  62. s += 7
  63. return v
  64. return None
  65. def get_array_dims(DIE):
  66. array_DIE = get_type_def(DIE, 'DW_TAG_array_type')
  67. if array_DIE is None:
  68. return []
  69. array_dim = []
  70. for range_DIE in array_DIE.iter_children():
  71. if range_DIE.tag == 'DW_TAG_subrange_type' and \
  72. 'DW_AT_upper_bound' in range_DIE.attributes:
  73. array_dim.append(range_DIE.attributes['DW_AT_upper_bound'].value + 1)
  74. return array_dim
  75. def get_struct_members(DIE, entry, expand_structs, struct_gaps):
  76. struct_DIE = get_type_def(DIE, 'DW_TAG_structure_type')
  77. if struct_DIE is None:
  78. return []
  79. members = []
  80. for member_DIE in struct_DIE.iter_children():
  81. if member_DIE.tag == 'DW_TAG_member' and 'DW_AT_name' in member_DIE.attributes:
  82. m_name = member_DIE.attributes['DW_AT_name'].value.decode('ascii')
  83. m_off = get_FORM_block1(member_DIE.attributes['DW_AT_data_member_location'])
  84. m_byte_size = get_type_size(member_DIE)[1]
  85. # still expand member arrays
  86. m_array_dim = get_array_dims(member_DIE)
  87. if m_byte_size == 1 and len(m_array_dim) > 1:
  88. # likely string, remove one dimension
  89. m_byte_size *= m_array_dim.pop()
  90. if len(m_array_dim) == 0 or (len(m_array_dim) == 1 and m_array_dim[0] == 1):
  91. # plain entry
  92. members.append(Member(m_name, m_off, m_byte_size))
  93. elif len(m_array_dim) == 1 and m_byte_size == 1:
  94. # likely string, avoid expansion
  95. members.append(Member(m_name + '[]', m_off, m_array_dim[0]))
  96. else:
  97. # expand array entries
  98. m_array_pos = m_off
  99. m_array_loc = [0] * len(m_array_dim)
  100. while True:
  101. # location index
  102. sfx = ''
  103. for d in range(len(m_array_dim)):
  104. sfx += '[{}]'.format(str(m_array_loc[d]).rjust(len(str(m_array_dim[d]-1)), '0'))
  105. members.append(Member(m_name + sfx, m_array_pos, m_byte_size))
  106. # advance
  107. if array_inc(m_array_loc, m_array_dim):
  108. break
  109. m_array_pos += m_byte_size
  110. if struct_gaps and len(members):
  111. # fill gaps in the middle
  112. members = list(sorted(members, key=lambda x: x.off))
  113. last_end = 0
  114. for n in range(len(members)):
  115. member = members[n]
  116. if member.off > last_end:
  117. members.append(Member('*UNKNOWN*', last_end, member.off - last_end))
  118. last_end = member.off + member.size
  119. if struct_gaps and len(members):
  120. # fill gap at the end
  121. members = list(sorted(members, key=lambda x: x.off))
  122. last = members[-1]
  123. last_end = last.off + last.size
  124. if entry.size > last_end:
  125. members.append(Member('*UNKNOWN*', last_end, entry.size - last_end))
  126. return members
  127. def get_elf_globals(path, expand_structs, struct_gaps=True):
  128. fd = open(path, "rb")
  129. if fd is None:
  130. return
  131. elffile = elftools.elf.elffile.ELFFile(fd)
  132. if elffile is None or not elffile.has_dwarf_info():
  133. return
  134. # probably not needed, since we're decoding expressions manually
  135. elftools.dwarf.descriptions.set_global_machine_arch(elffile.get_machine_arch())
  136. dwarfinfo = elffile.get_dwarf_info()
  137. grefs = []
  138. for CU in dwarfinfo.iter_CUs():
  139. file_entries = dwarfinfo.line_program_for_CU(CU).header["file_entry"]
  140. for DIE in CU.iter_DIEs():
  141. # handle only variable types
  142. if DIE.tag != 'DW_TAG_variable':
  143. continue
  144. if 'DW_AT_location' not in DIE.attributes:
  145. continue
  146. if 'DW_AT_name' not in DIE.attributes and \
  147. 'DW_AT_abstract_origin' not in DIE.attributes:
  148. continue
  149. # handle locations encoded directly as DW_OP_addr (leaf globals)
  150. loc = get_FORM_block1(DIE.attributes['DW_AT_location'])
  151. if loc is None or loc < SRAM_OFFSET or loc >= EEPROM_OFFSET:
  152. continue
  153. loc -= SRAM_OFFSET
  154. # variable name/type
  155. if 'DW_AT_name' not in DIE.attributes and \
  156. 'DW_AT_abstract_origin' in DIE.attributes:
  157. DIE = DIE.get_DIE_from_attribute('DW_AT_abstract_origin')
  158. if 'DW_AT_location' in DIE.attributes:
  159. # duplicate reference (handled directly), skip
  160. continue
  161. if 'DW_AT_name' not in DIE.attributes:
  162. continue
  163. if 'DW_AT_type' not in DIE.attributes:
  164. continue
  165. name = DIE.attributes['DW_AT_name'].value.decode('ascii')
  166. # get final storage size
  167. size = get_type_size(DIE)
  168. if size is None:
  169. continue
  170. byte_size = size[1]
  171. # location of main definition
  172. declpos = ''
  173. if 'DW_AT_decl_file' in DIE.attributes and \
  174. 'DW_AT_decl_line' in DIE.attributes:
  175. line = DIE.attributes['DW_AT_decl_line'].value
  176. fname = DIE.attributes['DW_AT_decl_file'].value
  177. if fname and fname - 1 < len(file_entries):
  178. fname = file_entries[fname-1].name.decode('ascii')
  179. declpos = '{}:{}'.format(fname, line)
  180. # fetch array dimensions (if known)
  181. array_dim = get_array_dims(DIE)
  182. # fetch structure members (one level only)
  183. entry = Entry(name, loc, byte_size, declpos)
  184. if not expand_structs or size[0].tag == 'DW_TAG_pointer_type':
  185. members = []
  186. else:
  187. members = get_struct_members(DIE, entry, expand_structs, struct_gaps)
  188. def expand_members(entry, members):
  189. if len(members) == 0:
  190. grefs.append(entry)
  191. else:
  192. for member in members:
  193. grefs.append(Entry(entry.name + '.' + member.name,
  194. entry.loc + member.off, member.size,
  195. entry.declpos))
  196. if byte_size == 1 and len(array_dim) > 1:
  197. # likely string, remove one dimension
  198. byte_size *= array_dim.pop()
  199. if len(array_dim) == 0 or (len(array_dim) == 1 and array_dim[0] == 1):
  200. # plain entry
  201. expand_members(entry, members)
  202. elif len(array_dim) == 1 and byte_size == 1:
  203. # likely string, avoid expansion
  204. grefs.append(Entry(entry.name + '[]', entry.loc,
  205. array_dim[0], entry.declpos))
  206. else:
  207. # expand array entries
  208. array_pos = loc
  209. array_loc = [0] * len(array_dim)
  210. while True:
  211. # location index
  212. sfx = ''
  213. for d in range(len(array_dim)):
  214. sfx += '[{}]'.format(str(array_loc[d]).rjust(len(str(array_dim[d]-1)), '0'))
  215. expand_members(Entry(entry.name + sfx, array_pos,
  216. byte_size, entry.declpos), members)
  217. # advance
  218. if array_inc(array_loc, array_dim):
  219. break
  220. array_pos += byte_size
  221. return grefs
  222. def decode_dump(path):
  223. fd = open(path, 'r')
  224. if fd is None:
  225. return None
  226. buf_addr = None # starting address
  227. buf_data = None # data
  228. for line in fd:
  229. tokens = line.split(maxsplit=1)
  230. if len(tokens) == 0 or tokens[0] == 'ok':
  231. break
  232. elif len(tokens) < 2 or tokens[0] == 'D2':
  233. continue
  234. addr = int.from_bytes(bytes.fromhex(tokens[0]), 'big')
  235. data = bytes.fromhex(tokens[1])
  236. if buf_addr is None:
  237. buf_addr = addr
  238. buf_data = data
  239. else:
  240. # grow buffer as needed
  241. if addr < buf_addr:
  242. buf_data = FILL_BYTE * (buf_addr - addr)
  243. buf_addr = addr
  244. addr_end = addr + len(data)
  245. buf_end = buf_addr + len(buf_data)
  246. if addr_end > buf_end:
  247. buf_data += FILL_BYTE * (addr_end - buf_end)
  248. # replace new part
  249. rep_start = addr - buf_addr
  250. rep_end = rep_start + len(data)
  251. buf_data = buf_data[:rep_start] + data + buf_data[rep_end:]
  252. return (buf_addr, buf_data)
  253. def annotate_refs(grefs, addr, data, width, gaps=True, overlaps=True):
  254. last_end = None
  255. for entry in grefs:
  256. if entry.loc < addr:
  257. continue
  258. if entry.loc + entry.size > addr + len(data):
  259. continue
  260. pos = entry.loc-addr
  261. end_pos = pos + entry.size
  262. buf = data[pos:end_pos]
  263. buf_repr = ''
  264. if len(buf) in [1, 2, 4]:
  265. # attempt to decode as integers
  266. buf_repr += ' I:' + str(int.from_bytes(buf, 'little')).rjust(10)
  267. if len(buf) in [4, 8]:
  268. # attempt to decode as floats
  269. typ = 'f' if len(buf) == 4 else 'd'
  270. buf_repr += ' F:' + '{:10.3f}'.format(unpack(typ, buf)[0])
  271. if last_end is not None:
  272. if gaps and last_end < pos:
  273. # decode gaps
  274. gap_size = pos - last_end
  275. gap_buf = data[last_end:pos]
  276. print('{:04x} {} {:4} R:{}'.format(addr+last_end, "*UNKNOWN*".ljust(width),
  277. gap_size, gap_buf.hex()))
  278. if overlaps and last_end > pos + 1:
  279. gap_size = pos - last_end
  280. print('{:04x} {} {:4}'.format(addr+last_end, "*OVERLAP*".ljust(width), gap_size))
  281. print('{:04x} {} {:4}{} R:{}'.format(entry.loc, entry.name.ljust(width),
  282. entry.size, buf_repr, buf.hex()))
  283. last_end = end_pos
  284. def print_map(grefs):
  285. print('OFFSET\tSIZE\tNAME\tDECLPOS')
  286. for entry in grefs:
  287. print('{:x}\t{}\t{}\t{}'.format(entry.loc, entry.size, entry.name, entry.declpos))
  288. def print_qdirstat(grefs):
  289. print('[qdirstat 1.0 cache file]')
  290. entries = {}
  291. for entry in grefs:
  292. # do not output registers when looking at space usage
  293. if entry.loc < SRAM_START:
  294. continue
  295. paths = list(filter(None, re.split(r'[\[\].]', entry.name)))
  296. base = entries
  297. for i in range(len(paths) - 1):
  298. name = paths[i]
  299. if name not in base:
  300. base[name] = {}
  301. base = base[name]
  302. name = paths[-1]
  303. if name in base:
  304. name = '{}_{:x}'.format(entry.name, entry.loc)
  305. base[name] = entry.size
  306. def walker(root, prefix):
  307. files = []
  308. dirs = []
  309. for name, entries in root.items():
  310. if type(entries) == int:
  311. files.append([name, entries])
  312. else:
  313. dirs.append([name, entries])
  314. # print files
  315. print('D\t{}\t{}\t0x0'.format(prefix, 0))
  316. for name, size in files:
  317. print('F\t{}\t{}\t0x0'.format(name, size))
  318. # recurse directories
  319. for name, entries in dirs:
  320. walker(entries, prefix + '/' + name)
  321. walker(entries, '/')
  322. def main():
  323. ap = argparse.ArgumentParser(description="""
  324. Generate a symbol table map starting directly from an ELF
  325. firmware with DWARF3 debugging information.
  326. When used along with a memory dump obtained from the D2 g-code,
  327. show the value of each symbol which is within the address range.
  328. """)
  329. ap.add_argument('elf', help='ELF file containing DWARF debugging information')
  330. ap.add_argument('--no-gaps', action='store_true',
  331. help='do not dump memory inbetween known symbols')
  332. ap.add_argument('--no-expand-structs', action='store_true',
  333. help='do not decode structure data')
  334. ap.add_argument('--overlaps', action='store_true',
  335. help='annotate overlaps greater than 1 byte')
  336. ap.add_argument('--name-width', type=int, default=50,
  337. help='set name column width')
  338. g = ap.add_mutually_exclusive_group(required=True)
  339. g.add_argument('dump', nargs='?', help='RAM dump obtained from D2 g-code')
  340. g.add_argument('--map', action='store_true', help='dump global memory map')
  341. g.add_argument('--qdirstat', action='store_true',
  342. help='dump qdirstat-compatible size usage map')
  343. args = ap.parse_args()
  344. grefs = get_elf_globals(args.elf, expand_structs=not args.no_expand_structs)
  345. grefs = list(sorted(grefs, key=lambda x: x.loc))
  346. if args.map:
  347. print_map(grefs)
  348. elif args.qdirstat:
  349. print_qdirstat(grefs)
  350. else:
  351. addr, data = decode_dump(args.dump)
  352. annotate_refs(grefs, addr, data,
  353. width=args.name_width,
  354. gaps=not args.no_gaps,
  355. overlaps=args.overlaps)
  356. if __name__ == '__main__':
  357. exit(main())