Skip to content

Instantly share code, notes, and snippets.

@devdanzin
Last active June 20, 2026 01:08
Show Gist options
  • Select an option

  • Save devdanzin/464cef74ca8186843f33a38078476ac4 to your computer and use it in GitHub Desktop.

Select an option

Save devdanzin/464cef74ca8186843f33a38078476ac4 to your computer and use it in GitHub Desktop.
OOM-0001: Segfault: `Py_DECREF` of a NULL `filename` in `do_warn` (`_warnings.c:1139`)
# Authoritative gdb backtrace (3.16_ft_debug_asan, commit 15d7406)
# Faulting object: filename == NULL (op=0x0)
Program received signal SIGSEGV, Segmentation fault.
#0 _Py_atomic_load_uint32_relaxed (obj=...) at ./Include/cpython/pyatomic_gcc.h:367
#1 Py_DECREF (lineno=..., op=0x0, filename=...) at ./Include/refcount.h:345
#2 do_warn (message=..., category=..., stack_level=..., source=..., skip_file_prefixes=...) at Python/_warnings.c:1139
#3 warnings_warn_impl (module=..., message=..., category=..., stacklevel=..., source=..., skip_file_prefixes=...) at Python/_warnings.c:1184
#4 warnings_warn (module=..., args=..., nargs=..., kwnames=...) at Python/clinic/_warnings.c.h:161
#5 cfunction_vectorcall_FASTCALL_KEYWORDS (func=..., args=..., nargsf=..., kwnames=...) at Objects/methodobject.c:465
# Sibling vehicle (multiprocessing_resource_tracker) faults one frame deeper:
# #2 setup_context (...) at Python/_warnings.c:1087 (handle_error: Py_DECREF(*filename))

Segfault: Py_DECREF of a NULL filename in do_warn (_warnings.c:1139)

