blob: 2b55e5e256695150c27de29326a1518df37e4a44 [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
Eli Benderskyebe51162011-10-27 17:34:02 +020013def bytelist2string(bytelist):
14 """ Convert a list of byte values (e.g. [0x10 0x20 0x00]) to a string
15 (e.g. '\x10\x20\x00').
16 """
17 return ''.join(chr(b) for b in bytelist)
18
19
Eli Benderskye0735d52011-09-08 20:12:44 +030020def struct_parse(struct, stream, stream_pos=None):
Eli Bendersky3f4de3e2011-09-14 05:58:06 +030021 """ Convenience function for using the given struct to parse a stream.
Eli Benderskye0735d52011-09-08 20:12:44 +030022 If stream_pos is provided, the stream is seeked to this position before
Eli Bendersky3f4de3e2011-09-14 05:58:06 +030023 the parsing is done. Otherwise, the current position of the stream is
24 used.
25 Wraps the error thrown by construct with ELFParseError.
Eli Benderskye0735d52011-09-08 20:12:44 +030026 """
27 try:
28 if stream_pos is not None:
29 stream.seek(stream_pos)
30 return struct.parse_stream(stream)
31 except ConstructError as e:
32 raise ELFParseError(e.message)
33
34
eliben116899e2011-09-08 17:15:53 +030035def elf_assert(cond, msg=''):
Eli Benderskye0735d52011-09-08 20:12:44 +030036 """ Assert that cond is True, otherwise raise ELFError(msg)
37 """
eliben44556512011-09-19 12:54:32 +030038 _assert_with_exception(cond, msg, ELFError)
Eli Benderskye0735d52011-09-08 20:12:44 +030039
eliben44556512011-09-19 12:54:32 +030040
41def dwarf_assert(cond, msg=''):
42 """ Assert that cond is True, otherwise raise DWARFError(msg)
43 """
44 _assert_with_exception(cond, msg, DWARFError)
45
46
47def _assert_with_exception(cond, msg, exception_type):
48 if not cond:
eliben033b44f2011-09-19 15:48:39 +030049 raise exception_type(msg)
50
eliben3b9ad822011-09-22 11:46:26 +030051
52from contextlib import contextmanager
53
54@contextmanager
55def preserve_stream_pos(stream):
56 """ Usage:
57
58 # stream has some position FOO (return value of stream.tell())
59 with preserve_stream_pos(stream):
60 # do stuff that manipulates the stream
61 # stream still has position FOO
62 """
63 saved_pos = stream.tell()
64 yield
65 stream.seek(saved_pos)