Skip to content

Commit a7e3488

Browse files
itamaroclaude
andauthored
relocatable.py test: check metadata, developer tooling and loader paths (#36)
Check metadata, developer tooling, and loader paths after a move Add the remaining `test` checks: - metadata.build-details: resolve every path in build-details.json as PEP 739 specifies (base_prefix relative to the file, the rest relative to base_prefix) and require it to exist inside the moved tree. - developer.python-config: python-config's --prefix, --exec-prefix, --includes and --ldflags must name the moved tree, not a stale prefix. Its stderr is included on failure, since the shell python-config used on Linux can fail there and still exit 0. - developer.c-extension: compile a minimal extension with the moved interpreter's LDSHARED, CCSHARED and python-config --includes, then import it. - loader.paths: inspect install names, rpaths, and needed libraries of the interpreter and every .so/.dylib (otool on macOS, readelf on Linux) for paths outside the tree and outside system directories. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3f992f8 commit a7e3488

2 files changed

Lines changed: 286 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ Either way, `gather` runs CPython's top-level `make install ENSUREPIP=no` into a
5454
- A few stdlib extension modules still work (ones that already fail in the build directory are skipped)
5555
- Those paths are still right when Python is run through a symlink
5656
- A venv created from it works
57+
- `build-details.json` and `python-config` give paths inside the moved tree
58+
- A C extension builds against it and imports
59+
- Native files don't link against libraries outside the moved tree
5760

5861
Each check prints `PASS`, `FAIL`, or `SKIP` (in color on a terminal, unless `NO_COLOR` is set). Some checks fail today. That's expected: they show what CPython still needs to fix.
5962

‎relocatability.py‎

Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ class DlInfo(ctypes.Structure):
8888
"path": sys.path,
8989
"config_paths": sysconfig.get_paths(),
9090
"config_vars": {key: sysconfig.get_config_var(key) for key in keys},
91+
"ext_suffix": sysconfig.get_config_var("EXT_SUFFIX"),
92+
"ldshared": sysconfig.get_config_var("LDSHARED"),
93+
"ccshared": sysconfig.get_config_var("CCSHARED"),
9194
}
9295
print(json.dumps(data, sort_keys=True))
9396
"""
@@ -157,6 +160,75 @@ def find_interpreter(root: pathlib.Path) -> pathlib.Path:
157160
return python
158161

159162

163+
def loader_paths(output: str, platform: str) -> list[str]:
164+
"""Return the absolute library paths in `otool` or `readelf` output."""
165+
paths = []
166+
if platform == "darwin":
167+
for line in output.splitlines():
168+
stripped = line.strip()
169+
if not stripped or (line.startswith("/") and stripped.endswith(":")):
170+
continue
171+
if stripped.startswith(("path ", "name ")):
172+
value = stripped.split(None, 1)[1].rsplit(" (offset ", 1)[0]
173+
elif line[:1].isspace():
174+
value = stripped.rsplit(" (", 1)[0]
175+
else:
176+
continue
177+
if value.startswith("/"):
178+
paths.append(value)
179+
elif platform.startswith("linux"):
180+
for line in output.splitlines():
181+
if "(RPATH)" not in line and "(RUNPATH)" not in line:
182+
continue
183+
match = re.search(r"\[([^]]*)\]", line)
184+
if match:
185+
values = match.group(1).split(":")
186+
paths.extend(value for value in values if value.startswith("/"))
187+
return paths
188+
189+
190+
BUILD_DETAILS_PATHS = (
191+
"base_interpreter",
192+
"libpython.dynamic",
193+
"libpython.dynamic_stableabi",
194+
"libpython.static",
195+
"c_api.headers",
196+
"c_api.pkgconfig_path",
197+
)
198+
199+
200+
def build_details_problems(
201+
data: dict[str, Any], directory: pathlib.Path, root: pathlib.Path
202+
) -> list[str]:
203+
"""Return paths in PEP 739 *data* that are outside *root* or missing.
204+
205+
*directory* holds build-details.json. PEP 739 says a relative `base_prefix`
206+
is relative to that directory, and other relative paths are relative to
207+
`base_prefix`.
208+
"""
209+
base_prefix = data.get("base_prefix")
210+
if not isinstance(base_prefix, str):
211+
return [f"base_prefix={base_prefix!r}"]
212+
resolved_base = directory / base_prefix
213+
problems = []
214+
if not path_is_within(resolved_base, root):
215+
problems.append(f"base_prefix={base_prefix!r}")
216+
for key in BUILD_DETAILS_PATHS:
217+
*parents, child = key.split(".")
218+
container = data
219+
for part in parents:
220+
container = container.get(part, {})
221+
value = container.get(child)
222+
if not isinstance(value, str):
223+
continue
224+
resolved = resolved_base / value
225+
if not path_is_within(resolved, root):
226+
problems.append(f"{key}={value!r} is outside the relocated tree")
227+
elif not resolved.exists():
228+
problems.append(f"{key}={value!r} does not exist")
229+
return problems
230+
231+
160232
def find_build_interpreter(build_dir: pathlib.Path) -> pathlib.Path:
161233
"""Return the interpreter built in *build_dir*.
162234
@@ -259,13 +331,17 @@ def run(self) -> list[CheckResult]:
259331
self._check("runtime.paths", self._check_runtime_paths)
260332
self._check("runtime.libpython", self._check_libpython)
261333
self._check("metadata.prefix-leaks", self._check_prefix_leaks)
334+
self._check("metadata.build-details", self._check_build_details)
335+
self._check("developer.python-config", self._check_python_config)
262336
for module in STDLIB_PROBES:
263337
self._check(
264338
f"stdlib.{module}",
265339
lambda module=module: self._check_stdlib(module),
266340
)
267341
self._check("runtime.symlink", self._check_symlink)
268342
self._check("runtime.venv", self._check_venv)
343+
self._check("developer.c-extension", self._check_c_extension)
344+
self._check("loader.paths", self._check_loader_paths)
269345
if self.full:
270346
self._check("stdlib.full-suite", self._check_full_suite)
271347
return self.results
@@ -492,6 +568,78 @@ def _check_prefix_leaks(self) -> str:
492568
)
493569
return f"scanned {files_checked} installed files"
494570

