Skip to content

Commit 2a5a5ca

Browse files
committed
cleanup_helper(): Make sure we invalidate all reference objects
before calling any callbacks. This is important since the callback objects only look at themselves to determine that they are invalide. This change avoids a segfault when callbacks use a different reference to an object in the process of being deallocated. This fixes SF bug #415660.
1 parent eb0d992 commit 2a5a5ca

1 file changed

Lines changed: 41 additions & 6 deletions

File tree

Modules/_weakref.c

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -740,22 +740,57 @@ cleanup_helper(PyObject *object)
740740
return;
741741
}
742742
list = GET_WEAKREFS_LISTPTR(object);
743-
while (*list != NULL) {
744-
PyWeakReference *current = *list;
745-
PyObject *callback = current->wr_callback;
743+
/* Remove the callback-less basic and proxy references */
744+
if (*list != NULL && (*list)->wr_callback == NULL) {
745+
clear_weakref(*list);
746+
if (*list != NULL && (*list)->wr_callback == NULL)
747+
clear_weakref(*list);
748+
}
749+
if (*list != NULL) {
750+
int count = getweakrefcount(*list);
746751

747-
Py_XINCREF(callback);
748-
clear_weakref(current);
749-
if (callback != NULL) {
752+
if (count == 1) {
753+
PyWeakReference *current = *list;
754+
PyObject *callback = current->wr_callback;
750755
PyObject *cbresult;
751756

757+
Py_INCREF(callback);
758+
clear_weakref(current);
752759
cbresult = PyObject_CallFunction(callback, "O", current);
753760
if (cbresult == NULL)
754761
PyErr_WriteUnraisable(callback);
755762
else
756763
Py_DECREF(cbresult);
757764
Py_DECREF(callback);
758765
}
766+
else {
767+
PyObject *tuple = PyTuple_New(count * 2);
768+
PyWeakReference *current = *list;
769+
int i = 0;
770+
771+
for (i = 0; i < count; ++i) {
772+
PyWeakReference *next = current->wr_next;
773+
774+
Py_INCREF(current);
775+
PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
776+
PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
777+
current->wr_callback = NULL;
778+
next = current->wr_next;
779+
clear_weakref(current);
780+
current = next;
781+
}
782+
for (i = 0; i < count; ++i) {
783+
PyObject *current = PyTuple_GET_ITEM(tuple, i * 2);
784+
PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1);
785+
PyObject *cbresult = PyObject_CallFunction(callback, "O",
786+
current);
787+
if (cbresult == NULL)
788+
PyErr_WriteUnraisable(callback);
789+
else
790+
Py_DECREF(cbresult);
791+
}
792+
Py_DECREF(tuple);
793+
}
759794
}
760795
return;
761796
}

0 commit comments

Comments
 (0)