Skip to content

Commit 3f992f8

Browse files
itamaroclaude
andauthored
relocatable.py test: check which libpython the moved interpreter loads (#35)
Check which libpython the moved interpreter actually loads Ask the dynamic loader, via dladdr(), which file Py_Initialize came from: libpython for a shared build, or the executable for a static one. Fail if it's outside the moved tree. This catches a shared build that starts and passes the other checks while loading libpython from its original install, which distribution.isolation can only warn might happen. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f4f1b66 commit 3f992f8

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ Either way, `gather` runs CPython's top-level `make install ENSUREPIP=no` into a
4949

5050
- The interpreter starts
5151
- `sys` and `sysconfig` paths point inside the moved tree
52+
- A shared build loads libpython from inside the moved tree, not from the original install
5253
- No installed file still mentions the old prefix
5354
- A few stdlib extension modules still work (ones that already fail in the build directory are skipped)
5455
- Those paths are still right when Python is run through a symlink

‎relocatability.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,37 @@
3535
STATUS_COLORS = {"PASS": "\033[32m", "FAIL": "\033[31m", "SKIP": "\033[33m"}
3636
RESET_COLOR = "\033[0m"
3737

38+
# Prints the file the C API was loaded from: libpython for a shared build,
39+
# the executable itself for a static one. dladdr() works on Linux and macOS.
40+
LIBPYTHON_PROBE = r"""
41+
import json
42+
import os
43+
44+
try:
45+
import ctypes
46+
except ImportError as exc:
47+
print(json.dumps({"skip": f"ctypes is not available: {exc}"}))
48+
raise SystemExit
49+
50+
51+
class DlInfo(ctypes.Structure):
52+
_fields_ = [
53+
("dli_fname", ctypes.c_char_p),
54+
("dli_fbase", ctypes.c_void_p),
55+
("dli_sname", ctypes.c_char_p),
56+
("dli_saddr", ctypes.c_void_p),
57+
]
58+
59+
60+
dladdr = ctypes.CDLL(None).dladdr
61+
dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(DlInfo)]
62+
info = DlInfo()
63+
address = ctypes.cast(ctypes.pythonapi.Py_Initialize, ctypes.c_void_p)
64+
if not dladdr(address, ctypes.byref(info)) or not info.dli_fname:
65+
raise SystemExit("dladdr() could not find Py_Initialize")
66+
print(json.dumps({"path": os.path.realpath(os.fsdecode(info.dli_fname))}))
67+
"""
68+
3869
# Seconds to wait for each probe.
3970
TIMEOUT = 30
4071

@@ -226,6 +257,7 @@ def run(self) -> list[CheckResult]:
226257
"""Run all the checks and return their results."""
227258
self._check("runtime.startup", self._check_startup)
228259
self._check("runtime.paths", self._check_runtime_paths)
260+
self._check("runtime.libpython", self._check_libpython)
229261
self._check("metadata.prefix-leaks", self._check_prefix_leaks)
230262
for module in STDLIB_PROBES:
231263
self._check(
@@ -386,6 +418,27 @@ def _check_runtime_paths(self) -> str:
386418
)
387419
return "runtime and sysconfig paths resolve inside the relocated tree"
388420

421+
def _check_libpython(self) -> str:
422+
if self.snapshot is None:
423+
raise CheckSkipped("the startup probe did not complete")
424+
completed = self._run_python(["-I", "-c", LIBPYTHON_PROBE])
425+
self._require_success(completed, "the libpython probe failed")
426+
try:
427+
result = json.loads(completed.stdout.strip().splitlines()[-1])
428+
except (IndexError, json.JSONDecodeError) as exc:
429+
raise CheckFailed(
430+
"the libpython probe did not produce valid JSON",
431+
[completed.stdout.rstrip(), completed.stderr.rstrip()],
432+
) from exc
433+
if "skip" in result:
434+
raise CheckSkipped(result["skip"])
435+
if not path_is_within(result["path"], self.root):
436+
raise CheckFailed(
437+
"the C API is loaded from outside the relocated tree",
438+
[result["path"]],
439+
)
440+
return f"the C API is loaded from {result['path']}"
441+
389442
def _check_prefix_leaks(self) -> str:
390443
binary_needles = {
391444
os.fsencode(prefix): label

0 commit comments

Comments
 (0)