Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/packaging/_manylinux.py: 24%
123 statements
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +0000
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +0000
1import collections
2import contextlib
3import functools
4import os
5import re
6import sys
7import warnings
8from typing import Dict, Generator, Iterator, NamedTuple, Optional, Tuple
10from ._elffile import EIClass, EIData, ELFFile, EMachine
12EF_ARM_ABIMASK = 0xFF000000
13EF_ARM_ABI_VER5 = 0x05000000
14EF_ARM_ABI_FLOAT_HARD = 0x00000400
17@contextlib.contextmanager
18def _parse_elf(path: str) -> Generator[Optional[ELFFile], None, None]:
19 try:
20 with open(path, "rb") as f:
21 yield ELFFile(f)
22 except (OSError, TypeError, ValueError):
23 yield None
26def _is_linux_armhf(executable: str) -> bool:
27 # hard-float ABI can be detected from the ELF header of the running
28 # process
29 # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
30 with _parse_elf(executable) as f:
31 return (
32 f is not None
33 and f.capacity == EIClass.C32
34 and f.encoding == EIData.Lsb
35 and f.machine == EMachine.Arm
36 and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
37 and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
38 )
41def _is_linux_i686(executable: str) -> bool:
42 with _parse_elf(executable) as f:
43 return (
44 f is not None
45 and f.capacity == EIClass.C32
46 and f.encoding == EIData.Lsb
47 and f.machine == EMachine.I386
48 )
51def _have_compatible_abi(executable: str, arch: str) -> bool:
52 if arch == "armv7l":
53 return _is_linux_armhf(executable)
54 if arch == "i686":
55 return _is_linux_i686(executable)
56 return arch in {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x"}
59# If glibc ever changes its major version, we need to know what the last
60# minor version was, so we can build the complete list of all versions.
61# For now, guess what the highest minor version might be, assume it will
62# be 50 for testing. Once this actually happens, update the dictionary
63# with the actual value.
64_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)
67class _GLibCVersion(NamedTuple):
68 major: int
69 minor: int
72def _glibc_version_string_confstr() -> Optional[str]:
73 """
74 Primary implementation of glibc_version_string using os.confstr.
75 """
76 # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
77 # to be broken or missing. This strategy is used in the standard library
78 # platform module.
79 # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
80 try:
81 # Should be a string like "glibc 2.17".
82 version_string: str = getattr(os, "confstr")("CS_GNU_LIBC_VERSION")
83 assert version_string is not None
84 _, version = version_string.rsplit()
85 except (AssertionError, AttributeError, OSError, ValueError):
86 # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
87 return None
88 return version
91def _glibc_version_string_ctypes() -> Optional[str]:
92 """
93 Fallback implementation of glibc_version_string using ctypes.
94 """
95 try:
96 import ctypes
97 except ImportError:
98 return None
100 # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
101 # manpage says, "If filename is NULL, then the returned handle is for the
102 # main program". This way we can let the linker do the work to figure out
103 # which libc our process is actually using.
104 #
105 # We must also handle the special case where the executable is not a
106 # dynamically linked executable. This can occur when using musl libc,
107 # for example. In this situation, dlopen() will error, leading to an
108 # OSError. Interestingly, at least in the case of musl, there is no
109 # errno set on the OSError. The single string argument used to construct
110 # OSError comes from libc itself and is therefore not portable to
111 # hard code here. In any case, failure to call dlopen() means we
112 # can proceed, so we bail on our attempt.
113 try:
114 process_namespace = ctypes.CDLL(None)
115 except OSError:
116 return None
118 try:
119 gnu_get_libc_version = process_namespace.gnu_get_libc_version
120 except AttributeError:
121 # Symbol doesn't exist -> therefore, we are not linked to
122 # glibc.
123 return None
125 # Call gnu_get_libc_version, which returns a string like "2.5"
126 gnu_get_libc_version.restype = ctypes.c_char_p
127 version_str: str = gnu_get_libc_version()
128 # py2 / py3 compatibility:
129 if not isinstance(version_str, str):
130 version_str = version_str.decode("ascii")
132 return version_str
135def _glibc_version_string() -> Optional[str]:
136 """Returns glibc version string, or None if not using glibc."""
137 return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
140def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
141 """Parse glibc version.
143 We use a regexp instead of str.split because we want to discard any
144 random junk that might come after the minor version -- this might happen
145 in patched/forked versions of glibc (e.g. Linaro's version of glibc
146 uses version strings like "2.20-2014.11"). See gh-3588.
147 """
148 m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
149 if not m:
150 warnings.warn(
151 f"Expected glibc version with 2 components major.minor,"
152 f" got: {version_str}",
153 RuntimeWarning,
154 )
155 return -1, -1
156 return int(m.group("major")), int(m.group("minor"))
159@functools.lru_cache()
160def _get_glibc_version() -> Tuple[int, int]:
161 version_str = _glibc_version_string()
162 if version_str is None:
163 return (-1, -1)
164 return _parse_glibc_version(version_str)
167# From PEP 513, PEP 600
168def _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:
169 sys_glibc = _get_glibc_version()
170 if sys_glibc < version:
171 return False
172 # Check for presence of _manylinux module.
173 try:
174 import _manylinux # noqa
175 except ImportError:
176 return True
177 if hasattr(_manylinux, "manylinux_compatible"):
178 result = _manylinux.manylinux_compatible(version[0], version[1], arch)
179 if result is not None:
180 return bool(result)
181 return True
182 if version == _GLibCVersion(2, 5):
183 if hasattr(_manylinux, "manylinux1_compatible"):
184 return bool(_manylinux.manylinux1_compatible)
185 if version == _GLibCVersion(2, 12):
186 if hasattr(_manylinux, "manylinux2010_compatible"):
187 return bool(_manylinux.manylinux2010_compatible)
188 if version == _GLibCVersion(2, 17):
189 if hasattr(_manylinux, "manylinux2014_compatible"):
190 return bool(_manylinux.manylinux2014_compatible)
191 return True
194_LEGACY_MANYLINUX_MAP = {
195 # CentOS 7 w/ glibc 2.17 (PEP 599)
196 (2, 17): "manylinux2014",
197 # CentOS 6 w/ glibc 2.12 (PEP 571)
198 (2, 12): "manylinux2010",
199 # CentOS 5 w/ glibc 2.5 (PEP 513)
200 (2, 5): "manylinux1",
201}
204def platform_tags(linux: str, arch: str) -> Iterator[str]:
205 if not _have_compatible_abi(sys.executable, arch):
206 return
207 # Oldest glibc to be supported regardless of architecture is (2, 17).
208 too_old_glibc2 = _GLibCVersion(2, 16)
209 if arch in {"x86_64", "i686"}:
210 # On x86/i686 also oldest glibc to be supported is (2, 5).
211 too_old_glibc2 = _GLibCVersion(2, 4)
212 current_glibc = _GLibCVersion(*_get_glibc_version())
213 glibc_max_list = [current_glibc]
214 # We can assume compatibility across glibc major versions.
215 # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
216 #
217 # Build a list of maximum glibc versions so that we can
218 # output the canonical list of all glibc from current_glibc
219 # down to too_old_glibc2, including all intermediary versions.
220 for glibc_major in range(current_glibc.major - 1, 1, -1):
221 glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
222 glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
223 for glibc_max in glibc_max_list:
224 if glibc_max.major == too_old_glibc2.major:
225 min_minor = too_old_glibc2.minor
226 else:
227 # For other glibc major versions oldest supported is (x, 0).
228 min_minor = -1
229 for glibc_minor in range(glibc_max.minor, min_minor, -1):
230 glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
231 tag = "manylinux_{}_{}".format(*glibc_version)
232 if _is_compatible(tag, arch, glibc_version):
233 yield linux.replace("linux", tag)
234 # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
235 if glibc_version in _LEGACY_MANYLINUX_MAP:
236 legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
237 if _is_compatible(legacy_tag, arch, glibc_version):
238 yield linux.replace("linux", legacy_tag)