Skip to content

The agent that grows with you

fix: stop os.environ writes from segfaulting threads in native getenv (glibc < 2.41)

teknium113caa104cd72
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.py
index e36a662ba1a..c7dfdb8bb53 100644
--- a/hermes_bootstrap.py
+++ b/hermes_bootstrap.py
@@ -280,6 +280,62 @@ def suppress_platform_ver_console() -> None:
pass # hardening only — never break an entry point
+def _glibc_frees_environ() -> bool:
+ """True on glibc < 2.41, whose ``setenv`` of a NEW name reallocs the ``environ`` array
+ and frees the old one (2.41+ never frees it, so a concurrent ``getenv`` stays safe)."""
+ if not sys.platform.startswith("linux"):
+ return False
+ try:
+ libc, _, version = (os.confstr("CS_GNU_LIBC_VERSION") or "").partition(" ")
+ return libc == "glibc" and tuple(int(p) for p in version.split(".")[:2]) < (2, 41)
+ except (AttributeError, OSError, TypeError, ValueError):
+ return False
+
+
+def install_never_free_environ() -> None:
+ """Make ``os.environ[new_name] = ...`` safe against native ``getenv`` in other threads.
+
+ On glibc < 2.41 adding a name reallocs ``environ`` and frees the old array while a
+ thread that dropped the GIL (``getaddrinfo``, OpenSSL's ``SSL_CERT_FILE`` lookup) may
+ still be walking it; the freed slots hold tcache pointers, so the walk segfaults the
+ whole process. Hermes writes new names at runtime from many places (``session.create``
+ turns on gateway prompts, the agent build sets ``HERMES_SESSION_ID``) while background
+ threads fetch catalogs, so the tui_gateway died with SIGSEGV. New names go into a
+ fresh array published with one pointer store, and no array is ever freed — glibc
+ 2.41's own fix. Replacing or removing an existing name is already in place in glibc.
+ """
+ if getattr(os.putenv, "_hermes_never_free_environ", False) or not _glibc_frees_environ():
+ return
+ import ctypes
+
+ try:
+ environ = ctypes.c_void_p.in_dll(ctypes.CDLL(None), "environ")
+ except (AttributeError, OSError, ValueError):
+ return
+ real_putenv = os.putenv
+ retained: list = [] # every array/entry handed to libc lives as long as the process
+
+ def _putenv(key, value) -> None:
+ name, val = os.fsencode(key), os.fsencode(value)
+ entries: list[int] = [] # raw pointers: libc owns (or we retain) what they point at
+ if environ.value:
+ array = ctypes.cast(environ.value, ctypes.POINTER(ctypes.c_void_p))
+ while entry := array[len(entries)]:
+ entries.append(entry)
+ prefix = name + b"="
+ if (not name or b"=" in name or b"\0" in name + val
+ or any(ctypes.string_at(e).startswith(prefix) for e in entries)):
+ real_putenv(key, value) # in-place replace, or the usual ValueError
+ return
+ line = ctypes.create_string_buffer(prefix + val)
+ fresh = (ctypes.c_void_p * (len(entries) + 2))(*entries, ctypes.addressof(line), None)
+ retained.extend((line, fresh))
+ environ.value = ctypes.addressof(fresh)
+
+ _putenv._hermes_never_free_environ = True # type: ignore[attr-defined]
+ os.putenv = _putenv
+
+
def harden_import_path(src_root: str | None = None) -> None:
"""Stop a package in the current directory from shadowing Hermes modules.
@@ -337,6 +393,7 @@ def export_scratch_tmp_env() -> None:
# Apply on import — entry points only need ``import hermes_bootstrap`` first.
apply_windows_utf8_bootstrap()
suppress_platform_ver_console()
+install_never_free_environ()
activate_durable_lazy_target()
install_happy_eyeballs_socket_connect()
export_scratch_tmp_env()
diff --git a/tests/test_hermes_bootstrap.py b/tests/test_hermes_bootstrap.py
index cca2a0fcc92..9a6ee3407c1 100644
--- a/tests/test_hermes_bootstrap.py
+++ b/tests/test_hermes_bootstrap.py
@@ -469,3 +469,35 @@ class TestHappyEyeballsSocketConnect:
monkeypatch.setitem(racer.__globals__, "_happy_eyeballs_create_connection", boom)
with pytest.raises(RuntimeError, match="racer bug"):
racer(("127.0.0.1", 1), 1.0)
+
+
+ sys.platform != "linux" or not (os.confstr("CS_GNU_LIBC_VERSION") or "").startswith("glibc"),
+ reason="environ array lifetime is a glibc property")
+class TestNeverFreeEnviron:
+ """A new ``os.environ`` name must never free the ``environ`` array another thread may be
+ walking in C ``getenv`` (getaddrinfo, OpenSSL) — glibc < 2.41 did, and the tui_gateway
+ segfaulted when ``session.create`` added names during the picker-prewarm fetch."""
+
+ def test_arrays_superseded_by_new_names_stay_intact(self):
+ # Fresh interpreter: the test process's own environ history must not matter.
+ subprocess.run([sys.executable, "-c", textwrap.dedent("""
+ import ctypes, os, hermes_bootstrap
+ environ = ctypes.c_void_p.in_dll(ctypes.CDLL(None), "environ")
+ def snapshot(addr):
+ array, out = ctypes.cast(addr, ctypes.POINTER(ctypes.c_void_p)), []
+ while array[len(out)]:
+ out.append(array[len(out)])
+ return out
+ seen, junk = {}, []
+ for i in range(80):
+ seen.setdefault(environ.value, snapshot(environ.value))
+ os.environ[f"HERMES_ENVIRON_PROBE_{i}"] = "1"
+ junk.append(os.urandom(40)) # interleave heap chunks so a realloc must move
+ assert len(seen) > 1, "environ never moved; the probe proves nothing"
+ # Compare raw words only: dereferencing a freed slot would crash the probe itself.
+ for addr, entries in seen.items():
+ words = ctypes.cast(addr, ctypes.POINTER(ctypes.c_void_p))
+ assert [words[i] for i in range(len(entries))] == entries, "a superseded environ array was freed"
+ assert os.environ["HERMES_ENVIRON_PROBE_79"] == "1"
+ """)], check=True, cwd=str(Path(__file__).resolve().parents[1]), timeout=60)