Merge branch 'master' of github.com:eliben/pyelftools
[pyelftools.git] / elftools / dwarf / dwarfinfo.py
1 #-------------------------------------------------------------------------------
2 # elftools: dwarf/dwarfinfo.py
3 #
4 # DWARFInfo - Main class for accessing DWARF debug information
5 #
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 from collections import namedtuple
10
11 from ..common.exceptions import DWARFError
12 from ..common.utils import (struct_parse, dwarf_assert,
13 parse_cstring_from_stream)
14 from .structs import DWARFStructs
15 from .compileunit import CompileUnit
16 from .abbrevtable import AbbrevTable
17 from .lineprogram import LineProgram
18 from .callframe import CallFrameInfo
19 from .locationlists import LocationLists
20 from .ranges import RangeLists
21 from .aranges import ARanges
22 from .namelut import NameLUT
23
24
25 # Describes a debug section
26 #
27 # stream: a stream object containing the data of this section
28 # name: section name in the container file
29 # global_offset: the global offset of the section in its container file
30 # size: the size of the section's data, in bytes
31 # address: the virtual address for the section's data
32 #
33 # 'name' and 'global_offset' are for descriptional purposes only and
34 # aren't strictly required for the DWARF parsing to work. 'address' is required
35 # to properly decode the special '.eh_frame' format.
36 #
37 DebugSectionDescriptor = namedtuple('DebugSectionDescriptor',
38 'stream name global_offset size address')
39
40
41 # Some configuration parameters for the DWARF reader. This exists to allow
42 # DWARFInfo to be independent from any specific file format/container.
43 #
44 # little_endian:
45 # boolean flag specifying whether the data in the file is little endian
46 #
47 # machine_arch:
48 # Machine architecture as a string. For example 'x86' or 'x64'
49 #
50 # default_address_size:
51 # The default address size for the container file (sizeof pointer, in bytes)
52 #
53 DwarfConfig = namedtuple('DwarfConfig',
54 'little_endian machine_arch default_address_size')
55
56
57 class DWARFInfo(object):
58 """ Acts also as a "context" to other major objects, bridging between
59 various parts of the debug infromation.
60 """
61 def __init__(self,
62 config,
63 debug_info_sec,
64 debug_aranges_sec,
65 debug_abbrev_sec,
66 debug_frame_sec,
67 eh_frame_sec,
68 debug_str_sec,
69 debug_loc_sec,
70 debug_ranges_sec,
71 debug_line_sec,
72 debug_pubtypes_sec,
73 debug_pubnames_sec):
74 """ config:
75 A DwarfConfig object
76
77 debug_*_sec:
78 DebugSectionDescriptor for a section. Pass None for sections
79 that don't exist. These arguments are best given with
80 keyword syntax.
81 """
82 self.config = config
83 self.debug_info_sec = debug_info_sec
84 self.debug_aranges_sec = debug_aranges_sec
85 self.debug_abbrev_sec = debug_abbrev_sec
86 self.debug_frame_sec = debug_frame_sec
87 self.eh_frame_sec = eh_frame_sec
88 self.debug_str_sec = debug_str_sec
89 self.debug_loc_sec = debug_loc_sec
90 self.debug_ranges_sec = debug_ranges_sec
91 self.debug_line_sec = debug_line_sec
92 self.debug_pubtypes_sec = debug_pubtypes_sec
93 self.debug_pubnames_sec = debug_pubnames_sec
94
95 # This is the DWARFStructs the context uses, so it doesn't depend on
96 # DWARF format and address_size (these are determined per CU) - set them
97 # to default values.
98 self.structs = DWARFStructs(
99 little_endian=self.config.little_endian,
100 dwarf_format=32,
101 address_size=self.config.default_address_size)
102
103 # Cache for abbrev tables: a dict keyed by offset
104 self._abbrevtable_cache = {}
105
106 @property
107 def has_debug_info(self):
108 """ Return whether this contains debug information.
109
110 It can be not the case when the ELF only contains .eh_frame, which is
111 encoded DWARF but not actually for debugging.
112 """
113 return bool(self.debug_info_sec)
114
115 def iter_CUs(self):
116 """ Yield all the compile units (CompileUnit objects) in the debug info
117 """
118 return self._parse_CUs_iter()
119
120 def get_abbrev_table(self, offset):
121 """ Get an AbbrevTable from the given offset in the debug_abbrev
122 section.
123
124 The only verification done on the offset is that it's within the
125 bounds of the section (if not, an exception is raised).
126 It is the caller's responsibility to make sure the offset actually
127 points to a valid abbreviation table.
128
129 AbbrevTable objects are cached internally (two calls for the same
130 offset will return the same object).
131 """
132 dwarf_assert(
133 offset < self.debug_abbrev_sec.size,
134 "Offset '0x%x' to abbrev table out of section bounds" % offset)
135 if offset not in self._abbrevtable_cache:
136 self._abbrevtable_cache[offset] = AbbrevTable(
137 structs=self.structs,
138 stream=self.debug_abbrev_sec.stream,
139 offset=offset)
140 return self._abbrevtable_cache[offset]
141
142 def get_string_from_table(self, offset):
143 """ Obtain a string from the string table section, given an offset
144 relative to the section.
145 """
146 return parse_cstring_from_stream(self.debug_str_sec.stream, offset)
147
148 def line_program_for_CU(self, CU):
149 """ Given a CU object, fetch the line program it points to from the
150 .debug_line section.
151 If the CU doesn't point to a line program, return None.
152 """
153 # The line program is pointed to by the DW_AT_stmt_list attribute of
154 # the top DIE of a CU.
155 top_DIE = CU.get_top_DIE()
156 if 'DW_AT_stmt_list' in top_DIE.attributes:
157 return self._parse_line_program_at_offset(
158 top_DIE.attributes['DW_AT_stmt_list'].value, CU.structs)
159 else:
160 return None
161
162 def has_CFI(self):
163 """ Does this dwarf info have a dwarf_frame CFI section?
164 """
165 return self.debug_frame_sec is not None
166
167 def CFI_entries(self):
168 """ Get a list of dwarf_frame CFI entries from the .debug_frame section.
169 """
170 cfi = CallFrameInfo(
171 stream=self.debug_frame_sec.stream,
172 size=self.debug_frame_sec.size,
173 address=self.debug_frame_sec.address,
174 base_structs=self.structs)
175 return cfi.get_entries()
176
177 def has_EH_CFI(self):
178 """ Does this dwarf info have a eh_frame CFI section?
179 """
180 return self.eh_frame_sec is not None
181
182 def EH_CFI_entries(self):
183 """ Get a list of eh_frame CFI entries from the .eh_frame section.
184 """
185 cfi = CallFrameInfo(
186 stream=self.eh_frame_sec.stream,
187 size=self.eh_frame_sec.size,
188 address=self.eh_frame_sec.address,
189 base_structs=self.structs,
190 for_eh_frame=True)
191 return cfi.get_entries()
192
193 def get_pubtypes(self):
194 """
195 Returns a NameLUT object that contains information read from the
196 .debug_pubtypes section in the ELF file.
197
198 NameLUT is essentially a dictionary containing the CU/DIE offsets of
199 each symbol. See the NameLUT doc string for more details.
200 """
201
202 if self.debug_pubtypes_sec:
203 return NameLUT(self.debug_pubtypes_sec.stream,
204 self.debug_pubtypes_sec.size,
205 self.structs)
206 else:
207 return None
208
209 def get_pubnames(self):
210 """
211 Returns a NameLUT object that contains information read from the
212 .debug_pubnames section in the ELF file.
213
214 NameLUT is essentially a dictionary containing the CU/DIE offsets of
215 each symbol. See the NameLUT doc string for more details.
216 """
217
218 if self.debug_pubnames_sec:
219 return NameLUT(self.debug_pubnames_sec.stream,
220 self.debug_pubnames_sec.size,
221 self.structs)
222 else:
223 return None
224
225 def get_aranges(self):
226 """ Get an ARanges object representing the .debug_aranges section of
227 the DWARF data, or None if the section doesn't exist
228 """
229 if self.debug_aranges_sec:
230 return ARanges(self.debug_aranges_sec.stream,
231 self.debug_aranges_sec.size,
232 self.structs)
233 else:
234 return None
235
236 def location_lists(self):
237 """ Get a LocationLists object representing the .debug_loc section of
238 the DWARF data, or None if this section doesn't exist.
239 """
240 if self.debug_loc_sec:
241 return LocationLists(self.debug_loc_sec.stream, self.structs)
242 else:
243 return None
244
245 def range_lists(self):
246 """ Get a RangeLists object representing the .debug_ranges section of
247 the DWARF data, or None if this section doesn't exist.
248 """
249 if self.debug_ranges_sec:
250 return RangeLists(self.debug_ranges_sec.stream, self.structs)
251 else:
252 return None
253
254 #------ PRIVATE ------#
255
256 def _parse_CUs_iter(self):
257 """ Parse CU entries from debug_info. Yield CUs in order of appearance.
258 """
259 if self.debug_info_sec is None:
260 return
261
262 offset = 0
263 while offset < self.debug_info_sec.size:
264 cu = self._parse_CU_at_offset(offset)
265 # Compute the offset of the next CU in the section. The unit_length
266 # field of the CU header contains its size not including the length
267 # field itself.
268 offset = ( offset +
269 cu['unit_length'] +
270 cu.structs.initial_length_field_size())
271 yield cu
272
273 def _parse_CU_at_offset(self, offset):
274 """ Parse and return a CU at the given offset in the debug_info stream.
275 """
276 # Section 7.4 (32-bit and 64-bit DWARF Formats) of the DWARF spec v3
277 # states that the first 32-bit word of the CU header determines
278 # whether the CU is represented with 32-bit or 64-bit DWARF format.
279 #
280 # So we peek at the first word in the CU header to determine its
281 # dwarf format. Based on it, we then create a new DWARFStructs
282 # instance suitable for this CU and use it to parse the rest.
283 #
284 initial_length = struct_parse(
285 self.structs.Dwarf_uint32(''), self.debug_info_sec.stream, offset)
286 dwarf_format = 64 if initial_length == 0xFFFFFFFF else 32
287
288
289 # Temporary structs for parsing the header
290 # The structs for the rest of the CU depend on the header data.
291 #
292 cu_structs = DWARFStructs(
293 little_endian=self.config.little_endian,
294 dwarf_format=dwarf_format,
295 address_size=4,
296 dwarf_version=2)
297
298 cu_header = struct_parse(
299 cu_structs.Dwarf_CU_header, self.debug_info_sec.stream, offset)
300
301 # structs for the rest of the CU, taking into account bitness and DWARF version
302 cu_structs = DWARFStructs(
303 little_endian=self.config.little_endian,
304 dwarf_format=dwarf_format,
305 address_size=cu_header['address_size'],
306 dwarf_version=cu_header['version'])
307
308 cu_die_offset = self.debug_info_sec.stream.tell()
309 dwarf_assert(
310 self._is_supported_version(cu_header['version']),
311 "Expected supported DWARF version. Got '%s'" % cu_header['version'])
312 return CompileUnit(
313 header=cu_header,
314 dwarfinfo=self,
315 structs=cu_structs,
316 cu_offset=offset,
317 cu_die_offset=cu_die_offset)
318
319 def _is_supported_version(self, version):
320 """ DWARF version supported by this parser
321 """
322 return 2 <= version <= 4
323
324 def _parse_line_program_at_offset(self, debug_line_offset, structs):
325 """ Given an offset to the .debug_line section, parse the line program
326 starting at this offset in the section and return it.
327 structs is the DWARFStructs object used to do this parsing.
328 """
329 lineprog_header = struct_parse(
330 structs.Dwarf_lineprog_header,
331 self.debug_line_sec.stream,
332 debug_line_offset)
333
334 # Calculate the offset to the next line program (see DWARF 6.2.4)
335 end_offset = ( debug_line_offset + lineprog_header['unit_length'] +
336 structs.initial_length_field_size())
337
338 return LineProgram(
339 header=lineprog_header,
340 stream=self.debug_line_sec.stream,
341 structs=structs,
342 program_start_offset=self.debug_line_sec.stream.tell(),
343 program_end_offset=end_offset)
344