Improve DWARF 5 compatibility. (#400)
[pyelftools.git] / elftools / elf / elffile.py
1 #-------------------------------------------------------------------------------
2 # elftools: elf/elffile.py
3 #
4 # ELFFile - main class for accessing ELF files
5 #
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 import io
10 import struct
11 import zlib
12
13 try:
14 import resource
15 PAGESIZE = resource.getpagesize()
16 except ImportError:
17 try:
18 # Windows system
19 import mmap
20 PAGESIZE = mmap.PAGESIZE
21 except ImportError:
22 # Jython
23 PAGESIZE = 4096
24
25 from ..common.py3compat import BytesIO
26 from ..common.exceptions import ELFError
27 from ..common.utils import struct_parse, elf_assert
28 from .structs import ELFStructs
29 from .sections import (
30 Section, StringTableSection, SymbolTableSection,
31 SymbolTableIndexSection, SUNWSyminfoTableSection, NullSection,
32 NoteSection, StabSection, ARMAttributesSection)
33 from .dynamic import DynamicSection, DynamicSegment
34 from .relocation import (RelocationSection, RelocationHandler,
35 RelrRelocationSection)
36 from .gnuversions import (
37 GNUVerNeedSection, GNUVerDefSection,
38 GNUVerSymSection)
39 from .segments import Segment, InterpSegment, NoteSegment
40 from ..dwarf.dwarfinfo import DWARFInfo, DebugSectionDescriptor, DwarfConfig
41 from ..ehabi.ehabiinfo import EHABIInfo
42 from .hash import ELFHashSection, GNUHashSection
43 from .constants import SHN_INDICES
44
45 class ELFFile(object):
46 """ Creation: the constructor accepts a stream (file-like object) with the
47 contents of an ELF file.
48
49 Accessible attributes:
50
51 stream:
52 The stream holding the data of the file - must be a binary
53 stream (bytes, not string).
54
55 elfclass:
56 32 or 64 - specifies the word size of the target machine
57
58 little_endian:
59 boolean - specifies the target machine's endianness
60
61 elftype:
62 string or int, either known value of E_TYPE enum defining ELF
63 type (e.g. executable, dynamic library or core dump) or integral
64 unparsed value
65
66 header:
67 the complete ELF file header
68
69 e_ident_raw:
70 the raw e_ident field of the header
71 """
72 def __init__(self, stream):
73 self.stream = stream
74 self._identify_file()
75 self.structs = ELFStructs(
76 little_endian=self.little_endian,
77 elfclass=self.elfclass)
78
79 self.structs.create_basic_structs()
80 self.header = self._parse_elf_header()
81 self.structs.create_advanced_structs(
82 self['e_type'],
83 self['e_machine'],
84 self['e_ident']['EI_OSABI'])
85 self.stream.seek(0)
86 self.e_ident_raw = self.stream.read(16)
87
88 self._section_header_stringtable = \
89 self._get_section_header_stringtable()
90 self._section_name_map = None
91
92 def num_sections(self):
93 """ Number of sections in the file
94 """
95 if self['e_shoff'] == 0:
96 return 0
97 # From the ELF ABI documentation at
98 # https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.sheader.html:
99 # "e_shnum normally tells how many entries the section header table
100 # contains. [...] If the number of sections is greater than or equal to
101 # SHN_LORESERVE (0xff00), e_shnum has the value SHN_UNDEF (0) and the
102 # actual number of section header table entries is contained in the
103 # sh_size field of the section header at index 0 (otherwise, the sh_size
104 # member of the initial entry contains 0)."
105 if self['e_shnum'] == 0:
106 return self._get_section_header(0)['sh_size']
107 return self['e_shnum']
108
109 def get_section(self, n):
110 """ Get the section at index #n from the file (Section object or a
111 subclass)
112 """
113 section_header = self._get_section_header(n)
114 return self._make_section(section_header)
115
116 def get_section_by_name(self, name):
117 """ Get a section from the file, by name. Return None if no such
118 section exists.
119 """
120 # The first time this method is called, construct a name to number
121 # mapping
122 #
123 if self._section_name_map is None:
124 self._make_section_name_map()
125 secnum = self._section_name_map.get(name, None)
126 return None if secnum is None else self.get_section(secnum)
127
128 def get_section_index(self, section_name):
129 """ Gets the index of the section by name. Return None if no such
130 section name exists.
131 """
132 # The first time this method is called, construct a name to number
133 # mapping
134 #
135 if self._section_name_map is None:
136 self._make_section_name_map()
137 return self._section_name_map.get(section_name, None)
138
139 def iter_sections(self, type=None):
140 """ Yield all the sections in the file. If the optional |type|
141 parameter is passed, this method will only yield sections of the
142 given type. The parameter value must be a string containing the
143 name of the type as defined in the ELF specification, e.g.
144 'SHT_SYMTAB'.
145 """
146 for i in range(self.num_sections()):
147 section = self.get_section(i)
148 if type is None or section['sh_type'] == type:
149 yield section
150
151 def num_segments(self):
152 """ Number of segments in the file
153 """
154 # From: https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI
155 # Section: 4.1.2 Number of Program Headers
156 # If the number of program headers is greater than or equal to
157 # PN_XNUM (0xffff), this member has the value PN_XNUM
158 # (0xffff). The actual number of program header table entries
159 # is contained in the sh_info field of the section header at
160 # index 0.
161 if self['e_phnum'] < 0xffff:
162 return self['e_phnum']
163 else:
164 return self.get_section(0)['sh_info']
165
166 def get_segment(self, n):
167 """ Get the segment at index #n from the file (Segment object)
168 """
169 segment_header = self._get_segment_header(n)
170 return self._make_segment(segment_header)
171
172 def iter_segments(self, type=None):
173 """ Yield all the segments in the file. If the optional |type|
174 parameter is passed, this method will only yield segments of the
175 given type. The parameter value must be a string containing the
176 name of the type as defined in the ELF specification, e.g.
177 'PT_LOAD'.
178 """
179 for i in range(self.num_segments()):
180 segment = self.get_segment(i)
181 if type is None or segment['p_type'] == type:
182 yield segment
183
184 def address_offsets(self, start, size=1):
185 """ Yield a file offset for each ELF segment containing a memory region.
186
187 A memory region is defined by the range [start...start+size). The
188 offset of the region is yielded.
189 """
190 end = start + size
191 # consider LOAD only to prevent same address being yielded twice
192 for seg in self.iter_segments(type='PT_LOAD'):
193 if (start >= seg['p_vaddr'] and
194 end <= seg['p_vaddr'] + seg['p_filesz']):
195 yield start - seg['p_vaddr'] + seg['p_offset']
196
197 def has_dwarf_info(self):
198 """ Check whether this file appears to have debugging information.
199 We assume that if it has the .debug_info or .zdebug_info section, it
200 has all the other required sections as well.
201 """
202 return bool(self.get_section_by_name('.debug_info') or
203 self.get_section_by_name('.zdebug_info') or
204 self.get_section_by_name('.eh_frame'))
205
206 def get_dwarf_info(self, relocate_dwarf_sections=True):
207 """ Return a DWARFInfo object representing the debugging information in
208 this file.
209
210 If relocate_dwarf_sections is True, relocations for DWARF sections
211 are looked up and applied.
212 """
213 # Expect that has_dwarf_info was called, so at least .debug_info is
214 # present.
215 # Sections that aren't found will be passed as None to DWARFInfo.
216
217 section_names = ('.debug_info', '.debug_aranges', '.debug_abbrev',
218 '.debug_str', '.debug_line', '.debug_frame',
219 '.debug_loc', '.debug_ranges', '.debug_pubtypes',
220 '.debug_pubnames', '.debug_addr',
221 '.debug_str_offsets', '.debug_line_str')
222
223
224 compressed = bool(self.get_section_by_name('.zdebug_info'))
225 if compressed:
226 section_names = tuple(map(lambda x: '.z' + x[1:], section_names))
227
228 # As it is loaded in the process image, .eh_frame cannot be compressed
229 section_names += ('.eh_frame', )
230
231 (debug_info_sec_name, debug_aranges_sec_name, debug_abbrev_sec_name,
232 debug_str_sec_name, debug_line_sec_name, debug_frame_sec_name,
233 debug_loc_sec_name, debug_ranges_sec_name, debug_pubtypes_name,
234 debug_pubnames_name, debug_addr_name, debug_str_offsets_name,
235 debug_line_str_name, eh_frame_sec_name) = section_names
236
237 debug_sections = {}
238 for secname in section_names:
239 section = self.get_section_by_name(secname)
240 if section is None:
241 debug_sections[secname] = None
242 else:
243 dwarf_section = self._read_dwarf_section(
244 section,
245 relocate_dwarf_sections)
246 if compressed and secname.startswith('.z'):
247 dwarf_section = self._decompress_dwarf_section(dwarf_section)
248 debug_sections[secname] = dwarf_section
249
250 return DWARFInfo(
251 config=DwarfConfig(
252 little_endian=self.little_endian,
253 default_address_size=self.elfclass // 8,
254 machine_arch=self.get_machine_arch()),
255 debug_info_sec=debug_sections[debug_info_sec_name],
256 debug_aranges_sec=debug_sections[debug_aranges_sec_name],
257 debug_abbrev_sec=debug_sections[debug_abbrev_sec_name],
258 debug_frame_sec=debug_sections[debug_frame_sec_name],
259 eh_frame_sec=debug_sections[eh_frame_sec_name],
260 debug_str_sec=debug_sections[debug_str_sec_name],
261 debug_loc_sec=debug_sections[debug_loc_sec_name],
262 debug_ranges_sec=debug_sections[debug_ranges_sec_name],
263 debug_line_sec=debug_sections[debug_line_sec_name],
264 debug_pubtypes_sec=debug_sections[debug_pubtypes_name],
265 debug_pubnames_sec=debug_sections[debug_pubnames_name],
266 debug_addr_sec=debug_sections[debug_addr_name],
267 debug_str_offsets_sec=debug_sections[debug_str_offsets_name],
268 debug_line_str_sec=debug_sections[debug_line_str_name]
269 )
270
271 def has_ehabi_info(self):
272 """ Check whether this file appears to have arm exception handler index table.
273 """
274 return any(self.iter_sections(type='SHT_ARM_EXIDX'))
275
276 def get_ehabi_infos(self):
277 """ Generally, shared library and executable contain 1 .ARM.exidx section.
278 Object file contains many .ARM.exidx sections.
279 So we must traverse every section and filter sections whose type is SHT_ARM_EXIDX.
280 """
281 _ret = []
282 if self['e_type'] == 'ET_REL':
283 # TODO: support relocatable file
284 assert False, "Current version of pyelftools doesn't support relocatable file."
285 for section in self.iter_sections(type='SHT_ARM_EXIDX'):
286 _ret.append(EHABIInfo(section, self.little_endian))
287 return _ret if len(_ret) > 0 else None
288
289 def get_machine_arch(self):
290 """ Return the machine architecture, as detected from the ELF header.
291 """
292 architectures = {
293 'EM_M32' : 'AT&T WE 32100',
294 'EM_SPARC' : 'SPARC',
295 'EM_386' : 'x86',
296 'EM_68K' : 'Motorola 68000',
297 'EM_88K' : 'Motorola 88000',
298 'EM_IAMCU' : 'Intel MCU',
299 'EM_860' : 'Intel 80860',
300 'EM_MIPS' : 'MIPS',
301 'EM_S370' : 'IBM System/370',
302 'EM_MIPS_RS3_LE' : 'MIPS RS3000 Little-endian',
303 'EM_PARISC' : 'Hewlett-Packard PA-RISC',
304 'EM_VPP500' : 'Fujitsu VPP500',
305 'EM_SPARC32PLUS' : 'Enhanced SPARC',
306 'EM_960' : 'Intel 80960',
307 'EM_PPC' : 'PowerPC',
308 'EM_PPC64' : '64-bit PowerPC',
309 'EM_S390' : 'IBM System/390',
310 'EM_SPU' : 'IBM SPU/SPC',
311 'EM_V800' : 'NEC V800',
312 'EM_FR20' : 'Fujitsu FR20',
313 'EM_RH32' : 'TRW RH-32',
314 'EM_RCE' : 'Motorola RCE',
315 'EM_ARM' : 'ARM',
316 'EM_ALPHA' : 'Digital Alpha',
317 'EM_SH' : 'Hitachi SH',
318 'EM_SPARCV9' : 'SPARC Version 9',
319 'EM_TRICORE' : 'Siemens TriCore embedded processor',
320 'EM_ARC' : 'Argonaut RISC Core, Argonaut Technologies Inc.',
321 'EM_H8_300' : 'Hitachi H8/300',
322 'EM_H8_300H' : 'Hitachi H8/300H',
323 'EM_H8S' : 'Hitachi H8S',
324 'EM_H8_500' : 'Hitachi H8/500',
325 'EM_IA_64' : 'Intel IA-64',
326 'EM_MIPS_X' : 'MIPS-X',
327 'EM_COLDFIRE' : 'Motorola ColdFire',
328 'EM_68HC12' : 'Motorola M68HC12',
329 'EM_MMA' : 'Fujitsu MMA',
330 'EM_PCP' : 'Siemens PCP',
331 'EM_NCPU' : 'Sony nCPU',
332 'EM_NDR1' : 'Denso NDR1',
333 'EM_STARCORE' : 'Motorola Star*Core',
334 'EM_ME16' : 'Toyota ME16',
335 'EM_ST100' : 'STMicroelectronics ST100',
336 'EM_TINYJ' : 'Advanced Logic TinyJ',
337 'EM_X86_64' : 'x64',
338 'EM_PDSP' : 'Sony DSP',
339 'EM_PDP10' : 'Digital Equipment PDP-10',
340 'EM_PDP11' : 'Digital Equipment PDP-11',
341 'EM_FX66' : 'Siemens FX66',
342 'EM_ST9PLUS' : 'STMicroelectronics ST9+ 8/16 bit',
343 'EM_ST7' : 'STMicroelectronics ST7 8-bit',
344 'EM_68HC16' : 'Motorola MC68HC16',
345 'EM_68HC11' : 'Motorola MC68HC11',
346 'EM_68HC08' : 'Motorola MC68HC08',
347 'EM_68HC05' : 'Motorola MC68HC05',
348 'EM_SVX' : 'Silicon Graphics SVx',
349 'EM_ST19' : 'STMicroelectronics ST19 8-bit',
350 'EM_VAX' : 'Digital VAX',
351 'EM_CRIS' : 'Axis Communications 32-bit',
352 'EM_JAVELIN' : 'Infineon Technologies 32-bit',
353 'EM_FIREPATH' : 'Element 14 64-bit DSP',
354 'EM_ZSP' : 'LSI Logic 16-bit DSP',
355 'EM_MMIX' : 'Donald Knuth\'s educational 64-bit',
356 'EM_HUANY' : 'Harvard University machine-independent object files',
357 'EM_PRISM' : 'SiTera Prism',
358 'EM_AVR' : 'Atmel AVR 8-bit',
359 'EM_FR30' : 'Fujitsu FR30',
360 'EM_D10V' : 'Mitsubishi D10V',
361 'EM_D30V' : 'Mitsubishi D30V',
362 'EM_V850' : 'NEC v850',
363 'EM_M32R' : 'Mitsubishi M32R',
364 'EM_MN10300' : 'Matsushita MN10300',
365 'EM_MN10200' : 'Matsushita MN10200',
366 'EM_PJ' : 'picoJava',
367 'EM_OPENRISC' : 'OpenRISC 32-bit',
368 'EM_ARC_COMPACT' : 'ARC International ARCompact',
369 'EM_XTENSA' : 'Tensilica Xtensa',
370 'EM_VIDEOCORE' : 'Alphamosaic VideoCore',
371 'EM_TMM_GPP' : 'Thompson Multimedia',
372 'EM_NS32K' : 'National Semiconductor 32000 series',
373 'EM_TPC' : 'Tenor Network TPC',
374 'EM_SNP1K' : 'Trebia SNP 1000',
375 'EM_ST200' : 'STMicroelectronics ST200',
376 'EM_IP2K' : 'Ubicom IP2xxx',
377 'EM_MAX' : 'MAX',
378 'EM_CR' : 'National Semiconductor CompactRISC',
379 'EM_F2MC16' : 'Fujitsu F2MC16',
380 'EM_MSP430' : 'Texas Instruments msp430',
381 'EM_BLACKFIN' : 'Analog Devices Blackfin',
382 'EM_SE_C33' : 'Seiko Epson S1C33',
383 'EM_SEP' : 'Sharp',
384 'EM_ARCA' : 'Arca RISC',
385 'EM_UNICORE' : 'PKU-Unity MPRC',
386 'EM_EXCESS' : 'eXcess',
387 'EM_DXP' : 'Icera Semiconductor Deep Execution Processor',
388 'EM_ALTERA_NIOS2' : 'Altera Nios II',
389 'EM_CRX' : 'National Semiconductor CompactRISC CRX',
390 'EM_XGATE' : 'Motorola XGATE',
391 'EM_C166' : 'Infineon C16x/XC16x',
392 'EM_M16C' : 'Renesas M16C',
393 'EM_DSPIC30F' : 'Microchip Technology dsPIC30F',
394 'EM_CE' : 'Freescale Communication Engine RISC core',
395 'EM_M32C' : 'Renesas M32C',
396 'EM_TSK3000' : 'Altium TSK3000',
397 'EM_RS08' : 'Freescale RS08',
398 'EM_SHARC' : 'Analog Devices SHARC',
399 'EM_ECOG2' : 'Cyan Technology eCOG2',
400 'EM_SCORE7' : 'Sunplus S+core7 RISC',
401 'EM_DSP24' : 'New Japan Radio (NJR) 24-bit DSP',
402 'EM_VIDEOCORE3' : 'Broadcom VideoCore III',
403 'EM_LATTICEMICO32' : 'Lattice FPGA RISC',
404 'EM_SE_C17' : 'Seiko Epson C17',
405 'EM_TI_C6000' : 'TI TMS320C6000',
406 'EM_TI_C2000' : 'TI TMS320C2000',
407 'EM_TI_C5500' : 'TI TMS320C55x',
408 'EM_TI_ARP32' : 'TI Application Specific RISC, 32bit',
409 'EM_TI_PRU' : 'TI Programmable Realtime Unit',
410 'EM_MMDSP_PLUS' : 'STMicroelectronics 64bit VLIW',
411 'EM_CYPRESS_M8C' : 'Cypress M8C',
412 'EM_R32C' : 'Renesas R32C',
413 'EM_TRIMEDIA' : 'NXP Semiconductors TriMedia',
414 'EM_QDSP6' : 'QUALCOMM DSP6',
415 'EM_8051' : 'Intel 8051',
416 'EM_STXP7X' : 'STMicroelectronics STxP7x',
417 'EM_NDS32' : 'Andes Technology RISC',
418 'EM_ECOG1' : 'Cyan Technology eCOG1X',
419 'EM_ECOG1X' : 'Cyan Technology eCOG1X',
420 'EM_MAXQ30' : 'Dallas Semiconductor MAXQ30',
421 'EM_XIMO16' : 'New Japan Radio (NJR) 16-bit',
422 'EM_MANIK' : 'M2000 Reconfigurable RISC',
423 'EM_CRAYNV2' : 'Cray Inc. NV2',
424 'EM_RX' : 'Renesas RX',
425 'EM_METAG' : 'Imagination Technologies META',
426 'EM_MCST_ELBRUS' : 'MCST Elbrus',
427 'EM_ECOG16' : 'Cyan Technology eCOG16',
428 'EM_CR16' : 'National Semiconductor CompactRISC CR16 16-bit',
429 'EM_ETPU' : 'Freescale',
430 'EM_SLE9X' : 'Infineon Technologies SLE9X',
431 'EM_L10M' : 'Intel L10M',
432 'EM_K10M' : 'Intel K10M',
433 'EM_AARCH64' : 'AArch64',
434 'EM_AVR32' : 'Atmel 32-bit',
435 'EM_STM8' : 'STMicroeletronics STM8 8-bit',
436 'EM_TILE64' : 'Tilera TILE64',
437 'EM_TILEPRO' : 'Tilera TILEPro',
438 'EM_MICROBLAZE' : 'Xilinx MicroBlaze 32-bit RISC',
439 'EM_CUDA' : 'NVIDIA CUDA',
440 'EM_TILEGX' : 'Tilera TILE-Gx',
441 'EM_CLOUDSHIELD' : 'CloudShield',
442 'EM_COREA_1ST' : 'KIPO-KAIST Core-A 1st generation',
443 'EM_COREA_2ND' : 'KIPO-KAIST Core-A 2nd generation',
444 'EM_ARC_COMPACT2' : 'Synopsys ARCompact V2',
445 'EM_OPEN8' : 'Open8 8-bit RISC',
446 'EM_RL78' : 'Renesas RL78',
447 'EM_VIDEOCORE5' : 'Broadcom VideoCore V',
448 'EM_78KOR' : 'Renesas 78KOR',
449 'EM_56800EX' : 'Freescale 56800EX',
450 'EM_BA1' : 'Beyond BA1',
451 'EM_BA2' : 'Beyond BA2',
452 'EM_XCORE' : 'XMOS xCORE',
453 'EM_MCHP_PIC' : 'Microchip 8-bit PIC',
454 'EM_INTEL205' : 'Reserved by Intel',
455 'EM_INTEL206' : 'Reserved by Intel',
456 'EM_INTEL207' : 'Reserved by Intel',
457 'EM_INTEL208' : 'Reserved by Intel',
458 'EM_INTEL209' : 'Reserved by Intel',
459 'EM_KM32' : 'KM211 KM32 32-bit',
460 'EM_KMX32' : 'KM211 KMX32 32-bit',
461 'EM_KMX16' : 'KM211 KMX16 16-bit',
462 'EM_KMX8' : 'KM211 KMX8 8-bit',
463 'EM_KVARC' : 'KM211 KVARC',
464 'EM_CDP' : 'Paneve CDP',
465 'EM_COGE' : 'Cognitive',
466 'EM_COOL' : 'Bluechip Systems CoolEngine',
467 'EM_NORC' : 'Nanoradio Optimized RISC',
468 'EM_CSR_KALIMBA' : 'CSR Kalimba',
469 'EM_Z80' : 'Zilog Z80',
470 'EM_VISIUM' : 'VISIUMcore',
471 'EM_FT32' : 'FTDI Chip FT32 32-bit RISC',
472 'EM_MOXIE' : 'Moxie',
473 'EM_AMDGPU' : 'AMD GPU',
474 'EM_RISCV' : 'RISC-V',
475 'EM_BPF' : 'Linux BPF - in-kernel virtual machine',
476 'EM_CSKY' : 'C-SKY',
477 'EM_FRV' : 'Fujitsu FR-V'
478 }
479
480 return architectures.get(self['e_machine'], '<unknown>')
481
482 def get_shstrndx(self):
483 """ Find the string table section index for the section header table
484 """
485 # From https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html:
486 # If the section name string table section index is greater than or
487 # equal to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX
488 # (0xffff) and the actual index of the section name string table section
489 # is contained in the sh_link field of the section header at index 0.
490 if self['e_shstrndx'] != SHN_INDICES.SHN_XINDEX:
491 return self['e_shstrndx']
492 else:
493 return self._get_section_header(0)['sh_link']
494
495 #-------------------------------- PRIVATE --------------------------------#
496
497 def __getitem__(self, name):
498 """ Implement dict-like access to header entries
499 """
500 return self.header[name]
501
502 def _identify_file(self):
503 """ Verify the ELF file and identify its class and endianness.
504 """
505 # Note: this code reads the stream directly, without using ELFStructs,
506 # since we don't yet know its exact format. ELF was designed to be
507 # read like this - its e_ident field is word-size and endian agnostic.
508 self.stream.seek(0)
509 magic = self.stream.read(4)
510 elf_assert(magic == b'\x7fELF', 'Magic number does not match')
511
512 ei_class = self.stream.read(1)
513 if ei_class == b'\x01':
514 self.elfclass = 32
515 elif ei_class == b'\x02':
516 self.elfclass = 64
517 else:
518 raise ELFError('Invalid EI_CLASS %s' % repr(ei_class))
519
520 ei_data = self.stream.read(1)
521 if ei_data == b'\x01':
522 self.little_endian = True
523 elif ei_data == b'\x02':
524 self.little_endian = False
525 else:
526 raise ELFError('Invalid EI_DATA %s' % repr(ei_data))
527
528 def _section_offset(self, n):
529 """ Compute the offset of section #n in the file
530 """
531 return self['e_shoff'] + n * self['e_shentsize']
532
533 def _segment_offset(self, n):
534 """ Compute the offset of segment #n in the file
535 """
536 return self['e_phoff'] + n * self['e_phentsize']
537
538 def _make_segment(self, segment_header):
539 """ Create a Segment object of the appropriate type
540 """
541 segtype = segment_header['p_type']
542 if segtype == 'PT_INTERP':
543 return InterpSegment(segment_header, self.stream)
544 elif segtype == 'PT_DYNAMIC':
545 return DynamicSegment(segment_header, self.stream, self)
546 elif segtype == 'PT_NOTE':
547 return NoteSegment(segment_header, self.stream, self)
548 else:
549 return Segment(segment_header, self.stream)
550
551 def _get_section_header(self, n):
552 """ Find the header of section #n, parse it and return the struct
553 """
554 return struct_parse(
555 self.structs.Elf_Shdr,
556 self.stream,
557 stream_pos=self._section_offset(n))
558
559 def _get_section_name(self, section_header):
560 """ Given a section header, find this section's name in the file's
561 string table
562 """
563 name_offset = section_header['sh_name']
564 return self._section_header_stringtable.get_string(name_offset)
565
566 def _make_section(self, section_header):
567 """ Create a section object of the appropriate type
568 """
569 name = self._get_section_name(section_header)
570 sectype = section_header['sh_type']
571
572 if sectype == 'SHT_STRTAB':
573 return StringTableSection(section_header, name, self)
574 elif sectype == 'SHT_NULL':
575 return NullSection(section_header, name, self)
576 elif sectype in ('SHT_SYMTAB', 'SHT_DYNSYM', 'SHT_SUNW_LDYNSYM'):
577 return self._make_symbol_table_section(section_header, name)
578 elif sectype == 'SHT_SYMTAB_SHNDX':
579 return self._make_symbol_table_index_section(section_header, name)
580 elif sectype == 'SHT_SUNW_syminfo':
581 return self._make_sunwsyminfo_table_section(section_header, name)
582 elif sectype == 'SHT_GNU_verneed':
583 return self._make_gnu_verneed_section(section_header, name)
584 elif sectype == 'SHT_GNU_verdef':
585 return self._make_gnu_verdef_section(section_header, name)
586 elif sectype == 'SHT_GNU_versym':
587 return self._make_gnu_versym_section(section_header, name)
588 elif sectype in ('SHT_REL', 'SHT_RELA'):
589 return RelocationSection(section_header, name, self)
590 elif sectype == 'SHT_DYNAMIC':
591 return DynamicSection(section_header, name, self)
592 elif sectype == 'SHT_NOTE':
593 return NoteSection(section_header, name, self)
594 elif sectype == 'SHT_PROGBITS' and name == '.stab':
595 return StabSection(section_header, name, self)
596 elif sectype == 'SHT_ARM_ATTRIBUTES':
597 return ARMAttributesSection(section_header, name, self)
598 elif sectype == 'SHT_HASH':
599 return self._make_elf_hash_section(section_header, name)
600 elif sectype == 'SHT_GNU_HASH':
601 return self._make_gnu_hash_section(section_header, name)
602 elif sectype == 'SHT_RELR':
603 return RelrRelocationSection(section_header, name, self)
604 else:
605 return Section(section_header, name, self)
606
607 def _make_section_name_map(self):
608 self._section_name_map = {}
609 for i, sec in enumerate(self.iter_sections()):
610 self._section_name_map[sec.name] = i
611
612 def _make_symbol_table_section(self, section_header, name):
613 """ Create a SymbolTableSection
614 """
615 linked_strtab_index = section_header['sh_link']
616 strtab_section = self.get_section(linked_strtab_index)
617 return SymbolTableSection(
618 section_header, name,
619 elffile=self,
620 stringtable=strtab_section)
621
622 def _make_symbol_table_index_section(self, section_header, name):
623 """ Create a SymbolTableIndexSection object
624 """
625 linked_symtab_index = section_header['sh_link']
626 return SymbolTableIndexSection(
627 section_header, name, elffile=self,
628 symboltable=linked_symtab_index)
629
630 def _make_sunwsyminfo_table_section(self, section_header, name):
631 """ Create a SUNWSyminfoTableSection
632 """
633 linked_strtab_index = section_header['sh_link']
634 strtab_section = self.get_section(linked_strtab_index)
635 return SUNWSyminfoTableSection(
636 section_header, name,
637 elffile=self,
638 symboltable=strtab_section)
639
640 def _make_gnu_verneed_section(self, section_header, name):
641 """ Create a GNUVerNeedSection
642 """
643 linked_strtab_index = section_header['sh_link']
644 strtab_section = self.get_section(linked_strtab_index)
645 return GNUVerNeedSection(
646 section_header, name,
647 elffile=self,
648 stringtable=strtab_section)
649
650 def _make_gnu_verdef_section(self, section_header, name):
651 """ Create a GNUVerDefSection
652 """
653 linked_strtab_index = section_header['sh_link']
654 strtab_section = self.get_section(linked_strtab_index)
655 return GNUVerDefSection(
656 section_header, name,
657 elffile=self,
658 stringtable=strtab_section)
659
660 def _make_gnu_versym_section(self, section_header, name):
661 """ Create a GNUVerSymSection
662 """
663 linked_strtab_index = section_header['sh_link']
664 strtab_section = self.get_section(linked_strtab_index)
665 return GNUVerSymSection(
666 section_header, name,
667 elffile=self,
668 symboltable=strtab_section)
669
670 def _make_elf_hash_section(self, section_header, name):
671 linked_symtab_index = section_header['sh_link']
672 symtab_section = self.get_section(linked_symtab_index)
673 return ELFHashSection(
674 section_header, name, self, symtab_section
675 )
676
677 def _make_gnu_hash_section(self, section_header, name):
678 linked_symtab_index = section_header['sh_link']
679 symtab_section = self.get_section(linked_symtab_index)
680 return GNUHashSection(
681 section_header, name, self, symtab_section
682 )
683
684 def _get_segment_header(self, n):
685 """ Find the header of segment #n, parse it and return the struct
686 """
687 return struct_parse(
688 self.structs.Elf_Phdr,
689 self.stream,
690 stream_pos=self._segment_offset(n))
691
692 def _get_section_header_stringtable(self):
693 """ Get the string table section corresponding to the section header
694 table.
695 """
696 stringtable_section_num = self.get_shstrndx()
697 return StringTableSection(
698 header=self._get_section_header(stringtable_section_num),
699 name='',
700 elffile=self)
701
702 def _parse_elf_header(self):
703 """ Parses the ELF file header and assigns the result to attributes
704 of this object.
705 """
706 return struct_parse(self.structs.Elf_Ehdr, self.stream, stream_pos=0)
707
708 def _read_dwarf_section(self, section, relocate_dwarf_sections):
709 """ Read the contents of a DWARF section from the stream and return a
710 DebugSectionDescriptor. Apply relocations if asked to.
711 """
712 # The section data is read into a new stream, for processing
713 section_stream = BytesIO()
714 section_stream.write(section.data())
715
716 if relocate_dwarf_sections:
717 reloc_handler = RelocationHandler(self)
718 reloc_section = reloc_handler.find_relocations_for_section(section)
719 if reloc_section is not None:
720 reloc_handler.apply_section_relocations(
721 section_stream, reloc_section)
722
723 return DebugSectionDescriptor(
724 stream=section_stream,
725 name=section.name,
726 global_offset=section['sh_offset'],
727 size=section.data_size,
728 address=section['sh_addr'])
729
730 @staticmethod
731 def _decompress_dwarf_section(section):
732 """ Returns the uncompressed contents of the provided DWARF section.
733 """
734 # TODO: support other compression formats from readelf.c
735 assert section.size > 12, 'Unsupported compression format.'
736
737 section.stream.seek(0)
738 # According to readelf.c the content should contain "ZLIB"
739 # followed by the uncompressed section size - 8 bytes in
740 # big-endian order
741 compression_type = section.stream.read(4)
742 assert compression_type == b'ZLIB', \
743 'Invalid compression type: %r' % (compression_type)
744
745 uncompressed_size = struct.unpack('>Q', section.stream.read(8))[0]
746
747 decompressor = zlib.decompressobj()
748 uncompressed_stream = BytesIO()
749 while True:
750 chunk = section.stream.read(PAGESIZE)
751 if not chunk:
752 break
753 uncompressed_stream.write(decompressor.decompress(chunk))
754 uncompressed_stream.write(decompressor.flush())
755
756 uncompressed_stream.seek(0, io.SEEK_END)
757 size = uncompressed_stream.tell()
758 assert uncompressed_size == size, \
759 'Wrong uncompressed size: expected %r, but got %r' % (
760 uncompressed_size, size,
761 )
762
763 return section._replace(stream=uncompressed_stream, size=size)