Skip to content

Commit

Permalink
get_string of StringTableSection return ascii-decoded strings now
Browse files Browse the repository at this point in the history
fix bugs
  • Loading branch information
JaySon-Huang committed Jun 3, 2015
1 parent b975892 commit 108eaea
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 111 deletions.
2 changes: 1 addition & 1 deletion elftools/elf/dynamic.py
Expand Up @@ -115,7 +115,7 @@ def _get_stringtable(self):

# That didn't work for some reason. Let's use the section header
# even though this ELF is super weird.
self._stringtable = self._elffile.get_section_by_name(b'.dynstr')
self._stringtable = self._elffile.get_section_by_name('.dynstr')
return self._stringtable

def _iter_tags(self, type=None):
Expand Down
22 changes: 11 additions & 11 deletions elftools/elf/elffile.py
Expand Up @@ -125,7 +125,7 @@ def has_dwarf_info(self):
We assume that if it has the debug_info section, it has all theother
required sections as well.
"""
return bool(self.get_section_by_name(b'.debug_info'))
return bool(self.get_section_by_name('.debug_info'))

def get_dwarf_info(self, relocate_dwarf_sections=True):
""" Return a DWARFInfo object representing the debugging information in
Expand All @@ -139,9 +139,9 @@ def get_dwarf_info(self, relocate_dwarf_sections=True):
# Sections that aren't found will be passed as None to DWARFInfo.
#
debug_sections = {}
for secname in (b'.debug_info', b'.debug_abbrev', b'.debug_str',
b'.debug_line', b'.debug_frame',
b'.debug_loc', b'.debug_ranges'):
for secname in ('.debug_info', '.debug_abbrev', '.debug_str',
'.debug_line', '.debug_frame',
'.debug_loc', '.debug_ranges'):
section = self.get_section_by_name(secname)
if section is None:
debug_sections[secname] = None
Expand All @@ -155,15 +155,15 @@ def get_dwarf_info(self, relocate_dwarf_sections=True):
little_endian=self.little_endian,
default_address_size=self.elfclass // 8,
machine_arch=self.get_machine_arch()),
debug_info_sec=debug_sections[b'.debug_info'],
debug_abbrev_sec=debug_sections[b'.debug_abbrev'],
debug_frame_sec=debug_sections[b'.debug_frame'],
debug_info_sec=debug_sections['.debug_info'],
debug_abbrev_sec=debug_sections['.debug_abbrev'],
debug_frame_sec=debug_sections['.debug_frame'],
# TODO(eliben): reading of eh_frame is not hooked up yet
eh_frame_sec=None,
debug_str_sec=debug_sections[b'.debug_str'],
debug_loc_sec=debug_sections[b'.debug_loc'],
debug_ranges_sec=debug_sections[b'.debug_ranges'],
debug_line_sec=debug_sections[b'.debug_line'])
debug_str_sec=debug_sections['.debug_str'],
debug_loc_sec=debug_sections['.debug_loc'],
debug_ranges_sec=debug_sections['.debug_ranges'],
debug_line_sec=debug_sections['.debug_line'])

def get_machine_arch(self):
""" Return the machine architecture, as detected from the ELF header.
Expand Down
4 changes: 2 additions & 2 deletions elftools/elf/relocation.py
Expand Up @@ -102,8 +102,8 @@ def find_relocations_for_section(self, section):
found.
"""
reloc_section_names = (
b'.rel' + section.name,
b'.rela' + section.name)
'.rel' + section.name,
'.rela' + section.name)
# Find the relocation section aimed at this one. Currently assume
# that either .rel or .rela section exists for this section, but
# not both.
Expand Down
2 changes: 1 addition & 1 deletion elftools/elf/sections.py
Expand Up @@ -65,7 +65,7 @@ def get_string(self, offset):
"""
table_offset = self['sh_offset']
s = parse_cstring_from_stream(self.stream, table_offset + offset)
return s
return s.decode('ascii')


class SymbolTableSection(Section):
Expand Down
2 changes: 1 addition & 1 deletion elftools/elf/segments.py
Expand Up @@ -92,7 +92,7 @@ def get_interp_name(self):
"""
path_offset = self['p_offset']
return struct_parse(
CString(''),
CString('', encoding='ascii'),
self.stream,
stream_pos=path_offset)

