Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
bpo-44184: Fix subtype_dealloc() for freed type
Fix a crash at Python exit when a deallocator function removes the
last strong reference to a heap type.

Don't read type memory after calling basedealloc() since
basedealloc() can deallocate the type and free its memory.
  • Loading branch information
vstinner committed May 21, 2021
commit 5bcd788fe8092c0125db0043b56fa9ef9442206a
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash at Python exit when a deallocator function removes the last strong
reference to a heap type.
Patch by Victor Stinner.
11 changes: 9 additions & 2 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1446,15 +1446,22 @@ subtype_dealloc(PyObject *self)
if (_PyType_IS_GC(base)) {
_PyObject_GC_TRACK(self);
}

// Don't read type memory after calling basedealloc() since basedealloc()
// can deallocate the type and free its memory.
int type_needs_decref = (type->tp_flags & Py_TPFLAGS_HEAPTYPE
&& !(base->tp_flags & Py_TPFLAGS_HEAPTYPE));

assert(basedealloc);
basedealloc(self);

/* Can't reference self beyond this point. It's possible tp_del switched
our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
reference counting. Only decref if the base type is not already a heap
allocated type. Otherwise, basedealloc should have decref'd it already */
if (type->tp_flags & Py_TPFLAGS_HEAPTYPE && !(base->tp_flags & Py_TPFLAGS_HEAPTYPE))
Py_DECREF(type);
if (type_needs_decref) {
Py_DECREF(type);
}

endlabel:
Py_TRASHCAN_END
Expand Down