Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 24 additions & 23 deletions .github/workflows/reusable-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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
30 changes: 21 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <patching approach>
../prebuilt-cpython/relocatable.py gather
../prebuilt-cpython/relocatable.py test
```

Expand All @@ -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
Expand All @@ -74,11 +79,18 @@ 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.

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-<commit>-<os>-<arch>.tar.gz
python3 cpython-<commit>-<os>-<arch>/fixup.py cpython-<commit>-<os>-<arch>/python
```

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.
Expand Down
89 changes: 89 additions & 0 deletions fixup.py
Original file line number Diff line number Diff line change
@@ -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())
Loading
Loading