setup_context() doesn't NULL-check PyUnicode_FromString("<sys>"); under OOM the resulting NULL filename is later Py_DECREF'd by do_warn (or by setup_context's own handle_error: label, which uses Py_DECREF not Py_XDECREF).

AI Disclaimer: this gist was drafted by Claude Code, which also generated the reduced reproducer.

Crash report

Emitting a warning while allocations are failing segfaults on a Py_DECREF of a NULL filename. setup_context() does not NULL-check PyUnicode_FromString("<sys>"), and the resulting NULL is later decref'd either by do_warn() (success path) or by setup_context()'s own handle_error: label (which uses Py_DECREF, not Py_XDECREF).

Reproducer

import _testcapi, warnings, faulthandler
faulthandler.enable()
warnings.simplefilter("always")
_testcapi.set_nomemory(0, 0)   # fail every allocation from here on
warnings.warn("boom")          # -> Py_DECREF(NULL) -> SIGSEGV

Deterministic (start=0). Reproduced on main.

Backtrace

#0 _Py_atomic_load_uint32_relaxed   Include/cpython/pyatomic_gcc.h
#1 Py_DECREF                        Include/refcount.h
#2 do_warn                          Python/_warnings.c:1139   <- Py_DECREF(filename), filename == NULL
#3 warnings_warn_impl               Python/_warnings.c:1184
#4 warnings_warn                    Python/clinic/_warnings.c.h:161

(gdb) frame 2; print filename → $1 = (PyObject *) 0x0.

Root cause

In setup_context() (_warnings.c), the f == NULL branch (~L1036):

if (f == NULL) {
    globals = interp->sysdict;
    *filename = PyUnicode_FromString("<sys>");   /* return value unchecked */
    *lineno = 0;
}

Under memory pressure two allocations fail in sequence:

  1. PyThreadState_GetFrame() returns NULL (its frame-object allocation fails), so the f == NULL branch is taken; then
  2. PyUnicode_FromString("<sys>") itself returns NULL, leaving *filename == NULL.

The NULL *filename then reaches a Py_DECREF:

  • if setup_context() returns success (registry and __name__ already present in globals, so no further allocation is needed), do_warn() runs its cleanup Py_DECREF(filename) at L1139 — NULL deref; or
  • if setup_context() instead hits handle_error: (L1084), that path runs Py_DECREF(*filename) (L1087, not Py_XDECREF) — NULL deref.

Suggested fix

    *filename = PyUnicode_FromString("<sys>");
    if (*filename == NULL) {
        goto handle_error;
    }

and at handle_error: use Py_XDECREF(*filename) (since *filename may legitimately be NULL there).

Notes

Found by OOM-injection fuzzing (set_nomemory). Same pattern as gh-146080 (Py_DECREF(NULL) in an _ssl.c error label). Code is long-standing, so 3.13–3.15 are likely affected as well (unverified).


Part of python/cpython#151763 — an umbrella tracking 35 OOM-related crash findings.

"""
Minimal reproducer: NULL-deref / segfault in CPython's warnings machinery under OOM.
Affected: CPython 3.16.0a0 (seen on a free-threaded debug+ASan build; the defect
is allocation-failure handling and is not build-specific).
Crash: SIGSEGV in Py_DECREF(filename) with filename == NULL.
Requires: a build exposing _testcapi.set_nomemory (debug/test builds).
Authoritative backtrace (gdb, debug build):
#0 _Py_atomic_load_uint32_relaxed Include/cpython/pyatomic_gcc.h:367
#1 Py_DECREF Include/refcount.h:345
#2 do_warn Python/_warnings.c:1139 <- Py_DECREF(filename), filename==NULL
#3 warnings_warn_impl Python/_warnings.c:1184
#4 warnings_warn Python/clinic/_warnings.c.h:161
...
Root cause (Python/_warnings.c, setup_context()):
The `f == NULL` branch assigns
*filename = PyUnicode_FromString("<sys>");
with NO NULL check. Under memory pressure two allocations fail in sequence:
(a) PyThreadState_GetFrame() returns NULL (its frame-object allocation
fails), so the `f == NULL` branch is taken; then
(b) PyUnicode_FromString("<sys>") itself returns NULL, leaving
*filename == NULL.
The NULL *filename is then passed to Py_DECREF:
- if setup_context() returns success (registry/__name__ already present in
globals, so no further allocation is needed), do_warn() runs its cleanup
`Py_DECREF(filename)` at _warnings.c:1139 -> NULL deref; OR
- if setup_context() instead reaches its `handle_error:` label, that path
runs `Py_DECREF(*filename)` (note: not Py_XDECREF) at _warnings.c:1087
-> NULL deref.
Both observed faulting sites (1139 and 1087) are the same NULL *filename.
Likely fix: NULL-check PyUnicode_FromString("<sys>") (goto handle_error on NULL),
and use Py_XDECREF(*filename) in the handle_error path.
This single defect accounts for 8 of the 13 "segfault" crashers in this run
(_pyio, asyncio_streams, asyncio_threads x2, genericpath, urllib_parse,
importlib._bootstrap_external via do_warn:1139; multiprocessing.resource_tracker
via setup_context:1087). The various stdlib modules are only vehicles that emit a
warning under OOM.
Self-sweeping: `python repro.py` runs the trigger under set_nomemory(N, 0) for N in a
sweep, each in a FRESH subprocess (a fresh process avoids cache warm-up shifting the OOM
window), and stops at the first N that crashes. Needs a debug build (the check is compiled
out under NDEBUG). Bare trigger (fixed N=0):
import _testcapi, warnings, faulthandler
faulthandler.enable()
warnings.simplefilter("always")
_testcapi.set_nomemory(0, 0) # fail every allocation from here on
warnings.warn("boom") # -> do_warn()/setup_context() Py_DECREF(NULL) -> SIGSEGV
"""
import os
import sys
import subprocess
TRIGGER = r"""
import _testcapi, warnings, faulthandler
faulthandler.enable()
warnings.simplefilter("always") # make sure warn() runs its full path every time
_testcapi.set_nomemory({n}, 0) # fail every allocation from this point on
warnings.warn("boom") # -> do_warn()/setup_context() Py_DECREF(NULL) -> SIGSEGV
"""
SIGNATURE = "do_warn"
def main():
env = {**os.environ, "ASAN_OPTIONS": "detect_leaks=0:abort_on_error=0"}
# env["PYTHON_GIL"] = "0" # ONLY if this bug is free-threading-only (this one is not)
for n in range(80):
out = subprocess.run([sys.executable, "-c", TRIGGER.format(n=n)],
capture_output=True, text=True, env=env)
if SIGNATURE in out.stdout + out.stderr:
print("reproduced at set_nomemory(%d, 0):" % n)
sys.stdout.write(out.stderr or out.stdout)
return 1
print("no crash in range(80); widen it for your build")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment