diff --git a/src/PythonQt.cpp b/src/PythonQt.cpp index 38b6ca314..964c2cb55 100644 --- a/src/PythonQt.cpp +++ b/src/PythonQt.cpp @@ -336,6 +336,43 @@ PythonQt* PythonQt::self() return _self; } +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 + PythonQt::PythonQt(int flags, const QByteArray& pythonQtModuleName) { _p = new PythonQtPrivate; @@ -412,6 +449,8 @@ PythonQt::PythonQt(int flags, const QByteArray& pythonQtModuleName) Py_INCREF(&PythonQtStdInRedirectType); initPythonQtModule(flags & RedirectStdOut, pythonQtModuleName); + + registerAtExitHook(); } PythonQt::~PythonQt() @@ -1597,6 +1636,27 @@ void PythonQt::removeSignalHandlers() _p->_signalReceivers.clear(); } +void PythonQt::clearShellInstanceWrappers() +{ + for (auto it = _p->_wrappedObjects.begin(); it != _p->_wrappedObjects.end(); ++it) { + PythonQtInstanceWrapper* wrap = it.value(); + if (!wrap || !wrap->_isShellInstance) { + continue; + } + // Same pointer that was passed when the wrapper was set on the shell instance. + // Do not use the map key: QObject entries are not removed when the C++ object is deleted + // (the QPointer becomes null instead), so the key may point to a deleted object. + void* shellInstance = wrap->_wrappedPtr ? wrap->_wrappedPtr : static_cast(wrap->_obj.data()); + if (!shellInstance) { + continue; // the C++ object has already been deleted + } + PythonQtShellSetInstanceWrapperCB* cb = wrap->classInfo()->shellSetInstanceWrapperCB(); + if (cb) { + (*cb)(shellInstance, nullptr); + } + } +} + namespace { //! adapted from python source file "pythonrun.c", function "handle_system_exit" //! return the exitcode instead of calling "Py_Exit". @@ -2404,6 +2464,12 @@ const QMetaObject* PythonQtPrivate::buildDynamicMetaObject(PythonQtClassWrapper* int PythonQtPrivate::handleMetaCall(QObject* object, PythonQtInstanceWrapper* wrapper, QMetaObject::Call call, int id, void** args) { + if (!wrapper) { + // The shell instance is no longer connected to a Python object + // (e.g., it was detached by clearShellInstanceWrappers() before Py_Finalize()), + // so there is no Python slot or property to call. + return -1; + } const QMetaObject* meta = object->metaObject(); int methodCount = meta->methodCount(); if (call == QMetaObject::InvokeMetaMethod) { diff --git a/src/PythonQt.h b/src/PythonQt.h index ae931fb97..33f44c912 100644 --- a/src/PythonQt.h +++ b/src/PythonQt.h @@ -405,6 +405,12 @@ class PYTHONQT_EXPORT PythonQt : public QObject //! globally removes all signal handlers (connections between QObjects and Python). void removeSignalHandlers(); + //! Detach all C++ shell instances (C++ objects of Python subclasses of wrapped classes) + //! from their Python wrappers, so that C++ virtual method calls no longer dispatch to Python. + //! This is called automatically by a Python atexit hook at the start of Py_Finalize(), + //! so that C++ objects that outlive the Python interpreter do not call into it. + void clearShellInstanceWrappers(); + //@} //--------------------------------------------------------------------------- diff --git a/tests/PythonQtTestCleanup.cpp b/tests/PythonQtTestCleanup.cpp index c8a2d738e..d2c4fe6ea 100644 --- a/tests/PythonQtTestCleanup.cpp +++ b/tests/PythonQtTestCleanup.cpp @@ -2,6 +2,8 @@ #include "PythonQt.h" #include "PythonQt_QtAll.h" +#include + void PythonQtTestCleanup::initTestCase() {} void PythonQtTestCleanup::cleanupTestCase() {} @@ -91,6 +93,129 @@ void PythonQtTestCleanup::testPyFinalizeThenPythonQtCleanup() PythonQt::cleanup(); } +void PythonQtTestCleanup::testShellInstanceSignalReceiverAfterPyFinalize() +{ + // Python subclass of a wrapped class (C++ shell instance) owned by C++ (it has a parent). + // The signal receiver becomes a child of the shell instance (the "self" of the slot). + QVERIFY(_helper->runScript("import PythonQt.QtCore\n" + "class MyTimer(PythonQt.QtCore.QTimer):\n" + " def onTimeout(self):\n" + " pass\n" + "timer = MyTimer(obj)\n" + "timer.connect('timeout()', timer.onTimeout)\n" + "obj.setPassed()\n")); + + if (Py_IsInitialized()) { + Py_Finalize(); + } + + // Deleting the signal receiver sends a QChildEvent to the shell instance, + // which must not call into the finalized interpreter. + PythonQt::cleanup(); +} + +void PythonQtTestCleanup::testDeleteChildOfShellInstanceAfterPyFinalize() +{ + QVERIFY(_helper->runScript("import PythonQt.QtCore\n" + "class MyTimer(PythonQt.QtCore.QTimer):\n" + " pass\n" + "timer = MyTimer(obj)\n" + "obj.setPassed()\n")); + QTimer* shellInstance = _helper->findChild(); + QVERIFY(shellInstance); + QObject* cppChild = new QObject(shellInstance); + + if (Py_IsInitialized()) { + Py_Finalize(); + } + + // Deleting the child sends a QChildEvent to the shell instance, + // which must not call into the finalized interpreter. + delete cppChild; + + PythonQt::cleanup(); +} + +void PythonQtTestCleanup::testCppConnectionToPythonSlotAfterPyFinalize() +{ + QVERIFY(_helper->runScript("import PythonQt.QtCore\n" + "class MyTimer(PythonQt.QtCore.QTimer):\n" + " @PythonQt.QtCore.Slot()\n" + " def onTriggered(self):\n" + " pass\n" + "timer = MyTimer(obj)\n" + "obj.setPassed()\n")); + QTimer* shellInstance = _helper->findChild(); + QVERIFY(shellInstance); + QVERIFY(QObject::connect(_helper, SIGNAL(triggered()), shellInstance, SLOT(onTriggered()))); + + if (Py_IsInitialized()) { + Py_Finalize(); + } + + // The shell instance's qt_metacall() must not call the Python slot in the finalized interpreter + QVERIFY(_helper->emitTriggered()); + + PythonQt::cleanup(); +} + +void PythonQtTestCleanup::testShellInstanceAfterPythonReinitialization() +{ + // Event type that the C++ base implementation does not handle (QObject::event() returns false) + QEvent testEvent(QEvent::Enter); + QTimer plainTimer; + QVERIFY(!QCoreApplication::sendEvent(&plainTimer, &testEvent)); + + // Python subclass of a wrapped class (C++ shell instance) owned by C++ (it has a parent), + // overriding a virtual method + QVERIFY(_helper->runScript("import PythonQt.QtCore\n" + "class MyTimer(PythonQt.QtCore.QTimer):\n" + " def event(self, event):\n" + " return True\n" + "timer = MyTimer(obj)\n" + "obj.setPassed()\n")); + QTimer* shellInstance = _helper->findChild(); + QVERIFY(shellInstance); + + // The Python override is called + QVERIFY(QCoreApplication::sendEvent(shellInstance, &testEvent)); + + if (Py_IsInitialized()) { + Py_Finalize(); + } + PythonQt::cleanup(); + + // Start a new interpreter while the shell instance created in the previous one is still alive + PythonQt::init(PythonQt::IgnoreSiteModule); + PythonQt_QtAll::init(); + + // The shell instance must not call the Python override from the previous interpreter, + // but fall back to the C++ base implementation + QVERIFY(!QCoreApplication::sendEvent(shellInstance, &testEvent)); +} + +void PythonQtTestCleanup::testShellInstanceDeletedBeforePyFinalize() +{ + // Python subclass of a wrapped class (C++ shell instance) owned by C++ (it has a parent) + QVERIFY(_helper->runScript("import PythonQt.QtCore\n" + "class MyTimer(PythonQt.QtCore.QTimer):\n" + " pass\n" + "timer = MyTimer(obj)\n" + "obj.setPassed()\n")); + QTimer* shellInstance = _helper->findChild(); + QVERIFY(shellInstance); + + // Delete the C++ object while its Python wrapper ("timer") is still alive + delete shellInstance; + + // Detaching shell instances from their wrappers at exit must not access the deleted object + // (the error is detected reliably only with a debug heap or address sanitizer) + if (Py_IsInitialized()) { + Py_Finalize(); + } + PythonQt::cleanup(); +} + bool PythonQtTestCleanupHelper::runScript(const char* script) { _passed = false; diff --git a/tests/PythonQtTestCleanup.h b/tests/PythonQtTestCleanup.h index 32e188b64..63992327e 100644 --- a/tests/PythonQtTestCleanup.h +++ b/tests/PythonQtTestCleanup.h @@ -21,6 +21,11 @@ private Q_SLOTS: void testCallQtMethodInDestructorWeakRefGuarded(); void testSignalReceiverCleanup(); void testPyFinalizeThenPythonQtCleanup(); + void testShellInstanceSignalReceiverAfterPyFinalize(); + void testDeleteChildOfShellInstanceAfterPyFinalize(); + void testCppConnectionToPythonSlotAfterPyFinalize(); + void testShellInstanceAfterPythonReinitialization(); + void testShellInstanceDeletedBeforePyFinalize(); private: PythonQtTestCleanupHelper* _helper; @@ -39,6 +44,14 @@ class PythonQtTestCleanupHelper : public QObject public Q_SLOTS: void setPassed() { _passed = true; } void onDestroyed(QObject*) {} + bool emitTriggered() + { + emit triggered(); + return true; + } + +Q_SIGNALS: + void triggered(); private: bool _passed;