Debian Codegraph @

mesonbuild/scripts/depfixer.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2016 The Meson development team
3
4 from __future__ import annotations
5
6
7 import sys
8 import os
9 import stat
10 import struct
11 import shutil
12 import subprocess
13 import typing as T
14
15 from ..mesonlib import OrderedSet, generate_list, Popen_safe
16
17 SHT_STRTAB = 3
18 DT_NEEDED = 1
19 DT_RPATH = 15
20 DT_RUNPATH = 29
21 DT_STRTAB = 5
22 DT_SONAME = 14
23 DT_MIPS_RLD_MAP_REL = 1879048245
24
25 # Global cache for tools
26 INSTALL_NAME_TOOL = False
27
28 # -------------------AIX-------------------------
29 # Reference documents:
30 # https://www.ibm.com/docs/en/aix/7.1?topic=formats-xcoff-object-file-format
31 # https://www.ibm.com/docs/en/aix/7.2?topic=formats-ar-file-format-big
32
33 # Size of magic number
34 XCOFF_MAGIC_SIZE = 2
35
36
37 def align(value: int, align_bytes: int) -> int:
38 # Function used by AIX to align value to align_bytes
39 align_bytes = 1 << align_bytes
40 return ((value + align_bytes - 1) // align_bytes) * align_bytes
41
42
43 class XcoffFixedLengthHeader:
44 # AIX archive fixed length header (struct fl_hdr)
45 FL_HDR_SIZE = 128
46 FL_HDR_FORMAT = '8s 20s 20s 20s 20s 20s 20s'
47
48 def __init__(self, file: T.BinaryIO) -> None:
49 header_data = file.read(self.FL_HDR_SIZE)
50 fl_magic, fl_memoff, fl_gstoff, fl_gst64off, fl_fstmoff, fl_lstmoff, fl_freeoff = struct.unpack(
51 self.FL_HDR_FORMAT, header_data
52 )
53 self.fl_magic = fl_magic
54 self.fl_fstmoff = int(fl_fstmoff)
55
56
57 class XcoffArchiveHeader:
58 # AIX archive header (struct ar_hdr)
59 AR_HDR_SIZE = 114
60 AR_HDR_FORMAT = '20s 20s 20s 12s 12s 12s 12s 4s 2s'
61
62 def __init__(self, file: T.BinaryIO) -> None:
63 header_data = file.read(self.AR_HDR_SIZE)
64 ar_size, ar_nxtmem, ar_prvmem, ar_date, ar_uid, ar_gid, ar_mode, ar_namlen, _ar_name = struct.unpack(
65 self.AR_HDR_FORMAT, header_data
66 )
67 ar_namlen_int = int(ar_namlen.strip())
68 # The Magic number always starts at the even byte boundary
69 self.ar_namlen = ar_namlen_int if ar_namlen_int % 2 == 0 else ar_namlen_int + 1
70 # Seek past the archive member name
71 file.seek(self.ar_namlen, os.SEEK_CUR)
72
73
74 class XcoffCompositeFileHeader:
75 # XCOFF composite file header
76 CFH_HDR_SIZE = 24
77 CFH_HDR_SIZE_32 = 20
78 CFH_HDR_FORMAT = '2s 2s 4s 8s 2s 2s 4s'
79 CFH_HDR_FORMAT_32 = '2s 2s 4s 4s 4s 2s 2s'
80
81 def __init__(self, file: T.BinaryIO, magic: int) -> None:
82 if magic == 0x01DF:
83 cfh_header_data = file.read(self.CFH_HDR_SIZE_32)
84 f_magic, f_nscns, f_timdat, f_symptr, f_nsyms, f_opthdr, f_flags = struct.unpack(
85 self.CFH_HDR_FORMAT_32, cfh_header_data
86 )
87 else:
88 cfh_header_data = file.read(self.CFH_HDR_SIZE)
89 f_magic, f_nscns, f_timdat, f_symptr, f_opthdr, f_flags, f_nsyms = struct.unpack(
90 self.CFH_HDR_FORMAT, cfh_header_data
91 )
92 self.f_flags = int.from_bytes(f_flags, byteorder='big')
93 self.f_opthdr = int.from_bytes(f_opthdr, byteorder='big')
94
95
96 class XcoffAuxiliaryHeader:
97 # XCOFF auxiliary header
98 AUX_HDR_SIZE = 120
99 AUX_HDR_SIZE_32 = 72
100 AUX_HDR_FORMAT = '2s 2s 4s 8s 8s 8s 2s 2s 2s 2s 2s 2s 2s 2s 2s 1s 1s 1s 1s 1s 1s 8s 8s 8s 8s 8s 8s 2s 2s 2s 10s'
101 AUX_HDR_FORMAT_32 = '2s 2s 4s 4s 4s 4s 4s 4s 4s 2s 2s 2s 2s 2s 2s 2s 2s 2s 1s 1s 4s 4s 4s 1s 1s 1s 1s 2s 2s'
102
103 def __init__(self, file: T.BinaryIO, magic: int, opthdr_size: int) -> None:
104 if magic == 0x01DF:
105 if opthdr_size < self.AUX_HDR_SIZE_32:
106 sys.exit(f'Error: Auxiliary header size {opthdr_size} is too small for 32-bit XCOFF')
107 aux_header_data = file.read(self.AUX_HDR_SIZE_32)
108 if len(aux_header_data) < self.AUX_HDR_SIZE_32:
109 sys.exit(f'Error: Could not read auxiliary header, got {len(aux_header_data)} bytes, expected {self.AUX_HDR_SIZE_32}')
110 (o_mflags, o_vstamp, o_tsize, o_dsize, o_bsize, o_entry, o_text_start, o_data_start, o_toc,
111 o_snentry, o_sntext, o_sndata, o_sntoc, o_snloader, o_snbss, o_algntext, o_algndata, o_modtype,
112 o_cpuflag, o_cputype, o_maxstack, o_maxdata, o_debugger, o_textpsize, o_datapsize, o_stackpsize,
113 o_flags, o_sntdata, o_sntbss) = struct.unpack(self.AUX_HDR_FORMAT_32, aux_header_data)
114 else:
115 if opthdr_size < self.AUX_HDR_SIZE:
116 sys.exit(f'Error: Auxiliary header size {opthdr_size} is too small for 64-bit XCOFF')
117 aux_header_data = file.read(self.AUX_HDR_SIZE)
118 if len(aux_header_data) < self.AUX_HDR_SIZE:
119 sys.exit(f'Error: Could not read auxiliary header, got {len(aux_header_data)} bytes, expected {self.AUX_HDR_SIZE}')
120 (o_mflags, o_vstamp, o_debugger, o_text_start, o_data_start, o_toc, o_snentry, o_sntext, o_sndata,
121 o_sntoc, o_snloader, o_snbss, o_algntext, o_algndata, o_modtype, o_cpuflag, o_cputype, o_textpsize,
122 o_datapsize, o_stackpsize, o_flags, o_tsize, o_dsize, o_bsize, o_entry, o_maxstack, o_maxdata,
123 o_sntdata, o_sntbss, o_x64flags, dummy) = struct.unpack(self.AUX_HDR_FORMAT, aux_header_data)
124
125 self.o_algntext = int.from_bytes(o_algntext, byteorder='big')
126 self.o_algndata = int.from_bytes(o_algndata, byteorder='big')
127 self.o_snloader = int.from_bytes(o_snloader, byteorder='big')
128
129
130 class XcoffSectionHeader:
131 # XCOFF section header
132 SCN_HDR_SIZE = 72
133 SCN_HDR_SIZE_32 = 40
134 SCN_HDR_FORMAT = '8s 8s 8s 8s 8s 8s 8s 4s 4s 4s 4s'
135 SCN_HDR_FORMAT_32 = '8s 4s 4s 4s 4s 4s 4s 2s 2s 2s 2s'
136
137 def __init__(self, file: T.BinaryIO, magic: int) -> None:
138 if magic == 0x01DF:
139 scn_header_data = file.read(self.SCN_HDR_SIZE_32)
140 if len(scn_header_data) < self.SCN_HDR_SIZE_32:
141 raise EOFError('End of archive member reached')
142 (s_name, s_paddr, s_vaddr, s_size, s_scnptr, s_relptr, s_lnnoptr, s_nreloc, s_nlnno, s_flags,
143 dummy) = struct.unpack(self.SCN_HDR_FORMAT_32, scn_header_data)
144 else:
145 scn_header_data = file.read(self.SCN_HDR_SIZE)
146 if len(scn_header_data) < self.SCN_HDR_SIZE:
147 raise EOFError('End of archive member reached')
148 (s_name, s_paddr, s_vaddr, s_size, s_scnptr, s_relptr, s_lnnoptr, s_nreloc, s_nlnno, s_flags,
149 dummy) = struct.unpack(self.SCN_HDR_FORMAT, scn_header_data)
150 self.s_scnptr = int.from_bytes(s_scnptr, byteorder='big')
151
152
153 class XcoffLoaderHeader:
154 # XCOFF loader header
155 LDR_HDR_SIZE = 56
156 LDR_HDR_SIZE_32 = 32
157 LDR_HDR_FORMAT = '4s 4s 4s 4s 4s 4s 8s 8s 8s 8s'
158 LDR_HDR_FORMAT_32 = '4s 4s 4s 4s 4s 4s 4s 4s'
159
160 def __init__(self, file: T.BinaryIO, magic: int) -> None:
161 if magic == 0x01DF:
162 ldr_header_data = file.read(self.LDR_HDR_SIZE_32)
163 (l_version, l_nsyms, l_nreloc, l_istlen, l_nimpid, l_impoff, l_stlen,
164 l_stoff) = struct.unpack(self.LDR_HDR_FORMAT_32, ldr_header_data)
165 else:
166 ldr_header_data = file.read(self.LDR_HDR_SIZE)
167 (l_version, l_nsyms, l_nreloc, l_istlen, l_nimpid, l_stlen, l_impoff, l_stoff, l_symoff,
168 l_rldoff) = struct.unpack(self.LDR_HDR_FORMAT, ldr_header_data)
169 self.l_impoff = int.from_bytes(l_impoff, byteorder='big')
170 self.l_istlen = int.from_bytes(l_istlen, byteorder='big')
171
172
173 def traverse_xcoff(file: T.BinaryIO, rpath_dirs_to_remove: T.Set[bytes], new_rpath: T.Optional[bytes], verbose: bool = True) -> None:
174 """Traverse XCOFF file or archive and modify Libpath entries.
175
176 Handles both standalone XCOFF shared objects (.so) and XCOFF archives (.a).
177 Archives are detected by magic number and processed member by member.
178 """
179 def dummy_print(*args: object) -> None:
180 pass
181 log_msg: T.Callable[..., None]
182 log_msg = print if verbose else dummy_print
183
184 # Detect if this is an archive by checking for magic number
185 magic_check = file.read(8)
186 file.seek(0)
187
188 # Read archive headers if this is an archive
189 ar_header: T.Optional[XcoffArchiveHeader] = None
190 if magic_check == b'<bigaf>\n':
191 fl_header = XcoffFixedLengthHeader(file)
192 file.seek(fl_header.fl_fstmoff)
193 ar_header = XcoffArchiveHeader(file)
194
195 composite_header_pos = file.tell()
196 # Read XCOFF magic number
197 magic_data = file.read(XCOFF_MAGIC_SIZE)
198 if len(magic_data) != XCOFF_MAGIC_SIZE:
199 sys.exit(0)
200 magic_number = struct.unpack('>H', magic_data)[0] # Big-endian 16-bit integer
201 if magic_number == 0x01DF:
202 log_msg(' Changing Libpath for a 32-bit Shared Object')
203 elif magic_number == 0x01F7:
204 log_msg(' Changing Libpath for a 64-bit Shared Object')
205 else:
206 log_msg(' Not a shared object')
207 sys.exit(0)
208 # Reposition to start of XCOFF headers
209 file.seek(composite_header_pos)
210 cfh_header = XcoffCompositeFileHeader(file, magic_number)
211 if not cfh_header.f_flags & 0x2000:
212 log_msg('Did not change rpath since not a shared library/archive')
213 return
214 # Read auxiliary header
215 aux_header = XcoffAuxiliaryHeader(file, magic_number, cfh_header.f_opthdr)
216
217 # Calculate the bytes_to_align
218 bytes_to_align = max(aux_header.o_algntext, aux_header.o_algndata)
219
220 # Seek to section header and read it
221 if magic_number == 0x01DF:
222 file.seek((aux_header.o_snloader - 1) * XcoffSectionHeader.SCN_HDR_SIZE_32, os.SEEK_CUR)
223 else:
224 file.seek((aux_header.o_snloader - 1) * XcoffSectionHeader.SCN_HDR_SIZE, os.SEEK_CUR)
225 try:
226 scn_header = XcoffSectionHeader(file, magic_number)
227 except EOFError:
228 return # End of archive member, nothing to fix
229
230 header_len = 0
231 if ar_header:
232 header_len = XcoffFixedLengthHeader.FL_HDR_SIZE + XcoffArchiveHeader.AR_HDR_SIZE + ar_header.ar_namlen
233 scnptrFromArchiveStart = scn_header.s_scnptr + align(header_len, bytes_to_align)
234 else:
235 scnptrFromArchiveStart = scn_header.s_scnptr
236
237 file.seek(scnptrFromArchiveStart)
238
239 # Read loader header
240 ldr_header = XcoffLoaderHeader(file, magic_number)
241
242 if ar_header:
243 scnptrFromArchiveStartPlusOff = scn_header.s_scnptr + ldr_header.l_impoff + align(header_len, bytes_to_align)
244 else:
245 scnptrFromArchiveStartPlusOff = scn_header.s_scnptr + ldr_header.l_impoff
246 file.seek(scnptrFromArchiveStartPlusOff)
247
248 # Read and update libpath
249 libpath = file.read(ldr_header.l_istlen)
250 build_libpath = libpath.split(b'\x00')[0]
251 # Build the new rpath by merging new_rpath with existing paths (excluding removed ones)
252 new_rpaths: OrderedSet[bytes] = OrderedSet()
253 if new_rpath:
254 new_rpaths.update(new_rpath.split(b':'))
255
256 new_rpaths.update(
257 path
258 for path in build_libpath.split(b':')
259 if path and path not in rpath_dirs_to_remove
260 )
261
262 install_rpath = b':'.join(new_rpaths)
263
264 # If the length of the build_rpath length is < install_rpath length then we do not have space to write
265 # the same hence exit. Otherwise, we can and the length has to be the same as build_rpath.
266 # If the install_rpath length is less than build_rpath length then pad the difference
267 if len(install_rpath) > len(build_libpath):
268 sys.exit('Error: install_rpath is bigger than build_rpath')
269 # Pad with colon bytes to match build_libpath length
270 install_rpath = install_rpath + (b':' * (len(build_libpath) - len(install_rpath)))
271 file.seek(scnptrFromArchiveStartPlusOff)
272 file.write(install_rpath)
273 log_msg(f'Successfully changed libpath from {build_libpath!r} to {install_rpath!r}')
274
275
276 def fix_aix(fname: str, rpath_dirs_to_remove: T.Set[bytes], new_rpath: T.Optional[bytes], verbose: bool = True) -> None:
277 """Writes Libpath to an xcoff shared object.
278
279 In AIX, shared modules are .so files and shared libraries are in .a archives.
280 Follows the same calling convention as fix_elf:
281 - Errors: sys.exit('error message')
282 - Wrong file type: sys.exit(0)
283 - Success: return normally
284 """
285 if new_rpath is None:
286 return
287
288 try:
289 with open(fname, 'r+b') as file:
290 traverse_xcoff(file, rpath_dirs_to_remove, new_rpath, verbose)
291 except FileNotFoundError:
292 sys.exit(f'Error: File not found: {fname}')
293 except Exception as e:
294 sys.exit(f'Unexpected error processing {fname}: {e}')
295
296
297 # ----------------ELF------------------
298
299 class DataSizes:
300 def __init__(self, ptrsize: int, is_le: bool) -> None:
301 if is_le:
302 p = '<'
303 else:
304 p = '>'
305 self.Char = p + 'c'
306 self.CharSize = 1
307 self.Half = p + 'h'
308 self.HalfSize = 2
309 self.Section = p + 'h'
310 self.SectionSize = 2
311 self.Word = p + 'I'
312 self.WordSize = 4
313 self.Sword = p + 'i'
314 self.SwordSize = 4
315 if ptrsize == 64:
316 self.Addr = p + 'Q'
317 self.AddrSize = 8
318 self.Off = p + 'Q'
319 self.OffSize = 8
320 self.XWord = p + 'Q'
321 self.XWordSize = 8
322 self.Sxword = p + 'q'
323 self.SxwordSize = 8
324 else:
325 self.Addr = p + 'I'
326 self.AddrSize = 4
327 self.Off = p + 'I'
328 self.OffSize = 4
329
330 class DynamicEntry(DataSizes):
331 def __init__(self, ifile: T.BinaryIO, ptrsize: int, is_le: bool) -> None:
332 super().__init__(ptrsize, is_le)
333 self.ptrsize = ptrsize
334 if ptrsize == 64:
335 self.d_tag = struct.unpack(self.Sxword, ifile.read(self.SxwordSize))[0]
336 self.val = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0]
337 else:
338 self.d_tag = struct.unpack(self.Sword, ifile.read(self.SwordSize))[0]
339 self.val = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
340
341 def write(self, ofile: T.BinaryIO) -> None:
342 if self.ptrsize == 64:
343 ofile.write(struct.pack(self.Sxword, self.d_tag))
344 ofile.write(struct.pack(self.XWord, self.val))
345 else:
346 ofile.write(struct.pack(self.Sword, self.d_tag))
347 ofile.write(struct.pack(self.Word, self.val))
348
349 class DynsymEntry(DataSizes):
350 def __init__(self, ifile: T.BinaryIO, ptrsize: int, is_le: bool) -> None:
351 super().__init__(ptrsize, is_le)
352 is_64 = ptrsize == 64
353 self.st_name = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
354 if is_64:
355 self.st_info = struct.unpack(self.Char, ifile.read(self.CharSize))[0]
356 self.st_other = struct.unpack(self.Char, ifile.read(self.CharSize))[0]
357 self.st_shndx = struct.unpack(self.Section, ifile.read(self.SectionSize))[0]
358 self.st_value = struct.unpack(self.Addr, ifile.read(self.AddrSize))[0]
359 self.st_size = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0]
360 else:
361 self.st_value = struct.unpack(self.Addr, ifile.read(self.AddrSize))[0]
362 self.st_size = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
363 self.st_info = struct.unpack(self.Char, ifile.read(self.CharSize))[0]
364 self.st_other = struct.unpack(self.Char, ifile.read(self.CharSize))[0]
365 self.st_shndx = struct.unpack(self.Section, ifile.read(self.SectionSize))[0]
366
367 class SectionHeader(DataSizes):
368 def __init__(self, ifile: T.BinaryIO, ptrsize: int, is_le: bool) -> None:
369 super().__init__(ptrsize, is_le)
370 is_64 = ptrsize == 64
371
372 # Elf64_Word
373 self.sh_name = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
374 # Elf64_Word
375 self.sh_type = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
376 # Elf64_Xword
377 if is_64:
378 self.sh_flags = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0]
379 else:
380 self.sh_flags = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
381 # Elf64_Addr
382 self.sh_addr = struct.unpack(self.Addr, ifile.read(self.AddrSize))[0]
383 # Elf64_Off
384 self.sh_offset = struct.unpack(self.Off, ifile.read(self.OffSize))[0]
385 # Elf64_Xword
386 if is_64:
387 self.sh_size = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0]
388 else:
389 self.sh_size = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
390 # Elf64_Word
391 self.sh_link = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
392 # Elf64_Word
393 self.sh_info = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
394 # Elf64_Xword
395 if is_64:
396 self.sh_addralign = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0]
397 else:
398 self.sh_addralign = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
399 # Elf64_Xword
400 if is_64:
401 self.sh_entsize = struct.unpack(self.XWord, ifile.read(self.XWordSize))[0]
402 else:
403 self.sh_entsize = struct.unpack(self.Word, ifile.read(self.WordSize))[0]
404
405 class Elf(DataSizes):
406 def __init__(self, bfile: str, verbose: bool = True) -> None:
407 self.bfile = bfile
408 self.verbose = verbose
409 self.sections: T.List[SectionHeader] = []
410 self.dynamic: T.List[DynamicEntry] = []
411 self.dynsym: T.List[DynsymEntry] = []
412 self.dynsym_strings: T.List[str] = []
413 self.open_bf(bfile)
414 try:
415 (self.ptrsize, self.is_le) = self.detect_elf_type()
416 super().__init__(self.ptrsize, self.is_le)
417 self.parse_header()
418 self.parse_sections()
419 self.parse_dynamic()
420 self.parse_dynsym()
421 self.parse_dynsym_strings()
422 except (struct.error, RuntimeError):
423 self.close_bf()
424 raise
425
426 def open_bf(self, bfile: str) -> None:
427 self.bf = None
428 self.bf_perms = None
429 try:
430 self.bf = open(bfile, 'r+b')
431 except PermissionError as e:
432 self.bf_perms = stat.S_IMODE(os.lstat(bfile).st_mode)
433 os.chmod(bfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
434 try:
435 self.bf = open(bfile, 'r+b')
436 except Exception:
437 os.chmod(bfile, self.bf_perms)
438 self.bf_perms = None
439 raise e
440
441 def close_bf(self) -> None:
442 if self.bf is not None:
443 if self.bf_perms is not None:
444 os.chmod(self.bf.fileno(), self.bf_perms)
445 self.bf_perms = None
446 self.bf.close()
447 self.bf = None
448
449 def __enter__(self) -> 'Elf':
450 return self
451
452 def __del__(self) -> None:
453 self.close_bf()
454
455 def __exit__(self, exc_type: T.Any, exc_value: T.Any, traceback: T.Any) -> None:
456 self.close_bf()
457
458 def detect_elf_type(self) -> T.Tuple[int, bool]:
459 data = self.bf.read(6)
460 if data[1:4] != b'ELF':
461 # This script gets called to non-elf targets too
462 # so just ignore them.
463 if self.verbose:
464 print(f'File {self.bfile!r} is not an ELF file.')
465 sys.exit(0)
466 if data[4] == 1:
467 ptrsize = 32
468 elif data[4] == 2:
469 ptrsize = 64
470 else:
471 sys.exit(f'File {self.bfile!r} has unknown ELF class.')
472 if data[5] == 1:
473 is_le = True
474 elif data[5] == 2:
475 is_le = False
476 else:
477 sys.exit(f'File {self.bfile!r} has unknown ELF endianness.')
478 return ptrsize, is_le
479
480 def parse_header(self) -> None:
481 self.bf.seek(0)
482 self.e_ident = struct.unpack('16s', self.bf.read(16))[0]
483 self.e_type = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
484 self.e_machine = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
485 self.e_version = struct.unpack(self.Word, self.bf.read(self.WordSize))[0]
486 self.e_entry = struct.unpack(self.Addr, self.bf.read(self.AddrSize))[0]
487 self.e_phoff = struct.unpack(self.Off, self.bf.read(self.OffSize))[0]
488 self.e_shoff = struct.unpack(self.Off, self.bf.read(self.OffSize))[0]
489 self.e_flags = struct.unpack(self.Word, self.bf.read(self.WordSize))[0]
490 self.e_ehsize = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
491 self.e_phentsize = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
492 self.e_phnum = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
493 self.e_shentsize = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
494 self.e_shnum = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
495 self.e_shstrndx = struct.unpack(self.Half, self.bf.read(self.HalfSize))[0]
496
497 def parse_sections(self) -> None:
498 self.bf.seek(self.e_shoff)
499 for _ in range(self.e_shnum):
500 self.sections.append(SectionHeader(self.bf, self.ptrsize, self.is_le))
501
502 def read_str(self) -> bytes:
503 arr = []
504 x = self.bf.read(1)
505 while x != b'\0':
506 arr.append(x)
507 x = self.bf.read(1)
508 if x == b'':
509 raise RuntimeError('Tried to read past the end of the file')
510 return b''.join(arr)
511
512 def find_section(self, target_name: bytes) -> T.Optional[SectionHeader]:
513 section_names = self.sections[self.e_shstrndx]
514 for i in self.sections:
515 self.bf.seek(section_names.sh_offset + i.sh_name)
516 name = self.read_str()
517 if name == target_name:
518 return i
519 return None
520
521 def parse_dynamic(self) -> None:
522 sec = self.find_section(b'.dynamic')
523 if sec is None:
524 return
525 self.bf.seek(sec.sh_offset)
526 while True:
527 e = DynamicEntry(self.bf, self.ptrsize, self.is_le)
528 self.dynamic.append(e)
529 if e.d_tag == 0:
530 break
531
532 def parse_dynsym(self) -> None:
533 sec = self.find_section(b'.dynsym')
534 if sec is None:
535 return
536 self.bf.seek(sec.sh_offset)
537 for i in range(sec.sh_size // sec.sh_entsize):
538 e = DynsymEntry(self.bf, self.ptrsize, self.is_le)
539 self.dynsym.append(e)
540
541 def parse_dynsym_strings(self) -> None:
542 sec = self.find_section(b'.dynstr')
543 if sec is None:
544 return
545 for i in self.dynsym:
546 self.bf.seek(sec.sh_offset + i.st_name)
547 self.dynsym_strings.append(self.read_str().decode())
548
549 @generate_list
550 def get_section_names(self) -> T.Generator[str, None, None]:
551 section_names = self.sections[self.e_shstrndx]
552 for i in self.sections:
553 self.bf.seek(section_names.sh_offset + i.sh_name)
554 yield self.read_str().decode()
555
556 def get_soname(self) -> T.Optional[str]:
557 soname = None
558 strtab = None
559 for i in self.dynamic:
560 if i.d_tag == DT_SONAME:
561 soname = i
562 if i.d_tag == DT_STRTAB:
563 strtab = i
564 if soname is None or strtab is None:
565 return None
566 self.bf.seek(strtab.val + soname.val)
567 return self.read_str().decode()
568
569 def get_entry_offset(self, entrynum: int) -> T.Optional[int]:
570 sec = self.find_section(b'.dynstr')
571 for i in self.dynamic:
572 if i.d_tag == entrynum:
573 res = sec.sh_offset + i.val
574 assert isinstance(res, int)
575 return res
576 return None
577
578 def get_rpath(self) -> T.Optional[str]:
579 offset = self.get_entry_offset(DT_RPATH)
580 if offset is None:
581 return None
582 self.bf.seek(offset)
583 return self.read_str().decode()
584
585 def get_runpath(self) -> T.Optional[str]:
586 offset = self.get_entry_offset(DT_RUNPATH)
587 if offset is None:
588 return None
589 self.bf.seek(offset)
590 return self.read_str().decode()
591
592 @generate_list
593 def get_deps(self) -> T.Generator[str, None, None]:
594 sec = self.find_section(b'.dynstr')
595 for i in self.dynamic:
596 if i.d_tag == DT_NEEDED:
597 offset = sec.sh_offset + i.val
598 self.bf.seek(offset)
599 yield self.read_str().decode()
600
601 def fix_deps(self, prefix: bytes) -> None:
602 sec = self.find_section(b'.dynstr')
603 deps = []
604 for i in self.dynamic:
605 if i.d_tag == DT_NEEDED:
606 deps.append(i)
607 for i in deps:
608 offset = sec.sh_offset + i.val
609 self.bf.seek(offset)
610 name = self.read_str()
611 if name.startswith(prefix):
612 basename = name.rsplit(b'/', maxsplit=1)[-1]
613 padding = b'\0' * (len(name) - len(basename))
614 newname = basename + padding
615 assert len(newname) == len(name)
616 self.bf.seek(offset)
617 self.bf.write(newname)
618
619 def fix_rpath(self, fname: str, rpath_dirs_to_remove: T.Set[bytes], new_rpath: bytes) -> None:
620 # The path to search for can be either rpath or runpath.
621 # Fix both of them to be sure.
622 self.fix_rpathtype_entry(fname, rpath_dirs_to_remove, new_rpath, DT_RPATH)
623 self.fix_rpathtype_entry(fname, rpath_dirs_to_remove, new_rpath, DT_RUNPATH)
624
625 def fix_rpathtype_entry(self, fname: str, rpath_dirs_to_remove: T.Set[bytes], new_rpath: bytes, entrynum: int) -> None:
626 rp_off = self.get_entry_offset(entrynum)
627 if rp_off is None:
628 if self.verbose:
629 print(f'File {fname!r} does not have an rpath. It should be a fully static executable.')
630 return
631 self.bf.seek(rp_off)
632
633 old_rpath = self.read_str()
634 # Some rpath entries may come from multiple sources.
635 # Only add each one once.
636 new_rpaths: OrderedSet[bytes] = OrderedSet()
637 if new_rpath:
638 new_rpaths.update(new_rpath.split(b':'))
639 if old_rpath:
640 # Filter out build-only rpath entries
641 # added by get_link_dep_subdirs() or
642 # specified by user with build_rpath.
643 for rpath_dir in old_rpath.split(b':'):
644 if not (rpath_dir in rpath_dirs_to_remove or
645 rpath_dir == (b'X' * len(rpath_dir))):
646 if rpath_dir:
647 new_rpaths.add(rpath_dir)
648
649 # Prepend user-specified new entries while preserving the ones that came from pkgconfig etc.
650 new_rpath = b':'.join(new_rpaths)
651
652 if len(old_rpath) < len(new_rpath):
653 msg = 'New rpath must not be longer than the old one.\n Old: {}\n New: {}'.format(old_rpath.decode('utf-8'), new_rpath.decode('utf-8'))
654 sys.exit(msg)
655 # The linker does read-only string deduplication. If there is a
656 # string that shares a suffix with the rpath, they might get
657 # deduped. This means changing the rpath string might break something
658 # completely unrelated. This has already happened once with X.org.
659 # Thus we want to keep this change as small as possible to minimize
660 # the chance of obliterating other strings. It might still happen
661 # but our behavior is identical to what chrpath does and it has
662 # been in use for ages so based on that this should be rare.
663 if not new_rpath:
664 self.remove_rpath_entry(entrynum)
665 else:
666 self.bf.seek(rp_off)
667 self.bf.write(new_rpath)
668 self.bf.write(b'\0')
669
670 def clean_rpath_entry_string(self, entrynum: int) -> None:
671 # Get the rpath string
672 offset = self.get_entry_offset(entrynum)
673 self.bf.seek(offset)
674 rpath_string = self.read_str().decode()
675 reused_str = ''
676
677 # Inspect the dyn strings and check if our rpath string
678 # ends with one of them.
679 # This is to handle a subtle optimization of the linker
680 # where one of the dyn function name offset in the dynstr
681 # table might be set at the an offset of the rpath string.
682 # Example:
683 #
684 # rpath offset = 1314 string = /usr/lib/foo
685 # dym function offset = 1322 string = foo
686 #
687 # In the following case, the dym function string offset is
688 # placed at the offset +10 of the rpath.
689 # To correctly clear the rpath entry AND keep normal
690 # functionality of this optimization (and the binary),
691 # parse the maximum string we can remove from the rpath entry.
692 #
693 # Since strings MUST be null terminated, we can always check
694 # if the rpath string ends with the dyn function string and
695 # calculate what we can actually remove accordingly.
696 for dynsym_string in self.dynsym_strings:
697 if rpath_string.endswith(dynsym_string):
698 if len(dynsym_string) > len(reused_str):
699 reused_str = dynsym_string
700
701 # Seek back to start of string
702 self.bf.seek(offset)
703 self.bf.write(b'X' * (len(rpath_string) - len(reused_str)))
704
705 def remove_rpath_entry(self, entrynum: int) -> None:
706 sec = self.find_section(b'.dynamic')
707 if sec is None:
708 return None
709 for (i, entry) in enumerate(self.dynamic):
710 if entry.d_tag == entrynum:
711 self.clean_rpath_entry_string(entrynum)
712 rpentry = self.dynamic[i]
713 rpentry.d_tag = 0
714 self.dynamic = self.dynamic[:i] + self.dynamic[i + 1:] + [rpentry]
715 break
716 # DT_MIPS_RLD_MAP_REL is relative to the offset of the tag. Adjust it consequently.
717 for entry in self.dynamic[i:]:
718 if entry.d_tag == DT_MIPS_RLD_MAP_REL:
719 entry.val += 2 * (self.ptrsize // 8)
720 break
721 self.bf.seek(sec.sh_offset)
722 for entry in self.dynamic:
723 entry.write(self.bf)
724 return None
725
726 def fix_elf(fname: str, rpath_dirs_to_remove: T.Set[bytes], new_rpath: T.Optional[bytes], verbose: bool = True) -> None:
727 if new_rpath is not None:
728 with Elf(fname, verbose) as e:
729 # note: e.get_rpath() and e.get_runpath() may be useful
730 e.fix_rpath(fname, rpath_dirs_to_remove, new_rpath)
731
732 def get_darwin_rpaths(fname: str) -> OrderedSet[str]:
733 p, out, _ = Popen_safe(['otool', '-l', fname], stderr=subprocess.DEVNULL)
734 if p.returncode != 0:
735 raise subprocess.CalledProcessError(p.returncode, p.args, out)
736 # Need to deduplicate rpaths, as macOS's install_name_tool
737 # is *very* allergic to duplicate -delete_rpath arguments
738 # when calling depfixer on installation.
739 result: OrderedSet[str] = OrderedSet()
740 current_cmd = 'FOOBAR'
741 for line in out.split('\n'):
742 line = line.strip()
743 if ' ' not in line:
744 continue
745 key, value = line.strip().split(' ', 1)
746 if key == 'cmd':
747 current_cmd = value
748 if key == 'path' and current_cmd == 'LC_RPATH':
749 rp = value.split('(', 1)[0].strip()
750 result.add(rp)
751 return result
752
753 def fix_darwin(fname: str, rpath_dirs_to_remove: T.Set[bytes], new_rpath: str, final_path: str, install_name_mappings: T.Dict[str, str]) -> None:
754 try:
755 old_rpaths = get_darwin_rpaths(fname)
756 except subprocess.CalledProcessError:
757 # Otool failed, which happens when invoked on a
758 # non-executable target. Just return.
759 return
760 new_rpaths: OrderedSet[str] = OrderedSet()
761 if new_rpath:
762 new_rpaths.update(new_rpath.split(':'))
763 # filter out build-only rpath entries, like in
764 # fix_rpathtype_entry
765 remove_rpaths = [x.decode('utf8') for x in rpath_dirs_to_remove]
766 for rpath_dir in old_rpaths:
767 if rpath_dir and rpath_dir not in remove_rpaths:
768 new_rpaths.add(rpath_dir)
769 try:
770 args = []
771 # compute diff, translate it into -delete_rpath and -add_rpath
772 # calls
773 for path in new_rpaths:
774 if path not in old_rpaths:
775 args += ['-add_rpath', path]
776 for path in old_rpaths:
777 if path not in new_rpaths:
778 args += ['-delete_rpath', path]
779 # Rewrite -install_name @rpath/libfoo.dylib to /path/to/libfoo.dylib
780 if fname.endswith('dylib'):
781 args += ['-id', final_path]
782 if install_name_mappings:
783 for old, new in install_name_mappings.items():
784 args += ['-change', old, new]
785 if args:
786 subprocess.check_call(['install_name_tool', fname] + args,
787 stdout=subprocess.DEVNULL,
788 stderr=subprocess.DEVNULL)
789 except Exception as err:
790 raise SystemExit(err)
791
792 def fix_jar(fname: str) -> None:
793 subprocess.check_call(['jar', 'xf', fname, 'META-INF/MANIFEST.MF'])
794 with open('META-INF/MANIFEST.MF', 'r+', encoding='utf-8') as f:
795 lines = f.readlines()
796 f.seek(0)
797 for line in lines:
798 if not line.startswith('Class-Path:'):
799 f.write(line)
800 f.truncate()
801 # jar -um doesn't allow removing existing attributes. Use -uM instead,
802 # which a) removes the existing manifest from the jar and b) disables
803 # special-casing for the manifest file, so we can re-add it as a normal
804 # archive member. This puts the manifest at the end of the jar rather
805 # than the beginning, but the spec doesn't forbid that.
806 subprocess.check_call(['jar', 'ufM', fname, 'META-INF/MANIFEST.MF'])
807
808 def fix_rpath(fname: str, rpath_dirs_to_remove: T.Set[bytes], new_rpath: T.Union[str, bytes], final_path: str, install_name_mappings: T.Dict[str, str], system: str, verbose: bool = True) -> None:
809 global INSTALL_NAME_TOOL # pylint: disable=global-statement
810 # Static libraries, import libraries, debug information, headers, etc
811 # never have rpaths
812 # DLLs and EXE currently do not need runtime path fixing
813
814 if fname.endswith(('.lib', '.pdb', '.h', '.hpp', '.dll', '.exe')):
815 return
816 # Shared libraries are .a files on AIX
817 if fname.endswith('.a') and system != 'aix':
818 return
819 if isinstance(new_rpath, str):
820 new_rpath = new_rpath.encode('utf8')
821 try:
822 if fname.endswith('.jar'):
823 fix_jar(fname)
824 return
825 if system == 'aix':
826 fix_aix(fname, rpath_dirs_to_remove, new_rpath, verbose)
827 else:
828 fix_elf(fname, rpath_dirs_to_remove, new_rpath, verbose)
829 return
830 except SystemExit as e:
831 if isinstance(e.code, int) and e.code == 0:
832 pass
833 else:
834 raise
835 # We don't look for this on import because it will do a useless PATH lookup
836 # on non-mac platforms. That can be expensive on some Windows machines
837 # (up to 30ms), which is significant with --only-changed. For details, see:
838 # https://github.com/mesonbuild/meson/pull/6612#discussion_r378581401
839 if INSTALL_NAME_TOOL is False:
840 INSTALL_NAME_TOOL = bool(shutil.which('install_name_tool'))
841 if INSTALL_NAME_TOOL:
842 if isinstance(new_rpath, bytes):
843 new_rpath = new_rpath.decode('utf8')
844 fix_darwin(fname, rpath_dirs_to_remove, new_rpath, final_path, install_name_mappings)