3e46b3a30a8b637477e882c1cb5572651a9b1e03
[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 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 = bytes2str(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'] = ''.join('%.2x' % ord(b) for b in desc_data)
40 elif note['n_type'] == 'NT_PRPSINFO':
41 note['n_desc'] = struct_parse(elffile.structs.Elf_Prpsinfo,
42 elffile.stream,
43 offset)
44 elif note['n_type'] == 'NT_FILE':
45 note['n_desc'] = struct_parse(elffile.structs.Elf_Nt_File,
46 elffile.stream,
47 offset)
48 else:
49 note['n_desc'] = desc_data
50 offset += roundup(note['n_descsz'], 2)
51 note['n_size'] = offset - note['n_offset']
52 yield note