[all-commits] [llvm/llvm-project] bab217: [mlir][python] Fix segfault at interpreter shutdow...
Maksim Levental via All-commits
all-commits at lists.llvm.org
Sun Jun 14 22:29:01 PDT 2026
Branch: refs/heads/users/makslevental/fix-PyThreadContextEntry-sigsegv
Home: https://github.com/llvm/llvm-project
Commit: bab217b338ae7ed2d5d43a735b75c3c667a36e6b
https://github.com/llvm/llvm-project/commit/bab217b338ae7ed2d5d43a735b75c3c667a36e6b
Author: makslevental <m_levental at apple.com>
Date: 2026-06-14 (Sun, 14 Jun 2026)
Changed paths:
M mlir/lib/Bindings/Python/IRCore.cpp
A mlir/test/python/context_shutdown.py
Log Message:
-----------
[mlir][python] Fix segfault at interpreter shutdown with entered contexts
The thread-local context stack (`PyThreadContextEntry::getStack()`)
holds `nb::object` references to Python Context, Location, and
InsertionPoint objects. When a Context is entered via `__enter__` but
never exited before the interpreter shuts down, these references
cause a segfault during process teardown.
The crash sequence:
1. User calls `ctx.__enter__()`, pushing a frame onto the
`static thread_local vector<PyThreadContextEntry>`.
2. The script ends; CPython runs `Py_FinalizeEx()` which tears down
the interpreter (clears modules, destroys remaining objects).
3. `main()` returns.
4. The C runtime destroys static/thread_local storage. On the main
thread, thread_local variables have the same destruction timing
as static storage — they are destroyed *after* main() returns.
5. The vector destructor runs, and each `PyThreadContextEntry`'s
`nb::object` members call `Py_DECREF` — but the interpreter is
already dead. This dereferences freed memory → SIGSEGV.
The fix registers a Python `atexit` handler that clears the
thread-local stack. Python's atexit handlers run *before*
`Py_FinalizeEx()`, while the interpreter is still fully alive,
so the `nb::object` decrefs execute safely.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply at anthropic.com>
To unsubscribe from these emails, change your notification settings at https://github.com/llvm/llvm-project/settings/notifications
More information about the All-commits
mailing list