Skip to content

Fix crashes when C++ shell instances outlive the Python interpreter - #377

Open
lassoan wants to merge 2 commits into
MeVisLab:mainfrom
lassoan:fix-shell-instance-after-py-finalize
Open

lassoan wants to merge 2 commits into
MeVisLab:mainfrom
lassoan:fix-shell-instance-after-py-finalize

Conversation

@lassoan

@lassoan lassoan commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

This PR fixes crash on application exit due to shell objects keep calling methods of deleted Python objects. I used Claude Opus 5.5 for the investigation of the problem and developing fixes and tests, but I reviewed the generated code and descriptions and ran tests in various environments, so I'm confident that the changes are appropriate and I can confirm that they fix the crashes on exit in 3D Slicer.


A Python subclass of a wrapped Qt class is backed by a C++ shell object. The shell keeps a _wrapper pointer to its Python object. Every overridden virtual method (event(), childEvent(), ...), metaObject() and qt_metacall() uses that pointer to call into Python.

When the shell is owned by C++ (for example, it was created with a parent), it keeps a reference to its Python wrapper. So Py_Finalize() never deallocates the wrapper, and _wrapper is never reset. Any later C++ call that reaches the shell then calls into a finalized interpreter and crashes:

python312!PyType_Lookup                              <- access violation
python312!PyObject_GenericGetAttrWithDict
PythonQtShell_QDockWidget::event
QApplication::notify
QObjectPrivate::setParent_helper                     <- QChildEvent(ChildRemoved)
PythonQt::removeSignalHandlers
PythonQt::cleanup
ctkAbstractPythonManager::~ctkAbstractPythonManager  <- Py_Finalize(); PythonQt::cleanup();

This crashes 3D Slicer on exit (Windows, Qt 6.12, Python 3.12). Slicer finalizes Python before calling PythonQt::cleanup(); the existing testPyFinalizeThenPythonQtCleanup test covers this order. Cleanup then deletes a signal receiver whose parent is a Python-subclassed widget.

PythonQt::removeSignalHandlers() before Py_Finalize() only avoids that one path. The same crash happens whenever a shell gets a virtual call after finalization:

  • A C++ child of a Python-subclassed object is deleted. The parent receives a QChildEvent, which goes to the shell's event() override.
  • A C++ signal emits into a Python @Slot. The connection was made before finalization and is emitted afterwards, so the call goes through qt_metacall() → PythonQtPrivate::handleMetaCall().
  • A new interpreter is started while old shell instances are still alive. _wrapper then points into the previous interpreter. Checking Py_IsInitialized() in the shell would not catch this, because it is true again.

Fix

  • New public method: PythonQt::clearShellInstanceWrappers() detaches all C++ shell instances from their Python wrappers. It uses the existing shellSetInstanceWrapperCB with nullptr, the same way PythonQtInstanceWrapper does when a wrapper is deleted. After this, the generated shell code falls back to the C++ base implementation because _wrapper is null.
    • It takes the shell pointer from the wrapper (_obj or _wrappedPtr), not from the _wrappedObjects key. When a QObject shell is deleted from C++ while its Python wrapper is alive, its map entry stays and only the QPointer becomes null. Using the key would write into the deleted object.
  • Automatic registration: PythonQt registers a Python atexit hook that calls clearShellInstanceWrappers(). atexit handlers run at the start of Py_Finalize() while the interpreter is still fully working, so reading the wrappers is safe. They run last-registered first, so handlers registered by application code still see the Python overrides. No change is needed in applications, and none in the generated wrappers.
  • Null check in handleMetaCall(): PythonQtPrivate::handleMetaCall() now returns early if the shell has no wrapper. Without it, a signal-slot connection made before the shell was detached would pass a null wrapper to callMethodInPython().
  • Memory leak fix (separate commit): PythonQtClassWrapper_Type now has a tp_dealloc that deletes the PythonQtDynamicClassInfo allocated for each Python subclass of a wrapped class. LeakSanitizer reported this existing leak in testShellInstanceDeletedBeforePyFinalize, the first test in which a Python subclass type is freed during Py_Finalize().

New tests

New tests in PythonQtTestCleanup. Each creates a Python subclass of QTimer that has a C++ parent.

Test What it does Before this PR
testShellInstanceSignalReceiverAfterPyFinalize Connects a signal to a method of the shell, then Py_Finalize() and PythonQt::cleanup() crash
testDeleteChildOfShellInstanceAfterPyFinalize Deletes a C++ child of the shell after Py_Finalize() crash
testCppConnectionToPythonSlotAfterPyFinalize Emits a C++ signal connected to a Python @Slot after Py_Finalize() crash
testShellInstanceAfterPythonReinitialization Checks that a Python event() override is no longer called after the interpreter is finalized and a new one is started crash
testShellInstanceDeletedBeforePyFinalize Deletes the shell from C++ while its Python wrapper is alive, then Py_Finalize() pass (a use-after-free here is detected only with a debug heap or sanitizer)

Testing

