Debian Codegraph @

src/auditwheel/lddtree.py

raw
1 # Copyright 2016 Robert McGibbon
2 # Copyright 2012-2014 Gentoo Foundation
3 # Copyright 2012-2014 Mike Frysinger <[email protected]>
4 # Copyright 2012-2014 The Chromium OS Authors
5 # Use of this source code is governed by a BSD-style license (BSD-3)
6 # Original version available from:
7 # https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-projects/pax-utils/lddtree.py
8 """Read the ELF dependency tree
9
10 This does not work like `ldd` in that we do not execute/load code (only read
11 files on disk).
12 """
13
14 from __future__ import annotations
15
16 import errno
17 import functools
18 import glob
19 import logging
20 import os
21 import re
22 from dataclasses import dataclass
23 from fnmatch import fnmatch
24 from pathlib import Path
25
26 from elftools.elf.constants import E_FLAGS
27 from elftools.elf.elffile import ELFFile
28 from elftools.elf.sections import NoteSection
29
30 from auditwheel.architecture import Architecture
31 from auditwheel.error import InvalidLibcError
32 from auditwheel.libc import Libc
33
34 log = logging.getLogger(__name__)
35 __all__ = ["LIBPYTHON_RE", "DynamicExecutable", "DynamicLibrary", "ldd"]
36
37 # Regex to match libpython shared library names
38 LIBPYTHON_RE = re.compile(r"^libpython\d+\.\d+m?.so(\.\d)*$")
39
40 # Regex to match ORIGIN references in rpaths.
41 ORIGIN_RE = re.compile(r"\$(ORIGIN|\{ORIGIN\})")
42
43
44 @dataclass(frozen=True)
45 class Platform:
46 _elf_osabi: str
47 _elf_class: int
48 _elf_little_endian: bool
49 _elf_machine: str
50 _base_arch: Architecture | None
51 _ext_arch: Architecture | None
52 _error_msg: str | None
53
54 def is_compatible(self, other: Platform) -> bool:
55 os_abis = frozenset((self._elf_osabi, other._elf_osabi))
56 compat_sets = (frozenset(f"ELFOSABI_{x}" for x in ("NONE", "SYSV", "GNU", "LINUX")),)
57 return (
58 (len(os_abis) == 1 or any(os_abis.issubset(x) for x in compat_sets))
59 and self._elf_class == other._elf_class
60 and self._elf_little_endian == other._elf_little_endian
61 and self._elf_machine == other._elf_machine
62 )
63
64 @property
65 def baseline_architecture(self) -> Architecture:
66 if self._base_arch is not None:
67 return self._base_arch
68 raise ValueError(self._error_msg)
69
70 @property
71 def extended_architecture(self) -> Architecture | None:
72 if self._error_msg is not None:
73 raise ValueError(self._error_msg)
74 return self._ext_arch
75
76
77 @dataclass(frozen=True)
78 class DynamicLibrary:
79 soname: str
80 path: str | None
81 realpath: Path | None
82 platform: Platform | None = None
83 needed: tuple[str, ...] = ()
84
85
86 @dataclass(frozen=True)
87 class DynamicExecutable:
88 interpreter: str | None
89 libc: Libc | None
90 path: str
91 realpath: Path
92 platform: Platform
93 needed: tuple[str, ...]
94 rpath: tuple[str, ...]
95 runpath: tuple[str, ...]
96 libraries: dict[str, DynamicLibrary]
97
98
99 def _get_platform(elf: ELFFile) -> Platform:
100 elf_osabi = elf.header["e_ident"]["EI_OSABI"]
101 elf_class = elf.elfclass
102 elf_little_endian = elf.little_endian
103 elf_machine = elf["e_machine"]
104 base_arch = {
105 ("EM_386", 32, True): Architecture.i686,
106 ("EM_X86_64", 64, True): Architecture.x86_64,
107 ("EM_PPC64", 64, True): Architecture.ppc64le,
108 ("EM_PPC64", 64, False): Architecture.ppc64,
109 ("EM_RISCV", 64, True): Architecture.riscv64,
110 ("EM_AARCH64", 64, True): Architecture.aarch64,
111 ("EM_S390", 64, False): Architecture.s390x,
112 ("EM_ARM", 32, True): Architecture.armv7l,
113 ("EM_LOONGARCH", 64, True): Architecture.loongarch64,
114 }.get((elf_machine, elf_class, elf_little_endian))
115 ext_arch: Architecture | None = None
116 error_msg: str | None = None
117 flags = elf["e_flags"]
118 assert base_arch is None or base_arch.baseline == base_arch # noqa: S101
119 if base_arch is None:
120 error_msg = "Unknown architecture"
121 elif base_arch == Architecture.x86_64:
122 for section in elf.iter_sections():
123 if not isinstance(section, NoteSection):
124 continue
125 for note in section.iter_notes():
126 if note["n_type"] != "NT_GNU_PROPERTY_TYPE_0":
127 continue
128 if note["n_name"] != "GNU":
129 continue
130 for prop in note["n_desc"]:
131 if prop.pr_type != "GNU_PROPERTY_X86_ISA_1_NEEDED":
132 continue
133 if prop.pr_datasz != 4:
134 continue
135 data = prop.pr_data
136 data -= data & 1 # clear baseline
137 if data & 8 == 8:
138 ext_arch = Architecture.x86_64_v4
139 break
140 if data & 4 == 4:
141 ext_arch = Architecture.x86_64_v3
142 break
143 if data & 2 == 2:
144 ext_arch = Architecture.x86_64_v2
145 break
146 if data != 0:
147 error_msg = "unknown x86_64 ISA"
148 break
149 elif base_arch == Architecture.armv7l:
150 if (flags & E_FLAGS.EF_ARM_EABIMASK) != E_FLAGS.EF_ARM_EABI_VER5:
151 error_msg = "Invalid ARM EABI version for armv7l"
152 elif (flags & E_FLAGS.EF_ARM_ABI_FLOAT_HARD) != E_FLAGS.EF_ARM_ABI_FLOAT_HARD:
153 error_msg = "armv7l shall use hard-float"
154 if error_msg is not None:
155 base_arch = None
156
157 return Platform(
158 elf_osabi,
159 elf_class,
160 elf_little_endian,
161 elf_machine,
162 base_arch,
163 ext_arch,
164 error_msg,
165 )
166
167
168 def normpath(path: str) -> str:
169 """Normalize a path
170
171 Python's os.path.normpath() doesn't handle some cases:
172 // -> //
173 //..// -> //
174 //..//..// -> ///
175 """
176 return os.path.normpath(path).replace("//", "/")
177
178
179 def readlink(path: str, root: str, *, prefixed: bool = False) -> str:
180 """Like os.readlink(), but relative to a ``root``
181
182 This does not currently handle the pathological case:
183 /lib/foo.so -> ../../../../../../../foo.so
184 This relies on the .. entries in / to point to itself.
185
186 Parameters
187 ----------
188 path
189 The symlink to read
190 root
191 The path to use for resolving absolute symlinks
192 prefixed
193 When False, the ``path`` must not have ``root`` prefixed to it, nor
194 will the return value have ``root`` prefixed. When True, ``path``
195 must have ``root`` prefixed, and the return value will have ``root``
196 added.
197
198 Returns
199 -------
200 A fully resolved symlink path
201
202 """
203 root = root.rstrip("/")
204 if prefixed:
205 path = path[len(root) :]
206
207 while os.path.islink(root + path):
208 path = os.path.join(os.path.dirname(path), os.readlink(root + path))
209
210 return normpath((root + path) if prefixed else path)
211
212
213 def dedupe(items: list[str]) -> list[str]:
214 """Remove all duplicates from ``items`` (keeping order)"""
215 seen: dict[str, str] = {}
216 return [seen.setdefault(x, x) for x in items if x not in seen]
217
218
219 def parse_ld_paths(str_ldpaths: str, path: str = "", root: str = "") -> list[str]:
220 """Parse the colon-delimited list of paths and apply ldso rules to each
221
222 Note the special handling as dictated by the ldso:
223 - Empty paths are equivalent to $PWD
224 - $ORIGIN is expanded to the directory containing the given file
225 - (TODO) $LIB and friends
226
227 Parameters
228 ----------
229 str_ldpaths
230 A colon-delimited string of paths
231 root
232 The path to prepend to all paths found
233 path
234 The object actively being parsed (used for $ORIGIN)
235
236 Returns
237 -------
238 list of processed paths
239
240 """
241 if not str_ldpaths:
242 return []
243
244 ldpaths: list[str] = []
245 for ldpath in str_ldpaths.split(":"):
246 if ldpath == "":
247 # The ldso treats "" paths as $PWD.
248 ldpath_ = os.getcwd()
249 elif re.search(ORIGIN_RE, ldpath):
250 if not path:
251 msg = "can't expand $ORIGIN without a path"
252 raise ValueError(msg)
253 ldpath_ = re.sub(ORIGIN_RE, os.path.dirname(os.path.abspath(path)), ldpath)
254 else:
255 ldpath_ = root + ldpath
256 ldpaths.append(normpath(ldpath_))
257 return [p for p in dedupe(ldpaths) if os.path.isdir(p)]
258
259
260 @functools.lru_cache
261 def parse_ld_so_conf(ldso_conf: str, *, root: str = "/", _first: bool = True) -> list[str]:
262 """Load all the paths from a given ldso config file
263
264 This should handle comments, whitespace, and "include" statements.
265
266 Parameters
267 ----------
268 ldso_conf
269 The file to scan
270 root
271 The path to prepend to all paths found
272 _first
273 Recursive use only; is this the first ELF?
274
275 Returns
276 -------
277 list of paths found
278
279 """
280 paths: list[str] = []
281
282 dbg_pfx = "" if _first else " "
283 try:
284 log.debug("%sparse_ld_so_conf(%s)", dbg_pfx, ldso_conf)
285 with open(ldso_conf) as f:
286 for input_line in f:
287 line = input_line.split("#", 1)[0].strip()
288 if not line:
289 continue
290 if line.startswith("include "):
291 line = line[8:]
292 if line[0] == "/":
293 line = root + line.lstrip("/")
294 else:
295 line = os.path.dirname(ldso_conf) + "/" + line
296 log.debug("%s glob: %s", dbg_pfx, line)
297 for path in glob.glob(line):
298 paths += parse_ld_so_conf(path, root=root, _first=False)
299 else:
300 paths += [normpath(root + line)]
301 except OSError as e:
302 if e.errno != errno.ENOENT:
303 log.warning(e)
304
305 if _first:
306 # TODO: Load paths from ldso itself.
307 # Remove duplicate entries to speed things up.
308 paths = [p for p in dedupe(paths) if os.path.isdir(p)]
309
310 return paths
311
312
313 @functools.lru_cache
314 def load_ld_paths(
315 libc: Libc | None,
316 root: str = "/",
317 prefix: str = "",
318 ) -> dict[str, list[str]]:
319 """Load linker paths from common locations
320
321 This parses the ld.so.conf and LD_LIBRARY_PATH env var.
322
323 Parameters
324 ----------
325 root
326 The root tree to prepend to paths
327 prefix
328 The path under ``root`` to search
329
330 Returns
331 -------
332 dict containing library paths to search
333
334 """
335 ldpaths: dict[str, list[str]] = {"conf": [], "env": [], "interp": []}
336
337 # Load up $LD_LIBRARY_PATH.
338 env_ldpath = os.environ.get("LD_LIBRARY_PATH")
339 if env_ldpath is not None:
340 if root != "/":
341 log.warning("ignoring LD_LIBRARY_PATH due to ROOT usage")
342 else:
343 # TODO: If this contains $ORIGIN, we probably have to parse this
344 # on a per-ELF basis so it can get turned into the right thing.
345 ldpaths["env"] = parse_ld_paths(env_ldpath, path="")
346
347 if libc == Libc.MUSL:
348 # from https://git.musl-libc.org/cgit/musl/tree/ldso
349 # /dynlink.c?id=3f701faace7addc75d16dea8a6cd769fa5b3f260#n1063
350 root_prefix = Path(root) / prefix
351 ld_musl = list((root_prefix / "etc").glob("ld-musl-*.path"))
352 assert len(ld_musl) <= 1 # noqa: S101
353 if len(ld_musl) == 0:
354 ldpaths["conf"] = [
355 root + "/lib",
356 root + "/usr/local/lib",
357 root + "/usr/lib",
358 ]
359 else:
360 ldpaths["conf"] = []
361 for ldpath in ld_musl[0].read_text().split(":"):
362 ldpath_stripped = ldpath.strip()
363 if ldpath_stripped == "":
364 continue
365 ldpaths["conf"].append(root + ldpath_stripped)
366 else:
367 # Load up /etc/ld.so.conf.
368 ldpaths["conf"] = parse_ld_so_conf(root + prefix + "/etc/ld.so.conf", root=root)
369 # the trusted directories are not necessarily in ld.so.conf
370 ldpaths["conf"].extend(["/lib", "/lib64/", "/usr/lib", "/usr/lib64"])
371 log.debug("linker ldpaths: %s", ldpaths)
372 return ldpaths
373
374
375 def ld_paths_from_arg(args_ldpaths: str | None) -> dict[str, list[str]] | None:
376 """Load linker paths from the --ldpaths option and the environment."""
377 if args_ldpaths is None:
378 # The option was not provided, so fall back on load_ld_paths.
379 return None
380
381 return {
382 "conf": parse_ld_paths(args_ldpaths),
383 "env": parse_ld_paths(os.environ.get("AUDITWHEEL_LD_LIBRARY_PATH", "")),
384 "interp": [],
385 }
386
387
388 def find_lib(
389 platform: Platform,
390 lib: str,
391 ldpaths: list[str],
392 root: str = "/",
393 ) -> tuple[Path | None, str | None]:
394 """Try to locate a ``lib`` that is compatible to ``elf`` in the given
395 ``ldpaths``
396
397 Parameters
398 ----------
399 platform : Platform
400 The platform which the library should be compatible with (ELF wise)
401 lib : str
402 The library (basename) to search for
403 ldpaths : list[str]
404 A list of paths to search
405 root : str
406 The root path to resolve symlinks
407
408 Returns
409 -------
410 Tuple of the full path to the desired library and the real path to it
411
412 """
413 for ldpath in ldpaths:
414 path = os.path.join(ldpath, lib)
415 target = Path(readlink(path, root, prefixed=True))
416
417 if target.exists():
418 with open(target, "rb") as f:
419 libelf = ELFFile(f)
420 if platform.is_compatible(_get_platform(libelf)):
421 return target, path
422
423 return None, None
424
425
426 def ldd(
427 path: Path,
428 root: str = "/",
429 prefix: str = "",
430 ldpaths: dict[str, list[str]] | None = None,
431 display: str | None = None,
432 exclude: frozenset[str] = frozenset(),
433 _all_libs: dict[str, DynamicLibrary] | None = None,
434 ) -> DynamicExecutable:
435 """Parse the ELF dependency tree of the specified file
436
437 Parameters
438 ----------
439 path
440 The ELF to scan
441 root
442 The root tree to prepend to paths; this applies to interp and rpaths
443 only as ``path`` and ``ldpaths`` are expected to be prefixed already
444 prefix
445 The path under ``root`` to search
446 ldpaths
447 dict containing library paths to search; should have the keys:
448 conf, env, interp. If not supplied, the function ``load_ld_paths``
449 will be called.
450 display
451 The path to show rather than ``path``
452 exclude
453 List of soname (DT_NEEDED) to exclude from the tree
454 _all_libs
455 Recursive use only; dict of all libs we've seen
456
457 Returns
458 -------
459 a dict containing information about all the ELFs; e.g.
460 {
461 'interp': '/lib64/ld-linux.so.2',
462 'needed': ['libc.so.6', 'libcurl.so.4',],
463 'libs': {
464 'libc.so.6': {
465 'path': '/lib64/libc.so.6',
466 'needed': [],
467 },
468 'libcurl.so.4': {
469 'path': '/usr/lib64/libcurl.so.4',
470 'needed': ['libc.so.6', 'librt.so.1',],
471 },
472 },
473 }
474
475 """
476 _first = _all_libs is None
477 if _all_libs is None:
478 _all_libs = {}
479
480 log.debug("ldd(%s)", path)
481
482 interpreter: str | None = None
483 libc: Libc | None = None
484 needed: list[str] = []
485 rpaths: list[str] = []
486 runpaths: list[str] = []
487
488 with open(path, "rb") as f:
489 elf = ELFFile(f)
490
491 # get the platform
492 platform = _get_platform(elf)
493
494 # If this is the first ELF, extract the interpreter.
495 if _first:
496 for segment in elf.iter_segments():
497 if segment.header.p_type != "PT_INTERP":
498 continue
499 interp = segment.get_interp_name()
500 log.debug(" interp = %s", interp)
501 interpreter = normpath(root + interp)
502 soname = os.path.basename(interpreter)
503 _all_libs[soname] = DynamicLibrary(
504 soname,
505 interpreter,
506 Path(readlink(interpreter, root, prefixed=True)),
507 platform,
508 )
509 # if we have an interpreter and it's not MUSL, assume GLIBC
510 libc = Libc.MUSL if soname.startswith("ld-musl-") else Libc.GLIBC
511 if ldpaths is None:
512 ldpaths = load_ld_paths(libc).copy()
513 # TODO: Should read it and scan for /lib paths.
514 ldpaths["interp"] = [
515 normpath(root + os.path.dirname(interp)),
516 normpath(
517 root + prefix + "/usr" + os.path.dirname(interp).lstrip(prefix),
518 ),
519 ]
520 log.debug(" ldpaths[interp] = %s", ldpaths["interp"])
521 break
522
523 # Parse the ELF's dynamic tags.
524 for segment in elf.iter_segments():
525 if segment.header.p_type != "PT_DYNAMIC":
526 continue
527 for t in segment.iter_tags():
528 if t.entry.d_tag == "DT_RPATH":
529 rpaths = parse_ld_paths(t.rpath, path=str(path), root=root)
530 elif t.entry.d_tag == "DT_RUNPATH":
531 runpaths = parse_ld_paths(t.runpath, path=str(path), root=root)
532 elif t.entry.d_tag == "DT_NEEDED":
533 needed.append(t.needed)
534 if runpaths:
535 # If both RPATH and RUNPATH are set, only the latter is used.
536 rpaths = []
537
538 # We assume there is only one PT_DYNAMIC. This is
539 # probably fine since the runtime ldso does the same.
540 break
541
542 del elf
543
544 if _first:
545 # get the libc based on dependencies
546 for soname in needed:
547 if soname.startswith(("libc.musl-", "ld-musl-")):
548 if libc is None:
549 libc = Libc.MUSL
550 if libc != Libc.MUSL:
551 msg = f"found a dependency on MUSL but the libc is already set to {libc}"
552 raise InvalidLibcError(msg)
553 elif soname == "libc.so.6" or soname.startswith(("ld-linux-", "ld64.so.")):
554 if libc is None:
555 libc = Libc.GLIBC
556 if libc != Libc.GLIBC:
557 msg = f"found a dependency on GLIBC but the libc is already set to {libc}"
558 raise InvalidLibcError(msg)
559 if libc is None:
560 # try the filename as a last resort
561 if path.name.endswith(("-arm-linux-musleabihf.so", "-linux-musl.so")):
562 libc = Libc.MUSL
563 elif path.name.endswith(("-arm-linux-gnueabihf.so", "-linux-gnu.so")):
564 # before python 3.11, musl was also using gnu
565 soabi = path.stem.split(".")[-1].split("-")
566 valid_python = tuple(f"3{minor}" for minor in range(11, 100))
567 if soabi[0] == "cpython" and soabi[1].startswith(valid_python):
568 libc = Libc.GLIBC
569
570 if ldpaths is None:
571 ldpaths = load_ld_paths(libc).copy()
572 # Propagate the rpaths used by the main ELF since those will be
573 # used at runtime to locate things.
574 ldpaths["rpath"] = rpaths
575 ldpaths["runpath"] = runpaths
576 log.debug(" ldpaths[rpath] = %s", rpaths)
577 log.debug(" ldpaths[runpath] = %s", runpaths)
578
579 assert ldpaths is not None # noqa: S101
580
581 all_ldpaths = (
582 ldpaths["rpath"]
583 + rpaths
584 + runpaths
585 + ldpaths["env"]
586 + ldpaths["runpath"]
587 + ldpaths["conf"]
588 + ldpaths["interp"]
589 )
590 _excluded_libs: set[str] = set()
591 for soname in needed:
592 if soname in _all_libs:
593 continue
594 if soname in _excluded_libs:
595 continue
596 if any(fnmatch(soname, e) for e in exclude):
597 log.info("Excluding %s", soname)
598 _excluded_libs.add(soname)
599 continue
600
601 # special case for libpython, see https://github.com/pypa/auditwheel/issues/589
602 # we want to return the dependency to be able to remove it later on but
603 # we don't want to analyze it for symbol versions nor do we want to analyze its
604 # dependencies as it will be removed.
605 if LIBPYTHON_RE.match(soname):
606 log.info("Skip %s resolution", soname)
607 _all_libs[soname] = DynamicLibrary(soname, None, None)
608 continue
609
610 realpath, fullpath = find_lib(platform, soname, all_ldpaths, root)
611 if realpath is not None and any(fnmatch(str(realpath), e) for e in exclude):
612 log.info("Excluding %s", realpath)
613 _excluded_libs.add(soname)
614 continue
615 _all_libs[soname] = DynamicLibrary(soname, fullpath, realpath)
616 if realpath is None or fullpath is None:
617 continue
618 dependency = ldd(realpath, root, prefix, ldpaths, fullpath, exclude, _all_libs)
619 _all_libs[soname] = DynamicLibrary(
620 soname,
621 fullpath,
622 realpath,
623 dependency.platform,
624 dependency.needed,
625 )
626
627 return DynamicExecutable(
628 interpreter,
629 libc,
630 str(path) if display is None else display,
631 path,
632 platform,
633 tuple(soname for soname in needed if soname not in _excluded_libs),
634 tuple(rpaths),
635 tuple(runpaths),
636 _all_libs,
637 )