From 912862fdd05fb5ddec84cbe0b38d6e79362cfd2e Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Tue, 17 Nov 2026 09:53:58 -0800 Subject: [PATCH 1/2] Split the install-time fix-up out of `gather` into fixup.py `gather --patch` and `--origin` replaced the placeholder prefix at build time, standing in for what an installer would do, and rewrote binaries to do it. Make the two steps explicit. `gather` now leaves the placeholder in, so the tree isn't tied to a location. `fixup.py` replaces it once the tree is where it will live: in text files only, so binaries and their signatures stay as built. It runs on any Python 3.12+ other than the one in the tree, lists the binaries that still contain the placeholder, and fails if no text file has it, so it can't be run twice. The build-time half of `--origin` is now `gather --relative-rpath`. `test` gathers, moves the tree and runs `fixup.py` before checking it; `--no-fixup` skips that step and `--relative-rpath` is passed on to `gather`. Co-Authored-By: Claude Fable 5.2 --- README.md | 23 +++++--- fixup.py | 89 +++++++++++++++++++++++++++++ relocatable.py | 150 +++++++++++++++++-------------------------------- 3 files changed, 155 insertions(+), 107 deletions(-) create mode 100644 fixup.py diff --git a/README.md b/README.md index d6f0cc6..40d30b6 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ It's broken up into subcommands to configure, make, gather, and test a relocatab ```shell ../prebuilt-cpython/relocatable.py configure ../prebuilt-cpython/relocatable.py make -../prebuilt-cpython/relocatable.py gather +../prebuilt-cpython/relocatable.py gather ../prebuilt-cpython/relocatable.py test ``` @@ -45,16 +45,21 @@ Some stdlib extension modules need third-party libraries that macOS doesn't prov `deps` downloads each source archive from [cpython-source-deps](https://github.com/python/cpython-source-deps), checks it, and installs only static libraries into deps/install, so the extension modules don't link against anything outside the installation. OpenSSL still has compiled-in paths for its configuration and modules under deps/install. Use `--deps-dir DIR` to put them somewhere else. -The key thing to note is which patching approach to specify with `relocatable.py gather`. There are: +`configure` uses a placeholder `--prefix`. `gather` runs CPython's top-level `make install ENSUREPIP=no` into a staging `DESTDIR` and moves the installed prefix into place, so the gathered tree contains everything a normal install provides (such as `build-details.json` and the unversioned `python3` links). The tree still has the placeholder in it, so it isn't tied to a location and can be packed up as is. -- `--patch` which rewrites all found paths of the placeholder `--prefix` argument to the target install directory (which defaults to dist/); this is meant to follow the approach used by conda. -- `--origin` which uses `patchelf` to do a more targeted path rewrite upfront and then to patch any remaining paths; this is meant to follow the approach used by python-build-standalone. +Replacing the placeholder is a separate step, done at install time. Once the tree is where it will live, run `fixup.py` on it with any Python 3.12+ other than the one in the tree: -Either way, `gather` runs CPython's top-level `make install ENSUREPIP=no` into a staging `DESTDIR` and moves the installed prefix into place, so the gathered tree contains everything a normal install provides (such as `build-details.json` and the unversioned `python3` links). Only the placeholder prefix is rewritten, and patched Mach-O files are re-signed ad hoc, since macOS refuses to run binaries whose code signature no longer matches. +```shell +python3 ../prebuilt-cpython/fixup.py dist/ +``` + +`fixup.py` replaces the placeholder with the tree's location in text files only and lists the binary files that still contain it. It never modifies a binary, so signatures stay valid. It fails if no text file in the tree has the placeholder, which is the case for a tree it has already been run on. + +`gather --relative-rpath` also uses `patchelf` to give the installed ELF files an `$ORIGIN`-relative RPATH, so they load libraries from inside the tree wherever it ends up; this follows what python-build-standalone does at build time. It's Linux only. ### Testing a relocated build -`relocatable.py test` checks whether a build still works after it has been moved. It gathers the build into a temporary directory (dist/ is left alone), renames that directory to a path of a different length with spaces in it, and runs these checks without patching anything again: +`relocatable.py test` checks whether a build still works after it has been moved. It gathers the build into a temporary directory (dist/ is left alone), renames that directory to a path of a different length with spaces in it, runs `fixup.py` on it, and runs these checks: - The interpreter starts - `sys` and `sysconfig` paths point inside the moved tree @@ -74,11 +79,11 @@ Each check prints `PASS`, `FAIL`, or `SKIP` (in color on a terminal, unless `NO_ ../prebuilt-cpython/relocatable.py test ``` -Use `--strategy origin` to gather with `--origin` (the default is `--patch`), `--full` to also run `python -m test --fast-ci`, `--work-dir DIR` to keep the temporary files (including `gather.log`, the `make install` output), and `--format json` for JSON output. +Use `--relative-rpath` to gather with `--relative-rpath`, `--no-fixup` to check the moved tree without running `fixup.py` (what a build that needs no install-time step would have to pass), `--full` to also run `python -m test --fast-ci`, `--work-dir DIR` to keep the temporary files (including `gather.log`, the `make install` output), and `--format json` for JSON output. -The Relocatability GitHub Actions workflow runs `test` with both strategies against CPython `main` on Linux and macOS, daily and for each pull request. Each run's summary lists the results, and the JSON is attached to the run. +The Relocatability GitHub Actions workflow runs `test` in each of those modes against CPython `main` on Linux and macOS, daily and for each pull request. Each run's summary lists the results, and the JSON is attached to the run. -If the build wasn't configured by `relocatable.py configure`, its `--prefix` is left alone and treated as the old location. If that directory still exists, the `distribution.isolation` check fails, because the moved build might be using files from it without anyone noticing. +If the build wasn't configured by `relocatable.py configure`, `fixup.py` isn't run, and its `--prefix` is treated as the old location. If that directory still exists, the `distribution.isolation` check fails, because the moved build might be using files from it without anyone noticing. ## Project Representatives These are people representing projects that have experience with prebuilt binaries for CPython. diff --git a/fixup.py b/fixup.py new file mode 100644 index 0000000..dcbc4f3 --- /dev/null +++ b/fixup.py @@ -0,0 +1,89 @@ +"""Set the prefix of an unpacked build made by `relocatable.py gather`. + +The build was configured with a placeholder prefix. This script replaces the +placeholder with the tree's actual location in the text files that contain +it. Binary files are never modified. + +Run it once, after unpacking the tree where it is going to live, with any +Python 3.12 or newer other than the one in the tree: + + python3 fixup.py PATH/TO/TREE + +It fails if no text file in the tree has the placeholder, which is the case +for a tree it has already been run on. +""" + +# /// script +# requires-python = ">=3.12" +# /// + +import argparse +import os +import pathlib +import sys + +PLACEHOLDER = "/the/knights/who/say/ni".ljust(255, "i") + + +def fixup(tree: pathlib.Path) -> tuple[list[pathlib.Path], list[pathlib.Path]]: + """Replace the placeholder prefix in the text files of *tree*. + + Return the text files that were rewritten and the binary files that + still contain the placeholder. + """ + tree = tree.resolve(strict=True) + if unsafe := set(os.fspath(tree)) & set("'\"\\\n"): + # The prefix ends up inside Python string literals in _sysconfigdata. + raise ValueError(f"{tree} contains {''.join(sorted(unsafe))!r}") + placeholder = os.fsencode(PLACEHOLDER) + prefix = os.fsencode(tree) + text = {} + binary = [] + for root, _, filenames in tree.walk(): + for filename in filenames: + path = root / filename + if path.is_symlink(): + continue + contents = path.read_bytes() + if placeholder not in contents: + continue + if b"\0" in contents: + binary.append(path) + else: + text[path] = contents + if not text: + raise ValueError( + f"no text file in {tree} has the placeholder prefix; " + "it has already been fixed up or wasn't built by relocatable.py" + ) + for path, contents in text.items(): + path.write_bytes(contents.replace(placeholder, prefix)) + return sorted(text), sorted(binary) + + +def main(args: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.partition("\n")[0]) + parser.add_argument("tree", type=pathlib.Path, help="the unpacked installation") + namespace = parser.parse_args(args) + try: + text, binary = fixup(namespace.tree) + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + tree = namespace.tree.resolve() + print(f"Set the prefix to {tree} in {len(text)} text files:") + for path in text: + print(f" {path.relative_to(tree)}") + if binary: + print(f"Left {len(binary)} binary files that contain the placeholder alone:") + # A .pyc file records where its source was when it was compiled. + if pyc := sum(path.suffix == ".pyc" for path in binary): + print(f" {pyc} .pyc files") + for path in binary: + if path.suffix != ".pyc": + print(f" {path.relative_to(tree)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/relocatable.py b/relocatable.py index c0b3a17..a7e63c4 100644 --- a/relocatable.py +++ b/relocatable.py @@ -24,6 +24,7 @@ import urllib.request from typing import TextIO +from fixup import PLACEHOLDER from relocatability import ( CheckFailed, CheckResult, @@ -35,11 +36,7 @@ ) -# Thin 32/64-bit Mach-O files in either byte order, and universal binaries. -MACHO_MAGIC = { - bytes.fromhex(magic) - for magic in ("feedface", "cefaedfe", "feedfacf", "cffaedfe", "cafebabe") -} +FIXUP_SCRIPT = pathlib.Path(__file__).with_name("fixup.py") @dataclasses.dataclass(frozen=True) @@ -146,7 +143,7 @@ def url(self) -> str: def placeholder_prefix() -> str: """Return the placeholder prefix used when building CPython.""" - return "/the/knights/who/say/ni".ljust(255, "i") + return PLACEHOLDER def configured_prefix(build_dir: pathlib.Path) -> str: @@ -158,40 +155,7 @@ def configured_prefix(build_dir: pathlib.Path) -> str: raise ValueError(f"no prefix found in {makefile}") -def patch_path(output_dir: pathlib.Path, patch: str) -> None: - """Replace placeholder prefixes with an eventual installation path.""" - target = os.fsencode(pathlib.Path(patch).resolve()) - placeholder = os.fsencode(placeholder_prefix()) - if len(target) > len(placeholder): - raise ValueError( - f"resolved patch path is {len(target)} bytes; " - f"the maximum is {len(placeholder)} bytes" - ) - - for root, _, filenames in output_dir.walk(): - for filename in filenames: - path = root / filename - if path.is_symlink(): - continue - contents = path.read_bytes() - if placeholder not in contents: - continue - replacement = target - if b"\0" in contents: - replacement = target.ljust(len(placeholder), b"\0") - path.write_bytes(contents.replace(placeholder, replacement)) - if contents[:4] in MACHO_MAGIC: - # Rewriting a Mach-O file invalidates its (ad-hoc) code - # signature, and arm64 macOS kills processes that load it. - subprocess.run( - ["codesign", "--force", "--sign", "-", path], - check=True, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) - - -def patch_origin(output_dir: pathlib.Path) -> None: +def set_relative_rpath(output_dir: pathlib.Path) -> None: """Make installed ELF files load libraries relative to themselves.""" lib_dir = output_dir / "lib" for root, _, filenames in output_dir.walk(): @@ -318,16 +282,15 @@ def run_gather( source_dir: pathlib.Path, build_dir: pathlib.Path, output_dir: pathlib.Path, - strategy: str, - install_dir: pathlib.Path, + relative_rpath: bool = False, log_file: TextIO | None = None, ) -> None: """Gather all the release files together. The build is installed exactly as configured (into a staging `DESTDIR`) - and the resulting prefix is moved to *output_dir*. Only the placeholder - prefix from `configure` is rewritten; a build configured with any other - prefix keeps it, so the gathered tree is a moved copy of that install. + and the resulting prefix is moved to *output_dir*. The tree keeps the + prefix it was configured with; fixup.py replaces the placeholder + prefix once the tree is where it will live. """ output_dir = output_dir.resolve() if output_dir.exists(): @@ -359,23 +322,23 @@ def run_gather( f"(e.g. a separate --exec-prefix), which cannot be gathered: " f"{leftovers[:5]}" ) - if strategy == "origin": + if relative_rpath: # python-build-standalone also patches CPython's source, rewrites # scripts and metadata, handles Mach-O, and ships shared libpython. # Those are intentionally excluded from this post-build ELF experiment. - patch_origin(output_dir) - patch_path(output_dir, os.fspath(install_dir)) + set_relative_rpath(output_dir) def run_test( source_dir: pathlib.Path, build_dir: pathlib.Path, - strategy: str, + relative_rpath: bool, + run_fixup: bool, work_dir: pathlib.Path | None, output_format: str, full: bool, ) -> int: - """Gather a build, move it, and check that it still works.""" + """Gather a build, move it, run fixup.py, and check that it works.""" def run(workspace: pathlib.Path) -> list[CheckResult]: original_prefix = workspace / "original-prefix" @@ -390,6 +353,7 @@ def run(workspace: pathlib.Path) -> list[CheckResult]: # `make install` prints thousands of lines, which would bury the results. gather_log = workspace / "gather.log" + fixup_output = [] try: prefix = configured_prefix(build_dir) with gather_log.open("w", encoding="utf-8") as log_file: @@ -397,13 +361,25 @@ def run(workspace: pathlib.Path) -> list[CheckResult]: source_dir, build_dir, original_prefix, - strategy, - original_prefix, + relative_rpath, log_file, ) original_prefix.rename(relocated_prefix) + # fixup.py only knows the placeholder prefix. + with_fixup = run_fixup and prefix == placeholder_prefix() + if with_fixup: + # Run it the way a user would, with a Python that isn't the + # one in the tree. + fixup_output = subprocess.run( + [sys.executable, FIXUP_SCRIPT, relocated_prefix], + check=True, + capture_output=True, + text=True, + ).stdout.splitlines() except (OSError, ValueError, subprocess.CalledProcessError) as exc: details = [] + if stderr := getattr(exc, "stderr", None): + details.append(stderr.strip()) if gather_log.exists(): lines = gather_log.read_text(errors="replace").splitlines() if lines: @@ -418,18 +394,21 @@ def run(workspace: pathlib.Path) -> list[CheckResult]: ) ] - if prefix == placeholder_prefix(): + if with_fixup: stale_prefix = None - summary = "gathered the installation and moved it without repatching" + summary = "gathered the installation, moved it and ran fixup.py" + elif prefix == placeholder_prefix(): + stale_prefix = None + summary = "gathered the installation and moved it without running fixup.py" else: # A build we didn't configure keeps its --prefix, so that's the # old location to look for. stale_prefix = pathlib.PurePosixPath(prefix) summary = ( f"installed the build configured for {prefix} " - "and moved it without patching" + "and moved it without running fixup.py" ) - results = [CheckResult("distribution.move", "PASS", summary)] + results = [CheckResult("distribution.move", "PASS", summary, fixup_output)] if stale_prefix is not None and os.path.lexists(stale_prefix): # The moved build could load libpython or the stdlib from the # old prefix and every other check would still pass. @@ -511,29 +490,26 @@ def parse_args(args: list[str] | None = None) -> argparse.Namespace: type=pathlib.Path, help="distribution directory (default: SOURCE_DIR/dist)", ) - patch_group = gather_parser.add_mutually_exclusive_group(required=True) - patch_group.add_argument( - "--patch", - nargs="?", - const=None, - default=argparse.SUPPRESS, - type=pathlib.Path, - metavar="INSTALL_DIR", - help=( - "patch in the eventual install directory (default: OUTPUT); " - "relative paths resolve from the current directory" - ), + relative_rpath_help = ( + "set an $ORIGIN-relative RPATH on the installed ELF files, so they " + "load libraries from inside the tree (Linux only; requires patchelf)" + ) + gather_parser.add_argument( + "--relative-rpath", action="store_true", help=relative_rpath_help ) test_parser = subparsers.add_parser( "test", parents=[common_parser], - help="Gather a build, move it, and check that it still works", + help="Gather a build, move it, run fixup.py, and check that it works", ) test_parser.add_argument( - "--strategy", - choices=("patch", "origin"), - default="patch", - help="gather strategy (default: patch)", + "--relative-rpath", action="store_true", help=relative_rpath_help + ) + test_parser.add_argument( + "--no-fixup", + dest="run_fixup", + action="store_false", + help="don't run fixup.py on the moved tree", ) test_parser.add_argument( "--work-dir", @@ -552,18 +528,6 @@ def parse_args(args: list[str] | None = None) -> argparse.Namespace: action="store_true", help="also run `python -m test --fast-ci` from the relocated tree", ) - patch_group.add_argument( - "--origin", - nargs="?", - const=None, - default=argparse.SUPPRESS, - type=pathlib.Path, - metavar="INSTALL_DIR", - help=( - "patch in the eventual install directory and use $ORIGIN for ELF " - "library lookup (default: OUTPUT; Linux only; requires patchelf)" - ), - ) namespace = parser.parse_args(args) if namespace.build_dir is None: namespace.build_dir = namespace.source_dir / "builddir" @@ -571,16 +535,6 @@ def parse_args(args: list[str] | None = None) -> argparse.Namespace: namespace.deps_dir = namespace.source_dir / "deps" if namespace.command == "gather" and namespace.output_dir is None: namespace.output_dir = namespace.source_dir / "dist" - if namespace.command == "gather": - if hasattr(namespace, "patch"): - namespace.patch_strategy = "patch" - install_dir = namespace.patch - else: - namespace.patch_strategy = "origin" - install_dir = namespace.origin - if install_dir is None: - install_dir = namespace.output_dir - namespace.install_dir = install_dir return namespace @@ -601,15 +555,15 @@ def main(args: list[str] | None = None) -> int: namespace.source_dir, namespace.build_dir, namespace.output_dir, - namespace.patch_strategy, - namespace.install_dir, + namespace.relative_rpath, ) return 0 case "test": return run_test( namespace.source_dir, namespace.build_dir, - namespace.strategy, + namespace.relative_rpath, + namespace.run_fixup, namespace.work_dir, namespace.output_format, namespace.full, From d8fb3c0869a0ed0d372176e9b807ce17c7ac4a47 Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Tue, 17 Nov 2026 09:53:58 -0800 Subject: [PATCH 2/2] Update the workflows for `gather` and `test` without strategies Run `test`, `test --no-fixup` and, on Linux, `test --relative-rpath`, with a summary table for each. The Build artifacts workflow uploaded trees patched for the runner's paths, which were no use anywhere else. Upload one tarball per platform instead, with the gathered tree and `fixup.py`. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/reusable-build.yml | 47 ++++++++++++++-------------- README.md | 7 +++++ 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/.github/workflows/reusable-build.yml b/.github/workflows/reusable-build.yml index 0122f05..001c0dc 100644 --- a/.github/workflows/reusable-build.yml +++ b/.github/workflows/reusable-build.yml @@ -80,14 +80,20 @@ jobs: working-directory: cpython run: python ../prebuilt-cpython/relocatable.py make - - name: Test (patch) + - name: Test working-directory: cpython continue-on-error: true - run: python ../prebuilt-cpython/relocatable.py test --strategy patch --format json > ../results-patch.json - - name: Test (origin) + run: python ../prebuilt-cpython/relocatable.py test --format json > ../results.json + # `--relative-rpath` only changes ELF files. + - name: Test (relative rpath) + if: runner.os == 'Linux' + working-directory: cpython + continue-on-error: true + run: python ../prebuilt-cpython/relocatable.py test --relative-rpath --format json > ../results-relative-rpath.json + - name: Test (no fixup) working-directory: cpython continue-on-error: true - run: python ../prebuilt-cpython/relocatable.py test --strategy origin --format json > ../results-origin.json + run: python ../prebuilt-cpython/relocatable.py test --no-fixup --format json > ../results-no-fixup.json - name: Summarize shell: python @@ -97,11 +103,14 @@ jobs: colours = {"PASS": "🟢", "FAIL": "🔴", "SKIP": "🟡"} lines = [] - for strategy in ("patch", "origin"): + tables = {"test": "results.json", "test --no-fixup": "results-no-fixup.json"} + if os.environ["RUNNER_OS"] == "Linux": + tables["test --relative-rpath"] = "results-relative-rpath.json" + for command, filename in tables.items(): # Fails the job if the harness crashed instead of reporting. - with open(f"results-{strategy}.json") as file: + with open(filename) as file: results = json.load(file) - lines += [f"### `--strategy {strategy}`", "", "| Check | Status | Summary |", "|---|---|---|"] + lines += [f"### `{command}`", "", "| Check | Status | Summary |", "|---|---|---|"] lines += [f"| `{r['name']}` | {colours[r['status']]} {r['status']} | {r['summary']} |" for r in results] lines.append("") with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: @@ -110,31 +119,23 @@ jobs: if: ${{ !cancelled() }} with: name: relocatability-${{ matrix.os }} - path: results-*.json + path: results*.json if-no-files-found: ignore - # `gather --origin` is Linux only. The tarballs keep the symlinks and - # file modes that the artifact zip drops. + # fixup.py goes with the tree. The tarball keeps the symlinks and file + # modes that the artifact zip drops. - name: Gather if: inputs.artifacts working-directory: cpython env: NAME: ${{ steps.commit.outputs.name }} - STRATEGIES: ${{ runner.os == 'Linux' && 'patch origin' || 'patch' }} run: | - for strategy in $STRATEGIES; do - python ../prebuilt-cpython/relocatable.py gather --output "$GITHUB_WORKSPACE/python" "--$strategy" - tar -C "$GITHUB_WORKSPACE" -czf "$GITHUB_WORKSPACE/$NAME-$strategy.tar.gz" python - done + python ../prebuilt-cpython/relocatable.py gather --output "$GITHUB_WORKSPACE/$NAME/python" + cp ../prebuilt-cpython/fixup.py "$GITHUB_WORKSPACE/$NAME/" + tar -C "$GITHUB_WORKSPACE" -czf "$GITHUB_WORKSPACE/$NAME.tar.gz" "$NAME" - uses: actions/upload-artifact@v7 if: inputs.artifacts with: - name: ${{ steps.commit.outputs.name }}-patch - path: ${{ steps.commit.outputs.name }}-patch.tar.gz - if-no-files-found: error - - uses: actions/upload-artifact@v7 - if: inputs.artifacts && runner.os == 'Linux' - with: - name: ${{ steps.commit.outputs.name }}-origin - path: ${{ steps.commit.outputs.name }}-origin.tar.gz + name: ${{ steps.commit.outputs.name }} + path: ${{ steps.commit.outputs.name }}.tar.gz if-no-files-found: error diff --git a/README.md b/README.md index 40d30b6..5ff1bd8 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,13 @@ Use `--relative-rpath` to gather with `--relative-rpath`, `--no-fixup` to check The Relocatability GitHub Actions workflow runs `test` in each of those modes against CPython `main` on Linux and macOS, daily and for each pull request. Each run's summary lists the results, and the JSON is attached to the run. +The Build artifacts workflow is run by hand and also attaches the build to the run: a tarball per platform with the gathered tree in `python/` and `fixup.py` next to it. To try one, unpack it, move `python/` to where it should live, and run `fixup.py` on it: + +```shell +tar -xf cpython---.tar.gz +python3 cpython---/fixup.py cpython---/python +``` + If the build wasn't configured by `relocatable.py configure`, `fixup.py` isn't run, and its `--prefix` is treated as the old location. If that directory still exists, the `distribution.isolation` check fails, because the moved build might be using files from it without anyone noticing. ## Project Representatives