blob: 8b9b9ae7d98ac41774677e002ace9f5555aef822 [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#-------------------------------------------------------------------------------
9from .exceptions import ELFParseError, ELFError
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 """
31 if not cond:
32 raise ELFError(msg)
33