1 #-------------------------------------------------------------------------------
2 # elftools: elf/structs.py
4 # Encapsulation of Construct structs for parsing an ELF file, adjusted for
5 # correct endianness and word-size.
7 # Eli Bendersky (eliben@gmail.com)
8 # This code is in the public domain
9 #-------------------------------------------------------------------------------
10 from ..construct
import (
11 UBInt8
, UBInt16
, UBInt32
, UBInt64
,
12 ULInt8
, ULInt16
, ULInt32
, ULInt64
,
13 SBInt32
, SLInt32
, SBInt64
, SLInt64
,
14 Struct
, Array
, Enum
, Padding
, BitStruct
, BitField
, Value
, String
, CString
,
17 from ..common
.construct_utils
import ULEB128
18 from ..common
.utils
import roundup
22 class ELFStructs(object):
23 """ Accessible attributes:
25 Elf_{byte|half|word|word64|addr|offset|sword|xword|xsword}:
26 Data chunks, as specified by the ELF standard, adjusted for
27 correct endianness and word-size.
42 Entries in relocation sections
44 def __init__(self
, little_endian
=True, elfclass
=32):
45 assert elfclass
== 32 or elfclass
== 64
46 self
.little_endian
= little_endian
47 self
.elfclass
= elfclass
50 self
.e_ident_osabi
= None
52 def __getstate__(self
):
53 return self
.little_endian
, self
.elfclass
, self
.e_type
, self
.e_machine
, self
.e_ident_osabi
55 def __setstate__(self
, state
):
56 self
.little_endian
, self
.elfclass
, e_type
, e_machine
, e_osabi
= state
57 self
.create_basic_structs()
58 self
.create_advanced_structs(e_type
, e_machine
, e_osabi
)
60 def create_basic_structs(self
):
61 """ Create word-size related structs and ehdr struct needed for
62 initial determining of ELF type.
64 if self
.little_endian
:
65 self
.Elf_byte
= ULInt8
66 self
.Elf_half
= ULInt16
67 self
.Elf_word
= ULInt32
68 self
.Elf_word64
= ULInt64
69 self
.Elf_addr
= ULInt32
if self
.elfclass
== 32 else ULInt64
70 self
.Elf_offset
= self
.Elf_addr
71 self
.Elf_sword
= SLInt32
72 self
.Elf_xword
= ULInt32
if self
.elfclass
== 32 else ULInt64
73 self
.Elf_sxword
= SLInt32
if self
.elfclass
== 32 else SLInt64
75 self
.Elf_byte
= UBInt8
76 self
.Elf_half
= UBInt16
77 self
.Elf_word
= UBInt32
78 self
.Elf_word64
= UBInt64
79 self
.Elf_addr
= UBInt32
if self
.elfclass
== 32 else UBInt64
80 self
.Elf_offset
= self
.Elf_addr
81 self
.Elf_sword
= SBInt32
82 self
.Elf_xword
= UBInt32
if self
.elfclass
== 32 else UBInt64
83 self
.Elf_sxword
= SBInt32
if self
.elfclass
== 32 else SBInt64
88 def create_advanced_structs(self
, e_type
=None, e_machine
=None, e_ident_osabi
=None):
89 """ Create all ELF structs except the ehdr. They may possibly depend
90 on provided e_type and/or e_machine parsed from ehdr.
93 self
.e_machine
= e_machine
94 self
.e_ident_osabi
= e_ident_osabi
102 self
._create
_sunw
_syminfo
()
103 self
._create
_gnu
_verneed
()
104 self
._create
_gnu
_verdef
()
105 self
._create
_gnu
_versym
()
106 self
._create
_gnu
_abi
()
107 self
._create
_gnu
_property
()
108 self
._create
_note
(e_type
)
110 self
._create
_arm
_attributes
()
111 self
._create
_elf
_hash
()
112 self
._create
_gnu
_hash
()
114 #-------------------------------- PRIVATE --------------------------------#
116 def _create_ehdr(self
):
117 self
.Elf_Ehdr
= Struct('Elf_Ehdr',
119 Array(4, self
.Elf_byte('EI_MAG')),
120 Enum(self
.Elf_byte('EI_CLASS'), **ENUM_EI_CLASS
),
121 Enum(self
.Elf_byte('EI_DATA'), **ENUM_EI_DATA
),
122 Enum(self
.Elf_byte('EI_VERSION'), **ENUM_E_VERSION
),
123 Enum(self
.Elf_byte('EI_OSABI'), **ENUM_EI_OSABI
),
124 self
.Elf_byte('EI_ABIVERSION'),
127 Enum(self
.Elf_half('e_type'), **ENUM_E_TYPE
),
128 Enum(self
.Elf_half('e_machine'), **ENUM_E_MACHINE
),
129 Enum(self
.Elf_word('e_version'), **ENUM_E_VERSION
),
130 self
.Elf_addr('e_entry'),
131 self
.Elf_offset('e_phoff'),
132 self
.Elf_offset('e_shoff'),
133 self
.Elf_word('e_flags'),
134 self
.Elf_half('e_ehsize'),
135 self
.Elf_half('e_phentsize'),
136 self
.Elf_half('e_phnum'),
137 self
.Elf_half('e_shentsize'),
138 self
.Elf_half('e_shnum'),
139 self
.Elf_half('e_shstrndx'),
142 def _create_leb128(self
):
143 self
.Elf_uleb128
= ULEB128
145 def _create_ntbs(self
):
146 self
.Elf_ntbs
= CString
148 def _create_phdr(self
):
149 p_type_dict
= ENUM_P_TYPE_BASE
150 if self
.e_machine
== 'EM_ARM':
151 p_type_dict
= ENUM_P_TYPE_ARM
152 elif self
.e_machine
== 'EM_AARCH64':
153 p_type_dict
= ENUM_P_TYPE_AARCH64
154 elif self
.e_machine
== 'EM_MIPS':
155 p_type_dict
= ENUM_P_TYPE_MIPS
157 if self
.elfclass
== 32:
158 self
.Elf_Phdr
= Struct('Elf_Phdr',
159 Enum(self
.Elf_word('p_type'), **p_type_dict
),
160 self
.Elf_offset('p_offset'),
161 self
.Elf_addr('p_vaddr'),
162 self
.Elf_addr('p_paddr'),
163 self
.Elf_word('p_filesz'),
164 self
.Elf_word('p_memsz'),
165 self
.Elf_word('p_flags'),
166 self
.Elf_word('p_align'),
169 self
.Elf_Phdr
= Struct('Elf_Phdr',
170 Enum(self
.Elf_word('p_type'), **p_type_dict
),
171 self
.Elf_word('p_flags'),
172 self
.Elf_offset('p_offset'),
173 self
.Elf_addr('p_vaddr'),
174 self
.Elf_addr('p_paddr'),
175 self
.Elf_xword('p_filesz'),
176 self
.Elf_xword('p_memsz'),
177 self
.Elf_xword('p_align'),
180 def _create_shdr(self
):
181 """Section header parsing.
183 Depends on e_machine because of machine-specific values in sh_type.
185 sh_type_dict
= ENUM_SH_TYPE_BASE
186 if self
.e_machine
== 'EM_ARM':
187 sh_type_dict
= ENUM_SH_TYPE_ARM
188 elif self
.e_machine
== 'EM_X86_64':
189 sh_type_dict
= ENUM_SH_TYPE_AMD64
190 elif self
.e_machine
== 'EM_MIPS':
191 sh_type_dict
= ENUM_SH_TYPE_MIPS
193 self
.Elf_Shdr
= Struct('Elf_Shdr',
194 self
.Elf_word('sh_name'),
195 Enum(self
.Elf_word('sh_type'), **sh_type_dict
),
196 self
.Elf_xword('sh_flags'),
197 self
.Elf_addr('sh_addr'),
198 self
.Elf_offset('sh_offset'),
199 self
.Elf_xword('sh_size'),
200 self
.Elf_word('sh_link'),
201 self
.Elf_word('sh_info'),
202 self
.Elf_xword('sh_addralign'),
203 self
.Elf_xword('sh_entsize'),
206 def _create_chdr(self
):
207 # Structure of compressed sections header. It is documented in Oracle
208 # "Linker and Libraries Guide", Part IV ELF Application Binary
209 # Interface, Chapter 13 Object File Format, Section Compression:
210 # https://docs.oracle.com/cd/E53394_01/html/E54813/section_compression.html
212 Enum(self
.Elf_word('ch_type'), **ENUM_ELFCOMPRESS_TYPE
),
213 self
.Elf_xword('ch_size'),
214 self
.Elf_xword('ch_addralign'),
216 if self
.elfclass
== 64:
217 fields
.insert(1, self
.Elf_word('ch_reserved'))
218 self
.Elf_Chdr
= Struct('Elf_Chdr', *fields
)
220 def _create_rel(self
):
221 # r_info is also taken apart into r_info_sym and r_info_type. This is
222 # done in Value to avoid endianity issues while parsing.
223 if self
.elfclass
== 32:
224 fields
= [self
.Elf_xword('r_info'),
226 lambda ctx
: (ctx
['r_info'] >> 8) & 0xFFFFFF),
228 lambda ctx
: ctx
['r_info'] & 0xFF)]
229 elif self
.e_machine
== 'EM_MIPS': # ELF64 MIPS
231 # The MIPS ELF64 specification
232 # (https://www.linux-mips.org/pub/linux/mips/doc/ABI/elf64-2.4.pdf)
233 # provides a non-standard relocation structure definition.
234 self
.Elf_word('r_sym'),
235 self
.Elf_byte('r_ssym'),
236 self
.Elf_byte('r_type3'),
237 self
.Elf_byte('r_type2'),
238 self
.Elf_byte('r_type'),
240 # Synthetize usual fields for compatibility with other
241 # architectures. This allows relocation consumers (including
242 # our readelf tests) to work without worrying about MIPS64
244 Value('r_info_sym', lambda ctx
: ctx
['r_sym']),
245 Value('r_info_ssym', lambda ctx
: ctx
['r_ssym']),
246 Value('r_info_type', lambda ctx
: ctx
['r_type']),
247 Value('r_info_type2', lambda ctx
: ctx
['r_type2']),
248 Value('r_info_type3', lambda ctx
: ctx
['r_type3']),
250 lambda ctx
: (ctx
['r_sym'] << 32)
251 |
(ctx
['r_ssym'] << 24)
252 |
(ctx
['r_type3'] << 16)
253 |
(ctx
['r_type2'] << 8)
256 else: # Other 64 ELFs
257 fields
= [self
.Elf_xword('r_info'),
259 lambda ctx
: (ctx
['r_info'] >> 32) & 0xFFFFFFFF),
261 lambda ctx
: ctx
['r_info'] & 0xFFFFFFFF)]
263 self
.Elf_Rel
= Struct('Elf_Rel',
264 self
.Elf_addr('r_offset'),
267 fields_and_addend
= fields
+ [self
.Elf_sxword('r_addend')]
268 self
.Elf_Rela
= Struct('Elf_Rela',
269 self
.Elf_addr('r_offset'),
273 # Elf32_Relr is typedef'd as Elf32_Word, Elf64_Relr as Elf64_Xword
274 # (see the glibc patch, for example:
275 # https://sourceware.org/pipermail/libc-alpha/2021-October/132029.html)
276 # For us, this is the same as self.Elf_addr (or self.Elf_xword).
277 self
.Elf_Relr
= Struct('Elf_Relr', self
.Elf_addr('r_offset'))
279 def _create_dyn(self
):
280 d_tag_dict
= dict(ENUM_D_TAG_COMMON
)
281 if self
.e_machine
in ENUMMAP_EXTRA_D_TAG_MACHINE
:
282 d_tag_dict
.update(ENUMMAP_EXTRA_D_TAG_MACHINE
[self
.e_machine
])
283 elif self
.e_ident_osabi
== 'ELFOSABI_SOLARIS':
284 d_tag_dict
.update(ENUM_D_TAG_SOLARIS
)
286 self
.Elf_Dyn
= Struct('Elf_Dyn',
287 Enum(self
.Elf_sxword('d_tag'), **d_tag_dict
),
288 self
.Elf_xword('d_val'),
289 Value('d_ptr', lambda ctx
: ctx
['d_val']),
292 def _create_sym(self
):
293 # st_info is hierarchical. To access the type, use
294 # container['st_info']['type']
295 st_info_struct
= BitStruct('st_info',
296 Enum(BitField('bind', 4), **ENUM_ST_INFO_BIND
),
297 Enum(BitField('type', 4), **ENUM_ST_INFO_TYPE
))
298 # st_other is hierarchical. To access the visibility,
299 # use container['st_other']['visibility']
300 st_other_struct
= BitStruct('st_other',
301 # https://openpowerfoundation.org/wp-content/uploads/2016/03/ABI64BitOpenPOWERv1.1_16July2015_pub4.pdf
302 # See 3.4.1 Symbol Values.
303 Enum(BitField('local', 3), **ENUM_ST_LOCAL
),
305 Enum(BitField('visibility', 3), **ENUM_ST_VISIBILITY
))
306 if self
.elfclass
== 32:
307 self
.Elf_Sym
= Struct('Elf_Sym',
308 self
.Elf_word('st_name'),
309 self
.Elf_addr('st_value'),
310 self
.Elf_word('st_size'),
313 Enum(self
.Elf_half('st_shndx'), **ENUM_ST_SHNDX
),
316 self
.Elf_Sym
= Struct('Elf_Sym',
317 self
.Elf_word('st_name'),
320 Enum(self
.Elf_half('st_shndx'), **ENUM_ST_SHNDX
),
321 self
.Elf_addr('st_value'),
322 self
.Elf_xword('st_size'),
325 def _create_sunw_syminfo(self
):
326 self
.Elf_Sunw_Syminfo
= Struct('Elf_Sunw_Syminfo',
327 Enum(self
.Elf_half('si_boundto'), **ENUM_SUNW_SYMINFO_BOUNDTO
),
328 self
.Elf_half('si_flags'),
331 def _create_gnu_verneed(self
):
332 # Structure of "version needed" entries is documented in
333 # Oracle "Linker and Libraries Guide", Chapter 13 Object File Format
334 self
.Elf_Verneed
= Struct('Elf_Verneed',
335 self
.Elf_half('vn_version'),
336 self
.Elf_half('vn_cnt'),
337 self
.Elf_word('vn_file'),
338 self
.Elf_word('vn_aux'),
339 self
.Elf_word('vn_next'),
341 self
.Elf_Vernaux
= Struct('Elf_Vernaux',
342 self
.Elf_word('vna_hash'),
343 self
.Elf_half('vna_flags'),
344 self
.Elf_half('vna_other'),
345 self
.Elf_word('vna_name'),
346 self
.Elf_word('vna_next'),
349 def _create_gnu_verdef(self
):
350 # Structure of "version definition" entries are documented in
351 # Oracle "Linker and Libraries Guide", Chapter 13 Object File Format
352 self
.Elf_Verdef
= Struct('Elf_Verdef',
353 self
.Elf_half('vd_version'),
354 self
.Elf_half('vd_flags'),
355 self
.Elf_half('vd_ndx'),
356 self
.Elf_half('vd_cnt'),
357 self
.Elf_word('vd_hash'),
358 self
.Elf_word('vd_aux'),
359 self
.Elf_word('vd_next'),
361 self
.Elf_Verdaux
= Struct('Elf_Verdaux',
362 self
.Elf_word('vda_name'),
363 self
.Elf_word('vda_next'),
366 def _create_gnu_versym(self
):
367 # Structure of "version symbol" entries are documented in
368 # Oracle "Linker and Libraries Guide", Chapter 13 Object File Format
369 self
.Elf_Versym
= Struct('Elf_Versym',
370 Enum(self
.Elf_half('ndx'), **ENUM_VERSYM
),
373 def _create_gnu_abi(self
):
374 # Structure of GNU ABI notes is documented in
375 # https://code.woboq.org/userspace/glibc/csu/abi-note.S.html
376 self
.Elf_abi
= Struct('Elf_abi',
377 Enum(self
.Elf_word('abi_os'), **ENUM_NOTE_ABI_TAG_OS
),
378 self
.Elf_word('abi_major'),
379 self
.Elf_word('abi_minor'),
380 self
.Elf_word('abi_tiny'),
383 def _create_gnu_property(self
):
384 # Structure of GNU property notes is documented in
385 # https://github.com/hjl-tools/linux-abi/wiki/linux-abi-draft.pdf
386 def roundup_padding(ctx
):
387 if self
.elfclass
== 32:
388 return roundup(ctx
.pr_datasz
, 2) - ctx
.pr_datasz
389 return roundup(ctx
.pr_datasz
, 3) - ctx
.pr_datasz
391 def classify_pr_data(ctx
):
392 if type(ctx
.pr_type
) is not str:
394 if ctx
.pr_type
.startswith('GNU_PROPERTY_X86_'):
395 return ('GNU_PROPERTY_X86_*', 4, 0)
396 return (ctx
.pr_type
, ctx
.pr_datasz
, self
.elfclass
)
398 self
.Elf_Prop
= Struct('Elf_Prop',
399 Enum(self
.Elf_word('pr_type'), **ENUM_NOTE_GNU_PROPERTY_TYPE
),
400 self
.Elf_word('pr_datasz'),
401 Switch('pr_data', classify_pr_data
, {
402 ('GNU_PROPERTY_STACK_SIZE', 4, 32): self
.Elf_word('pr_data'),
403 ('GNU_PROPERTY_STACK_SIZE', 8, 64): self
.Elf_word64('pr_data'),
404 ('GNU_PROPERTY_X86_*', 4, 0): self
.Elf_word('pr_data'),
406 default
=Field('pr_data', lambda ctx
: ctx
.pr_datasz
)
408 Padding(roundup_padding
)
411 def _create_note(self
, e_type
=None):
412 # Structure of "PT_NOTE" section
414 self
.Elf_ugid
= self
.Elf_half
if self
.elfclass
== 32 and self
.e_machine
in {
427 self
.Elf_Nhdr
= Struct('Elf_Nhdr',
428 self
.Elf_word('n_namesz'),
429 self
.Elf_word('n_descsz'),
430 Enum(self
.Elf_word('n_type'),
431 **(ENUM_NOTE_N_TYPE
if e_type
!= "ET_CORE"
432 else ENUM_CORE_NOTE_N_TYPE
)),
435 # A process psinfo structure according to
436 # http://elixir.free-electrons.com/linux/v2.6.35/source/include/linux/elfcore.h#L84
437 if self
.elfclass
== 32:
438 self
.Elf_Prpsinfo
= Struct('Elf_Prpsinfo',
439 self
.Elf_byte('pr_state'),
440 String('pr_sname', 1),
441 self
.Elf_byte('pr_zomb'),
442 self
.Elf_byte('pr_nice'),
443 self
.Elf_xword('pr_flag'),
444 self
.Elf_ugid('pr_uid'),
445 self
.Elf_ugid('pr_gid'),
446 self
.Elf_word('pr_pid'),
447 self
.Elf_word('pr_ppid'),
448 self
.Elf_word('pr_pgrp'),
449 self
.Elf_word('pr_sid'),
450 String('pr_fname', 16),
451 String('pr_psargs', 80),
454 self
.Elf_Prpsinfo
= Struct('Elf_Prpsinfo',
455 self
.Elf_byte('pr_state'),
456 String('pr_sname', 1),
457 self
.Elf_byte('pr_zomb'),
458 self
.Elf_byte('pr_nice'),
460 self
.Elf_xword('pr_flag'),
461 self
.Elf_ugid('pr_uid'),
462 self
.Elf_ugid('pr_gid'),
463 self
.Elf_word('pr_pid'),
464 self
.Elf_word('pr_ppid'),
465 self
.Elf_word('pr_pgrp'),
466 self
.Elf_word('pr_sid'),
467 String('pr_fname', 16),
468 String('pr_psargs', 80),
471 # A PT_NOTE of type NT_FILE matching the definition in
472 # https://chromium.googlesource.com/
473 # native_client/nacl-binutils/+/upstream/master/binutils/readelf.c
475 self
.Elf_Nt_File
= Struct('Elf_Nt_File',
476 self
.Elf_xword("num_map_entries"),
477 self
.Elf_xword("page_size"),
478 Array(lambda ctx
: ctx
.num_map_entries
,
479 Struct('Elf_Nt_File_Entry',
480 self
.Elf_addr('vm_start'),
481 self
.Elf_addr('vm_end'),
482 self
.Elf_offset('page_offset'))),
483 Array(lambda ctx
: ctx
.num_map_entries
,
484 CString('filename')))
486 def _create_stabs(self
):
487 # Structure of one stabs entry, see binutils/bfd/stabs.c
488 # Names taken from https://sourceware.org/gdb/current/onlinedocs/stabs.html#Overview
489 self
.Elf_Stabs
= Struct('Elf_Stabs',
490 self
.Elf_word('n_strx'),
491 self
.Elf_byte('n_type'),
492 self
.Elf_byte('n_other'),
493 self
.Elf_half('n_desc'),
494 self
.Elf_word('n_value'),
497 def _create_arm_attributes(self
):
498 # Structure of a build attributes subsection header. A subsection is
499 # either public to all tools that process the ELF file or private to
500 # the vendor's tools.
501 self
.Elf_Attr_Subsection_Header
= Struct('Elf_Attr_Subsection',
502 self
.Elf_word('length'),
503 self
.Elf_ntbs('vendor_name',
507 # Structure of a build attribute tag.
508 self
.Elf_Attribute_Tag
= Struct('Elf_Attribute_Tag',
509 Enum(self
.Elf_uleb128('tag'),
513 def _create_elf_hash(self
):
514 # Structure of the old SYSV-style hash table header. It is documented
515 # in the Oracle "Linker and Libraries Guide", Part IV ELF Application
516 # Binary Interface, Chapter 14 Object File Format, Section Hash Table
518 # https://docs.oracle.com/cd/E53394_01/html/E54813/chapter6-48031.html
520 self
.Elf_Hash
= Struct('Elf_Hash',
521 self
.Elf_word('nbuckets'),
522 self
.Elf_word('nchains'),
523 Array(lambda ctx
: ctx
['nbuckets'], self
.Elf_word('buckets')),
524 Array(lambda ctx
: ctx
['nchains'], self
.Elf_word('chains')))
526 def _create_gnu_hash(self
):
527 # Structure of the GNU-style hash table header. Documentation for this
528 # table is mostly in the GLIBC source code, a good explanation of the
529 # format can be found in this blog post:
530 # https://flapenguin.me/2017/05/10/elf-lookup-dt-gnu-hash/
531 self
.Gnu_Hash
= Struct('Gnu_Hash',
532 self
.Elf_word('nbuckets'),
533 self
.Elf_word('symoffset'),
534 self
.Elf_word('bloom_size'),
535 self
.Elf_word('bloom_shift'),
536 Array(lambda ctx
: ctx
['bloom_size'], self
.Elf_xword('bloom')),
537 Array(lambda ctx
: ctx
['nbuckets'], self
.Elf_word('buckets')))