elf_mem_map 6.4 KB

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