Skip to content

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

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

lassoan wants to merge 1 commit 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 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().

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 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.

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.

1 participant