Expand Down
11 changes: 4 additions & 7 deletions examples/elf_low_high_api.py
Expand Up @@ -61,21 +61,18 @@ def section_info_highlevel(stream):
elffile = ELFFile(stream)

# Just use the public methods of ELFFile to get what we need
# Note that section names, like everything read from the file, are bytes
# objects.
# Note that section names are strings.
print(' %s sections' % elffile.num_sections())
section = elffile.get_section_by_name(b'.symtab')
section = elffile.get_section_by_name('.symtab')

if not section:
print(' No symbol table found. Perhaps this ELF has been stripped?')
return

# A section type is in its header, but the name was decoded and placed in
# a public attribute.
# bytes2str is used to print the name of the section for consistency of
# output between Python 2 and 3. The section name is a bytes object.
print(' Section name: %s, type: %s' %(
bytes2str(section.name), section['sh_type']))
section.name, section['sh_type']))

# But there's more... If this section is a symbol table section (which is
# the case in the sample ELF file that comes with the examples), we can
Expand All @@ -84,7 +81,7 @@ def section_info_highlevel(stream):
num_symbols = section.num_symbols()
print(" It's a symbol section with %s symbols" % num_symbols)
print(" The name of the last symbol in the section is: %s" % (
bytes2str(section.get_symbol(num_symbols - 1).name)))
section.get_symbol(num_symbols - 1).name))


if __name__ == '__main__':
Expand Down
8 changes: 4 additions & 4 deletions examples/elf_relocations.py
Expand Up @@ -27,15 +27,15 @@ def process_file(filename):

# Read the .rela.dyn section from the file, by explicitly asking
# ELFFile for this section
# Recall that section names are bytes objects
reladyn_name = b'.rela.dyn'
# The section names are strings
reladyn_name = '.rela.dyn'
reladyn = elffile.get_section_by_name(reladyn_name)

if not isinstance(reladyn, RelocationSection):
print(' The file has no %s section' % bytes2str(reladyn_name))
print(' The file has no %s section' % reladyn_name)

print(' %s section with %s relocations' % (
bytes2str(reladyn_name), reladyn.num_relocations()))
reladyn_name, reladyn.num_relocations()))

for reloc in reladyn.iter_relocations():
print(' Relocation (%s)' % 'RELA' if reloc.is_RELA() else 'REL')
Expand Down
6 changes: 3 additions & 3 deletions examples/elf_show_debug_sections.py
Expand Up @@ -23,9 +23,9 @@ def process_file(filename):
elffile = ELFFile(f)

for section in elffile.iter_sections():
# Section names are bytes objects
if section.name.startswith(b'.debug'):
print(' ' + bytes2str(section.name))
# Section names are string
if section.name.startswith('.debug'):
print(' ' + section.name)


if __name__ == '__main__':
Expand Down
51 changes: 25 additions & 26 deletions scripts/readelf.py
Expand Up @@ -204,7 +204,7 @@ def display_program_headers(self, show_heading=True):

if isinstance(segment, InterpSegment):
self._emitline(' [Requesting program interpreter: %s]' %
bytes2str(segment.get_interp_name()))
segment.get_interp_name())

# Sections to segments mapping
#
Expand All @@ -221,7 +221,7 @@ def display_program_headers(self, show_heading=True):
for section in self.elffile.iter_sections():
if ( not section.is_null() and
segment.section_in_segment(section)):
self._emit('%s ' % bytes2str(section.name))
self._emit('%s ' % section.name)

self._emitline('')

Expand All @@ -248,7 +248,7 @@ def display_section_headers(self, show_heading=True):
#
for nsec, section in enumerate(self.elffile.iter_sections()):
self._emit(' [%2u] %-17.17s %-15.15s ' % (
nsec, bytes2str(section.name), describe_sh_type(section['sh_type'])))
nsec, section.name, describe_sh_type(section['sh_type'])))

