Wrapper for elf object which allows easy access to symbols and rom
| 306 | |
| 307 | |
| 308 | class ElfFileSimple(ELFFile): |
| 309 | """Wrapper for elf object which allows easy access to symbols and rom""" |
| 310 | |
| 311 | def __init__(self, data): |
| 312 | """Construct a ElfFileSimple from bytes or a bytearray""" |
| 313 | super(ElfFileSimple, self).__init__(BytesIO(data)) |
| 314 | self.symbols = self._read_symbol_table() |
| 315 | |
| 316 | def _read_symbol_table(self): |
| 317 | """Read the symbol table into the field "symbols" for easy use""" |
| 318 | section = self.get_section_by_name(".symtab") |
| 319 | if not section: |
| 320 | raise Exception("Missing symbol table") |
| 321 | |
| 322 | if not isinstance(section, SymbolTableSection): |
| 323 | raise Exception("Invalid symbol table section") |
| 324 | |
| 325 | symbols = {} |
| 326 | for symbol in section.iter_symbols(): |
| 327 | name_str = symbol.name |
| 328 | if name_str in symbols: |
| 329 | logging.debug("Duplicate symbol %s", name_str) |
| 330 | symbols[name_str] = SymbolSimple(name_str, symbol["st_value"], |
| 331 | symbol["st_size"]) |
| 332 | return symbols |
| 333 | |
| 334 | def read(self, addr, size): |
| 335 | """Read program data from the elf file |
| 336 | |
| 337 | :param addr: physical address (load address) to read from |
| 338 | :param size: number of bytes to read |
| 339 | :return: Requested data or None if address is unmapped |
| 340 | """ |
| 341 | for segment in self.iter_segments(): |
| 342 | seg_addr = segment["p_paddr"] |
| 343 | seg_size = min(segment["p_memsz"], segment["p_filesz"]) |
| 344 | if addr >= seg_addr + seg_size: |
| 345 | continue |
| 346 | if addr + size <= seg_addr: |
| 347 | continue |
| 348 | # There is at least some overlap |
| 349 | |
| 350 | if addr >= seg_addr and addr + size <= seg_addr + seg_size: |
| 351 | # Region is fully contained |
| 352 | data = segment.data() |
| 353 | start = addr - seg_addr |
| 354 | return data[start:start + size] |
| 355 | |
| 356 | |
| 357 | if __name__ == '__main__': |