Debian Codegraph @

util/qualcomm/elf_segment_extractor.py

raw symbols SCIP
1 #!/usr/bin/env python
2 import sys
3 import os
4 import struct
5 import argparse # Import the argparse module
6
7 # --- Constants for ELF parsing ---
8
9 # e_ident (first 16 bytes of ELF header)
10 EI_MAG0 = 0 # File identifier
11 EI_MAG1 = 1
12 EI_MAG2 = 2
13 EI_MAG3 = 3
14 EI_CLASS = 4 # File class (32-bit or 64-bit)
15 EI_DATA = 5 # Data encoding (endianness)
16 EI_VERSION = 6 # ELF header version
17 EI_OSABI = 7 # OS/ABI identification
18 EI_ABIVERSION = 8 # ABI version
19 EI_PAD = 9 # Start of padding bytes
20
21 # ELF Class definitions
22 ELFCLASSNONE = 0
23 ELFCLASS32 = 1 # 32-bit ELF
24 ELFCLASS64 = 2 # 64-bit ELF
25
26 # ELF Data encoding definitions
27 ELFDATANONE = 0
28 ELFDATA2LSB = 1 # Little-endian
29 ELFDATA2MSB = 2 # Big-endian
30
31 # ELF Header offsets and sizes (for 32-bit and 64-bit)
32 # All values are in bytes
33 ELF_HEADER_SIZE_32 = 52
34 ELF_HEADER_SIZE_64 = 64
35
36 # Program Header (Phdr) offsets and sizes (relative to start of Phdr entry)
37 # These vary based on ELF class (32-bit or 64-bit)
38
39 # 32-bit Program Header (Elf32_Phdr) structure
40 # typedef struct {
41 # Elf32_Word p_type; /* Segment type */
42 # Elf32_Off p_offset; /* Segment file offset */
43 # Elf32_Addr p_vaddr; /* Segment virtual address */
44 # Elf32_Addr p_paddr; /* Segment physical address */
45 # Elf32_Word p_filesz; /* Segment size in file */
46 # Elf32_Word p_memsz; /* Segment size in memory */
47 # Elf32_Word p_flags; /* Segment flags */
48 # Elf32_Word p_align; /* Segment alignment */
49 # } Elf32_Phdr;
50 PHDR_32_FMT = '<IIIIIIII' # Little-endian, 8 unsigned ints (4 bytes each)
51 PHDR_32_SIZE = 32 # Total size of 32-bit program header entry
52
53 # 64-bit Program Header (Elf64_Phdr) structure
54 # typedef struct {
55 # Elf64_Word p_type; /* Segment type */
56 # Elf64_Word p_flags; /* Segment flags */
57 # Elf64_Off p_offset; /* Segment file offset */
58 # Elf64_Addr p_vaddr; /* Segment virtual address */
59 # Elf64_Addr p_paddr; /* Segment physical address */
60 # Elf64_Xword p_filesz; /* Segment size in file */
61 # Elf64_Xword p_memsz; /* Segment size in memory */
62 # Elf64_Xword p_align; /* Segment alignment */
63 # } Elf64_Phdr;
64 # Note: p_type and p_flags are 4 bytes, others are 8 bytes
65 PHDR_64_FMT = '<IIQQQQQQ' # Little-endian, 2 unsigned ints (4 bytes), 6 unsigned long longs (8 bytes)
66 PHDR_64_SIZE = 56 # Total size of 64-bit program header entry
67
68 def parse_elf_header(f):
69 """
70 Parses the ELF header from the given file object and returns both parsed info and raw header bytes.
71
72 Args:
73 f (file): The file object opened in binary read mode.
74
75 Returns:
76 tuple: A tuple containing (dict: parsed ELF header information, bytes: raw ELF header data).
77 Returns (None, None) if the file is not a valid ELF or unsupported.
78 """
79 f.seek(0)
80 e_ident = f.read(16)
81
82 # Check ELF magic bytes
83 if not (e_ident[EI_MAG0] == 0x7F and
84 e_ident[EI_MAG1] == ord('E') and
85 e_ident[EI_MAG2] == ord('L') and
86 e_ident[EI_MAG3] == ord('F')):
87 print("Error: Not an ELF file (invalid magic bytes).")
88 return None, None
89
90 elf_class = e_ident[EI_CLASS]
91 elf_data_encoding = e_ident[EI_DATA]
92
93 endian_char = ''
94 if elf_data_encoding == ELFDATA2LSB:
95 endian_char = '<' # Little-endian
96 elif elf_data_encoding == ELFDATA2MSB:
97 endian_char = '>' # Big-endian
98 else:
99 print("Error: Unsupported ELF data encoding.")
100 return None, None
101
102 raw_header_bytes = b'' # To store the entire raw ELF header
103
104 if elf_class == ELFCLASS32:
105 # 32-bit ELF header format: 2xH, 5xI, 6xH (Total 36 bytes for remaining header)
106 header_fmt = f"{endian_char}HHI IIII HHHHHH"
107 header_data_rest = f.read(ELF_HEADER_SIZE_32 - 16)
108 raw_header_bytes = e_ident + header_data_rest # Concatenate e_ident with the rest
109
110 (e_type, e_machine, e_version, e_entry, e_phoff, e_shoff,
111 e_flags, e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx) = \
112 struct.unpack(header_fmt, header_data_rest)
113 elf_header = {
114 'class': elf_class,
115 'endian': endian_char,
116 'e_phoff': e_phoff,
117 'e_phentsize': e_phentsize,
118 'e_phnum': e_phnum,
119 'ehsize': ELF_HEADER_SIZE_32
120 }
121 elif elf_class == ELFCLASS64:
122 # 64-bit ELF header format: 2xH, 1xI, 3xQ, 1xI, 6xH (Total 48 bytes for remaining header)
123 header_fmt = f"{endian_char}HHI QQQ I HHHHHH"
124 header_data_rest = f.read(ELF_HEADER_SIZE_64 - 16)
125 raw_header_bytes = e_ident + header_data_rest # Concatenate e_ident with the rest
126
127 (e_type, e_machine, e_version, e_entry, e_phoff, e_shoff,
128 e_flags, e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx) = \
129 struct.unpack(header_fmt, header_data_rest)
130 elf_header = {
131 'class': elf_class,
132 'endian': endian_char,
133 'e_phoff': e_phoff,
134 'e_phentsize': e_phentsize,
135 'e_phnum': e_phnum,
136 'ehsize': ELF_HEADER_SIZE_64
137 }
138 else:
139 print("Error: Unsupported ELF class.")
140 return None, None
141
142 return elf_header, raw_header_bytes
143
144 def parse_program_header(f, elf_header, segment_index):
145 """
146 Parses a specific program header (segment) from the ELF file.
147
148 Args:
149 f (file): The file object.
150 elf_header (dict): Parsed ELF header information.
151 segment_index (int): The 0-based index of the program header to parse.
152
153 Returns:
154 dict: A dictionary containing parsed program header information (p_offset, p_filesz, p_type, p_flags).
155 Returns None if the index is out of bounds or parsing fails.
156 """
157 e_phoff = elf_header['e_phoff']
158 e_phentsize = elf_header['e_phentsize']
159 e_phnum = elf_header['e_phnum']
160 endian_char = elf_header['endian']
161 elf_class = elf_header['class']
162
163 if not (0 <= segment_index < e_phnum):
164 print(f"Error: Segment index {segment_index} is out of bounds.")
165 print(f"This ELF file has {e_phnum} segments (0 to {e_phnum - 1}).")
166 return None
167
168 # Calculate the offset to the desired program header entry
169 phdr_offset = e_phoff + (segment_index * e_phentsize)
170 f.seek(phdr_offset)
171
172 if elf_class == ELFCLASS32:
173 if e_phentsize != PHDR_32_SIZE:
174 print(f"Warning: Unexpected phentsize for 32-bit ELF: {e_phentsize}. Expected {PHDR_32_SIZE}.")
175 phdr_data = f.read(PHDR_32_SIZE)
176 (p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags, p_align) = \
177 struct.unpack(f"{endian_char}{PHDR_32_FMT[1:]}", phdr_data)
178 elif elf_class == ELFCLASS64:
179 if e_phentsize != PHDR_64_SIZE:
180 print(f"Warning: Unexpected phentsize for 64-bit ELF: {e_phentsize}. Expected {PHDR_64_SIZE}.")
181 phdr_data = f.read(PHDR_64_SIZE)
182 (p_type, p_flags, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_align) = \
183 struct.unpack(f"{endian_char}{PHDR_64_FMT[1:]}", phdr_data)
184 else:
185 print("Error: Unsupported ELF class for parsing program header.")
186 return None
187
188 return {
189 'p_type': p_type,
190 'p_offset': p_offset,
191 'p_vaddr': p_vaddr,
192 'p_paddr': p_paddr,
193 'p_filesz': p_filesz,
194 'p_memsz': p_memsz,
195 'p_flags': p_flags,
196 'p_align': p_align
197 }
198
199
200 def extract_elf_data(elf_file_path: str, output_file_path: str, extract_eh: bool, extract_pht: bool, segment_args_str: str = None, extract_hashtable: bool = False):
201 """
202 Extracts specified components from an ELF file (ELF Header, Program Headers, a specific Segment)
203 and concatenates them into a single output binary file.
204
205 Args:
206 elf_file_path (str): The path to the ELF file.
207 output_file_path (str): The path to the output binary file.
208 extract_eh (bool): True to extract the ELF header, False otherwise.
209 extract_pht (bool): True to extract all Program Headers, False otherwise.
210 segment_args_str (str, optional): A comma-separated string of 0-based segment indices,
211 or '$' / 'N' for the last segment. None if not extracting segments.
212 extract_hashtable (bool): True to extract segments where p_type is NULL (0) and p_flags is 0x02000000.
213 """
214 try:
215 with open(elf_file_path, 'rb') as f:
216 elf_header_info, raw_elf_header_bytes = parse_elf_header(f)
217 if elf_header_info is None:
218 return
219
220 output_data = b''
221
222 # 1. Extract ELF Header if requested
223 if extract_eh:
224 output_data += raw_elf_header_bytes
225 print(f"Included ELF Header ({len(raw_elf_header_bytes)} bytes).")
226
227 # 2. Extract Program Header Table (PHT) if requested
228 num_segments = elf_header_info['e_phnum']
229 all_program_headers_bytes = b''
230 if extract_pht:
231 if num_segments > 0:
232 f.seek(elf_header_info['e_phoff'])
233 all_program_headers_bytes = f.read(elf_header_info['e_phentsize'] * num_segments)
234 output_data += all_program_headers_bytes
235 print(f"Included all {num_segments} Program Headers ({len(all_program_headers_bytes)} bytes).")
236 else:
237 print("Warning: No Program Headers found in ELF file to extract for PHT.")
238
239 # 3. Extract specific Segment data if requested via --segment
240 if segment_args_str is not None:
241 segments_to_extract_indices = []
242 # Split the comma-separated string and process each segment argument
243 for seg_arg in segment_args_str.split(','):
244 seg_arg = seg_arg.strip() # Remove any whitespace
245 if not seg_arg: # Skip empty strings from multiple commas (e.g., "0,,1")
246 continue
247
248 actual_segment_index = None
249 if seg_arg == "$" or seg_arg.upper() == "N":
250 if num_segments == 0:
251 print(f"Error: No segments found in ELF file '{elf_file_path}'. Cannot extract last segment for '{seg_arg}'.")
252 return
253 actual_segment_index = num_segments - 1
254 print(f"'{seg_arg}' detected. Auto-selecting last segment (index {actual_segment_index}).")
255 else:
256 try:
257 actual_segment_index = int(seg_arg)
258 except ValueError:
259 print(f"Error: Invalid segment index or alias '{seg_arg}'. Segment index must be an integer, '$', or 'N'.")
260 return
261
262 if not (0 <= actual_segment_index < num_segments):
263 print(f"Error: Segment index {actual_segment_index} is out of bounds for '{elf_file_path}'.")
264 print(f"This ELF file has {num_segments} segments (0 to {num_segments - 1}).")
265 return
266
267 segments_to_extract_indices.append(actual_segment_index)
268
269 # Now extract data for each resolved segment index
270 for current_segment_index in segments_to_extract_indices:
271 segment_info = parse_program_header(f, elf_header_info, current_segment_index)
272 if segment_info is None:
273 # Error message already printed by parse_program_header
274 return
275
276 p_offset = segment_info['p_offset']
277 p_filesz = segment_info['p_filesz']
278
279 if p_filesz > 0:
280 f.seek(p_offset)
281 segment_data_bytes = f.read(p_filesz)
282 output_data += segment_data_bytes
283 print(f"Included Segment {current_segment_index} data ({len(segment_data_bytes)} bytes) via --segment.")
284 else:
285 print(f"Warning: Segment {current_segment_index} has no data in the file (p_filesz is 0). Skipping via --segment.")
286
287 # 4. Extract segments based on --hashtable criteria
288 if extract_hashtable:
289 print("\nSearching for segments with p_type = 0 (NULL) and p_flags = 0x02000000...")
290 found_hashtable_segments = False
291 for i in range(num_segments):
292 segment_info = parse_program_header(f, elf_header_info, i)
293 if segment_info is None:
294 continue # Skip if parsing failed for this segment
295
296 if segment_info['p_type'] == 0 and segment_info['p_flags'] == 0x02000000:
297 found_hashtable_segments = True
298 p_offset = segment_info['p_offset']
299 p_filesz = segment_info['p_filesz']
300
301 if p_filesz > 0:
302 f.seek(p_offset)
303 segment_data_bytes = f.read(p_filesz)
304 output_data += segment_data_bytes
305 print(f"Included Segment {i} (Type: NULL, Flags: 0x{segment_info['p_flags']:x}) data ({len(segment_data_bytes)} bytes) via --hashtable.")
306 else:
307 print(f"Warning: Segment {i} (Type: NULL, Flags: 0x{segment_info['p_flags']:x}) has no data in the file (p_filesz is 0). Skipping via --hashtable.")
308 if not found_hashtable_segments:
309 print("No segments found matching --hashtable criteria.")
310
311 # Write the concatenated data to the output file
312 if output_data:
313 try:
314 with open(output_file_path, 'wb') as out_f:
315 out_f.write(output_data)
316 print(f"\nSuccessfully wrote {len(output_data)} bytes to '{output_file_path}'")
317 except IOError as io_e:
318 print(f"Error writing to output file '{output_file_path}': {io_e}")
319 except Exception as write_e:
320 print(f"An unexpected error occurred while writing: {write_e}")
321 else:
322 print("No data extracted based on the provided options. Output file was not created.")
323
324
325 except FileNotFoundError:
326 print(f"Error: ELF file not found at '{elf_file_path}'")
327 except Exception as e:
328 print(f"An error occurred: {e}")
329
330 if __name__ == "__main__":
331 parser = argparse.ArgumentParser(
332 description="Extracts ELF Header, Program Headers, and/or specific Segments from an ELF file.",
333 formatter_class=argparse.RawTextHelpFormatter
334 )
335
336 parser.add_argument(
337 '--eh',
338 action='store_true',
339 help='Extract the ELF Header.'
340 )
341 parser.add_argument(
342 '--pht',
343 action='store_true',
344 help='Extract all Program Headers (Program Header Table).'
345 )
346 parser.add_argument(
347 '--segment',
348 type=str,
349 help='Specify a comma-separated list of 0-based segment indices to extract (e.g., "0,1,2").\n'
350 'Use "$" or "N" for the last segment (e.g., "0,N"). Segments will be concatenated in order.'
351 )
352 parser.add_argument(
353 '--hashtable',
354 action='store_true',
355 help='Extract all segments where p_type is NULL (0) and p_flags is 0x02000000.'
356 )
357 parser.add_argument(
358 'elf_file_path',
359 type=str,
360 help='Path to the input ELF file.'
361 )
362 parser.add_argument(
363 'output_file_path',
364 type=str,
365 help='Path to the output binary file where extracted data will be concatenated.'
366 )
367
368 args = parser.parse_args()
369
370 # Ensure at least one extraction option is provided
371 if not args.eh and not args.pht and args.segment is None and not args.hashtable:
372 parser.error("At least one extraction option (--eh, --pht, --segment, or --hashtable) must be provided.")
373
374 extract_elf_data(
375 args.elf_file_path,
376 args.output_file_path,
377 args.eh,
378 args.pht,
379 args.segment,
380 args.hashtable # Pass the new argument to the function
381 )