if self.elffile.elfclass == 32:
self._emitline('%s %s %s %s %3s %2s %3s %2s' % (
Expand Down Expand Up @@ -292,11 +292,11 @@ def display_symbol_tables(self):

if section['sh_entsize'] == 0:
self._emitline("\nSymbol table '%s' has a sh_entsize of zero!" % (
bytes2str(section.name)))
section.name))
continue

self._emitline("\nSymbol table '%s' contains %s entries:" % (
bytes2str(section.name), section.num_symbols()))
section.name, section.num_symbols()))

if self.elffile.elfclass == 32:
self._emitline(' Num: Value Size Type Bind Vis Ndx Name')
Expand All @@ -310,7 +310,7 @@ def display_symbol_tables(self):
if (section['sh_type'] == 'SHT_DYNSYM' and
self._versioninfo['type'] == 'GNU'):
version = self._symbol_version(nsym)
if (version['name'] != bytes2str(symbol.name) and
if (version['name'] != symbol.name and
version['index'] not in ('VER_NDX_LOCAL',
'VER_NDX_GLOBAL')):
if version['filename']:
Expand All @@ -333,7 +333,7 @@ def display_symbol_tables(self):
describe_symbol_bind(symbol['st_info']['bind']),
describe_symbol_visibility(symbol['st_other']['visibility']),
describe_symbol_shndx(symbol['st_shndx']),
bytes2str(symbol.name),
symbol.name,
version_info))

def display_dynamic_tags(self):
Expand All @@ -353,13 +353,13 @@ def display_dynamic_tags(self):
padding = 20 + (8 if self.elffile.elfclass == 32 else 0)
for tag in section.iter_tags():
if tag.entry.d_tag == 'DT_NEEDED':
parsed = 'Shared library: [%s]' % bytes2str(tag.needed)
parsed = 'Shared library: [%s]' % tag.needed
elif tag.entry.d_tag == 'DT_RPATH':
parsed = 'Library rpath: [%s]' % bytes2str(tag.rpath)
parsed = 'Library rpath: [%s]' % tag.rpath
elif tag.entry.d_tag == 'DT_RUNPATH':
parsed = 'Library runpath: [%s]' % bytes2str(tag.runpath)
parsed = 'Library runpath: [%s]' % tag.runpath
elif tag.entry.d_tag == 'DT_SONAME':
parsed = 'Library soname: [%s]' % bytes2str(tag.soname)
parsed = 'Library soname: [%s]' % tag.soname
elif tag.entry.d_tag.endswith(('SZ', 'ENT')):
parsed = '%i (bytes)' % tag['d_val']
elif tag.entry.d_tag.endswith(('NUM', 'COUNT')):
Expand Down Expand Up @@ -410,7 +410,7 @@ def display_relocations(self):

has_relocation_sections = True
self._emitline("\nRelocation section '%s' at offset %s contains %s entries:" % (
bytes2str(section.name),
section.name,
self._format_hex(section['sh_offset']),
section.num_relocations()))
if section.is_RELA():
Expand Down Expand Up @@ -448,7 +448,7 @@ def display_relocations(self):
symbol['st_value'],
fullhex=True, lead0x=False),
' ' if self.elffile.elfclass == 32 else '',
bytes2str(symbol_name)))
symbol_name))
if section.is_RELA():
self._emit(' %s %x' % (
'+' if rel['r_addend'] >= 0 else '-',
Expand Down Expand Up @@ -520,14 +520,14 @@ def display_version_info(self):
self._format_hex(offset, fieldsize=6,
alternate=True),
verdef['vd_version'], flags, verdef['vd_ndx'],
verdef['vd_cnt'], bytes2str(name)))
verdef['vd_cnt'], name))

