9e349182dea2f1308743a3d3f37e48f31770f8d5
[pyelftools.git] / examples / elf_notes.py
1 #-------------------------------------------------------------------------------
2 # elftools example: elf_notes.py
3 #
4 # An example of obtaining note sections from an ELF file and examining
5 # the notes it contains.
6 #
7 # Eli Bendersky (eliben@gmail.com)
8 # This code is in the public domain
9 #-------------------------------------------------------------------------------
10 from __future__ import print_function
11 import sys
12
13 # If pyelftools is not installed, the example can also run from the root or
14 # examples/ dir of the source distribution.
15 sys.path[0:0] = ['.', '..']
16
17 from elftools.elf.elffile import ELFFile
18 from elftools.elf.sections import NoteSection
19
20
21 def process_file(filename):
22 print('Processing file:', filename)
23 with open(filename, 'rb') as f:
24 for sect in ELFFile(f).iter_sections():
25 if not isinstance(sect, NoteSection):
26 continue
27 print(' Note section "%s" at offset 0x%.8x with size %d' % (
28 sect.name, sect.header['sh_offset'], sect.header['sh_size']))
29 for note in sect.iter_notes():
30 print(' Name:', note['n_name'])
31 print(' Type:', note['n_type'])
32 desc = note['n_desc']
33 if note['n_type'] == 'NT_GNU_ABI_TAG':
34 print(' Desc: %s, ABI: %d.%d.%d' % (
35 desc['abi_os'],
36 desc['abi_major'],
37 desc['abi_minor'],
38 desc['abi_tiny']))
39 elif note['n_type'] == 'NT_GNU_BUILD_ID':
40 print(' Desc:', desc)
41 else:
42 print(' Desc:', ''.join('%.2x' % ord(b) for b in desc))
43
44
45 if __name__ == '__main__':
46 if sys.argv[1] == '--test':
47 for filename in sys.argv[2:]:
48 process_file(filename)