Repository navigation
Description
Bug report
Bug description:
In a very long working directory, os.getcwd() can allocate memory without bound and end in MemoryError.
I have only reproduced this on illumos, in a working directory longer than PATH_MAX. It is unlikely to be hit in common environments: Linux and macOS are not affected. From reading the kernel sources, though, it looks like it could also happen on NetBSD and OpenBSD.
This is a regression of gh-53431 (bpo-9185): it was fixed in 2.7 only, and Python 3 has had the original behaviour again since 3.5.
What happens
- On POSIX,
os.getcwd()/os.getcwdb()(posix_getcwd()inModules/posixmodule.c) retry the Cgetcwd()with a buffer 1024 bytes larger each time it fails withERANGE. - The only limit is
PY_SSIZE_T_MAX. - POSIX says
ERANGEmeans the buffer is too small, so the loop normally ends after a retry or two. - On illumos, in a working directory longer than
PATH_MAX(1024),getcwd()can keep failing withERANGEwhatever the buffer size. os.getcwd()then keeps reallocating until memory runs out, and raisesMemoryError.
How it showed up
- In our CI on OmniOS r151060 (system Python 3.13.16), one test took about 13 minutes and exhausted the VM's memory. The traceback ended in
posixpath.realpath->os.getcwd(), followed bylost sys.stderr. - importlib resolves the
''entry ofsys.pathwithos.getcwd(). So evenpython3 -c "import json"started in such a directory ends the same way.
History
- os.getcwd causes infinite loop on solaris #53431 (bpo-9185, 2010) reported the same problem on Solaris and OpenBSD. bpo-15765 (2012) reported it on NetBSD.
- Both were fixed only in 2.7: on those platforms,
getcwd()is called once with a fixedPATH_MAX + 2buffer. - os.getcwd() hardcodes max path len #53492 (bpo-9246) added the growing loop to Python 3 in 2015. The 2.7 workaround was not carried over.
Reproducer
No dependencies. The script:
- builds a deep directory with relative
mkdir/chdir, until the cwd is longer than the target length; - calls
os.getcwd()twice in a child process whose address space is capped at 512 MiB; - exits 1 if a call raised
MemoryErroror timed out.
getcwd_past_path_max.py
"""Reproducer: os.getcwd() in a working directory longer than PATH_MAX.
The parent creates a directory chain one 200-byte component at a time
(relative mkdir + chdir, so no single path argument is longer than
PATH_MAX) until the cwd is longer than the target length, then calls
os.getcwd() twice in a child process whose address space is capped, so
that an unbounded retry loop ends in MemoryError instead of exhausting
the machine. Exits 1 if a call raised MemoryError or timed out, else 0.
usage: python3 getcwd_past_path_max.py [target_length]
"""
import os
import subprocess
import sys
import tempfile
CHILD = r"""
import os, resource, sys
limit = 512 * 1024 * 1024
for name in ("RLIMIT_AS", "RLIMIT_VMEM", "RLIMIT_DATA"):
if hasattr(resource, name):
try:
resource.setrlimit(getattr(resource, name), (limit, limit))
break
except (ValueError, OSError):
pass
for i in (1, 2):
try:
r = os.getcwd()
print(f"call {i}: ok, {len(os.fsencode(r))} bytes", flush=True)
except MemoryError:
print(f"call {i}: MemoryError", flush=True)
sys.exit(1)
except OSError as e:
print(f"call {i}: OSError errno={e.errno} ({os.strerror(e.errno)})", flush=True)
"""
def main() -> int:
path_max = os.pathconf("/", "PC_PATH_MAX")
target = int(sys.argv[1]) if len(sys.argv) > 1 else path_max
root = tempfile.mkdtemp(prefix="gcwd-")
os.chdir(root)
length = len(os.fsencode(os.path.realpath(root)))
depth = 0
while length <= target:
os.mkdir("d" * 200)
os.chdir("d" * 200)
length += 201
depth += 1
print(f"{sys.platform} Python {sys.version.split()[0]}: PATH_MAX {path_max}, cwd {length} bytes", flush=True)
try:
out = subprocess.run([sys.executable, "-I", "-c", CHILD], timeout=300)
code = 1 if out.returncode != 0 else 0
except subprocess.TimeoutExpired:
print("child: timed out after 300 s", flush=True)
code = 1
for _ in range(depth):
os.chdir("..")
os.rmdir("d" * 200)
os.chdir("/")
os.rmdir(root)
print("VULNERABLE (unbounded retry)" if code else "not affected", flush=True)
return code
if __name__ == "__main__":
sys.exit(main())Results:
| Platform | Python | cwd length | Result | Exit |
|---|---|---|---|---|
| illumos (OmniOS r151060) | 3.13.16 | 1224 and 5043 bytes | first call succeeds, second raises MemoryError |
1 |
| Linux (glibc) | 3.11 / 3.13 / 3.15 | 4239 and 5043 bytes | both calls succeed | 0 |
| Linux (musl) | 3.13 | 4239 and 5043 bytes | both calls raise OSError(ENAMETOOLONG) |
0 |
| macOS | 3.11 / 3.13 / 3.15 | 1084 and 5104 bytes | both calls succeed | 0 |
Why illumos does this
From the illumos-gate source, and checked on OmniOS r151060 by calling libc getcwd() through ctypes:
- The kernel's
dogetcwd()first re-reads the cached cwd string (u_cwd) withpn_get(). pn_get()only accepts strings shorter thanMAXPATHLEN.- Once a call has succeeded with a large enough buffer, the cached cwd is longer than
MAXPATHLEN. - From then on
pn_get()fails withENAMETOOLONGon every call, and thegetcwdsyscall turns that intoERANGEwhatever the buffer size, until the process changes directory.
So the first os.getcwd() after a chdir() succeeds, and the second one never returns.
Calling libc getcwd() directly on OmniOS shows exactly this: right after chdir(), getcwd(buf, 1 MiB) succeeds, and the next getcwd(buf, 1 MiB) fails with ERANGE.
This is an illumos bug: it contradicts both POSIX and the illumos man page. But CPython should not turn a libc bug into unbounded memory growth, as was agreed for Solaris in gh-53431.
From the NetBSD and OpenBSD kernel sources, the same may happen there for a cwd longer than 4 * MAXPATHLEN. I have not checked that on a real system.
Possible fix
Stop growing the buffer at a fixed size (e.g. 1 MiB), and raise the ERANGE from the last call as OSError. No platform-specific code is needed.
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -4716,6 +4716,11 @@ posix_getcwd(int use_bytes)
return resobj;
#else
const size_t chunk = 1024;
+ /* Some getcwd() implementations keep failing with ERANGE for a working
+ directory longer than PATH_MAX, whatever the size of the buffer
+ (illumos). Stop growing the buffer at this size and raise the
+ ERANGE error rather than growing it until memory runs out. */
+ const size_t max_buflen = 1024 * 1024;
char *buf = NULL;
char *cwd = NULL;
@@ -4724,13 +4729,12 @@ posix_getcwd(int use_bytes)
Py_BEGIN_ALLOW_THREADS
do {
char *newbuf;
- if (buflen <= PY_SSIZE_T_MAX - chunk) {
- buflen += chunk;
- newbuf = PyMem_RawRealloc(buf, buflen);
- }
- else {
- newbuf = NULL;
+ if (buflen >= max_buflen) {
+ /* errno is still ERANGE from the last getcwd() call */
+ break;
}
+ buflen += chunk;
+ newbuf = PyMem_RawRealloc(buf, buflen);
if (newbuf == NULL) {
PyMem_RawFree(buf);
buf = NULL;What I checked with this patch on main:
- With an
LD_PRELOADshim whosegetcwd()always fails withERANGE, the patched build raisesOSError(ERANGE)at once instead ofMemoryError. - A 5043-byte cwd on Linux is still returned.
test_ospasses.- I have not built the patch on illumos.
I can open a PR if this approach is acceptable.
Notes on the tests
No existing test reaches this code path on the affected platforms:
test_posix.test_getcwd_long_pathnameswas added for bpo-9185, but its body never runs. It is indented under thereturnof theexcept:clause (already noted in os.getcwd() hardcodes max path len #53492 in 2013).test_os.test_getcwd_long_pathuses absolute paths. On a platform whosePATH_MAXis 1024, it stops atENAMETOOLONGfrommkdir()before the cwd gets longer thanPATH_MAX.
CPython versions tested on:
3.11, 3.13, 3.15, CPython main branch
Operating systems tested on:
Linux, macOS, Other
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsNo status
Activity
docs: CPython の getcwd の件を、報告した issue (python/cpython#162441) で指す (DR…