Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/PythonQt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -412,6 +449,8 @@ PythonQt::PythonQt(int flags, const QByteArray& pythonQtModuleName)
Py_INCREF(&PythonQtStdInRedirectType);

initPythonQtModule(flags & RedirectStdOut, pythonQtModuleName);

registerAtExitHook();
}

PythonQt::~PythonQt()
Expand Down Expand Up @@ -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<void*>(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".
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 6 additions & 0 deletions src/PythonQt.h
Original file line number Diff line number Diff line change
Expand Up @@ -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();

//@}

//---------------------------------------------------------------------------
Expand Down
125 changes: 125 additions & 0 deletions tests/PythonQtTestCleanup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#include "PythonQt.h"
#include "PythonQt_QtAll.h"

#include <QTimer>

void PythonQtTestCleanup::initTestCase() {}

void PythonQtTestCleanup::cleanupTestCase() {}
Expand Down Expand Up @@ -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<QTimer*>();
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<QTimer*>();
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<QTimer*>();
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<QTimer*>();
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;
Expand Down
13 changes: 13 additions & 0 deletions tests/PythonQtTestCleanup.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
Loading