diff --git a/relenv/relocate.py b/relenv/relocate.py index f1c1c05c..655c87dc 100755 --- a/relenv/relocate.py +++ b/relenv/relocate.py @@ -25,8 +25,10 @@ "is_elf", "parse_otool_l", "parse_readelf_d", + "parse_readelf_d_needed", "parse_macho", "parse_rpath", + "read_needed", "handle_macho", "is_in_dir", "handle_elf", @@ -272,6 +274,52 @@ def parse_rpath(path: str | os.PathLike[str]) -> list[str]: return parse_readelf_d(proc.stdout.decode()) +def parse_readelf_d_needed(stdout: str) -> list[str]: + """ + Parse DT_NEEDED entries from ``readelf -d `` output. + + ``readelf -d`` prints every dynamic-section entry; DT_NEEDED rows look + like:: + + 0x0000000000000001 (NEEDED) Shared library: [libssl.so.3] + + The SONAME is in square brackets. This is the architecture-agnostic + equivalent of ``ldd``'s first column, with the critical difference + that ``readelf`` parses ELF metadata directly and works for + cross-compiled binaries where the host dynamic linker would error + out. + + :param stdout: Output of ``readelf -d ``. + :return: List of SONAMEs (strings without brackets) in file order. + """ + needed: list[str] = [] + for line in stdout.splitlines(): + if "NEEDED" not in line: + continue + start = line.find("[") + end = line.find("]", start) + if start == -1 or end == -1 or end <= start + 1: + continue + needed.append(line[start + 1 : end]) + return needed + + +def read_needed(path: str | os.PathLike[str]) -> list[str]: + """ + Run ``readelf -d `` and return the DT_NEEDED SONAMEs. + + Toolchain-aware: :func:`_get_readelf_binary` already prefers the + target toolchain's ``readelf`` when ``RELENV_BUILDENV`` is set, so this + works on ELFs of any architecture. + + :param path: The path to the ELF file. + :return: The SONAMEs the binary depends on, in dynamic-section order. + """ + readelf = _get_readelf_binary() + proc = subprocess.run([readelf, "-d", path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return parse_readelf_d_needed(proc.stdout.decode()) + + def handle_macho( path: str | os.PathLike[str], root_dir: str | os.PathLike[str], @@ -423,43 +471,78 @@ def handle_elf( """ if root is None: root = libs - proc = subprocess.run(["ldd", path], stderr=subprocess.PIPE, stdout=subprocess.PIPE) + # gh-37: the original implementation shelled out to the host ``ldd``, + # which fails on cross-compiled ELFs (the host dynamic linker refuses + # to load a foreign-arch object: either "not a dynamic executable" or + # a non-zero exit with empty stdout). The ensuing "needs_rpath stays + # False -> remove_rpath(path)" silently stripped RPATH from every + # cross-built binary. Use ``readelf -d`` instead: it parses the ELF's + # dynamic section directly, is arch-agnostic, and ``_get_readelf_binary`` + # already prefers the target toolchain's ``readelf`` so even an + # x86_64 host building aarch64 picks up the right tool. + # + # In ``rpath_only`` mode (the default -- what finalize uses) we never + # needed the host linker's path resolution anyway: all we care about + # is whether the binary's DT_NEEDED SONAMEs refer to libraries we + # already laid down under ``libs/``. That's a filesystem-local check + # that works identically for native and cross builds. needs_rpath = False + libs_dir = pathlib.Path(libs) + root_dir = pathlib.Path(root) - for line in proc.stdout.decode().splitlines(): - if line.find("=>") == -1: - log.debug("Skip ldd output line: %s", line) - continue - - lib_name, location_info = [_.strip() for _ in line.split("=>", 1)] - if location_info == "not found": - # It is likely that something was not compiled correctly - log.warning("Unable to find library %s linked from %s", lib_name, path) + for soname in read_needed(path): + if soname in LIBCLIBS: + log.debug("Skipping glibc lib %s", soname) continue - linked_lib = location_info.rsplit(" ", 1)[0].strip() - lib_basename = os.path.basename(linked_lib) - - if lib_name in LIBCLIBS: - log.debug("Skipping glibc lib %s", lib_name) + candidate = libs_dir / soname + if candidate.exists(): + needs_rpath = True + log.info("File already within libs directory: %s", candidate) continue - if is_in_dir(linked_lib, root): + # Fall back to a shallow search of root_dir -- covers the case + # where the needed SONAME lives somewhere under the prefix but + # not directly in libs (e.g. architecture-specific subdirs). + try: + hits = [p for p in root_dir.rglob(soname) if p.is_file()] + except OSError: + hits = [] + if hits: needs_rpath = True - log.info("File already within root directory: %s", linked_lib) + log.info("File already within root directory: %s", hits[0]) continue - relocated_path = os.path.join(libs, lib_basename) - - if os.path.exists(relocated_path): + relocated_path = libs_dir / soname + if relocated_path.exists(): log.debug("Relocated library exists: %s", relocated_path) elif rpath_only: - log.warning("In `rpath_only mode` but %s is not in %s", linked_lib, root) + log.warning("In `rpath_only mode` but %s is not in %s", soname, root) else: - # If we aren't in `rpath_only` mode, we can copy + # Non-rpath_only mode is only used by the ``relenv relocate`` + # CLI on already-installed native onedirs. Cross builds never + # exercise this path (finalize is always rpath_only=True), so + # the host ``ldd`` fallback is retained here for native + # relocation only. + ldd_proc = subprocess.run(["ldd", path], stderr=subprocess.PIPE, stdout=subprocess.PIPE) + linked_lib: str | None = None + for line in ldd_proc.stdout.decode().splitlines(): + if " => " not in line: + continue + name, info = [p.strip() for p in line.split("=>", 1)] + if name != soname or info.startswith("not found"): + continue + linked_lib = info.rsplit(" ", 1)[0].strip() + break + if not linked_lib or not os.path.exists(linked_lib): + log.warning( + "Could not resolve %s on host for copying (cross build?)", + soname, + ) + continue log.info("Copy %s to %s", linked_lib, relocated_path) - shutil.copy(linked_lib, relocated_path) - shutil.copymode(linked_lib, relocated_path) + shutil.copy(linked_lib, str(relocated_path)) + shutil.copymode(linked_lib, str(relocated_path)) needs_rpath = True if needs_rpath: diff --git a/tests/test_relocate.py b/tests/test_relocate.py index 1d597969..5f626598 100644 --- a/tests/test_relocate.py +++ b/tests/test_relocate.py @@ -15,6 +15,7 @@ is_macho, main, parse_readelf_d, + parse_readelf_d_needed, patch_rpath, remove_rpath, ) @@ -156,6 +157,46 @@ def test_parse_readelf_d_rpath() -> None: assert parse_readelf_d(section) == ["$ORIGIN/../.."] +def test_parse_readelf_d_needed() -> None: + """gh-37: DT_NEEDED parsing used to replace host ``ldd`` on cross builds.""" + section = dedent( + """ + Dynamic section at offset 0xbdd40 contains 28 entries: + Tag Type Name/Value + 0x0000000000000001 (NEEDED) Shared library: [libz.so.1] + 0x0000000000000001 (NEEDED) Shared library: [libbz2.so.1] + 0x0000000000000001 (NEEDED) Shared library: [libpng15.so.15] + 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] + 0x000000000000000e (SONAME) Library soname: [libfreetype.so.6] + 0x000000000000000f (RPATH) Library rpath: [$ORIGIN] + """ + ) + assert parse_readelf_d_needed(section) == [ + "libz.so.1", + "libbz2.so.1", + "libpng15.so.15", + "libc.so.6", + ] + + +def test_parse_readelf_d_needed_empty() -> None: + section = dedent( + """ + Dynamic section at offset 0x58000 contains 3 entries: + Tag Type Name/Value + 0x000000000000000e (SONAME) Library soname: [libfoo.so.1] + 0x000000000000000c (INIT) 0x51f8 + """ + ) + assert parse_readelf_d_needed(section) == [] + + +def test_parse_readelf_d_needed_malformed() -> None: + # Lines with "NEEDED" but no bracket pair must not explode. + section = "0x0000000000000001 (NEEDED) Shared library: broken\n" + assert parse_readelf_d_needed(section) == [] + + def test_is_in_dir(tmp_path: pathlib.Path) -> None: parent = tmp_path / "foo" child = tmp_path / "foo" / "bar" / "bang" @@ -231,43 +272,47 @@ def test_handle_elf(tmp_path: pathlib.Path) -> None: libcrypt = tmp_path / "libcrypt.so.2" libcrypt.touch() + needed = ["libcrypt.so.2", "libm.so.6", "libc.so.6"] + # Non-rpath_only mode falls back to host ``ldd`` to resolve + # not-yet-bundled SONAMEs for copying. Provide that resolution via a + # mocked subprocess.run keyed on argv[0]. ldd_ret = f""" - linux-vdso.so.1 => linux-vdso.so.1 (0x0123456789) libcrypt.so.2 => {libcrypt} (0x0123456789) libm.so.6 => /usr/lib/libm.so.6 (0x0123456789) libc.so.6 => /usr/lib/libc.so.6 (0x0123456789) """.encode() + def fake_run(argv: Any, **_kwargs: Any) -> MagicMock: + if argv and str(argv[0]).endswith("ldd"): + return MagicMock(stdout=ldd_ret) + return MagicMock(stdout=b"") + with proj: - with patch("subprocess.run", return_value=MagicMock(stdout=ldd_ret)): - with patch("relenv.relocate.patch_rpath") as patch_rpath_mock: - handle_elf(str(pybin), str(proj.libs_dir), False, str(proj.root_dir)) - assert not (proj.libs_dir / "linux-vdso.so.1").exists() - assert (proj.libs_dir / "libcrypt.so.2").exists() - assert not (proj.libs_dir / "libm.so.6").exists() - assert not (proj.libs_dir / "libc.so.6").exists() - assert patch_rpath_mock.call_count == 1 - patch_rpath_mock.assert_called_with(str(pybin), "$ORIGIN/../lib") + with patch("relenv.relocate.read_needed", return_value=needed): + with patch("subprocess.run", side_effect=fake_run): + with patch("relenv.relocate.patch_rpath") as patch_rpath_mock: + handle_elf(str(pybin), str(proj.libs_dir), False, str(proj.root_dir)) + assert (proj.libs_dir / "libcrypt.so.2").exists() + assert not (proj.libs_dir / "libm.so.6").exists() + assert not (proj.libs_dir / "libc.so.6").exists() + assert patch_rpath_mock.call_count == 1 + patch_rpath_mock.assert_called_with(str(pybin), "$ORIGIN/../lib") def test_handle_elf_rpath_only(tmp_path: pathlib.Path) -> None: proj = LinuxProject(tmp_path / "proj") pybin = proj.add_simple_elf("python", "foo") libcrypt = proj.libs_dir / "libcrypt.so.2" - fake = tmp_path / "fake.so.2" - fake.touch() - ldd_ret = f""" - linux-vdso.so.1 => linux-vdso.so.1 (0x0123456789) - libcrypt.so.2 => {libcrypt} (0x0123456789) - fake.so.2 => {fake} (0x0123456789) - libm.so.6 => /usr/lib/libm.so.6 (0x0123456789) - libc.so.6 => /usr/lib/libc.so.6 (0x0123456789) - """.encode() + # rpath_only=True: ``handle_elf`` only cares about DT_NEEDED entries + # that resolve to files already present under ``libs``. ``fake.so.2`` + # is in the NEEDED list but not under libs, so it should log a warning + # and be skipped (no copy, no rpath contribution from it alone). + needed = ["libcrypt.so.2", "fake.so.2", "libm.so.6", "libc.so.6"] with proj: libcrypt.touch() - with patch("subprocess.run", return_value=MagicMock(stdout=ldd_ret)): + with patch("relenv.relocate.read_needed", return_value=needed): with patch("relenv.relocate.patch_rpath") as patch_rpath_mock: handle_elf(str(pybin), str(proj.libs_dir), True, str(proj.root_dir)) assert not (proj.libs_dir / "fake.so.2").exists() @@ -309,15 +354,11 @@ def test_handle_elf_removes_rpath_when_no_relenv_libs(tmp_path: pathlib.Path) -> proj = LinuxProject(tmp_path / "proj") module = proj.add_simple_elf("array.so", "lib", "python3.10", "lib-dynload") - # ldd output showing only system libraries - ldd_ret = b""" - linux-vdso.so.1 => linux-vdso.so.1 (0x0123456789) - libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x0123456789) - libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x0123456789) - """ + # DT_NEEDED entries referring only to the LIBCLIBS allow-list (glibc) + needed = ["libpthread.so.0", "libc.so.6"] with proj: - with patch("subprocess.run", return_value=MagicMock(stdout=ldd_ret)): + with patch("relenv.relocate.read_needed", return_value=needed): with patch("relenv.relocate.remove_rpath") as remove_rpath_mock: with patch("relenv.relocate.patch_rpath") as patch_rpath_mock: handle_elf(str(module), str(proj.libs_dir), True, str(proj.root_dir)) @@ -334,16 +375,10 @@ def test_handle_elf_sets_rpath_when_relenv_libs_present(tmp_path: pathlib.Path) libssl = proj.libs_dir / "libssl.so.3" libssl.touch() - # ldd output showing relenv-built library - ldd_ret = f""" - linux-vdso.so.1 => linux-vdso.so.1 (0x0123456789) - libssl.so.3 => {libssl} (0x0123456789) - libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x0123456789) - libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x0123456789) - """.encode() + needed = ["libssl.so.3", "libpthread.so.0", "libc.so.6"] with proj: - with patch("subprocess.run", return_value=MagicMock(stdout=ldd_ret)): + with patch("relenv.relocate.read_needed", return_value=needed): with patch("relenv.relocate.remove_rpath") as remove_rpath_mock: with patch("relenv.relocate.patch_rpath") as patch_rpath_mock: handle_elf(str(module), str(proj.libs_dir), True, str(proj.root_dir)) @@ -351,3 +386,42 @@ def test_handle_elf_sets_rpath_when_relenv_libs_present(tmp_path: pathlib.Path) assert patch_rpath_mock.call_count == 1 assert remove_rpath_mock.call_count == 0 patch_rpath_mock.assert_called_with(str(module), "$ORIGIN/../..") + + +def test_handle_elf_keeps_rpath_on_cross_build(tmp_path: pathlib.Path) -> None: + """ + gh-37: on a cross-build the host ``ldd`` cannot read a foreign-arch + ELF and historically emitted empty output -- which drove + ``handle_elf`` down the "no relenv libs linked -> remove_rpath" path + for every single cross-built binary. With the ``readelf -d`` DT_NEEDED + rewrite, ``handle_elf`` consults ELF metadata directly (arch-agnostic) + and correctly sees the bundled ``libssl`` dependency, so RPATH is + preserved instead of stripped. + """ + proj = LinuxProject(tmp_path / "proj") + module = proj.add_simple_elf("_ssl.so", "lib", "python3.10", "lib-dynload") + libssl = proj.libs_dir / "libssl.so.3" + libssl.touch() + + needed = ["libssl.so.3", "libpthread.so.0", "libc.so.6"] + + # Simulate the exact cross-compile failure mode: host ``ldd`` exits + # non-zero with empty stdout because the ELF is a foreign arch. Any + # subprocess.run call (there shouldn't be one for rpath_only=True, + # since read_needed is mocked) returns the broken ldd result -- if + # ``handle_elf`` were still consulting ldd we'd see it fall through to + # remove_rpath. + broken_ldd_ret = MagicMock(stdout=b"", returncode=1) + + with proj: + with patch("relenv.relocate.read_needed", return_value=needed): + with patch("subprocess.run", return_value=broken_ldd_ret): + with patch("relenv.relocate.remove_rpath") as remove_rpath_mock: + with patch("relenv.relocate.patch_rpath") as patch_rpath_mock: + handle_elf(str(module), str(proj.libs_dir), True, str(proj.root_dir)) + assert patch_rpath_mock.call_count == 1, ( + "gh-37: cross-built binary with bundled DT_NEEDED " + "should get its RPATH patched, not removed." + ) + assert remove_rpath_mock.call_count == 0 + patch_rpath_mock.assert_called_with(str(module), "$ORIGIN/../..") diff --git a/tests/test_relocate_module.py b/tests/test_relocate_module.py index 56a5dbac..75c83ccc 100644 --- a/tests/test_relocate_module.py +++ b/tests/test_relocate_module.py @@ -101,13 +101,11 @@ def test_handle_elf_sets_rpath(monkeypatch: pytest.MonkeyPatch, tmp_path: pathli resident = lib_dir / "libfoo.so" resident.write_text("library") - def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]: - if cmd[0] == "ldd": - stdout = f"libfoo.so => {resident} (0x00007)\nlibc.so.6 => /lib/libc.so.6 (0x00007)\n" - return subprocess.CompletedProcess(cmd, 0, stdout=stdout.encode(), stderr=b"") - raise AssertionError(f"Unexpected command {cmd}") - - monkeypatch.setattr(relocate.subprocess, "run", fake_run) + # gh-37: handle_elf no longer shells out to the host ``ldd`` for the + # rpath-only path; it calls ``read_needed`` which runs ``readelf -d`` + # on the ELF. Stub that out so this unit test doesn't need a real + # cross-compiled binary. + monkeypatch.setattr(relocate, "read_needed", lambda path: ["libfoo.so", "libc.so.6"]) captured: dict[str, str] = {}