Debian Codegraph @

src/auditwheel/libc.py

raw
1 from __future__ import annotations
2
3 import logging
4 import os
5 import re
6 import subprocess
7 from dataclasses import dataclass
8 from enum import Enum
9 from pathlib import Path
10
11 from auditwheel.error import InvalidLibcError
12
13 logger = logging.getLogger(__name__)
14
15
16 @dataclass(frozen=True, order=True)
17 class LibcVersion:
18 major: int
19 minor: int
20
21
22 class Libc(Enum):
23 value: str
24
25 GLIBC = "glibc"
26 MUSL = "musl"
27 ANDROID = "android"
28
29 def __str__(self) -> str:
30 return self.value
31
32 def get_current_version(self) -> LibcVersion:
33 if self == Libc.MUSL:
34 return _get_musl_version(_find_musl_libc())
35 if self == Libc.GLIBC:
36 return _get_glibc_version()
37 msg = f"can't determine version of libc '{self}'"
38 raise InvalidLibcError(msg)
39
40 @staticmethod
41 def detect() -> Libc:
42 # check musl first, default to GLIBC
43 try:
44 _find_musl_libc()
45 logger.debug("Detected musl libc")
46 return Libc.MUSL # noqa: TRY300
47 except InvalidLibcError:
48 logger.debug("Falling back to GNU libc")
49 return Libc.GLIBC
50
51 @property
52 def tag_prefix(self) -> str:
53 return {
54 Libc.GLIBC: "manylinux",
55 Libc.MUSL: "musllinux",
56 Libc.ANDROID: "android",
57 }[self]
58
59
60 def _find_musl_libc() -> Path:
61 try:
62 (dl_path,) = list(Path("/lib").glob("libc.musl-*.so.1"))
63 except ValueError:
64 msg = "musl libc not detected"
65 logger.debug("%s", msg)
66 raise InvalidLibcError(msg) from None
67
68 return dl_path
69
70
71 def _get_musl_version(ld_path: Path) -> LibcVersion:
72 try:
73 ld = subprocess.run(
74 [ld_path],
75 check=False,
76 errors="strict",
77 stderr=subprocess.PIPE,
78 ).stderr
79 except FileNotFoundError as err:
80 msg = "failed to determine musl version"
81 logger.exception("%s", msg)
82 raise InvalidLibcError(msg) from err
83
84 match = re.search(r"Version (?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)", ld)
85 if not match:
86 msg = f"failed to parse musl version from string {ld!r}"
87 raise InvalidLibcError(msg) from None
88
89 return LibcVersion(int(match.group("major")), int(match.group("minor")))
90
91
92 def _get_glibc_version() -> LibcVersion:
93 # CS_GNU_LIBC_VERSION is only for glibc and shall return e.g. "glibc 2.3.4"
94 try:
95 version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
96 if version_string is None:
97 msg = "failed to determine glibc version"
98 raise InvalidLibcError(msg)
99 _, version = version_string.rsplit()
100 except (AttributeError, OSError, ValueError) as err:
101 # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
102 msg = "failed to determine glibc version"
103 raise InvalidLibcError(msg) from err
104
105 m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version)
106 if not m:
107 msg = f"failed to parse glibc version from string {version!r}"
108 raise InvalidLibcError(msg)
109
110 return LibcVersion(int(m.group("major")), int(m.group("minor")))