GH-135552: Make the GC clear weakrefs later (GH-136189)

Fix a bug caused by the garbage collector clearing weakrefs too early.  The
weakrefs in the ``tp_subclasses`` dictionary are needed in order to correctly
invalidate type caches (for example, by calling ``PyType_Modified()``).
Clearing weakrefs before calling finalizers causes the caches to not be
correctly invalidated.  That can cause crashes since the caches can refer to
invalid objects.  Defer the clearing of weakrefs without callbacks until after
finalizers are executed.
This commit is contained in:
Neil Schemenauer 2025-08-07 16:32:17 -07:00 committed by GitHub
parent deb385a143
commit 350c58ba4e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 317 additions and 140 deletions

View file

@ -214,7 +214,7 @@ clear_current_module(PyInterpreterState *interp, PyObject *expected)
if (PyDict_GetItemRef(dict, INTERP_KEY, &ref) < 0) {
goto error;
}
if (ref != NULL) {
if (ref != NULL && ref != Py_None) {
PyObject *current = NULL;
int rc = PyWeakref_GetRef(ref, &current);
/* We only need "current" for pointer comparison. */