Debian Codegraph @

src/auditwheel/wheel_abi.py

raw
1 from __future__ import annotations
2
3 import dataclasses
4 import functools
5 import itertools
6 import logging
7 from collections import defaultdict
8 from copy import deepcopy
9 from dataclasses import dataclass
10 from pathlib import Path
11 from typing import TYPE_CHECKING, TypeVar
12
13 from auditwheel import json
14 from auditwheel.elfutils import (
15 elf_file_filter,
16 elf_find_ucs2_symbols,
17 elf_find_versioned_symbols,
18 elf_is_python_extension,
19 elf_references_pyfpe_jbuf,
20 )
21 from auditwheel.error import InvalidLibcError, NonPlatformWheelError
22 from auditwheel.genericpkgctx import InGenericPkgCtx
23 from auditwheel.lddtree import DynamicExecutable, DynamicLibrary, ld_paths_from_arg, ldd
24 from auditwheel.libc import Libc
25 from auditwheel.policy import ExternalReference, Policy, WheelPolicies
26
27 if TYPE_CHECKING:
28 from collections.abc import Mapping
29
30 from auditwheel.architecture import Architecture
31
32 log = logging.getLogger(__name__)
33
34
35 @dataclass(frozen=True)
36 class WheelAbIInfo:
37 policies: WheelPolicies
38 full_external_refs: dict[Path, dict[str, ExternalReference]]
39 overall_policy: Policy
40 external_refs: dict[str, ExternalReference]
41 ref_policy: Policy
42 versioned_symbols: dict[str, set[str]]
43 sym_policy: Policy
44 ucs_policy: Policy
45 pyfpe_policy: Policy
46 blacklist_policy: Policy
47 machine_policy: Policy
48 graft_policy: Policy
49
50
51 @dataclass(frozen=True)
52 class WheelElfData:
53 policies: WheelPolicies
54 full_elftree: dict[Path, DynamicExecutable]
55 full_external_refs: dict[Path, dict[str, ExternalReference]]
56 versioned_symbols: dict[str, set[str]]
57 uses_ucs2_symbols: bool
58 uses_pyfpe_jbuf: bool
59
60
61 def _fixup_elf_trees(
62 py_elf_trees: dict[Path, DynamicExecutable],
63 nonpy_elftree: dict[Path, DynamicExecutable],
64 ) -> None:
65 # Auditwheel assumes that if a dependency in a non-Python ELF tree can be resolved
66 # in any other fully resolved ELF tree, then it can be loaded from other
67 # non-Python ELF trees as well. Python extension ELF trees are not
68 # fixed up; they should always be valid in the first place. We fix up
69 # non-Python ELF trees with that assumption in mind.
70 resolved_executables = [
71 executable
72 for executable in itertools.chain(py_elf_trees.values(), nonpy_elftree.values())
73 if all(library.realpath is not None for library in executable.libraries.values())
74 ]
75
76 def _get_reference(path_to_elf: Path) -> DynamicExecutable | None:
77 assert path_to_elf.is_file() # noqa: S101
78 for candidate in resolved_executables:
79 for library in candidate.libraries.values():
80 assert library.realpath is not None # noqa: S101
81 assert library.realpath.is_file() # noqa: S101
82 if path_to_elf.samefile(library.realpath):
83 return candidate
84 return None
85
86 for elf_path, elf_executable in nonpy_elftree.items():
87 need_resolution = any(
88 elf_library.realpath is None for elf_library in elf_executable.libraries.values()
89 )
90 if not need_resolution:
91 continue
92 reference = _get_reference(elf_executable.realpath)
93 if reference is None:
94 continue
95 ref_name = reference.realpath.name
96 libraries_new: dict[str, DynamicLibrary] = {}
97 soname_all = set(elf_executable.libraries.keys())
98 for soname, elf_library in elf_executable.libraries.items():
99 if elf_library.realpath is None and soname in reference.libraries:
100 libraries_new[soname] = reference.libraries[soname]
101 # we need to add newly found dependencies as well
102 needed_new = set(libraries_new[soname].needed) - soname_all
103 while needed_new:
104 needed_new_copy = needed_new.copy()
105 soname_all |= needed_new_copy
106 for soname_needed in needed_new_copy:
107 if soname_needed in reference.libraries:
108 libraries_new[soname_needed] = reference.libraries[soname_needed]
109 needed_new.update(libraries_new[soname_needed].needed)
110 else:
111 log.warning("%s not found in %s ELF tree", soname_needed, ref_name)
112 needed_new -= soname_all
113 else:
114 if elf_library.realpath is None:
115 log.warning("%s not found in %s ELF tree", soname, ref_name)
116 libraries_new[soname] = elf_library
117 nonpy_elftree[elf_path] = dataclasses.replace(elf_executable, libraries=libraries_new)
118
119
120 @functools.lru_cache
121 def get_wheel_elfdata(
122 libc: Libc | None,
123 architecture: Architecture | None,
124 wheel_fn: Path,
125 exclude: frozenset[str],
126 args_ldpaths: str | None,
127 ) -> WheelElfData:
128 full_elftree: dict[Path, DynamicExecutable] = {}
129 nonpy_elftree: dict[Path, DynamicExecutable] = {}
130 full_external_refs: dict[Path, dict[str, ExternalReference]] = {}
131 versioned_symbols: dict[str, set[str]] = defaultdict(set)
132 uses_ucs2_symbols = False
133 uses_pyfpe_jbuf = False
134 policies: WheelPolicies | None = None
135
136 # Android is cross-compiled, so ldpaths should never be loaded from the build machine.
137 if libc == Libc.ANDROID and args_ldpaths is None:
138 args_ldpaths = ""
139
140 with InGenericPkgCtx(wheel_fn) as ctx:
141 shared_libraries_in_purelib = []
142 shared_libraries_with_invalid_machine = []
143
144 platform_wheel = False
145 for fn, elf in elf_file_filter(ctx.iter_files()):
146 # Check for invalid binary wheel format: no shared library should
147 # be found in purelib
148 so_name = fn.name
149
150 # If this is in purelib, add it to the list of shared libraries in
151 # purelib
152 if any(p.name == "purelib" for p in fn.parents):
153 shared_libraries_in_purelib.append(so_name)
154
155 # If at least one shared library exists in purelib, this is going
156 # to fail and there's no need to do further checks
157 if not shared_libraries_in_purelib:
158 log.debug("processing: %s", fn)
159 elftree = ldd(fn, exclude=exclude, ldpaths=ld_paths_from_arg(args_ldpaths))
160
161 try:
162 elf_arch = elftree.platform.baseline_architecture
163 except ValueError:
164 shared_libraries_with_invalid_machine.append(so_name)
165 log.warning("ignoring: %s with unknown architecture", so_name)
166 continue
167 if architecture is None:
168 log.info("setting architecture to %s", elf_arch.value)
169 architecture = elf_arch
170 elif elf_arch != architecture.baseline:
171 shared_libraries_with_invalid_machine.append(so_name)
172 log.warning("ignoring: %s with %s architecture", so_name, elf_arch)
173 continue
174
175 if elftree.libc is not None:
176 if libc is None:
177 log.info("setting libc to %s", elftree.libc)
178 libc = elftree.libc
179 elif libc != elftree.libc:
180 log.warning("ignoring: %s with %s libc", so_name, elftree.libc)
181 continue
182
183 if policies is None and libc is not None and architecture is not None:
184 policies = WheelPolicies(libc=libc, arch=architecture, wheel_fn=wheel_fn)
185
186 platform_wheel = True
187
188 for key, value in elf_find_versioned_symbols(elf):
189 log.debug("key %s, value %s", key, value)
190 versioned_symbols[key].add(value)
191
192 is_py_ext, py_ver = elf_is_python_extension(fn, elf)
193
194 # If the ELF is a Python extention, we definitely need to
195 # include its external dependencies.
196 if is_py_ext:
197 if policies is None:
198 assert architecture is not None # noqa: S101
199 assert libc is None # noqa: S101
200 msg = f"couldn't detect libc for python extension {fn}"
201 raise InvalidLibcError(msg)
202 full_elftree[fn] = elftree
203 uses_pyfpe_jbuf |= elf_references_pyfpe_jbuf(elf)
204 if py_ver == 2:
205 uses_ucs2_symbols |= any(True for _ in elf_find_ucs2_symbols(elf))
206 full_external_refs[fn] = policies.lddtree_external_references(
207 elftree,
208 ctx.path,
209 )
210 else:
211 # If the ELF is not a Python extension, it might be
212 # included in the wheel already because auditwheel repair
213 # vendored it, so we will check whether we should include
214 # its internal references later.
215 nonpy_elftree[fn] = elftree
216
217 # If at least one shared library exists in purelib, raise an error
218 if shared_libraries_in_purelib:
219 libraries = "\n\t".join(shared_libraries_in_purelib)
220 msg = (
221 "Invalid binary wheel, found the following shared library/libraries "
222 f"in purelib folder:\n\t{libraries}\n"
223 "The wheel has to be platlib compliant in order to be repaired by "
224 "auditwheel."
225 )
226 raise RuntimeError(msg)
227
228 if not platform_wheel:
229 arch = None if architecture is None else architecture.value
230 raise NonPlatformWheelError(arch, shared_libraries_with_invalid_machine)
231
232 _fixup_elf_trees(full_elftree, nonpy_elftree)
233
234 # Get a list of all external libraries needed by ELFs in the wheel.
235 needed_libs = {
236 lib
237 for elf in itertools.chain(full_elftree.values(), nonpy_elftree.values())
238 for lib in elf.needed
239 }
240
241 if policies is None:
242 # we have no python extensions, either we have shared libraries with
243 # no dependencies on libc (unlikely) or a statically linked executable
244 # let's fallback to the host libc
245 assert architecture is not None # noqa: S101
246 assert libc is None # noqa: S101
247 libc = Libc.detect()
248 log.warning("couldn't detect wheel libc, defaulting to %s", str(libc))
249 policies = WheelPolicies(libc=libc, arch=architecture)
250
251 for fn, elf_tree in nonpy_elftree.items():
252 # If a non-pyextension ELF file is not needed by something else
253 # inside the wheel, then it was not checked by the logic above and
254 # we should walk its elftree.
255 if fn.name not in needed_libs:
256 full_elftree[fn] = elf_tree
257
258 # Even if a non-pyextension ELF file is not needed, we
259 # should include it as an external reference, because
260 # it might require additional external libraries.
261 full_external_refs[fn] = policies.lddtree_external_references(
262 elf_tree,
263 ctx.path,
264 )
265
266 log.debug("full_elftree:\n%s", json.dumps(full_elftree))
267 log.debug(
268 "full_external_refs (will be repaired):\n%s",
269 json.dumps(full_external_refs),
270 )
271
272 return WheelElfData(
273 policies,
274 full_elftree,
275 full_external_refs,
276 versioned_symbols,
277 uses_ucs2_symbols,
278 uses_pyfpe_jbuf,
279 )
280
281
282 def get_external_libs(external_refs: dict[str, ExternalReference]) -> dict[Path, str]:
283 """Get external library dependencies for all policies excluding the default
284 linux policy
285 :param external_refs: external references for all policies
286 :return: {realpath: soname} e.g.
287 {'/path/to/external_ref.so.1.2.3': 'external_ref.so.1'}
288 """
289 result: dict[Path, str] = {}
290 for external_ref in external_refs.values():
291 # linux tag (priority 0) has no white-list, do not analyze it
292 if external_ref.policy.priority == 0:
293 continue
294 # go through all libs, retrieving their soname and realpath
295 for libname, realpath in external_ref.libs.items():
296 if realpath and realpath not in result:
297 result[Path(realpath)] = libname
298 return result
299
300
301 def get_versioned_symbols(libs: dict[Path, str]) -> dict[str, dict[str, set[str]]]:
302 """Get versioned symbols used in libraries
303 :param libs: {realpath: soname} dict to search for versioned symbols e.g.
304 {'/path/to/external_ref.so.1.2.3': 'external_ref.so.1'}
305 :return: {soname: {depname: set([symbol_version])}} e.g.
306 {'external_ref.so.1': {'libc.so.6', set(['GLIBC_2.5','GLIBC_2.12'])}}
307 """
308 result = {}
309 for path, elf in elf_file_filter(libs.keys()):
310 # {depname: set(symbol_version)}, e.g. {'libc.so.6', set(['GLIBC_2.5','GLIBC_2.12'])}
311 elf_versioned_symbols: dict[str, set[str]] = defaultdict(set)
312 for key, value in elf_find_versioned_symbols(elf):
313 log.debug("path %s, key %s, value %s", path, key, value)
314 elf_versioned_symbols[key].add(value)
315 result[libs[path]] = elf_versioned_symbols
316 return result
317
318
319 def get_symbol_policies(
320 policies: WheelPolicies,
321 versioned_symbols: dict[str, set[str]],
322 external_versioned_symbols: dict[str, dict[str, set[str]]],
323 external_refs: dict[str, ExternalReference],
324 ) -> list[tuple[Policy, dict[str, set[str]]]]:
325 """Get symbol policies
326 Since white-list is different per policy, this function inspects
327 versioned_symbol per policy when including external refs
328 :param versioned_symbols: versioned symbols for the current wheel
329 :param external_versioned_symbols: versioned symbols for external libs
330 :param external_refs: external references for all policies
331 :return: list of tuples of the form (policy, versioned_symbols),
332 e.g. [(<Policy: manylinux...>, {'libc.so.6', set(['GLIBC_2.5'])})]
333 """
334 result = []
335 for external_ref in external_refs.values():
336 # skip the linux policy
337 if external_ref.policy.priority == 0:
338 continue
339 policy_symbols = deepcopy(versioned_symbols)
340 for soname in external_ref.libs:
341 if soname not in external_versioned_symbols:
342 continue
343 ext_symbols = external_versioned_symbols[soname]
344 for k in iter(ext_symbols):
345 policy_symbols[k].update(ext_symbols[k])
346 # if the white-list policy changed, we don't want to allow highest priority policy
347 # than the current one, that is, only restrict to a lower priority policy
348 found_policy = min(
349 external_ref.policy,
350 policies.versioned_symbols_policy(policy_symbols),
351 )
352 result.append((found_policy, policy_symbols))
353 return result
354
355
356 def _get_machine_policy(
357 policies: WheelPolicies,
358 elftree_by_fn: dict[Path, DynamicExecutable],
359 external_so_names: frozenset[str],
360 ) -> Policy:
361 """
362 Determine the most appropriate machine policy for the wheel based on ELF
363 architectures and whitelisted external dependencies.
364 The function inspects the extended architecture of each top-level ELF file
365 in ``elftree_by_fn`` and of any library dependencies whose SONAME appears in
366 ``external_so_names``. If an ELF file requires instructions that are not
367 covered by ``policies.architecture``, the overall policy is downgraded to
368 reflect that requirement.
369 If the offending ELF file corresponds to an external shared object
370 (i.e. its SONAME is in ``external_so_names``), the function looks for a
371 policy whose whitelist contains that SONAME and uses the highest-priority
372 such policy instead of unconditionally falling back to the baseline
373 ``policies.linux`` policy. Informational or warning logs are emitted to
374 record any such downgrades.
375 :param policies: Collection of available wheel policies, including the
376 target architecture, the baseline ``linux`` policy, and the highest
377 (most permissive) default policy.
378 :param elftree_by_fn: Mapping from ELF file paths to their corresponding
379 :class:`DynamicExecutable` objects, used to inspect platforms and
380 dependency graphs.
381 :param external_so_names: Set of SONAMEs that are treated as external
382 references and may be whitelisted by individual policies.
383 :return: The selected :class:`Policy` after considering all relevant ELF
384 files and their dependencies.
385 """
386 result = policies.highest
387 machine_to_check: dict[Path, tuple[str | None, Architecture | None]] = {}
388 for fn, dynamic_executable in elftree_by_fn.items():
389 if fn in machine_to_check:
390 continue
391 machine_to_check[fn] = (None, dynamic_executable.platform.extended_architecture)
392 for dependency in dynamic_executable.libraries.values():
393 if dependency.soname not in external_so_names:
394 continue
395 if dependency.realpath is None:
396 continue
397 assert dependency.platform is not None # noqa: S101
398 if dependency.realpath in machine_to_check:
399 continue
400 machine_to_check[dependency.realpath] = (
401 dependency.soname,
402 dependency.platform.extended_architecture,
403 )
404
405 for fn, (soname, extended_architecture) in machine_to_check.items():
406 if extended_architecture is None:
407 continue
408 if policies.architecture.is_superset(extended_architecture):
409 continue
410 if soname is not None:
411 found_policy = policies.linux
412 for policy in policies:
413 if soname in policy.whitelist:
414 found_policy = max(found_policy, policy)
415 if policies.linux.priority < found_policy.priority:
416 log.info(
417 "ELF file %r requires %r instruction set, not in %r, whitelisted in %r",
418 fn,
419 extended_architecture.value,
420 policies.architecture.value,
421 found_policy.name,
422 )
423 result = min(result, found_policy)
424 continue
425 log.warning(
426 "ELF file %r requires %r instruction set, not in %r",
427 fn,
428 extended_architecture.value,
429 policies.architecture.value,
430 )
431 result = policies.linux
432
433 return result
434
435
436 def analyze_wheel_abi(
437 libc: Libc | None,
438 architecture: Architecture | None,
439 wheel_fn: Path,
440 exclude: frozenset[str],
441 *,
442 disable_isa_ext_check: bool,
443 allow_graft: bool,
444 requested_policy_base_name: str | None = None,
445 args_ldpaths: str | None = None,
446 ) -> WheelAbIInfo:
447 data = get_wheel_elfdata(libc, architecture, wheel_fn, exclude, args_ldpaths)
448 policies = data.policies
449 elftree_by_fn = data.full_elftree
450 external_refs_by_fn = data.full_external_refs
451 versioned_symbols = data.versioned_symbols
452
453 external_refs: dict[str, ExternalReference] = {
454 p.name: ExternalReference({}, {}, p) for p in policies
455 }
456
457 for fn in elftree_by_fn:
458 update(external_refs, external_refs_by_fn[fn])
459
460 log.debug("external reference info")
461 log.debug(json.dumps(external_refs))
462
463 external_libs = get_external_libs(external_refs)
464 external_versioned_symbols = get_versioned_symbols(external_libs)
465 symbol_policies = get_symbol_policies(
466 policies,
467 versioned_symbols,
468 external_versioned_symbols,
469 external_refs,
470 )
471 symbol_policy = policies.versioned_symbols_policy(versioned_symbols)
472
473 # let's keep the highest priority policy and
474 # corresponding versioned_symbols
475 symbol_policy, versioned_symbols = max(
476 symbol_policies,
477 key=lambda x: x[0],
478 default=(symbol_policy, versioned_symbols),
479 )
480
481 ref_policy = max(
482 (e.policy for e in external_refs.values() if len(e.libs) == 0),
483 default=policies.linux,
484 )
485
486 blacklist_policy = max(
487 (e.policy for e in external_refs.values() if len(e.blacklist) == 0),
488 default=policies.linux,
489 )
490
491 # don't allow highest priority policies with more grafted libraries
492 # than the requested policy
493 if requested_policy_base_name is None or requested_policy_base_name == "auto":
494 graft_lib_count = min(
495 (len(e.libs) for e in external_refs.values() if e.policy != policies.linux),
496 default=0,
497 )
498 else:
499 graft_lib_count = min(
500 (
501 len(e.libs)
502 for e in external_refs.values()
503 if e.policy.name.startswith(f"{requested_policy_base_name}_")
504 ),
505 default=0,
506 )
507 graft_policy = max(
508 (e.policy for e in external_refs.values() if len(e.libs) <= graft_lib_count),
509 default=policies.linux,
510 )
511
512 if disable_isa_ext_check:
513 machine_policy = policies.highest
514 else:
515 machine_policy = _get_machine_policy(
516 policies,
517 elftree_by_fn,
518 frozenset(external_libs.values()),
519 )
520
521 ucs_policy = policies.linux if data.uses_ucs2_symbols else policies.highest
522 pyfpe_policy = policies.linux if data.uses_pyfpe_jbuf else policies.highest
523
524 overall_policy = min(
525 symbol_policy,
526 ucs_policy,
527 pyfpe_policy,
528 blacklist_policy,
529 machine_policy,
530 )
531
532 if requested_policy_base_name is not None:
533 overall_policy = min(overall_policy, graft_policy)
534
535 if not allow_graft:
536 overall_policy = min(overall_policy, ref_policy)
537
538 return WheelAbIInfo(
539 policies,
540 external_refs_by_fn,
541 overall_policy,
542 external_refs,
543 ref_policy,
544 versioned_symbols,
545 symbol_policy,
546 ucs_policy,
547 pyfpe_policy,
548 blacklist_policy,
549 machine_policy,
550 graft_policy,
551 )
552
553
554 _T = TypeVar("_T", ExternalReference, Path | None)
555
556
557 def update(d: dict[str, _T], u: Mapping[str, _T]) -> None:
558 for k, v in u.items():
559 if isinstance(v, ExternalReference):
560 assert k in d # noqa: S101
561 assert isinstance(d[k], ExternalReference) # noqa: S101
562 assert d[k].policy == v.policy # noqa: S101
563 # update blacklist
564 for lib, symbols in v.blacklist.items():
565 if lib not in d[k].blacklist:
566 d[k].blacklist[lib] = sorted(symbols)
567 else:
568 d[k].blacklist[lib] = sorted(
569 set(d[k].blacklist[lib]) | set(symbols),
570 )
571 # libs
572 update(d[k].libs, v.libs)
573 elif isinstance(v, (Path, type(None))):
574 d[k] = v
575 else:
576 msg = f"can't update {d} with {k}:{v}"
577 raise TypeError(msg)