Repository navigation
Conversation
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.
3 tasks
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
_wrapperpointer to its Python object. Every overridden virtual method (event(),childEvent(), ...),metaObject()andqt_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_wrapperis never reset. Any later C++ call that reaches the shell then calls into a finalized interpreter and crashes:This crashes 3D Slicer on exit (Windows, Qt 6.12, Python 3.12). Slicer finalizes Python before calling
PythonQt::cleanup(); the existingtestPyFinalizeThenPythonQtCleanuptest covers this order. Cleanup then deletes a signal receiver whose parent is a Python-subclassed widget.PythonQt::removeSignalHandlers()beforePy_Finalize()only avoids that one path. The same crash happens whenever a shell gets a virtual call after finalization:QChildEvent, which goes to the shell'sevent()override.@Slot. The connection was made before finalization and is emitted afterwards, so the call goes throughqt_metacall()→PythonQtPrivate::handleMetaCall()._wrapperthen points into the previous interpreter. CheckingPy_IsInitialized()in the shell would not catch this, because it is true again.Fix
PythonQt::clearShellInstanceWrappers()detaches all C++ shell instances from their Python wrappers. It uses the existingshellSetInstanceWrapperCBwithnullptr, the same wayPythonQtInstanceWrapperdoes when a wrapper is deleted. After this, the generated shell code falls back to the C++ base implementation because_wrapperis null._objor_wrappedPtr), not from the_wrappedObjectskey. When a QObject shell is deleted from C++ while its Python wrapper is alive, its map entry stays and only theQPointerbecomes null. Using the key would write into the deleted object.PythonQtregisters a Pythonatexithook that callsclearShellInstanceWrappers().atexithandlers run at the start ofPy_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.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 tocallMethodInPython().Tests
New tests in
PythonQtTestCleanup. Each creates a Python subclass ofQTimerthat has a C++ parent.testShellInstanceSignalReceiverAfterPyFinalizePy_Finalize()andPythonQt::cleanup()testDeleteChildOfShellInstanceAfterPyFinalizePy_Finalize()testCppConnectionToPythonSlotAfterPyFinalize@SlotafterPy_Finalize()testShellInstanceAfterPythonReinitializationevent()override is no longer called after the interpreter is finalized and a new one is startedtestShellInstanceDeletedBeforePyFinalizePy_Finalize()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:mainPythonQtTestCleanupteststestShellInstanceDeletedBeforePyFinalizePythonQtTestCleanuptests in one processPythonQtTestApi,PythonQtTestSignalHandler,PythonQtTestSlotCallingtestShellInstanceAfterPythonReinitializationfailed 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).testShellInstanceDeletedBeforePyFinalizereports heap corruption there ifclearShellInstanceWrappers()uses the_wrappedObjectskey.I also tested this in 3D Slicer (Qt 6.12), using the commontk/PythonQt fork with this change applied:
py_nomainwindow_qSlicerDICOMModuleGenericTestpasses, and the application exits with code 0 instead of 0xC0000005.py_nomainwindow_qSlicerDICOMModuleGenericTest,py_DICOMPluginTestsandpy_WebEngineTestexit cleanly under the debug heap.py_WebEngineTestis failing for an unrelated reason, independent of this change).