elf_mem_map 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. while True:
  48. if 'DW_AT_byte_size' in type_DIE.attributes:
  49. byte_size = type_DIE.attributes.get('DW_AT_byte_size')
  50. if 'DW_AT_type' not in type_DIE.attributes:
  51. break
  52. type_DIE = type_DIE.get_DIE_from_attribute('DW_AT_type')
  53. if byte_size is None:
  54. continue
  55. size = byte_size.value
  56. grefs.append(Entry(name, loc, size))
  57. return grefs
  58. def decode_dump(path):
  59. fd = open(path, 'r')
  60. if fd is None:
  61. return None
  62. buf_addr = None # starting address
  63. buf_data = None # data
  64. for line in fd:
  65. tokens = line.split(maxsplit=1)
  66. if len(tokens) == 0 or tokens[0] == 'ok':
  67. break
  68. elif len(tokens) < 2 or tokens[0] == 'D2':
  69. continue
  70. addr = int.from_bytes(bytes.fromhex(tokens[0]), 'big')
  71. data = bytes.fromhex(tokens[1])
  72. if buf_addr is None:
  73. buf_addr = addr
  74. buf_data = data
  75. else:
  76. # grow buffer as needed
  77. if addr < buf_addr:
  78. buf_data = FILL_BYTE * (buf_addr - addr)
  79. buf_addr = addr
  80. addr_end = addr + len(data)
  81. buf_end = buf_addr + len(buf_data)
  82. if addr_end > buf_end:
  83. buf_data += FILL_BYTE * (addr_end - buf_end)
  84. # replace new part
  85. rep_start = addr - buf_addr
  86. rep_end = rep_start + len(data)
  87. buf_data = buf_data[:rep_start] + data + buf_data[rep_end:]
  88. return (buf_addr, buf_data)
  89. def annotate_refs(grefs, addr, data, width=45, gaps=True):
  90. last_end = None
  91. for entry in grefs:
  92. if entry.loc < addr:
  93. continue
  94. if entry.loc + entry.size > addr + len(data):
  95. continue
  96. pos = entry.loc-addr
  97. end_pos = pos + entry.size
  98. buf = data[pos:end_pos]
  99. buf_repr = ''
  100. if len(buf) in [1, 2, 4]:
  101. # attempt to decode as integers
  102. buf_repr += ' I:' + str(int.from_bytes(buf, 'big')).rjust(10)
  103. if len(buf) in [4, 8]:
  104. # attempt to decode as floats
  105. buf_repr += ' F:' + '{:10.3f}'.format(unpack('f', buf)[0])
  106. if gaps and last_end is not None and last_end < pos:
  107. # decode gaps
  108. gap_size = pos - last_end
  109. gap_buf = data[last_end:pos]
  110. print('{:04x} {} {:4} R:{}'.format(addr+last_end, "*UNKNOWN*".ljust(width),
  111. gap_size, gap_buf.hex()))
  112. print('{:04x} {} {:4}{} R:{}'.format(entry.loc, entry.name.ljust(width),
  113. entry.size, buf_repr, buf.hex()))
  114. last_end = end_pos
  115. def print_map(grefs):
  116. print('OFFSET\tSIZE\tNAME')
  117. for entry in grefs:
  118. print('{:x}\t{}\t{}'.format(entry.loc, entry.size, entry.name))
  119. def main():
  120. ap = argparse.ArgumentParser(description="""
  121. Generate a symbol table map starting directly from an ELF
  122. firmware with DWARF2 debugging information.
  123. When used along with a memory dump obtained from the D2 g-code,
  124. show the value of each symbol which is within the address range.
  125. """)
  126. ap.add_argument('elf', help='ELF file containing DWARF2 debugging information')
  127. g = ap.add_mutually_exclusive_group(required=True)
  128. g.add_argument('dump', nargs='?', help='RAM dump obtained from D2 g-code')
  129. g.add_argument('--map', action='store_true', help='dump global memory map')
  130. args = ap.parse_args()
  131. grefs = get_elf_globals(args.elf)
  132. grefs = list(sorted(grefs, key=lambda x: x.loc))
  133. if args.dump is None:
  134. print_map(grefs)
  135. else:
  136. addr, data = decode_dump(args.dump)
  137. annotate_refs(grefs, addr, data)
  138. if __name__ == '__main__':
  139. exit(main())