Skip to content

Commit 9e6f729

Browse files
authored
Some resilience to malformed ELF header (#628)
* Som resilience to malformed ELF header * Better enum fallback * String table lazy load
1 parent 3b2d8c4 commit 9e6f729

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

elftools/elf/descriptions.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def describe_ei_data(x):
2727

2828

2929
def describe_ei_version(x):
30-
s = '%d' % ENUM_E_VERSION[x]
30+
s = str(ENUM_E_VERSION.get(x, f"{x} <unknown>"))
3131
if x == 'EV_CURRENT':
3232
s += ' (current)'
3333
return s
@@ -41,9 +41,10 @@ def describe_e_type(x, elffile=None):
4141
if elffile is not None and x == 'ET_DYN':
4242
# Detect whether this is a normal SO or a PIE executable
4343
dynamic = elffile.get_section_by_name('.dynamic')
44-
for t in dynamic.iter_tags('DT_FLAGS_1'):
45-
if t.entry.d_val & ENUM_DT_FLAGS_1['DF_1_PIE']:
46-
return 'DYN (Position-Independent Executable file)'
44+
if dynamic:
45+
for t in dynamic.iter_tags('DT_FLAGS_1'):
46+
if t.entry.d_val & ENUM_DT_FLAGS_1['DF_1_PIE']:
47+
return 'DYN (Position-Independent Executable file)'
4748
return _DESCR_E_TYPE.get(x, _unknown)
4849

4950

@@ -52,7 +53,7 @@ def describe_e_machine(x):
5253

5354

5455
def describe_e_version_numeric(x):
55-
return '0x%x' % ENUM_E_VERSION[x]
56+
return f"{ENUM_E_VERSION.get(x, x):#x}"
5657

5758

5859
def describe_p_type(x):

elftools/elf/elffile.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,7 @@ def __init__(self, stream, stream_loader=None):
8484
self.stream.seek(0)
8585
self.e_ident_raw = self.stream.read(16)
8686

87-
self._section_header_stringtable = \
88-
self._get_section_header_stringtable()
87+
self._section_header_stringtable = None # Lazy load
8988
self._section_name_map = None
9089
self.stream_loader = stream_loader
9190

@@ -693,8 +692,10 @@ def _get_section_name(self, section_header):
693692
""" Given a section header, find this section's name in the file's
694693
string table
695694
"""
696-
if self._section_header_stringtable is None:
697-
raise ELFParseError("String Table not found")
695+
if self._section_header_stringtable is None: # Try to lazy load
696+
self._section_header_stringtable = self._get_section_header_stringtable()
697+
if self._section_header_stringtable is None: # If absent (or badly malformed)
698+
raise ELFParseError("String Table not found")
698699

699700
name_offset = section_header['sh_name']
700701
return self._section_header_stringtable.get_string(name_offset)

0 commit comments

Comments
 (0)