Skip to content

os.getcwd() in a very long working directory can allocate memory without bound and end in MemoryError #162441

Open

Description

@kawaz

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() in Modules/posixmodule.c) retry the C getcwd() with a buffer 1024 bytes larger each time it fails with ERANGE.
  • The only limit is PY_SSIZE_T_MAX.
  • POSIX says ERANGE means 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 with ERANGE whatever the buffer size.
  • os.getcwd() then keeps reallocating until memory runs out, and raises MemoryError.

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 by lost sys.stderr.
  • importlib resolves the '' entry of sys.path with os.getcwd(). So even python3 -c "import json" started in such a directory ends the same way.

History

Reproducer

No dependencies. The script:

  1. builds a deep directory with relative mkdir / chdir, until the cwd is longer than the target length;
  2. calls os.getcwd() twice in a child process whose address space is capped at 512 MiB;
  3. exits 1 if a call raised MemoryError or 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) with pn_get().
  • pn_get() only accepts strings shorter than MAXPATHLEN.
  • Once a call has succeeded with a large enough buffer, the cached cwd is longer than MAXPATHLEN.
  • From then on pn_get() fails with ENAMETOOLONG on every call, and the getcwd syscall turns that into ERANGE whatever 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_PRELOAD shim whose getcwd() always fails with ERANGE, the patched build raises OSError(ERANGE) at once instead of MemoryError.
  • A 5043-byte cwd on Linux is still returned.
  • test_os passes.
  • 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_pathnames was added for bpo-9185, but its body never runs. It is indented under the return of the except: clause (already noted in os.getcwd() hardcodes max path len #53492 in 2013).
  • test_os.test_getcwd_long_path uses absolute paths. On a platform whose PATH_MAX is 1024, it stops at ENAMETOOLONG from mkdir() before the cwd gets longer than PATH_MAX.

CPython versions tested on:

3.11, 3.13, 3.15, CPython main branch

Operating systems tested on:

Linux, macOS, Other

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions