elf: Fix SHA256 calculation

The comment says it returns the "SHA256 hash of the input ELF file", but this is
not true - it was the SHA256 hash of the output ELF file. As the parser may
change some bytes around in minor ways, these were often not the same.
This commit is contained in:
Angus Gratton
2023-04-13 11:43:06 +10:00
committed by BOT
parent 2d26ace5e5
commit 76e1212c8f

View File

@ -126,6 +126,8 @@ class ElfFile(object):
self.load_segments = [] # type: list[ElfSegment]
self.note_segments = [] # type: list[ElfNoteSegment]
self.sha256 = b'' # type: bytes
if elf_path and os.path.isfile(elf_path):
self.read_elf(elf_path)
@ -156,6 +158,13 @@ class ElfFile(object):
sec.data,
sec.sh.sh_flags) for sec in self._model.sections]
# calculate sha256 of the input bytes (note: this may not be the same as the sha256 of any generated
# output struct, as the ELF parser may change some details.)
sha256 = hashlib.sha256()
sha256.update(elf_bytes)
self.sha256 = sha256.digest()
@staticmethod
def _parse_string_table(byte_str, offset): # type: (bytes, int) -> str
section_name_str = byte_str[offset:]
@ -215,15 +224,6 @@ class ElfFile(object):
return Struct(*args)
@property
def sha256(self): # type: () -> bytes
"""
:return: SHA256 hash of the input ELF file
"""
sha256 = hashlib.sha256()
sha256.update(self._struct.build(self._model)) # type: ignore
return sha256.digest()
class ElfSection(object):
SHF_WRITE = 0x01