Debian Codegraph @

mbn/elf.py

raw symbols SCIP
1 # SPDX-License-Identifier: GPL-2.0-only
2 # Copyright (C) 2021 Stephan Gerhold
3 # Data classes are based on the header definitions in the ELF(5) man page.
4 # Also see: https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
5 from __future__ import annotations
6
7 import dataclasses
8 from dataclasses import dataclass
9 from struct import Struct
10 from typing import List, BinaryIO
11
12
13 @dataclass
14 class Ehdr:
15 ei_magic: bytes
16 ei_class: int
17 ei_data: int
18 ei_version: int
19 ei_os_abi: int
20 ei_abi_version: int
21 e_type: int
22 e_machine: int
23 e_version: int
24 # Address size specific part
25 e_entry: int = 0
26 e_phoff: int = 0
27 e_shoff: int = 0
28 # End part
29 e_flags: int = 0
30 e_ehsize: int = 0
31 e_phentsize: int = 0
32 e_phnum: int = 0
33 e_shentsize: int = 0
34 e_shnum: int = 0
35 e_shstrndx: int = 0
36
37 START_FORMAT = Struct('<4s5B7xHHL')
38 START_COUNT = 9
39 MEM_FORMAT32 = Struct('<LLL')
40 MEM_FORMAT64 = Struct('<QQQ')
41 MEM_COUNT = 3
42 END_FORMAT = Struct('<L6H')
43 END_COUNT = 7
44
45 CLASS32 = 1
46 CLASS64 = 2
47
48 @staticmethod
49 def parse(b: bytes) -> Ehdr:
50 hdr_unpack = Ehdr.START_FORMAT.unpack_from(b)
51 hdr = Ehdr(*hdr_unpack)
52 assert hdr.ei_magic == b'\x7fELF', f"Invalid ELF header magic: {hdr.ei_magic}"
53 assert hdr.ei_data == 1, "Only little endian supported at the moment"
54 assert hdr.ei_version == 1, f"Unexpected ei_version: {hdr.ei_version}"
55 assert hdr.e_version == 1, f"Unexpected e_version: {hdr.e_version}"
56
57 if hdr.ei_class == Ehdr.CLASS32:
58 mem_format = Ehdr.MEM_FORMAT32
59 else:
60 assert hdr.ei_class == Ehdr.CLASS64, f"Unexpected ei_class: {hdr.ei_class}"
61 mem_format = Ehdr.MEM_FORMAT64
62
63 mem_unpack = mem_format.unpack_from(b, Ehdr.START_FORMAT.size)
64 end_unpack = Ehdr.END_FORMAT.unpack_from(b, Ehdr.START_FORMAT.size + mem_format.size)
65 return Ehdr(*hdr_unpack, *mem_unpack, *end_unpack)
66
67 def save(self, f: BinaryIO) -> int:
68 unpack = dataclasses.astuple(self)
69 written = f.write(Ehdr.START_FORMAT.pack(*unpack[:Ehdr.START_COUNT]))
70
71 if self.ei_class == Ehdr.CLASS32:
72 mem_format = Ehdr.MEM_FORMAT32
73 else:
74 mem_format = Ehdr.MEM_FORMAT64
75 written += f.write(
76 mem_format.pack(*unpack[Ehdr.START_COUNT:Ehdr.START_COUNT + Ehdr.MEM_COUNT]))
77 written += f.write(Ehdr.END_FORMAT.pack(*unpack[-Ehdr.END_COUNT:]))
78 return written
79
80
81 @dataclass
82 class Phdr:
83 p_type: int
84 p_offset: int
85 p_vaddr: int
86 p_paddr: int
87 p_filesz: int
88 p_memsz: int
89 p_flags: int
90 p_align: int
91
92 data = None
93
94 FORMAT32 = Struct('<8L')
95 FORMAT64 = Struct('<LL6Q')
96
97 PT_NULL = 0
98 PT_LOAD = 1
99
100 @staticmethod
101 def parse(b: bytes, offset: int, ei_class: int) -> Phdr:
102 if ei_class == Ehdr.CLASS32:
103 unpack = Phdr.FORMAT32.unpack_from(b, offset)
104 else:
105 unpack = list(Phdr.FORMAT64.unpack_from(b, offset))
106
107 # ELFCLASS64 has flags directly before offset for alignment
108 flags = unpack.pop(1)
109 unpack.insert(-1, flags)
110
111 return Phdr(*unpack)
112
113 def save(self, f: BinaryIO, ei_class: int) -> int:
114 unpack = dataclasses.astuple(self)
115
116 if ei_class == Ehdr.CLASS32:
117 return f.write(Phdr.FORMAT32.pack(*unpack))
118 else:
119 unpack = list(unpack)
120
121 # ELFCLASS64 has flags directly before offset for alignment
122 flags = unpack.pop(-2)
123 unpack.insert(1, flags)
124
125 return f.write(Phdr.FORMAT64.pack(*unpack))
126
127
128 def _pad(f: BinaryIO, offset: int, pos: int) -> int:
129 assert offset >= pos, f"{offset} >= {pos}"
130 pad = offset - pos
131 if pad:
132 assert f.write(b'\0' * pad) == pad
133 return offset
134
135
136 def align(i: int, alignment: int) -> int:
137 mask = max(alignment - 1, 0)
138 return (i + mask) & ~mask
139
140
141 @dataclass
142 class Elf:
143 ehdr: Ehdr
144 phdrs: List[Phdr]
145
146 def total_header_size(self):
147 return self.ehdr.e_phoff + len(self.phdrs) * self.ehdr.e_phentsize
148
149 @staticmethod
150 def parse(b: bytes) -> Elf:
151 ehdr = Ehdr.parse(b)
152 view = memoryview(b)
153
154 # Parse program headers
155 phdrs = []
156 offset = ehdr.e_phoff
157 for i in range(ehdr.e_phnum):
158 phdr = Phdr.parse(b, offset, ehdr.ei_class)
159 phdrs.append(phdr)
160
161 # Store data if necessary
162 if phdr.p_filesz and phdr.p_offset:
163 phdr.data = view[phdr.p_offset:phdr.p_offset + phdr.p_filesz]
164
165 offset += ehdr.e_phentsize
166
167 return Elf(ehdr, phdrs)
168
169 def update(self):
170 # Rearrange all segments according to their alignment
171 pos = self.total_header_size()
172 for phdr in sorted(self.phdrs, key=lambda phdr: phdr.p_offset):
173 if phdr.p_offset and phdr.p_filesz:
174 phdr.p_offset = align(pos, phdr.p_align)
175 pos = phdr.p_offset + phdr.p_filesz
176
177 # Ensure program header count is correct
178 self.ehdr.e_phnum = len(self.phdrs)
179
180 # TODO: Clear out sections for now. Those are not read at the moment.
181 # Also, I don't think the Qualcomm firmware loader has any use for these.
182 self.ehdr.e_shoff = 0
183 self.ehdr.e_shnum = 0
184 self.ehdr.e_shstrndx = 0
185
186 def save_header(self, f: BinaryIO) -> int:
187 pos = self.ehdr.save(f)
188 pos = _pad(f, self.ehdr.e_phoff, pos)
189
190 # Write program headers
191 for phdr in self.phdrs:
192 pos += phdr.save(f, self.ehdr.ei_class)
193
194 return pos
195
196 def save(self, f: BinaryIO) -> int:
197 pos = self.save_header(f)
198
199 # Write segment data
200 for phdr in sorted(self.phdrs, key=lambda phdr: phdr.p_offset):
201 if phdr.data:
202 pos = _pad(f, phdr.p_offset, pos)
203 pos += f.write(phdr.data)
204
205 return pos