382da94e9d730d3cce5c1796e5d1030f173ed7d6
[pyelftools.git] / elftools / elf / notes.py
1 #-------------------------------------------------------------------------------
2 # elftools: elf/notes.py
3 #
4 # ELF notes
5 #
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 from ..common.py3compat import bytes2hex, bytes2str
10 from ..common.utils import struct_parse, roundup
11 from ..construct import CString
12
13
14 def iter_notes(elffile, offset, size):
15 """ Yield all the notes in a section or segment.
16 """
17 end = offset + size
18 while offset < end:
19 note = struct_parse(
20 elffile.structs.Elf_Nhdr,
21 elffile.stream,
22 stream_pos=offset)
23 note['n_offset'] = offset
24 offset += elffile.structs.Elf_Nhdr.sizeof()
25 elffile.stream.seek(offset)
26 # n_namesz is 4-byte aligned.
27 disk_namesz = roundup(note['n_namesz'], 2)
28 note['n_name'] = bytes2str(
29 CString('').parse(elffile.stream.read(disk_namesz)))
30 offset += disk_namesz
31
32 desc_data = elffile.stream.read(note['n_descsz'])
33 note['n_descdata'] = desc_data
34 if note['n_type'] == 'NT_GNU_ABI_TAG':
35 note['n_desc'] = struct_parse(elffile.structs.Elf_abi,
36 elffile.stream,
37 offset)
38 elif note['n_type'] == 'NT_GNU_BUILD_ID':
39 note['n_desc'] = bytes2hex(desc_data)
40 elif note['n_type'] == 'NT_GNU_GOLD_VERSION':
41 note['n_desc'] = bytes2str(desc_data)
42 elif note['n_type'] == 'NT_PRPSINFO':
43 note['n_desc'] = struct_parse(elffile.structs.Elf_Prpsinfo,
44 elffile.stream,
45 offset)
46 elif note['n_type'] == 'NT_FILE':
47 note['n_desc'] = struct_parse(elffile.structs.Elf_Nt_File,
48 elffile.stream,
49 offset)
50 else:
51 note['n_desc'] = desc_data
52 offset += roundup(note['n_descsz'], 2)
53 note['n_size'] = offset - note['n_offset']
54 yield note