Skip to content

Commit

Permalink
Clear greenlet weakrefs first
Browse files Browse the repository at this point in the history
Otherwise user code may resurrect greenlet when
it is already destroyed, making references to
freed objects possible (see the test case).
  • Loading branch information
snaury committed May 13, 2012
1 parent dae2314 commit 744eef4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 3 additions & 3 deletions greenlet.c
Original file line number Diff line number Diff line change
Expand Up @@ -820,14 +820,14 @@ static void green_dealloc(PyGreenlet* self)
goto green_dealloc_end;
}
}
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
Py_CLEAR(self->parent);
Py_CLEAR(self->run_info);
Py_CLEAR(self->exc_type);
Py_CLEAR(self->exc_value);
Py_CLEAR(self->exc_traceback);
Py_CLEAR(self->dict);
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
Py_CLEAR(self->run_info);
Py_TYPE(self)->tp_free((PyObject*) self);
green_dealloc_end:
#ifdef GREENLET_USE_GC
Expand Down
14 changes: 14 additions & 0 deletions tests/test_weakref.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,17 @@ def test_inactive_weakref(self):
o = weakref.ref(greenlet.greenlet())
gc.collect()
self.assertEqual(o(), None)

def test_dealloc_weakref(self):
seen = []
def worker():
try:
greenlet.getcurrent().parent.switch()
finally:
seen.append(g())
g = greenlet.greenlet(worker)
g.switch()
g2 = greenlet.greenlet(lambda: None, g)
g = weakref.ref(g2)
g2 = None
self.assertEqual(seen, [None])

0 comments on commit 744eef4

Please sign in to comment.