| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import itertools |
| 4 |
import json |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import platform |
| 8 |
import shutil |
| 9 |
import stat |
| 10 |
from pathlib import Path |
| 11 |
from subprocess import check_call |
| 12 |
from typing import TYPE_CHECKING |
| 13 |
|
| 14 |
from auditwheel.elfutils import elf_read_dt_needed |
| 15 |
from auditwheel.hashfile import hashfile |
| 16 |
from auditwheel.lddtree import LIBPYTHON_RE |
| 17 |
from auditwheel.policy import get_replace_platforms |
| 18 |
from auditwheel.sboms import create_sbom_for_wheel |
| 19 |
from auditwheel.tools import is_subdir, unique_by_index |
| 20 |
from auditwheel.wheeltools import WHEEL_INFO_RE, InWheelCtx, add_platforms |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from collections.abc import Iterable |
| 24 |
|
| 25 |
from auditwheel.patcher import ElfPatcher |
| 26 |
from auditwheel.wheel_abi import WheelAbIInfo |
| 27 |
|
| 28 |
logger = logging.getLogger(__name__) |
| 29 |
|
| 30 |
|
| 31 |
def repair_wheel( |
| 32 |
wheel_abi: WheelAbIInfo, |
| 33 |
wheel_path: Path, |
| 34 |
abis: list[str], |
| 35 |
lib_sdir: str, |
| 36 |
out_dir: Path, |
| 37 |
*, |
| 38 |
update_tags: bool, |
| 39 |
patcher: ElfPatcher, |
| 40 |
strip: bool, |
| 41 |
zip_compression_level: int, |
| 42 |
) -> Path | None: |
| 43 |
external_refs_by_fn = wheel_abi.full_external_refs |
| 44 |
# Do not repair a pure wheel, i.e. has no external refs |
| 45 |
if not external_refs_by_fn: |
| 46 |
return None |
| 47 |
|
| 48 |
soname_map: dict[str, tuple[str, Path]] = {} |
| 49 |
|
| 50 |
out_dir = out_dir.resolve(strict=True) |
| 51 |
wheel_fname = wheel_path.name |
| 52 |
|
| 53 |
output_wheel = out_dir / wheel_fname |
| 54 |
with InWheelCtx(wheel_path) as ctx: |
| 55 |
ctx.out_wheel = output_wheel |
| 56 |
ctx.zip_compression_level = zip_compression_level |
| 57 |
|
| 58 |
match = WHEEL_INFO_RE(wheel_fname) |
| 59 |
if not match: |
| 60 |
msg = f"Failed to parse wheel file name: {wheel_fname}" |
| 61 |
raise ValueError(msg) |
| 62 |
|
| 63 |
dest_dir = Path(match.group("name") + lib_sdir) |
| 64 |
dist_info_dirs = list(ctx.path.glob("*.dist-info")) |
| 65 |
assert len(dist_info_dirs) == 1, ( # noqa: S101 |
| 66 |
"Expected exactly one .dist-info directory, " |
| 67 |
f"found {len(dist_info_dirs)}: {dist_info_dirs}" |
| 68 |
) |
| 69 |
sbom_filepaths: list[Path] = [] |
| 70 |
|
| 71 |
# here, fn is a path to an ELF file (lib or executable) in |
| 72 |
# the wheel, and v['libs'] contains its required libs |
| 73 |
for fn, v in external_refs_by_fn.items(): |
| 74 |
ext_libs = v[abis[0]].libs |
| 75 |
replacements: list[tuple[str, str]] = [] |
| 76 |
for soname, src_path in ext_libs.items(): |
| 77 |
# Handle libpython dependencies by removing them |
| 78 |
if LIBPYTHON_RE.match(soname): |
| 79 |
logger.warning( |
| 80 |
"Removing %s dependency from %s. " |
| 81 |
"Linking with libpython is forbidden for manylinux/musllinux wheels.", |
| 82 |
soname, |
| 83 |
str(fn), |
| 84 |
) |
| 85 |
patcher.remove_needed(fn, soname) |
| 86 |
continue |
| 87 |
|
| 88 |
if src_path is None: |
| 89 |
msg = ( |
| 90 |
"Cannot repair wheel, because required " |
| 91 |
f'library "{soname}" could not be located' |
| 92 |
) |
| 93 |
raise ValueError(msg) |
| 94 |
|
| 95 |
if not dest_dir.exists(): |
| 96 |
dest_dir.mkdir() |
| 97 |
sbom_filepaths.append(src_path) |
| 98 |
new_soname, new_path = copylib(src_path, dest_dir, patcher) |
| 99 |
soname_map[soname] = (new_soname, new_path) |
| 100 |
replacements.append((soname, new_soname)) |
| 101 |
if replacements: |
| 102 |
patcher.replace_needed(fn, *replacements) |
| 103 |
|
| 104 |
if len(ext_libs) > 0: |
| 105 |
new_fn = fn |
| 106 |
if _path_is_script(fn): |
| 107 |
new_fn = _replace_elf_script_with_shim(match.group("name"), fn) |
| 108 |
new_rpath = Path("$ORIGIN") / os.path.relpath(dest_dir, new_fn.parent) |
| 109 |
append_rpath_within_wheel(new_fn, str(new_rpath), ctx.name, patcher) |
| 110 |
|
| 111 |
# we grafted in a bunch of libraries and modified their sonames, but |
| 112 |
# they may have internal dependencies (DT_NEEDED) on one another, so |
| 113 |
# we need to update those records so each now knows about the new |
| 114 |
# name of the other. |
| 115 |
# we also clear or set RPATH depending on the presence of internal dependencies |
| 116 |
for _, path in soname_map.values(): |
| 117 |
needed = elf_read_dt_needed(path) # TODO perf, we already read those at some point |
| 118 |
replacements = [] |
| 119 |
for n in needed: |
| 120 |
if n in soname_map: |
| 121 |
replacements.append((n, soname_map[n][0])) |
| 122 |
if replacements: |
| 123 |
patcher.set_rpath(path, "$ORIGIN") |
| 124 |
patcher.replace_needed(path, *replacements) |
| 125 |
else: |
| 126 |
patcher.clear_rpath(path) |
| 127 |
|
| 128 |
if update_tags: |
| 129 |
output_wheel = add_platforms(ctx, abis, get_replace_platforms(abis[0])) |
| 130 |
|
| 131 |
if strip: |
| 132 |
libs_to_strip = [path for (_, path) in soname_map.values()] |
| 133 |
extensions = external_refs_by_fn.keys() |
| 134 |
strip_symbols(itertools.chain(libs_to_strip, extensions)) |
| 135 |
|
| 136 |
# If we grafted packages with identities we add an SBOM to the wheel. |
| 137 |
# We recalculate the checksum at this point because there can be |
| 138 |
# modifications to libraries during patching. |
| 139 |
sbom_data = create_sbom_for_wheel( |
| 140 |
wheel_fname=output_wheel.name, |
| 141 |
sbom_filepaths=sbom_filepaths, |
| 142 |
) |
| 143 |
if sbom_data: |
| 144 |
sbom_dir = Path(dist_info_dirs[0], "sboms") |
| 145 |
sbom_dir.mkdir(exist_ok=True) |
| 146 |
(sbom_dir / "auditwheel.cdx.json").write_text(json.dumps(sbom_data)) |
| 147 |
|
| 148 |
return output_wheel |
| 149 |
|
| 150 |
|
| 151 |
def strip_symbols(libraries: Iterable[Path]) -> None: |
| 152 |
for lib in libraries: |
| 153 |
logger.info("Stripping symbols from %s", lib) |
| 154 |
check_call(["strip", "-s", lib]) |
| 155 |
|
| 156 |
|
| 157 |
def copylib(src_path: Path, dest_dir: Path, patcher: ElfPatcher) -> tuple[str, Path]: |
| 158 |
"""Graft a shared library from the system into the wheel and update the |
| 159 |
relevant links. |
| 160 |
|
| 161 |
1) Copy the file from src_path to dest_dir/ |
| 162 |
2) Rename the shared object from soname to soname.<unique> |
| 163 |
""" |
| 164 |
# Copy the a shared library from the system (src_path) into the wheel |
| 165 |
|
| 166 |
with src_path.open("rb") as f: |
| 167 |
shorthash = hashfile(f)[:8] |
| 168 |
|
| 169 |
src_name = src_path.name |
| 170 |
base, ext = src_name.split(".", 1) |
| 171 |
new_soname = f"{base}-{shorthash}.{ext}" if not base.endswith(f"-{shorthash}") else src_name |
| 172 |
|
| 173 |
dest_path = dest_dir / new_soname |
| 174 |
if dest_path.exists(): |
| 175 |
return new_soname, dest_path |
| 176 |
|
| 177 |
logger.debug("Grafting: %s -> %s", src_path, dest_path) |
| 178 |
shutil.copy2(src_path, dest_path) |
| 179 |
statinfo = dest_path.stat() |
| 180 |
if not statinfo.st_mode & stat.S_IWRITE: |
| 181 |
dest_path.chmod(statinfo.st_mode | stat.S_IWRITE) |
| 182 |
|
| 183 |
patcher.set_soname(dest_path, new_soname) |
| 184 |
|
| 185 |
return new_soname, dest_path |
| 186 |
|
| 187 |
|
| 188 |
def append_rpath_within_wheel( |
| 189 |
lib_name: Path, |
| 190 |
rpath: str, |
| 191 |
wheel_base_dir: Path, |
| 192 |
patcher: ElfPatcher, |
| 193 |
) -> None: |
| 194 |
"""Add a new rpath entry to a file while preserving as many existing |
| 195 |
rpath entries as possible. |
| 196 |
|
| 197 |
In order to preserve an rpath entry it must: |
| 198 |
|
| 199 |
1) Point to a location within wheel_base_dir. |
| 200 |
2) Not be a duplicate of an already-existing rpath entry. |
| 201 |
""" |
| 202 |
if not lib_name.is_absolute(): |
| 203 |
lib_name = lib_name.absolute() |
| 204 |
lib_dir = lib_name.parent |
| 205 |
if not wheel_base_dir.is_absolute(): |
| 206 |
wheel_base_dir = wheel_base_dir.absolute() |
| 207 |
|
| 208 |
def is_valid_rpath(rpath: str) -> bool: |
| 209 |
return _is_valid_rpath(rpath, lib_dir, wheel_base_dir) |
| 210 |
|
| 211 |
old_rpaths = patcher.get_rpath(lib_name) |
| 212 |
rpaths = list(filter(is_valid_rpath, old_rpaths.split(":"))) |
| 213 |
rpaths = unique_by_index([*rpaths, rpath]) |
| 214 |
patcher.set_rpath(lib_name, ":".join(rpaths)) |
| 215 |
|
| 216 |
|
| 217 |
def _is_valid_rpath(rpath: str, lib_dir: Path, wheel_base_dir: Path) -> bool: |
| 218 |
full_rpath_entry = _resolve_rpath_tokens(rpath, lib_dir) |
| 219 |
if not Path(full_rpath_entry).is_absolute(): |
| 220 |
logger.debug( |
| 221 |
"rpath entry %s could not be resolved to an absolute path -- discarding it.", |
| 222 |
rpath, |
| 223 |
) |
| 224 |
return False |
| 225 |
if not is_subdir(full_rpath_entry, wheel_base_dir): |
| 226 |
logger.debug("rpath entry %s points outside the wheel -- discarding it.", rpath) |
| 227 |
return False |
| 228 |
logger.debug("Preserved rpath entry %s", rpath) |
| 229 |
return True |
| 230 |
|
| 231 |
|
| 232 |
def _resolve_rpath_tokens(rpath: str, lib_base_dir: Path) -> str: |
| 233 |
# See https://www.man7.org/linux/man-pages/man8/ld.so.8.html#DESCRIPTION |
| 234 |
system_lib_dir = "lib64" if platform.architecture()[0] == "64bit" else "lib" |
| 235 |
system_processor_type = platform.machine() |
| 236 |
token_replacements = { |
| 237 |
"ORIGIN": str(lib_base_dir), |
| 238 |
"LIB": system_lib_dir, |
| 239 |
"PLATFORM": system_processor_type, |
| 240 |
} |
| 241 |
for token, target in token_replacements.items(): |
| 242 |
rpath = rpath.replace(f"${token}", target) # $TOKEN |
| 243 |
rpath = rpath.replace(f"${{{token}}}", target) # ${TOKEN} |
| 244 |
return rpath |
| 245 |
|
| 246 |
|
| 247 |
def _path_is_script(path: Path) -> bool: |
| 248 |
# Looks something like "uWSGI-2.0.21.data/scripts/uwsgi" |
| 249 |
components = path.parts |
| 250 |
return len(components) == 3 and components[0].endswith(".data") and components[1] == "scripts" |
| 251 |
|
| 252 |
|
| 253 |
def _replace_elf_script_with_shim(package_name: str, orig_path: Path) -> Path: |
| 254 |
"""Move an ELF script and replace it with a shim. |
| 255 |
|
| 256 |
We can't directly rewrite the RPATH of ELF executables in the "scripts" |
| 257 |
directory since scripts aren't installed to a consistent relative path to |
| 258 |
platlib files. |
| 259 |
|
| 260 |
Instead, we move the executable into a special directory in platlib and put |
| 261 |
a shim script in its place which execs the real executable. |
| 262 |
|
| 263 |
More context: https://github.com/pypa/auditwheel/issues/340 |
| 264 |
|
| 265 |
Returns the new path of the moved executable. |
| 266 |
""" |
| 267 |
scripts_dir = Path(f"{package_name}.scripts") |
| 268 |
scripts_dir.mkdir(exist_ok=True) |
| 269 |
|
| 270 |
new_path = scripts_dir / orig_path.name |
| 271 |
orig_path.rename(new_path) |
| 272 |
|
| 273 |
with orig_path.open("w", newline="\n") as f: |
| 274 |
f.write(_script_shim(new_path)) |
| 275 |
orig_path.chmod(new_path.stat().st_mode) |
| 276 |
|
| 277 |
return new_path |
| 278 |
|
| 279 |
|
| 280 |
def _script_shim(binary_path: Path) -> str: |
| 281 |
return f"""\ |
| 282 |
#!python |
| 283 |
import os |
| 284 |
import sys |
| 285 |
import sysconfig |
| 286 |
|
| 287 |
|
| 288 |
if __name__ == "__main__": |
| 289 |
os.execv( |
| 290 |
os.path.join(sysconfig.get_path("platlib"), {binary_path.as_posix()!r}), |
| 291 |
sys.argv, |
| 292 |
) |
| 293 |
""" |