571+
def _check_build_details(self) -> str:
572+
files = list(self.root.rglob("build-details.json"))
573+
if not files:
574+
raise CheckFailed("build-details.json is not installed")
575+
failures: list[str] = []
576+
for path in files:
577+
try:
578+
data = json.loads(path.read_text(encoding="utf-8"))
579+
except (OSError, json.JSONDecodeError) as exc:
580+
failures.append(f"{path}: {exc}")
581+
continue
582+
failures.extend(
583+
f"{path}: {problem}" for problem in build_details_problems(
584+
data, path.parent, self.root
585+
)
586+
)
587+
if failures:
588+
raise CheckFailed(
589+
"build-details.json contains non-relocated paths", failures
590+
)
591+
return f"validated {len(files)} build-details.json file(s)"
592+
593+
def _python_config(self) -> pathlib.Path:
594+
candidates = sorted((self.root / "bin").glob("python*-config"))
595+
if not candidates:
596+
raise CheckFailed("no installed python-config script found")
597+
config = candidates[0]
598+
try:
599+
first_line = config.open(encoding="utf-8").readline().strip()
600+
except (OSError, UnicodeError) as exc:
601+
raise CheckFailed("could not read the installed python-config", [str(exc)])
602+
if first_line.startswith("#!"):
603+
interpreter = first_line[2:].split()[0]
604+
if interpreter.startswith("/") and not pathlib.Path(interpreter).exists():
605+
raise CheckFailed(
606+
"python-config has a stale shebang",
607+
[f"{config}: {first_line}"],
608+
)
609+
return config
610+
611+
def _check_python_config(self) -> str:
612+
config = self._python_config()
613+
outputs = {}
614+
errors = []
615+
for option in (
616+
"--prefix",
617+
"--exec-prefix",
618+
"--includes",
619+
"--ldflags",
620+
"--extension-suffix",
621+
):
622+
completed = self._run([config, option])
623+
self._require_success(completed, f"python-config {option} failed")
624+
outputs[option] = completed.stdout.strip()
625+
if completed.stderr.strip():
626+
errors.append(f"{option} stderr: {completed.stderr.strip()}")
627+
628+
failures = []
629+
for option in ("--prefix", "--exec-prefix"):
630+
if not path_is_within(outputs[option], self.root):
631+
failures.append(f"{option} reports {outputs[option]!r}")
632+
output = "\n".join(outputs.values())
633+
for prefix, label in self._stale_prefixes().items():
634+
if prefix in output:
635+
failures.append(f"output contains the {label}")
636+
if failures:
637+
failures.append(f"output:\n{output}")
638+
# The shell python-config can fail on stderr and still exit 0.
639+
failures.extend(errors)
640+
raise CheckFailed("python-config reports stale paths", failures)
641+
return "python-config reports the relocated prefix"
642+
495643
def _check_stdlib(self, module: str) -> str:
496644
if self.broken_modules is not None and module in self.broken_modules:
497645
raise CheckSkipped(
@@ -546,6 +694,141 @@ def _check_venv(self) -> str:
546694
raise CheckFailed("the venv contains stale paths", failures)
547695
return "a venv created by the relocated interpreter works"
548696

697+
def _check_c_extension(self) -> str:
698+
if self.snapshot is None:
699+
raise CheckSkipped("the startup probe did not complete")
700+
config = self._python_config()
701+
includes = self._run([config, "--includes"])
702+
self._require_success(includes, "python-config --includes failed")
703+
ldshared = self.snapshot.get("ldshared")
704+
ext_suffix = self.snapshot.get("ext_suffix")
705+
if not isinstance(ldshared, str) or not ldshared:
706+
raise CheckFailed("sysconfig did not provide LDSHARED")
707+
if not isinstance(ext_suffix, str) or not ext_suffix:
708+
raise CheckFailed("sysconfig did not provide EXT_SUFFIX")
709+
710+
extension_dir = self.work_dir / "extension"
711+
extension_dir.mkdir(exist_ok=True)
712+
source = extension_dir / "reloc_probe.c"
713+
source.write_text(
714+
"""
715+
#include <Python.h>
716+
717+
static PyObject *
718+
answer(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(ignored))
719+
{
720+
return PyLong_FromLong(42);
721+
}
722+
723+
static PyMethodDef reloc_probe_methods[] = {
724+
{.ml_name = "answer", .ml_meth = answer, .ml_flags = METH_NOARGS},
725+
{NULL, NULL, 0, NULL},
726+
};
727+
728+
static PyModuleDef_Slot reloc_probe_slots[] = {
729+
{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
730+
{Py_mod_gil, Py_MOD_GIL_NOT_USED},
731+
{0, NULL},
732+
};
733+
734+
static struct PyModuleDef reloc_probe_module = {
735+
.m_base = PyModuleDef_HEAD_INIT,
736+
.m_name = "reloc_probe",
737+
.m_size = 0,
738+
.m_methods = reloc_probe_methods,
739+
.m_slots = reloc_probe_slots,
740+
};
741+
742+
PyMODINIT_FUNC
743+
PyInit_reloc_probe(void)
744+
{
745+
return PyModuleDef_Init(&reloc_probe_module);
746+
}
747+
""".lstrip(),
748+
encoding="utf-8",
749+
)
750+
extension = extension_dir / f"reloc_probe{ext_suffix}"
751+
command = [
752+
*shlex.split(ldshared),
753+
# e.g. -fPIC on Linux; LDSHARED doesn't include it.
754+
*shlex.split(self.snapshot.get("ccshared") or ""),
755+
*shlex.split(includes.stdout),
756+
os.fspath(source),
757+
"-o",
758+
os.fspath(extension),
759+
]
760+
completed = self._run(command, cwd=extension_dir)
761+
self._require_success(completed, "compiling a C extension failed")
762+
probe = (
763+
"import os, sys; sys.path.insert(0, os.getcwd()); "
764+
"import reloc_probe; assert reloc_probe.answer() == 42"
765+
)
766+
completed = self._run_python(["-I", "-c", probe], cwd=extension_dir)
767+
self._require_success(completed, "importing the compiled C extension failed")
768+
return "compiled and imported a C extension"
769+
770+
def _binaries(self) -> list[pathlib.Path]:
771+
files = []
772+
if self.python is not None:
773+
files.append(self.python.resolve())
774+
for pattern in ("*.so", "*.dylib"):
775+
files.extend(path for path in self.root.rglob(pattern) if path.is_file())
776+
return sorted(set(files))
777+
778+
def _check_loader_paths(self) -> str:
779+
if sys.platform == "darwin":
780+
tool = shutil.which("otool")
781+
commands = ([tool, "-L"], [tool, "-l"]) if tool else ()
782+
elif sys.platform.startswith("linux"):
783+
tool = shutil.which("readelf")
784+
commands = ([tool, "-d"],) if tool else ()
785+
else:
786+
raise CheckSkipped(
787+
f"loader inspection is not implemented on {sys.platform}"
788+
)
789+
if not commands:
790+
raise CheckSkipped("the platform loader inspection tool is unavailable")
791+
792+
failures: list[str] = []
793+
inspected = []
794+
for path in self._binaries():
795+
outputs = []
796+
for prefix in commands:
797+
completed = self._run([*prefix, path])
798+
if completed.returncode:
799+
continue
800+
outputs.append(completed.stdout)
801+
if not outputs:
802+
continue
803+
inspected.append(path)
804+
output = "\n".join(outputs)
805+
for prefix, label in self._stale_prefixes().items():
806+
if prefix in output:
807+
failures.append(f"{path}: loader metadata contains the {label}")
808+
for value in loader_paths(output, sys.platform):
809+
if path_is_within(value, self.root):
810+
continue
811+
system_prefixes = (
812+
"/lib/",
813+
"/lib64/",
814+
"/usr/lib/",
815+
"/System/Library/",
816+
)
817+
if value.startswith(system_prefixes):
818+
continue
819+
failures.append(f"{path}: loader metadata references {value}")
820+
if failures:
821+
raise CheckFailed(
822+
"loader metadata contains stale paths", failures[:50]
823+
)
824+
if not inspected:
825+
raise CheckSkipped("no binaries could be inspected")
826+
interpreter = self.python.resolve() if self.python is not None else None
827+
libraries = sum(path != interpreter for path in inspected)
828+
if interpreter in inspected:
829+
return f"inspected the interpreter and {libraries} shared libraries"
830+
return f"inspected {libraries} shared libraries"
831+
549832
def _check_full_suite(self) -> str:
550833
completed = self._run_python(
551834
["-I", "-m", "test", "--fast-ci", "--timeout=900"],

0 commit comments

Comments
 (0)