Debian Codegraph @

src/auditwheel/policy/__init__.py

raw
1 from __future__ import annotations
2
3 import json
4 import logging
5 import re
6 from collections import defaultdict
7 from dataclasses import dataclass, replace
8 from pathlib import Path
9 from typing import TYPE_CHECKING, Any
10
11 from auditwheel.architecture import Architecture
12 from auditwheel.elfutils import filter_undefined_symbols
13 from auditwheel.error import InvalidLibcError
14 from auditwheel.lddtree import LIBPYTHON_RE
15 from auditwheel.libc import Libc
16 from auditwheel.tools import is_subdir
17 from auditwheel.wheeltools import android_api_level, get_wheel_platforms
18
19 if TYPE_CHECKING:
20 from collections.abc import Generator, Iterable
21
22 from auditwheel.lddtree import DynamicExecutable
23
24 _HERE = Path(__file__).parent
25 _MUSL_POLICY_RE = re.compile(r"^musllinux_\d+_\d+$")
26
27 logger = logging.getLogger(__name__)
28
29 _POLICY_JSON_MAP = {
30 Libc.GLIBC: _HERE / "manylinux-policy.json",
31 Libc.MUSL: _HERE / "musllinux-policy.json",
32 Libc.ANDROID: _HERE / "android-policy.json",
33 }
34
35
36 @dataclass(frozen=True)
37 class Policy:
38 name: str
39 aliases: tuple[str, ...]
40 priority: int
41 symbol_versions: dict[str, frozenset[str]]
42 whitelist: frozenset[str]
43 blacklist: dict[str, frozenset[str]]
44
45 def __lt__(self, other: Any) -> bool: # noqa: ANN401
46 if not isinstance(other, Policy):
47 raise NotImplementedError
48 return self.priority < other.priority
49
50
51 @dataclass()
52 class ExternalReference:
53 libs: dict[str, Path | None]
54 blacklist: dict[str, list[str]]
55 policy: Policy
56
57
58 class WheelPolicies:
59 def __init__(
60 self,
61 *,
62 libc: Libc,
63 arch: Architecture,
64 wheel_fn: Path | None = None,
65 musl_policy: str | None = None,
66 ) -> None:
67 if libc != Libc.MUSL and musl_policy is not None:
68 msg = f"'musl_policy' shall be None for libc {libc.name}"
69 raise ValueError(msg)
70 if libc == Libc.MUSL:
71 if musl_policy is None:
72 try:
73 musl_version = libc.get_current_version()
74 musl_policy = f"musllinux_{musl_version.major}_{musl_version.minor}"
75 except InvalidLibcError:
76 logger.warning(
77 "can't determine musl libc version, latest known version will be used.",
78 )
79 elif _MUSL_POLICY_RE.match(musl_policy) is None:
80 msg = f"Invalid 'musl_policy': '{musl_policy}'"
81 raise ValueError(msg)
82 policies = json.loads(_POLICY_JSON_MAP[libc].read_text())
83 self._policies: list[Policy] = []
84 self._architecture = arch
85 self._libc_variant = libc
86 self._musl_policy = musl_policy
87
88 base_arch = arch.baseline.value
89 _validate_pep600_compliance(policies)
90 for policy in policies:
91 if self._musl_policy is not None and policy["name"] not in {
92 "linux",
93 self._musl_policy,
94 }:
95 continue
96 if arch.value in policy["symbol_versions"] or policy["name"] == "linux":
97 name = f"{policy['name']}_{base_arch}"
98 if policy["name"] != "linux":
99 symbol_versions = {
100 k: frozenset(v) for k, v in policy["symbol_versions"][base_arch].items()
101 }
102 else:
103 symbol_versions = {}
104 aliases = tuple(f"{alias}_{base_arch}" for alias in policy["aliases"])
105 whitelist = _fixup_musl_libc_soname(libc, arch, policy["lib_whitelist"])
106 blacklist = {k: frozenset(v) for k, v in policy["blacklist"].items()}
107 policy_ = Policy(
108 name=name,
109 aliases=aliases,
110 priority=policy["priority"],
111 symbol_versions=symbol_versions,
112 whitelist=whitelist,
113 blacklist=blacklist,
114 )
115 self._policies.append(policy_)
116
117 self._policies.sort()
118
119 if self._libc_variant == Libc.MUSL:
120 if musl_policy is None:
121 self._musl_policy = "_".join(self._policies[1].name.split("_")[0:3])
122 self._policies = [self._policies[0], self._policies[1]]
123 assert len(self._policies) == 2, self._policies # noqa: S101
124
125 elif self._libc_variant == Libc.ANDROID:
126 # Android wheels always have a platform tag with an API level (OS version). We won't
127 # change that tag, we'll only use it to determine which libraries need to be grafted.
128 if wheel_fn is None:
129 msg = "wheel_fn is required when selecting Android policies"
130 raise ValueError(msg)
131
132 platforms = get_wheel_platforms(wheel_fn.name)
133 if len(platforms) != 1:
134 msg = f"Android wheels must have exactly one platform tag, got {platforms}"
135 raise ValueError(msg)
136 platform = platforms[0]
137 api_level = android_api_level(platform)
138
139 # One or two new API levels are created every year, so the policy file only lists the
140 # levels in which the available libraries changed
141 # (https://developer.android.com/ndk/guides/stable_apis). We should use the policy with
142 # the highest API level that's less than or equal to the wheel's tag.
143 for p in self._policies:
144 if p.name.startswith("android") and android_api_level(p.name) <= api_level:
145 # Rename the policy to match the existing tag, and remove all other policies.
146 self._policies = [self.linux, replace(p, name=platform)]
147 break
148 else:
149 # The minimum API level is 21, which was the first version to be officially
150 # supported by Python (see PEP 738).
151 msg = f"no Android policies match the platform tag {platform!r}"
152 raise ValueError(msg)
153
154 def __iter__(self) -> Generator[Policy]:
155 yield from self._policies
156
157 @property
158 def libc(self) -> Libc:
159 return self._libc_variant
160
161 @property
162 def architecture(self) -> Architecture:
163 return self._architecture
164
165 @property
166 def highest(self) -> Policy:
167 return self._policies[-1]
168
169 @property
170 def lowest(self) -> Policy:
171 """Lowest policy that's not linux"""
172 return self._policies[1]
173
174 @property
175 def linux(self) -> Policy:
176 return self._policies[0]
177
178 def get_policy_by_name(self, name: str) -> Policy:
179 matches = [p for p in self._policies if p.name == name or name in p.aliases]
180 if len(matches) == 0:
181 msg = f"no policy named {name!r} found"
182 raise LookupError(msg)
183 if len(matches) > 1:
184 msg = "Internal error. Policies should be unique"
185 raise RuntimeError(msg)
186 return matches[0]
187
188 def versioned_symbols_policy(
189 self,
190 versioned_symbols: dict[str, set[str]],
191 ) -> Policy:
192 def policy_is_satisfied(
193 policy_name: str,
194 policy_sym_vers: dict[str, set[str]],
195 ) -> bool:
196 policy_satisfied = True
197 for name in set(required_vers) & set(policy_sym_vers):
198 if not required_vers[name].issubset(policy_sym_vers[name]):
199 for symbol in required_vers[name] - policy_sym_vers[name]:
200 logger.debug(
201 "Package requires %s, incompatible with policy %s which requires %s",
202 symbol,
203 policy_name,
204 policy_sym_vers[name],
205 )
206 policy_satisfied = False
207 return policy_satisfied
208
209 required_vers: dict[str, set[str]] = {}
210 for symbols in versioned_symbols.values():
211 for symbol in symbols:
212 sym_name, _, _ = symbol.partition("_")
213 required_vers.setdefault(sym_name, set()).add(symbol)
214 for p in self._policies[::-1]:
215 policy_sym_vers = {
216 sym_name: {sym_name + "_" + version for version in versions}
217 for sym_name, versions in p.symbol_versions.items()
218 }
219 if policy_is_satisfied(p.name, policy_sym_vers):
220 return p
221
222 # the base policy (generic linux) should always match
223 msg = "Internal error" # pragma: no cover
224 raise RuntimeError(msg) # pragma: no cover
225
226 def lddtree_external_references(
227 self,
228 lddtree: DynamicExecutable,
229 wheel_path: Path,
230 ) -> dict[str, ExternalReference]:
231 def filter_libs(
232 libs: Iterable[str],
233 whitelist: frozenset[str],
234 ) -> Generator[str]:
235 for lib in libs:
236 if "ld-linux" in lib or lib in ["ld64.so.2", "ld64.so.1"]:
237 # always exclude ELF dynamic linker/loader
238 # 'ld64.so.2' on s390x
239 # 'ld64.so.1' on ppc64le
240 # 'ld-linux*' on other platforms
241 continue
242 if self.libc == Libc.ANDROID and LIBPYTHON_RE.match(lib):
243 # libpython dependencies are normal on Android.
244 continue
245 if lib in whitelist:
246 # exclude any libs in the whitelist
247 continue
248 yield lib
249
250 def get_req_external(libs: set[str], whitelist: frozenset[str]) -> set[str]:
251 # get all the required external libraries
252 libs = libs.copy()
253 reqs = set()
254 while libs:
255 lib = libs.pop()
256 reqs.add(lib)
257 for dep in filter_libs(lddtree.libraries[lib].needed, whitelist):
258 if dep not in reqs:
259 libs.add(dep)
260 return reqs
261
262 ret: dict[str, ExternalReference] = {}
263 for p in self._policies:
264 needed_external_libs: set[str] = set()
265 blacklist = {}
266
267 if p != self.linux:
268 # special-case the generic linux platform here, because it
269 # doesn't have a whitelist. or, you could say its
270 # whitelist is the complete set of all libraries. so nothing
271 # is considered "external" that needs to be copied in.
272 whitelist = p.whitelist
273 blacklist_libs = set(p.blacklist.keys()) & set(lddtree.needed)
274 blacklist_reduced = {k: p.blacklist[k] for k in blacklist_libs}
275 blacklist = filter_undefined_symbols(
276 lddtree.realpath,
277 blacklist_reduced,
278 )
279 needed_external_libs = get_req_external(
280 set(filter_libs(lddtree.needed, whitelist)),
281 whitelist,
282 )
283
284 pol_ext_deps: dict[str, Path | None] = {}
285 for lib in needed_external_libs:
286 if is_subdir(lddtree.libraries[lib].realpath, wheel_path):
287 # we didn't filter libs that resolved via RPATH out
288 # earlier because we wanted to make sure to pick up
289 # our elf's indirect dependencies. But now we want to
290 # filter these ones out, since they're not "external".
291 logger.debug("RPATH FTW: %s", lib)
292 continue
293 pol_ext_deps[lib] = lddtree.libraries[lib].realpath
294 ret[p.name] = ExternalReference(pol_ext_deps, blacklist, p)
295 return ret
296
297
298 def _validate_pep600_compliance(policies: Any) -> None: # noqa: ANN401
299 symbol_versions: dict[str, dict[str, set[str]]] = {}
300 lib_whitelist: set[str] = set()
301 for policy in sorted(policies, key=lambda x: x["priority"], reverse=True):
302 if policy["name"] == "linux":
303 continue
304 if not lib_whitelist.issubset(set(policy["lib_whitelist"])):
305 diff = lib_whitelist - set(policy["lib_whitelist"])
306 msg = (
307 'Invalid "policy.json" file. Missing whitelist libraries in '
308 f'"{policy["name"]}" compared to previous policies: {diff}'
309 )
310 raise ValueError(msg)
311 lib_whitelist.update(policy["lib_whitelist"])
312 for arch in policy["symbol_versions"]:
313 symbol_versions_arch = symbol_versions.get(arch, defaultdict(set))
314 for prefix in policy["symbol_versions"][arch]:
315 policy_symbol_versions = set(policy["symbol_versions"][arch][prefix])
316 if not symbol_versions_arch[prefix].issubset(policy_symbol_versions):
317 diff = symbol_versions_arch[prefix] - policy_symbol_versions
318 msg = (
319 'Invalid "policy.json" file. Symbol versions missing '
320 f'in "{policy["name"]}_{arch}" for "{prefix}" '
321 f"compared to previous policies: {diff}"
322 )
323 raise ValueError(msg)
324 symbol_versions_arch[prefix].update(
325 policy["symbol_versions"][arch][prefix],
326 )
327 symbol_versions[arch] = symbol_versions_arch
328
329
330 def _fixup_musl_libc_soname(
331 libc: Libc,
332 arch: Architecture,
333 whitelist: list[str],
334 ) -> frozenset[str]:
335 if libc != Libc.MUSL:
336 return frozenset(whitelist)
337 soname_map = {
338 "libc.so": {
339 Architecture.x86_64: "libc.musl-x86_64.so.1",
340 Architecture.i686: "libc.musl-x86.so.1",
341 Architecture.aarch64: "libc.musl-aarch64.so.1",
342 Architecture.s390x: "libc.musl-s390x.so.1",
343 Architecture.ppc64le: "libc.musl-ppc64le.so.1",
344 Architecture.armv7l: "libc.musl-armv7.so.1",
345 Architecture.riscv64: "libc.musl-riscv64.so.1",
346 Architecture.loongarch64: "libc.musl-loongarch64.so.1",
347 },
348 }
349 new_whitelist = []
350 for soname in whitelist:
351 if soname in soname_map:
352 new_soname = soname_map[soname][arch.baseline]
353 logger.debug("Replacing whitelisted '%s' by '%s'", soname, new_soname)
354 new_whitelist.append(new_soname)
355 else:
356 new_whitelist.append(soname)
357 return frozenset(new_whitelist)
358
359
360 def get_replace_platforms(name: str) -> list[str]:
361 """Extract platform tag replacement rules from policy
362
363 >>> get_replace_platforms('linux_x86_64')
364 []
365 >>> get_replace_platforms('linux_i686')
366 []
367 >>> get_replace_platforms('manylinux1_x86_64')
368 ['linux_x86_64']
369 >>> get_replace_platforms('manylinux1_i686')
370 ['linux_i686']
371
372 """
373 if name.startswith("linux"):
374 return []
375 if name.startswith("manylinux_"):
376 return ["linux_" + "_".join(name.split("_")[3:])]
377 if name.startswith("musllinux_"):
378 return ["linux_" + "_".join(name.split("_")[3:])]
379 return ["linux_" + "_".join(name.split("_")[1:])]
380
381
382 __all__ = [
383 "WheelPolicies",
384 ]