2355ed485895d6e0403c6e53c4155826af683ae7
1 #-------------------------------------------------------------------------------
2 # elftools: common/utils.py
4 # Miscellaneous utilities for elftools
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 from contextlib
import contextmanager
10 from .exceptions
import ELFParseError
, ELFError
, DWARFError
11 from ..construct
import ConstructError
, ULInt8
15 def merge_dicts(*dicts
):
16 "Given any number of dicts, merges them into a new one."""
23 def bytelist2string(bytelist):
24 """ Convert a list of byte values (e.g. [0x10 0x20 0x00]) to a bytes object
25 (e.g. b'\x10\x20\x00').
27 return b''.join(bytes((b,)) for b in bytelist)
30 def struct_parse(struct, stream, stream_pos=None):
31 """ Convenience function for using the given struct to parse a stream.
32 If stream_pos is provided, the stream is seeked to this position before
33 the parsing is done. Otherwise, the current position of the stream is
35 Wraps the error thrown by construct with ELFParseError.
38 if stream_pos is not None:
39 stream.seek(stream_pos)
40 return struct.parse_stream(stream)
41 except ConstructError as e:
42 raise ELFParseError(str(e))
45 def parse_cstring_from_stream(stream, stream_pos=None):
46 """ Parse a C-string from the given stream. The string is returned without
47 the terminating \x00 byte. If the terminating byte wasn't found, None
48 is returned (the stream is exhausted).
49 If stream_pos is provided, the stream is seeked to this position before
50 the parsing is done. Otherwise, the current position of the stream is
52 Note: a bytes object is returned here, because this is what's read from
55 if stream_pos is not None:
56 stream.seek(stream_pos)
61 chunk = stream.read(CHUNKSIZE)
62 end_index = chunk.find(b'\x00')
64 chunks.append(chunk[:end_index])
69 if len(chunk) < CHUNKSIZE:
71 return b''.join(chunks) if found else None
74 def elf_assert(cond, msg=''):
75 """ Assert that cond is True, otherwise raise ELFError(msg)
77 _assert_with_exception(cond, msg, ELFError)
80 def dwarf_assert(cond, msg=''):
81 """ Assert that cond is True, otherwise raise DWARFError(msg)
83 _assert_with_exception(cond, msg, DWARFError)
87 def preserve_stream_pos(stream):
89 # stream has some position FOO (return value of stream.tell())
90 with preserve_stream_pos(stream):
91 # do stuff that manipulates the stream
92 # stream still has position FOO
94 saved_pos = stream.tell()
96 stream.seek(saved_pos)
99 def roundup(num, bits):
100 """ Round up a number to nearest multiple of 2^bits. The result is a number
101 where the least significant bits passed in bits are 0.
103 return (num - 1 | (1 << bits) - 1) + 1
105 def read_blob(stream, length):
106 """Read length bytes from stream, return a list of ints
108 return [struct_parse(ULInt8(''), stream) for i in range(length)]
110 def save_dwarf_section(section, filename):
111 """Debug helper: dump section contents into a file
112 Section is expected to be one of the debug_xxx_sec elements of DWARFInfo
114 stream = section.stream
116 stream.seek(0, os.SEEK_SET)
117 section.stream.seek(0)
118 with open(filename, 'wb') as file:
119 data = stream.read(section.size)
121 stream.seek(pos, os.SEEK_SET)
124 """Return an iterator over the elements of a bytes object.
126 For example, for b'abc' yields b'a', b'b' and then b'c'.
128 for i in range(len(b)):
131 def bytes2hex(b, sep=''):
134 return sep.join(map('{:02x}'.format, b))
136 #------------------------- PRIVATE -------------------------
138 def _assert_with_exception(cond, msg, exception_type):
140 raise exception_type(msg)