elf_mem_map 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. SRAM_OFFSET = 0x800000
  8. EEPROM_OFFSET = 0x810000
  9. FILL_BYTE = b'\0'
  10. Entry = namedtuple('Entry', ['name', 'loc', 'size'])
  11. def array_inc(loc, dim, idx=0):
  12. if idx == len(dim):
  13. return True
  14. loc[idx] += 1
  15. if loc[idx] == dim[idx]:
  16. loc[idx] = 0
  17. return array_inc(loc, dim, idx+1)
  18. return False
  19. def get_elf_globals(path):
  20. fd = open(path, "rb")
  21. if fd is None:
  22. return
  23. elffile = elftools.elf.elffile.ELFFile(fd)
  24. if elffile is None or not elffile.has_dwarf_info():
  25. return
  26. # probably not needed, since we're decoding expressions manually
  27. elftools.dwarf.descriptions.set_global_machine_arch(elffile.get_machine_arch())
  28. dwarfinfo = elffile.get_dwarf_info()
  29. grefs = []
  30. for CU in dwarfinfo.iter_CUs():
  31. for DIE in CU.iter_DIEs():
  32. # handle only variable types
  33. if DIE.tag != 'DW_TAG_variable':
  34. continue
  35. if 'DW_AT_name' not in DIE.attributes:
  36. continue
  37. if 'DW_AT_location' not in DIE.attributes:
  38. continue
  39. if 'DW_AT_type' not in DIE.attributes:
  40. continue
  41. # handle locations encoded directly as DW_OP_addr (leaf globals)
  42. at_loc = DIE.attributes['DW_AT_location']
  43. if at_loc.form != 'DW_FORM_block1' or at_loc.value[0] != 3:
  44. continue
  45. loc = (at_loc.value[1]) + (at_loc.value[2] << 8) \
  46. + (at_loc.value[3] << 16) + (at_loc.value[4] << 24)
  47. if loc < SRAM_OFFSET or loc >= EEPROM_OFFSET:
  48. continue
  49. loc -= SRAM_OFFSET
  50. # variable name
  51. name = DIE.attributes['DW_AT_name'].value.decode('ascii')
  52. # recurse on type to find the final storage definition
  53. type_DIE = DIE
  54. byte_size = None
  55. array_dim = []
  56. while True:
  57. if 'DW_AT_byte_size' in type_DIE.attributes:
  58. byte_size = type_DIE.attributes.get('DW_AT_byte_size')
  59. if 'DW_AT_type' not in type_DIE.attributes:
  60. break
  61. type_DIE = type_DIE.get_DIE_from_attribute('DW_AT_type')
  62. if type_DIE.tag == 'DW_TAG_array_type':
  63. # fetch array dimensions (if known)
  64. for range_DIE in type_DIE.iter_children():
  65. if range_DIE.tag == 'DW_TAG_subrange_type' and \
  66. 'DW_AT_upper_bound' in range_DIE.attributes:
  67. array_dim.append(range_DIE.attributes['DW_AT_upper_bound'].value + 1)
  68. if byte_size is None:
  69. continue
  70. size = byte_size.value
  71. if len(array_dim) == 0 or (len(array_dim) == 1 and array_dim[0] == 1):
  72. # plain entry
  73. grefs.append(Entry(name, loc, size))
  74. elif len(array_dim) == 1 and size == 1:
  75. # likely string, avoid expansion
  76. grefs.append(Entry('{}[]'.format(name), loc, array_dim[0]))
  77. else:
  78. # expand array entries
  79. array_pos = loc
  80. array_loc = [0] * len(array_dim)
  81. while True:
  82. # location index
  83. sfx = ''
  84. for d in range(len(array_dim)):
  85. sfx += '[{}]'.format(array_loc[d])
  86. grefs.append(Entry(name + sfx, array_pos, size))
  87. # advance
  88. array_pos += size
  89. if array_inc(array_loc, array_dim):
  90. break
  91. return grefs
  92. def decode_dump(path):
  93. fd = open(path, 'r')
  94. if fd is None:
  95. return None
  96. buf_addr = None # starting address
  97. buf_data = None # data
  98. for line in fd:
  99. tokens = line.split(maxsplit=1)
  100. if len(tokens) == 0 or tokens[0] == 'ok':
  101. break
  102. elif len(tokens) < 2 or tokens[0] == 'D2':
  103. continue
  104. addr = int.from_bytes(bytes.fromhex(tokens[0]), 'big')
  105. data = bytes.fromhex(tokens[1])
  106. if buf_addr is None:
  107. buf_addr = addr
  108. buf_data = data
  109. else:
  110. # grow buffer as needed
  111. if addr < buf_addr:
  112. buf_data = FILL_BYTE * (buf_addr - addr)
  113. buf_addr = addr
  114. addr_end = addr + len(data)
  115. buf_end = buf_addr + len(buf_data)
  116. if addr_end > buf_end:
  117. buf_data += FILL_BYTE * (addr_end - buf_end)
  118. # replace new part
  119. rep_start = addr - buf_addr
  120. rep_end = rep_start + len(data)
  121. buf_data = buf_data[:rep_start] + data + buf_data[rep_end:]
  122. return (buf_addr, buf_data)
  123. def annotate_refs(grefs, addr, data, width=45, gaps=True):
  124. last_end = None
  125. for entry in grefs:
  126. if entry.loc < addr:
  127. continue
  128. if entry.loc + entry.size > addr + len(data):
  129. continue
  130. pos = entry.loc-addr
  131. end_pos = pos + entry.size
  132. buf = data[pos:end_pos]
  133. buf_repr = ''
  134. if len(buf) in [1, 2, 4]:
  135. # attempt to decode as integers
  136. buf_repr += ' I:' + str(int.from_bytes(buf, 'big')).rjust(10)
  137. if len(buf) in [4, 8]:
  138. # attempt to decode as floats
  139. typ = 'f' if len(buf) == 4 else 'd'
  140. buf_repr += ' F:' + '{:10.3f}'.format(unpack(typ, buf)[0])
  141. if gaps and last_end is not None and last_end < pos:
  142. # decode gaps
  143. gap_size = pos - last_end
  144. gap_buf = data[last_end:pos]
  145. print('{:04x} {} {:4} R:{}'.format(addr+last_end, "*UNKNOWN*".ljust(width),
  146. gap_size, gap_buf.hex()))
  147. print('{:04x} {} {:4}{} R:{}'.format(entry.loc, entry.name.ljust(width),
  148. entry.size, buf_repr, buf.hex()))
  149. last_end = end_pos
  150. def print_map(grefs):
  151. print('OFFSET\tSIZE\tNAME')
  152. for entry in grefs:
  153. print('{:x}\t{}\t{}'.format(entry.loc, entry.size, entry.name))
  154. def main():
  155. ap = argparse.ArgumentParser(description="""
  156. Generate a symbol table map starting directly from an ELF
  157. firmware with DWARF2 debugging information.
  158. When used along with a memory dump obtained from the D2 g-code,
  159. show the value of each symbol which is within the address range.
  160. """)
  161. ap.add_argument('elf', help='ELF file containing DWARF2 debugging information')
  162. g = ap.add_mutually_exclusive_group(required=True)
  163. g.add_argument('dump', nargs='?', help='RAM dump obtained from D2 g-code')
  164. g.add_argument('--map', action='store_true', help='dump global memory map')
  165. args = ap.parse_args()
  166. grefs = get_elf_globals(args.elf)
  167. grefs = list(sorted(grefs, key=lambda x: x.loc))
  168. if args.dump is None:
  169. print_map(grefs)
  170. else:
  171. addr, data = decode_dump(args.dump)
  172. annotate_refs(grefs, addr, data)
  173. if __name__ == '__main__':
  174. exit(main())