blob: a36b3ec3e6a014ce83e051273837563525965097 [file] [log] [blame]
Eli Benderskye0735d52011-09-08 20:12:44 +03001#-------------------------------------------------------------------------------
2# elftools: common/utils.py
3#
4# Miscellaneous utilities for elftools
5#
6# Eli Bendersky (eliben@gmail.com)
7# This code is in the public domain
8#-------------------------------------------------------------------------------
eliben033b44f2011-09-19 15:48:39 +03009from .exceptions import ELFParseError, ELFError, DWARFError
elibena7c25472011-09-18 17:31:10 +030010from ..construct import ConstructError
Eli Benderskye0735d52011-09-08 20:12:44 +030011
12
13def struct_parse(struct, stream, stream_pos=None):
Eli Bendersky3f4de3e2011-09-14 05:58:06 +030014 """ Convenience function for using the given struct to parse a stream.
Eli Benderskye0735d52011-09-08 20:12:44 +030015 If stream_pos is provided, the stream is seeked to this position before
Eli Bendersky3f4de3e2011-09-14 05:58:06 +030016 the parsing is done. Otherwise, the current position of the stream is
17 used.
18 Wraps the error thrown by construct with ELFParseError.
Eli Benderskye0735d52011-09-08 20:12:44 +030019 """
20 try:
21 if stream_pos is not None:
22 stream.seek(stream_pos)
23 return struct.parse_stream(stream)
24 except ConstructError as e:
25 raise ELFParseError(e.message)
26
27
eliben116899e2011-09-08 17:15:53 +030028def elf_assert(cond, msg=''):
Eli Benderskye0735d52011-09-08 20:12:44 +030029 """ Assert that cond is True, otherwise raise ELFError(msg)
30 """
eliben44556512011-09-19 12:54:32 +030031 _assert_with_exception(cond, msg, ELFError)
Eli Benderskye0735d52011-09-08 20:12:44 +030032
eliben44556512011-09-19 12:54:32 +030033
34def dwarf_assert(cond, msg=''):
35 """ Assert that cond is True, otherwise raise DWARFError(msg)
36 """
37 _assert_with_exception(cond, msg, DWARFError)
38
39
40def _assert_with_exception(cond, msg, exception_type):
41 if not cond:
eliben033b44f2011-09-19 15:48:39 +030042 raise exception_type(msg)
43