From 4a48975ea779af405fe919db7a5f2d7b815e8c69 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sun, 27 Nov 2011 06:34:47 +0200 Subject: [PATCH] some performance improvements --- elftools/common/utils.py | 14 ++++++++++++++ elftools/dwarf/dwarfinfo.py | 8 +++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/elftools/common/utils.py b/elftools/common/utils.py index 2b55e5e..2ce6746 100644 --- a/elftools/common/utils.py +++ b/elftools/common/utils.py @@ -32,6 +32,20 @@ def struct_parse(struct, stream, stream_pos=None): raise ELFParseError(e.message) +def parse_cstring_from_stream(stream, stream_pos=None): + """ Parse a C-string from the given stream. The string is returned without + the terminating \x00 byte. + If stream_pos is provided, the stream is seeked to this position before + the parsing is done. Otherwise, the current position of the stream is + used. + """ + # I could've just used construct.CString, but this function is 4x faster. + # Since it's needed a lot, I created it as an optimization. + if stream_pos is not None: + stream.seek(stream_pos) + return ''.join(iter(lambda: stream.read(1), '\x00')) + + def elf_assert(cond, msg=''): """ Assert that cond is True, otherwise raise ELFError(msg) """ diff --git a/elftools/dwarf/dwarfinfo.py b/elftools/dwarf/dwarfinfo.py index bfbba8d..db42017 100644 --- a/elftools/dwarf/dwarfinfo.py +++ b/elftools/dwarf/dwarfinfo.py @@ -10,7 +10,8 @@ from collections import namedtuple from ..construct import CString from ..common.exceptions import DWARFError -from ..common.utils import struct_parse, dwarf_assert +from ..common.utils import (struct_parse, dwarf_assert, + parse_cstring_from_stream) from .structs import DWARFStructs from .compileunit import CompileUnit from .abbrevtable import AbbrevTable @@ -115,10 +116,7 @@ class DWARFInfo(object): """ Obtain a string from the string table section, given an offset relative to the section. """ - return struct_parse( - CString(''), - self.debug_str_sec.stream, - stream_pos=offset) + return parse_cstring_from_stream(self.debug_str_sec.stream, offset) #------ PRIVATE ------# -- 2.30.2