Finish refactoring out py3compat and delete the file
[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.utils import struct_parse, bytes2hex, roundup, bytes2str
10 from ..construct import CString
11
12
13 def iter_notes(elffile, offset, size):
14 """ Yield all the notes in a section or segment.
15 """
16 end = offset + size
17 while offset < end:
18 note = struct_parse(
19 elffile.structs.Elf_Nhdr,
20 elffile.stream,
21 stream_pos=offset)
22 note['n_offset'] = offset
23 offset += elffile.structs.Elf_Nhdr.sizeof()
24 elffile.stream.seek(offset)
25 # n_namesz is 4-byte aligned.
26 disk_namesz = roundup(note['n_namesz'], 2)
27 note['n_name'] = bytes2str(
28 CString('').parse(elffile.stream.read(disk_namesz)))
29 offset += disk_namesz
30
31 desc_data = elffile.stream.read(note['n_descsz'])
32 note['n_descdata'] = desc_data
33 if note['n_type'] == 'NT_GNU_ABI_TAG':
34 note['n_desc'] = struct_parse(elffile.structs.Elf_abi,
35 elffile.stream,
36 offset)
37 elif note['n_type'] == 'NT_GNU_BUILD_ID':
38 note['n_desc'] = bytes2hex(desc_data)
39 elif note['n_type'] == 'NT_GNU_GOLD_VERSION':
40 note['n_desc'] = bytes2str(desc_data)
41 elif note['n_type'] == 'NT_PRPSINFO':
42 note['n_desc'] = struct_parse(elffile.structs.Elf_Prpsinfo,
43 elffile.stream,
44 offset)
45 elif note['n_type'] == 'NT_FILE':
46 note['n_desc'] = struct_parse(elffile.structs.Elf_Nt_File,
47 elffile.stream,
48 offset)
49 elif note['n_type'] == 'NT_GNU_PROPERTY_TYPE_0':
50 off = offset
51 props = []
52 while off < end:
53 p = struct_parse(elffile.structs.Elf_Prop, elffile.stream, off)
54 off += roundup(p.pr_datasz + 8, 2 if elffile.elfclass == 32 else 3)
55 props.append(p)
56 note['n_desc'] = props
57 else:
58 note['n_desc'] = desc_data
59 offset += roundup(note['n_descsz'], 2)
60 note['n_size'] = offset - note['n_offset']
61 yield note