]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-108295: Fix crashes with TypeVar weakrefs (GH-108517) (#108527)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 27 Aug 2023 14:12:57 +0000 (07:12 -0700)
committerGitHub <noreply@github.com>
Sun, 27 Aug 2023 14:12:57 +0000 (16:12 +0200)
gh-108295: Fix crashes with TypeVar weakrefs (GH-108517)
(cherry picked from commit 482fad7f01567447b7259ebf58d62999fcdc5964)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Lib/test/test_typing.py
Misc/NEWS.d/next/Library/2023-08-26-08-38-57.gh-issue-108295.Pn0QRM.rst [new file with mode: 0644]
Objects/typevarobject.c

index c88152de7725fb04ac2f83abe5f5caa144417922..6c9f168b63f96de46c686e5307362a7266743f23 100644 (file)
@@ -544,6 +544,16 @@ class TypeVarTests(BaseTestCase):
                 with self.assertRaises(TypeError):
                     list[T][arg]
 
+    def test_many_weakrefs(self):
+        # gh-108295: this used to segfault
+        for cls in (ParamSpec, TypeVarTuple, TypeVar):
+            with self.subTest(cls=cls):
+                vals = weakref.WeakValueDictionary()
+
+                for x in range(100000):
+                    vals[x] = cls(str(x))
+                del vals
+
 
 def template_replace(templates: list[str], replacements: dict[str, list[str]]) -> list[tuple[str]]:
     """Renders templates with possible combinations of replacements.
diff --git a/Misc/NEWS.d/next/Library/2023-08-26-08-38-57.gh-issue-108295.Pn0QRM.rst b/Misc/NEWS.d/next/Library/2023-08-26-08-38-57.gh-issue-108295.Pn0QRM.rst
new file mode 100644 (file)
index 0000000..7e61ed4
--- /dev/null
@@ -0,0 +1 @@
+Fix crashes related to use of weakrefs on :data:`typing.TypeVar`.
index 97f39136996fcc7ef0916c8076a3b8a8e395d4d2..069e1d98ea49788d3d5161cdc074ec1def4a098b 100644 (file)
@@ -201,6 +201,7 @@ typevar_dealloc(PyObject *self)
     Py_XDECREF(tv->constraints);
     Py_XDECREF(tv->evaluate_constraints);
     _PyObject_ClearManagedDict(self);
+    PyObject_ClearWeakRefs(self);
 
     Py_TYPE(self)->tp_free(self);
     Py_DECREF(tp);
@@ -743,6 +744,7 @@ paramspec_dealloc(PyObject *self)
     Py_DECREF(ps->name);
     Py_XDECREF(ps->bound);
     _PyObject_ClearManagedDict(self);
+    PyObject_ClearWeakRefs(self);
 
     Py_TYPE(self)->tp_free(self);
     Py_DECREF(tp);
@@ -1022,6 +1024,7 @@ typevartuple_dealloc(PyObject *self)
 
     Py_DECREF(tvt->name);
     _PyObject_ClearManagedDict(self);
+    PyObject_ClearWeakRefs(self);
 
     Py_TYPE(self)->tp_free(self);
     Py_DECREF(tp);