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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Changed

- macOS: `isolate-usr-local` defaults to `auto`, which now masks `/usr/local` only when Homebrew is installed there (`/usr/local/bin/brew`), instead of looking for specific headers. Use `isolate-usr-local: none` to turn isolation off

### Fixed

- On macOS with `/opt/homebrew` on `PATH`, removing it from the `PATH` used to compile modules also dropped the folder where already compiled modules install their binaries (`deps/bin`), and the `/usr/bin:/bin` fallback
Expand Down
21 changes: 17 additions & 4 deletions docs/concepts/folder-masking.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
---
type: Concept
title: Folder Masking (macOS)
description: On macOS, /usr/local is temporarily masked with a RAM disk during the build so that CPython's configure cannot accidentally discover and dynamically link Homebrew libraries.
description: On macOS, /usr/local is masked with a RAM disk during the build when Homebrew is installed there, so that the compiler cannot accidentally pick up and dynamically link its libraries.
tags: [macos, folder-mask, concept, isolation]
timestamp: 2026-06-23T00:00:00Z
timestamp: 2026-12-03T00:00:00Z
---

# Folder Masking (macOS)

On macOS, `/usr/local` is historically where Homebrew and other package managers install libraries and headers. If CPython's `configure` discovers those during a build, it may **dynamically link** against them — silently breaking [portability](/concepts/portability.md), because the resulting binary would depend on libraries that won't exist on another machine.
On macOS, Apple's clang looks for headers and libraries in `/usr/local/include` and `/usr/local/lib` by default, which is where Intel Homebrew installs (also used via Rosetta on Apple silicon). If the build picks those up, it may **dynamically link** against them — breaking [portability](/concepts/portability.md), because the resulting binary would depend on libraries that won't exist on another machine. Homebrew on Apple silicon installs in `/opt/homebrew`, which the compiler doesn't look at by default.

## The mask

To prevent this, the build temporarily **masks** `/usr/local` with an empty RAM disk for the duration of the compile. With `/usr/local` appearing empty, `configure` falls back to the statically-compiled libraries in `build/deps/` (see [static linking](/concepts/static-linking.md)) instead of system ones.
To prevent this, the build can temporarily **mask** `/usr/local/{etc,include,lib,opt}` with an empty RAM disk for the duration of the compile. With those appearing empty, `configure` falls back to the statically-compiled libraries in `build/deps/` (see [static linking](/concepts/static-linking.md)) instead of system ones.

This is driven by the `isolate-usr-local` [config](/configuration/portable-python-yml.md) setting:

- `auto` (the default on macOS): use `mount-shadow` only when Homebrew is installed in `/usr/local` (`/usr/local/bin/brew` exists).
- `mount-shadow`: mask as described here. It needs `hdiutil` and `mount` (macOS only), the build aborts on other platforms.
- `gettext-tiny`: no masking, compile a dummy `libintl.h` instead, which takes out the main culprit.
- `none`: no isolation.

Without masking, a build that ends up dynamically linking a library from `/usr/local` is still reported as failed at the end of the build (see [portability](/concepts/portability.md)): masking avoids wasting that build. The mask is global: other processes on the same machine don't see `/usr/local/{etc,include,lib,opt}` while the build runs.

Masking may go away in the future, if no longer needed (Intel Macs are on their way out).

`/opt/homebrew` (Homebrew on Apple silicon) is not masked, it is removed from the `PATH` used to compile modules instead (unless `allow-homebrew` is set).

This is implemented by `FolderMask` and orchestrated by `BuildContext`:

Expand Down
34 changes: 34 additions & 0 deletions docs/configuration/portable-python-yml.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ portable-python is configured via a YAML file — by default `portable-python.ym
| `cpython-compile-all` | bool | Whether to byte-compile the stdlib. |
| `cpython-additional-packages` | list | Extra pip packages to install into the build. |
| `cpython-use-github` | bool | Fetch the available version list from GitHub tags instead of python.org. |
| `cpython-clean` | list | Extra globs removed in the second cleanup pass, along with `cpython-clean-2nd-pass`. |
| `cpython-symlink` | list | Files to ensure exist in the install (default: `bin/python`), symlinked to the matching main file (eg: `bin/python3.14`). |
| `cpython-validate-script` | path | Python script run with the freshly built python before packaging, the build fails if it fails. Relative to the config file that sets it. |
| `cpython-check-venvs` | string | Check that the built python can create a venv: `venv` (default), `copies` (`--copies` venv), `all` (both), or `""` to skip. |
| `cpython-pep668-externally-managed` | map | Mark the install as [externally managed](https://peps.python.org/pep-0668/): its keys are written to `EXTERNALLY-MANAGED` (an `Error` key is required), and `bin/pip*` are removed. |
| `allowed-system-libs` | regex | Opt-in: fail a portable build (no `--prefix`, no `--enable-shared`) if its `.so` files link a system library whose path doesn't match. Also used by `inspect` (unless `--prefix`). |
| `isolate-usr-local` | string | macOS: keep the build from picking up libraries in `/usr/local`: `auto` (default, masks `/usr/local` if Homebrew is installed there), `mount-shadow`, `gettext-tiny` or `none`, see [folder masking](/concepts/folder-masking.md). |
| `env` | map | Extra env vars set while compiling every module (eg: `MACOSX_DEPLOYMENT_TARGET`, `13` by default on macOS). Env vars computed by portable-python itself (eg: `PATH`, `LDFLAGS`) take precedence. |
| `manifest` | map | Files written into the install, see below. |
| `compiled-by` | string | Recorded as `compiled-by` in the build-info manifest (default: portable-python's PyPI URL). The `PP_ORIGIN` env var takes precedence. |
| `include` | path | Layer another config file (a leading `+` puts it in front). |
| `allow-homebrew` | bool | Keep `/opt/homebrew` folders in the `PATH` used to compile modules (removed by default, to reduce the chances of linking against homebrew libraries on macOS). |

Expand Down Expand Up @@ -57,6 +67,18 @@ Replace `{module}` with the lowercased module name (e.g. `openssl`):
| `{module}-patches` | Source patches to apply before compiling. |
| `{module}-debian` | Debian package name for dependency detection. |

The `cpython-clean*` globs can also be given per platform, with a `-{platform}` suffix (eg: `cpython-clean-1st-pass-linux`), applied in addition to the generic ones.

## `manifest`

Files written in the install folder (relative paths), set a key to `""` to not write that file (a key with no value means: use the default).

| Key | Default | Content |
|-----|---------|---------|
| `build-info` | `.manifest.yml` | How the build was done: cpython version and source, selected modules, `./configure` args, compilation info (date, host, `compiled-by`), and `additional-info`. |
| `inspection-report` | `.inspection-report.yml` | Report of the built python's modules and `.so` files (same as the `inspect` command). |
| `additional-info` | | Map of extra info to record in `build-info`, a value of the form `$NAME` is expanded from env var `NAME`. |

## Platform-specific overrides

Sections named for a platform (`linux`, `macos`, `windows`) override generic keys; the most specific match for `PPG.target` wins. `MACOSX_DEPLOYMENT_TARGET` defaults to `13` (Ventura).
Expand All @@ -80,4 +102,16 @@ openssl-http-headers:
# Per-platform configure args
macos:
openssl-configure: --with-terminfo-dirs=/usr/share/terminfo

manifest:
additional-info:
support: [email protected]
build-url: $BUILD_URL

cpython-validate-script: validate.py # Next to this config file
cpython-pep668-externally-managed:
Error: Global pip installations are not allowed, please use a virtual environment.

linux:
allowed-system-libs: "(/usr)?/lib/.*"
```
3 changes: 3 additions & 0 deletions docs/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## 2026-12-03

* **Update**: [Folder masking](/concepts/folder-masking.md): `isolate-usr-local` defaults to `auto` on macOS, which masks `/usr/local` only when Homebrew is installed there, and `none` turns isolation off.
* **Update**: [Configuration](/configuration/portable-python-yml.md): documented the remaining config keys (`cpython-clean`, `cpython-symlink`, `cpython-validate-script`, `cpython-check-venvs`, `cpython-pep668-externally-managed`, `allowed-system-libs`, `isolate-usr-local`, `env`, `manifest`, `compiled-by`) and the `-{platform}` suffix of the cleanup globs.
* **Update**: [Folder masking](/concepts/folder-masking.md): masking is opt-in via `isolate-usr-local`, and covers `/usr/local/{etc,include,lib,opt}`.
* **Update**: [Configuration](/configuration/portable-python-yml.md): documented `allow-homebrew`.
* **Update**: [Cpython](/architecture/cpython.md): `sysconfig` refers to the C++ compiler by name rather than by its build host path, and compiler wrappers recorded in `sysconfig` are reported with a warning.

Expand Down
30 changes: 13 additions & 17 deletions src/portable_python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,13 @@ def correct_permissions(path: pathlib.Path, expected: int, dryrun: runez.DryrunS

class FolderMask:
"""
Unfortunately, python source ./configure and setup.py looks at /usr/local/... we DON'T want that for a portable build
as that implies machine where our binary would run must also have the /usr/local/... stuff
TODO: find a less hacky way of doing this, or contribute an upstream option to stop looking at /usr/local/
On macos, Apple's clang looks for headers and libraries in /usr/local/include and /usr/local/lib by default,
a portable build must not pick up libraries from there (the machine where it runs would need them as well).
This is where Intel homebrew installs (/opt/homebrew, used on Apple silicon, is not looked at by default).

On macos, we temporarily mask /usr/local with an empty RAM disk mount...
We temporarily mask /usr/local/{etc,include,lib,opt} with an empty RAM disk mount...
This is unfortunately global, and will temporarily mask /usr/local for other workers on the same macos box as well
This may go away in the future, if no longer needed (Intel macs are on their way out).
"""

def __init__(self, target_folder):
Expand Down Expand Up @@ -149,22 +150,17 @@ def _resolved_isolation(self):
Returns
-------
str | None
What strategy to use to work around the fact that python's ./configure script looks at /usr/local
What strategy to use to work around the fact that the compiler looks at /usr/local on macos
"""
v = PPG.config.get_value("isolate-usr-local")
if v == "none":
return None

if v == "auto":
v = None
folder = os.path.join(self.usr_local, "include")
if PPG.target.is_macos and os.path.isdir(folder):
fnames = ["libintl.h"]
if self.setup.python_builder.active_module("gdbm"):
fnames.append("dbm.h")
fnames.append("gdbm.h")

for fname in fnames:
fpath = os.path.join(folder, fname)
if os.path.exists(fpath):
return "mount-shadow"
# A homebrew installation in /usr/local (Intel, or Rosetta on Apple silicon) means lots of libraries there
# Otherwise, any dynamic link to a library in /usr/local still gets reported as a build failure at the end
brew = os.path.join(self.usr_local, "bin", "brew")
return "mount-shadow" if PPG.target.is_macos and os.path.exists(brew) else None

return v

Expand Down
1 change: 1 addition & 0 deletions src/portable_python/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
macos:
env:
MACOSX_DEPLOYMENT_TARGET: 13 # Ventura, released June 2022
isolate-usr-local: auto # Mask /usr/local only if homebrew is installed there
"""


Expand Down
15 changes: 15 additions & 0 deletions tests/test_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,18 @@ def test_cleanup(cli, monkeypatch):
assert "mount failed" in cli.logged
assert f"Cleaning up isolation hack/mask for {os.getcwd()}/etc" in cli.logged
assert f"Cleaning up isolation hack/mask for {os.getcwd()}/include" in cli.logged

# 'auto' (the default on macos) masks /usr/local only when homebrew is installed there
cli.run("-ntmacos-arm64", "build", f.version)
assert cli.succeeded
assert "isolate-usr-local: mount-shadow" in cli.logged

runez.write("pp.yml", "isolate-usr-local: none", logger=None)
cli.run("-ntmacos-arm64", "-cpp.yml", "build", f.version)
assert cli.succeeded
assert "isolate-usr-local" not in cli.logged

runez.delete("bin/brew", logger=None)
cli.run("-ntmacos-arm64", "build", f.version)
assert cli.succeeded
assert "isolate-usr-local" not in cli.logged