verdaux_offset = (
offset + verdef['vd_aux'] + verdaux['vda_next'])
for idx, verdaux in enumerate(verdaux_iter, start=1):
self._emitline(' %s: Parent %i: %s' %
(self._format_hex(verdaux_offset, fieldsize=4),
idx, bytes2str(verdaux.name)))
idx, verdaux.name))
verdaux_offset += verdaux['vda_next']

offset += verdef['vd_next']
Expand All @@ -541,7 +541,7 @@ def display_version_info(self):
self._emitline(' %s: Version: %i File: %s Cnt: %i' % (
self._format_hex(offset, fieldsize=6,
alternate=True),
verneed['vn_version'], bytes2str(verneed.name),
verneed['vn_version'], verneed.name,
verneed['vn_cnt']))

vernaux_offset = offset + verneed['vn_aux']
Expand All @@ -556,7 +556,7 @@ def display_version_info(self):
self._emitline(
' %s: Name: %s Flags: %s Version: %i' % (
self._format_hex(vernaux_offset, fieldsize=4),
bytes2str(vernaux.name), flags,
vernaux.name, flags,
vernaux['vna_other']))

vernaux_offset += vernaux['vna_next']
Expand All @@ -573,7 +573,7 @@ def display_hex_dump(self, section_spec):
section_spec))
return

self._emitline("\nHex dump of section '%s':" % bytes2str(section.name))
self._emitline("\nHex dump of section '%s':" % section.name)
self._note_relocs_for_section(section)
addr = section['sh_addr']
data = section.data()
Expand Down Expand Up @@ -616,7 +616,7 @@ def display_string_dump(self, section_spec):
section_spec))
return

self._emitline("\nString dump of section '%s':" % bytes2str(section.name))
self._emitline("\nString dump of section '%s':" % section.name)

found = False
data = section.data()
Expand Down Expand Up @@ -717,16 +717,15 @@ def _print_version_section_header(self, version_section, name, lead0x=True,
num_entries = version_section.num_symbols()

self._emitline("\n%s section '%s' contains %s entries:" %
(name, bytes2str(version_section.name), num_entries))
(name, version_section.name, num_entries))
self._emitline('%sAddr: %s Offset: %s Link: %i (%s)' % (
' ' * indent,
self._format_hex(
version_section['sh_addr'], fieldsize=16, lead0x=lead0x),
self._format_hex(
version_section['sh_offset'], fieldsize=6, lead0x=True),
version_section['sh_link'],
bytes2str(
self.elffile.get_section(version_section['sh_link']).name)
self.elffile.get_section(version_section['sh_link']).name
)
)

Expand Down Expand Up @@ -785,12 +784,12 @@ def _symbol_version(self, nsym):
index <= self._versioninfo['verdef'].num_versions()):
_, verdaux_iter = \
self._versioninfo['verdef'].get_version(index)
symbol_version['name'] = bytes2str(next(verdaux_iter).name)
symbol_version['name'] = next(verdaux_iter).name
else:
verneed, vernaux = \
self._versioninfo['verneed'].get_version(index)
symbol_version['name'] = bytes2str(vernaux.name)
symbol_version['filename'] = bytes2str(verneed.name)
symbol_version['name'] = vernaux.name
symbol_version['filename'] = verneed.name

symbol_version['index'] = index
return symbol_version
Expand All @@ -807,7 +806,7 @@ def _section_from_spec(self, spec):
return None
except ValueError:
# Not a number. Must be a name then
return self.elffile.get_section_by_name(str2bytes(spec))
return self.elffile.get_section_by_name(spec)

def _note_relocs_for_section(self, section):
""" If there are relocation sections pointing to the givne section,
Expand Down
6 changes: 3 additions & 3 deletions test/test_double_dynstr_section.py
Expand Up @@ -22,9 +22,9 @@ class TestDoubleDynstrSections(unittest.TestCase):
"""

reference_data = [
b'libz.so.1',
b'libc.so.6',
b'lib_versioned.so.1',
'libz.so.1',
'libc.so.6',
'lib_versioned.so.1',
]

def _test_double_dynstr_section_generic(self, testfile):
Expand Down

0 comments on commit 108eaea

Please sign in to comment.