Windows 11, MSVC 2022, Qt 6.12.0, Python 3.12, Release. Each cleanup test ran in its own process, with and without PYTHONQT_ENABLE_THREAD_SUPPORT:

main This PR
Existing 5 PythonQtTestCleanup tests pass pass
New tests 1–4 crash (access violation) pass
testShellInstanceDeletedBeforePyFinalize pass pass
All PythonQtTestCleanup tests in one process crash pass
PythonQtTestApi, PythonQtTestSignalHandler, PythonQtTestSlotCalling pass pass

testShellInstanceAfterPythonReinitialization failed in all of 10 runs without this fix. It checks behaviour (the override must no longer be called) rather than relying on a crash, so a run where the stale pointer happens not to crash still fails the test.

The CI ubuntu job (Qt 5.15, Python 3.12, AddressSanitizer, UndefinedBehaviorSanitizer and LeakSanitizer) passes in a local ubuntu:24.04 container.

The cleanup suite and the main suite also run clean under the Windows debug heap (process started in cdb). testShellInstanceDeletedBeforePyFinalize reports heap corruption there if clearShellInstanceWrappers() uses the _wrappedObjects key.

I also tested this in 3D Slicer (Qt 6.12), using the commontk/PythonQt fork with this change applied:

  • The crash on exit is fixed. py_nomainwindow_qSlicerDICOMModuleGenericTest passes, and the application exits with code 0 instead of 0xC0000005.
  • py_nomainwindow_qSlicerDICOMModuleGenericTest, py_DICOMPluginTests and py_WebEngineTest exit cleanly under the debug heap.
  • The full test suite passes 716 of 717 tests. (py_WebEngineTest is failing for an unrelated reason, independent of this change).

A shell instance (the C++ object behind a Python subclass of a wrapped
class) keeps a pointer to its Python wrapper and uses it in its virtual
method overrides, metaObject() and qt_metacall(). If the shell is owned
by C++, it keeps the wrapper alive, so Py_Finalize() never resets this
pointer. Any later virtual call on the shell then calls into the
finalized interpreter and crashes, for example the QChildEvent sent when
PythonQt::cleanup() deletes a signal receiver, or when a C++ child of
the shell is deleted. If a new interpreter is started, the shell uses a
wrapper from the previous one.

Add PythonQt::clearShellInstanceWrappers() and call it from an atexit
hook, which runs at the start of Py_Finalize() while the interpreter is
still working. Take the shell pointer from the wrapper, not from the
wrapped object map: QObject entries stay in the map after the C++
object is deleted, so the key may point to a deleted object.

Ignore calls on shell instances without a wrapper in
PythonQtPrivate::handleMetaCall().

Add tests to PythonQtTestCleanup.
@lassoan
lassoan force-pushed the fix-shell-instance-after-py-finalize branch from 40c1dbe to c9809c9 Compare December 1, 2026 20:23
PythonQtClassWrapper_init() allocates a PythonQtDynamicClassInfo for
each Python subclass of a wrapped class, but PythonQtClassWrapper_Type
had no tp_dealloc, so it was never deleted when the type object was
freed. Add a tp_dealloc that deletes it.

The leak was reported by LeakSanitizer in
testShellInstanceDeletedBeforePyFinalize, where the Python subclass
type is freed during Py_Finalize().
Comment thread src/PythonQt.cpp
Comment on lines +339 to +375
namespace {
//! Called by Python's atexit module at the start of Py_Finalize(), while the interpreter
//! is still fully functional (atexit handlers run last-registered first, so this runs after
//! the handlers registered by application code).
PyObject* PythonQt_atexitClearShellInstanceWrappers(PyObject* /*self*/, PyObject* /*args*/)
{
if (PythonQt::self()) {
PythonQt::self()->clearShellInstanceWrappers();
}
Py_RETURN_NONE;
}

PyMethodDef PythonQtAtExitMethodDef = {"_clearShellInstanceWrappers", PythonQt_atexitClearShellInstanceWrappers,
METH_NOARGS, "Detach C++ shell instances from their Python wrappers before the interpreter is finalized."};

//! Register PythonQt_atexitClearShellInstanceWrappers() with Python's atexit module,
//! so that C++ objects that outlive the interpreter no longer call into Python.
void registerAtExitHook()
{
PythonQtObjectPtr atexitModule;
atexitModule.setNewRef(PyImport_ImportModule("atexit"));
if (!atexitModule) {
PyErr_Print();
std::cerr << "PythonQt: could not import atexit, shell instances will not be detached at exit" << std::endl;
return;
}
PythonQtObjectPtr hook;
hook.setNewRef(PyCFunction_New(&PythonQtAtExitMethodDef, nullptr));
PythonQtObjectPtr result;
result.setNewRef(PyObject_CallMethod(atexitModule.object(), "register", "O", hook.object()));
if (!result) {
PyErr_Print();
std::cerr << "PythonQt: could not register atexit hook, shell instances will not be detached at exit" << std::endl;
}
}
} // namespace

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was there a reason not to use the C function Py_AtExit?
From the documentation it seems as if it has been around since Python 3.0.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants