elf_mem_map: switch to a named tuple for extensibility

This commit is contained in:
Yuri D'Elia 2021-06-02 18:13:43 +02:00 committed by DRracer
parent f2192dc5e6
commit 40b737e33d

View file

@ -2,6 +2,7 @@
import argparse import argparse
import elftools.elf.elffile import elftools.elf.elffile
import elftools.dwarf.descriptions import elftools.dwarf.descriptions
from collections import namedtuple
from struct import unpack from struct import unpack
SRAM_OFFSET = 0x800000 SRAM_OFFSET = 0x800000
@ -9,6 +10,9 @@ EEPROM_OFFSET = 0x810000
FILL_BYTE = b'\0' FILL_BYTE = b'\0'
Entry = namedtuple('Entry', ['name', 'loc', 'size'])
def get_elf_globals(path): def get_elf_globals(path):
fd = open(path, "rb") fd = open(path, "rb")
if fd is None: if fd is None:
@ -60,7 +64,7 @@ def get_elf_globals(path):
continue continue
size = byte_size.value size = byte_size.value
grefs.append([name, loc, size]) grefs.append(Entry(name, loc, size))
return grefs return grefs
@ -106,14 +110,14 @@ def decode_dump(path):
def annotate_refs(grefs, addr, data, width=45, gaps=True): def annotate_refs(grefs, addr, data, width=45, gaps=True):
last_end = None last_end = None
for name, loc, size in grefs: for entry in grefs:
if loc < addr: if entry.loc < addr:
continue continue
if loc + size > addr + len(data): if entry.loc + entry.size > addr + len(data):
continue continue
pos = loc-addr pos = entry.loc-addr
end_pos = pos + size end_pos = pos + entry.size
buf = data[pos:end_pos] buf = data[pos:end_pos]
buf_repr = '' buf_repr = ''
@ -131,15 +135,15 @@ def annotate_refs(grefs, addr, data, width=45, gaps=True):
print('{:04x} {} {:4} R:{}'.format(addr+last_end, "*UNKNOWN*".ljust(width), print('{:04x} {} {:4} R:{}'.format(addr+last_end, "*UNKNOWN*".ljust(width),
gap_size, gap_buf.hex())) gap_size, gap_buf.hex()))
print('{:04x} {} {:4}{} R:{}'.format(loc, name.ljust(width), size, print('{:04x} {} {:4}{} R:{}'.format(entry.loc, entry.name.ljust(width),
buf_repr, buf.hex())) entry.size, buf_repr, buf.hex()))
last_end = end_pos last_end = end_pos
def print_map(grefs): def print_map(grefs):
print('OFFSET\tSIZE\tNAME') print('OFFSET\tSIZE\tNAME')
for name, loc, size in grefs: for entry in grefs:
print('{:x}\t{}\t{}'.format(loc, size, name)) print('{:x}\t{}\t{}'.format(entry.loc, entry.size, entry.name))
def main(): def main():
@ -156,7 +160,7 @@ def main():
args = ap.parse_args() args = ap.parse_args()
grefs = get_elf_globals(args.elf) grefs = get_elf_globals(args.elf)
grefs = list(sorted(grefs, key=lambda x: x[1])) grefs = list(sorted(grefs, key=lambda x: x.loc))
if args.dump is None: if args.dump is None:
print_map(grefs) print_map(grefs)
else: else: