python-build-standalone: Creating venvs via standard library's `venv.create(..., with_pip=True)` fails for binaries linked against libpython dynamically
Minimal example:
import subprocess
import venv
from tempfile import mkdtemp
from traceback import print_exc
tmp_dir_path = mkdtemp(prefix="venv-create-bug-example.")
print(f"creating venv in: {tmp_dir_path}")
try:
venv.create(tmp_dir_path, with_pip=True)
except subprocess.CalledProcessError as e:
print_exc()
print(f"subprocess stdout:\n{e.stdout}")
print(f"subprocess stderr:\n{e.stderr}")
exit(1)
Running this with a python-build-standalone binary that has a shared library dependency on libpython*.so, e.g. cpython-3.12.7+20241016-x86_64-unknown-linux-gnu-install_only will make this fail with (extra newlines inserted for readability):
creating venv in: /tmp/venv-create-bug-example.pj058eb3
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command
'['/tmp/venv-create-bug-example.pj058eb3/bin/python', '-m', 'ensurepip', '--upgrade', '--default-pip']'
returned non-zero exit status 127.
subprocess stdout:
b'/tmp/venv-create-bug-example.pj058eb3/bin/python:
error while loading shared libraries:
/tmp/venv-create-bug-example.pj058eb3/bin/../lib/libpython3.12.so.1.0:
cannot open shared object file: No such file or directory\n'
...
Obviously, this is because the python binary links against libpython*.so dynamically with a relative path, and there no longer is a libpython*.so at this path when the Python executable (or a symlink to it) finds itself in the venv.
See also the corresponding issue in uv:
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 15 (4 by maintainers)
Commits related to this issue
- Fix python lib https://github.com/indygreg/python-build-standalone/issues/381 — committed to domcloud/bridge by willnode 2 years ago
- Fix virtual environment creation when bootstrapping build environments with a standalone Python (#505) Per https://github.com/astral-sh/python-build-standalone/issues/381#issuecomment-2616817789 this... — committed to astral-sh/python-build-standalone by zanieb 2 years ago
So there’s like three classes of issues that are all very similar-sounding but are not exactly the same thing:
libpython3.13.so.1.0runtime library?libpython3.13.sodevelopment library?libpython3.13.so.1.0runtime library?This issue is about the interpreter not finding the runtime library. If you can’t find it, then the Python interpreter cannot start up and is completely broken. The reason for this is that it references its own runtime library by relative path from its binary location:
If you move/copy the binary to some location and do not preserve a
../lib/libpython3.13.so.1.0, then it will fail to start up.The specific reason
venv.create(symlinks=False, with_pip=True)fails is that thevenvmodule tries to runensurepipon the venv it just created. If you leave it off, it still creates a venv that does not work, but because it never tries to run code in there, it returns successfully. (Arguably this is a bug.)On the other hand, if you symlink the binary, then
$ORIGINis interpreted relative to the target of the symlink, and everything still works. (Except in Valgrind, which has a bug that it causes scripts to see$ORIGINas the script itself instead of the interpreter.)There’s two ways that you can avoid caring about this problem. The first is that you build your Python interpreter so that the libpython guts are statically linked into
bin/pythonand it doesn’t carry a runtime dependency on libpython in a separate file. The second is that you install your Python interpreter globally so that instead of having an$ORIGIN-relative dependency, it just has an unqualifiedlibpython3.13.so.1.0dependency that gets looked up in e.g. /usr/lib. python-build-standalone’s Pythons don’t do either of these. Neither Xcode’s, which is why they have the same problem and why Apple patches their stdlib to throw if you ask it to make a copy-based venv.(I suppose one thing we can do is to statically link libpython into our interpreter. I’m not sure off hand why we don’t, though the argument that comes to mind is disk space.)
The second problem is about compiling (or more specifically, linking) code that needs to link libpython. For those, you generally need to find a
libpython3.13.soto satisfy-lpython3.13, and you probably also need to find the<Python.h>C header and its friends, at least if you’re writing C. There is, apparently, some build tool that tries to findlibpython3.13.sorelative tobin/pythonby convention. This works fine outside a venv but breaks inside one. I don’t think we do anything in particular to encourage people to look for a nonexistentvenv/lib/libpython3.13.so, but C packaging is all about guessing games, so I don’t entirely blame that code if it exists. The best thing we can do is improve that build helper to guess better.Again, a systemwide Python with the python3-dev package (or whatever your OS calls it) installed is going to have something like a
/usr/lib/libpython3.13.so, and-lpython3.13will get resolved out of there, no need to go finding it specifically. So if there’s some build tool that auto-detects stuff based on a venv and doescc whatever.c -Ivenv/include -Lvenv/lib -lpython3.13, then the compiler is going to successfully find/usr/lib/libpython3.13.so(and/usr/include/Python.h) and not care that your-I/-Lsettings are bogus. But for a relocatable Python like ours, we don’t get that benefit.The third problem is that, supposing you’ve gotten past the second problem and successfully compiled some program that links libpython, your program is going to need to locate the runtime library in order to run. Again, for a systemwide Python this just works. But for a relocatable Python, you either need to get an
$ORIGIN-relative library reference or rpath into your program, or you need to set$LD_LIBRARY_PATHat runtime (or add the relocatable Python to systemwide config).Note that this third problem is orthogonal from venvs; it’s pretty unlikely that you’re going to compile your own program into the same directory as
bin/python, so the$ORIGIN/../lib/libpython3.13.sosyntax from the Python interpreter itself is not particularly helpful to this program. You almost certainly want to referencelibpython3.13.soby absolute path in this case.So, recapping: this issue is only the first problem of that list. astral-sh/uv#6812 is sort of all three problems. It was reported by demonstrating the Python interpreter failing to find libpython under
ldd(which would be problem one, except this is actually just a bug inlddand not a real problem—the first problem doesn’t actually happen in symlink-based venvs). It was reported as a compilation problem, which is the second problem. And it turns out that what it actually is, at least in part, is that the compilation works fine but running something likecargo test, which generates a binary that links libpython, is broken, which is the third problem.So:
Currently (AIUI)
uv venv/ the uv-virtualenv crate does only symlink-based venvs on UNIX and only copy-based venvs on Windows. This problem doesn’t apply at all to symlink-based venvs. I am not yet caught up on how the Windows side of things works but I don’t believe there’s an equivalent problem there. So I think there’s nothing foruv venvto do currently. If we do implement copy-based venvs for UNIX, then yes, we could detect it, but I’m not sure why we would.(My parenthetical proposal in the previous comment is to address the second and third problems, which do apply to symlink-based venvs. In that case, yes,
uv venvwould need to detect the need to symlink both the development-time namelibpython3.13.soand the runtime namelibpython.3.13.so.1.0, and it would be straightforward to do so.)No, because this is about the first problem, where the Python interpreter is wholly broken, and
venv.create(symlinks=False, with_pip=False)creates a broken, unusable venv without reporting an error to you (and the error message thatvenv.create(symlinks=False, with_pip=True)gives you is unhelpful).I don’t think we’re guaranteed to be within uv here. Even setting aside that this is the python-build-standalone repo—the issue on the uv side is about running
cargo testinside an activated venv that was created by uv, so uv the binary isn’t running at the point where we get the failure.Lemme know if this is still confusing, I can barely keep the various problems straight 😃
Another option here is rewriting the ELF binary so the
DT_NEEDEDentry for libpython is correctly referenced from the virtualenv. This entails rewriting ELF binaries at venv creation time. This would usually entail calling out to a linker or a tool likepatchelf. But we could potentially ship the functionality as part ofuvor PBS somehow.A problem here is we don’t know what the new value for
DT_NEEDEDwill be until the venv is created. A potential trick here is to reserve a bunch of NULL bytes in the string table atpythonbinary build time. We should be able to achieve this using a minimal linker script and theFILLdirective to create extra NULLs at the end of the.dynstrsection.When the venv is created, we write the source location of libpython into this reserved/empty strtab space and update the
DT_NEEDEDrecord to point to that strtab entry. Might need to also adjust section headers so the new string table size is reported properly.This shouldn’t be terribly difficult to achieve with the
objectorgoblinRust crates. Rewriting/resizing the string table / section to accommodate a new entry is much more complex. But if all you need to do is patch a few dozen bytes inside the ELF because you reserved space in.dynstrfor an absolute path, it should be fast and safe.Yeah, I agree — that’s what I meant when I said it was distinct. I think we’re all on the same page here, I was just sharing those use-cases for context on what people are asking for.
I don’t know of anyone that’s asking for copy-based venvs on Unix. I wouldn’t be surprised if something came up if we banned it, but I’d be willing to give it a try here (where release iteration times are much faster than CPython).
Even with
python3 -m venv --copies, you’re still left with a reference in pyvenv.cfg to the original installation’s standard library, so I think the premises of 7865 that the given commands are sufficient to get you a venv that’s “self contained and does not rely on the user’s local files” is not true and the premise of 6782 thatvenv --copiesdoes what they want is not true. I definitely see the value of giving users a way to get something that is truly self-contained, but I recall seeing somewhere an argument that this is no longer a virtual environment, and what you want at that point is just another unpack of a python-build-standalone distribution and installing packages straight into that distribution.I don’t know of any use case on UNIX actually wants copy-based venvs (as I argued in python/cpython#129382). My only hesitation was that it’s a thing the code currently supports and currently defaults to, but I would be more than happy to break it and say symlinks only. Apple seems to have gotten away with doing that.
Just to share more context, people also want fully portable virtual environments, e.g.,
but I think that’s distinct from a typical copy-based venv.
Does that realistically matter in systems where symlinks are available?
Copy-based venvs exist primarily for Windows, where symlink support is problematic. Are there any use-cases for copy-based venvs in systems like macOS, which implement the kind of code signing you mentioned?
If not, I think the best solution is to simply adjust the UX so that users don’t run into these scenarios by mistake.
We could fix the issue with a more complex solution like requiring certain tooling to set the
RPATHproperly, but I think that if we can avoid that kind of complexity, that would be best. Practically, I think this mostly becomes a non-issue if there aren’t any real need world use-cases.To be clear #505 is just working around this issue for this repository’s own Python code in the build scripts (when the Python interpreter itself is from python-build-standalone)—it’s not intended as a fix for the outputs of this repository / does not change the outputs.
I’m inclined to say that copy-based venvs are just unsupported for python-build-standalone (as they are for Xcode’s Pythons), but yeah, having
venvdo some rpath patching after it creates the environment would also work, at the risk of maybe breaking code signatures or other things that depend on the copy being bit-for-bit identical to the binary we distribute.This is a little bit different from astral-sh/uv#6812. While they’re both sort of about
libpython.sonot being in the venv, the impact is different. In theuvissue, runningbin/pythonworks fine, butldd bin/pythonreports a spurious issue (which is a bug inldd), and some build systems are unhappy about not being able to find libpython (which might be because they are trustingldd, or might be some other, build-system-specific cause). The issue here is thatbin/pythonjust doesn’t work at all and the venv is completely broken.You can repro this with the CLI tool:
The reason is that
venv.main()decides between copies and symlinks based onos.name == 'nt', whereasvenv.EnvBuilder/venv.createjust defaults tosymlinks=False. This means, incidentally, that you can work around this issue withvenv.create(...symlinks=True), which is probably a good idea for its own sake in that it matches the default behavior ofpython -m venvon UNIX.Some fun facts about how other distributions of Python approach this:
bin/pythonlinkinglibpython.so, but because they hard-code paths in/nixand set rpaths, a venv created with--copiesworks fine because the copied Python binary still has the rpath set pointing to the original location oflibpython.so. This won’t quite work for us because we don’t know in advance where someone is unpacking the interpreter (and for e.g.uvit’s in the user’s homedir which varies with their username). We could modify the copiedbin/pythonto set an rpath, but making the venvbin/pythonno longer bit-for-bit identical to the original one seems like it might break something else unexpected.--copiesand to change the default behavior ofEnvBuilder, and a comment specifically calls out the equivalent problem as the reason they don’t allow it:(I have no idea what
TRAIN_STYLEis. Some internal Apple thing about release vs. internal builds? “Developer Tools”?)