From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Thu, 26 Sep 2024 20:51:58 +0000 (+0200) Subject: [3.13] gh-124538: Fix crash when using `gc.get_referents` on an untracked capsule... X-Git-Tag: v3.13.0rc3~74 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=22dee7b695a591c1d72f59f7c7b805f6c819b596;p=thirdparty%2FPython%2Fcpython.git [3.13] gh-124538: Fix crash when using `gc.get_referents` on an untracked capsule object (GH-124559) (#124588) gh-124538: Fix crash when using `gc.get_referents` on an untracked capsule object (GH-124559) (cherry picked from commit f923605658a29ff9af5a62edc1fc10191977627b) Co-authored-by: Peter Bierma --- diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py index 906f9884d679..bb7df1f5cfa7 100644 --- a/Lib/test/test_gc.py +++ b/Lib/test/test_gc.py @@ -1048,6 +1048,24 @@ class GCTests(unittest.TestCase): callback.assert_not_called() gc.enable() + @cpython_only + def test_get_referents_on_capsule(self): + # gh-124538: Calling gc.get_referents() on an untracked capsule must not crash. + import _datetime + import _socket + untracked_capsule = _datetime.datetime_CAPI + tracked_capsule = _socket.CAPI + + # For whoever sees this in the future: if this is failing + # after making datetime's capsule tracked, that's fine -- this isn't something + # users are relying on. Just find a different capsule that is untracked. + self.assertFalse(gc.is_tracked(untracked_capsule)) + self.assertTrue(gc.is_tracked(tracked_capsule)) + + self.assertEqual(len(gc.get_referents(untracked_capsule)), 0) + gc.get_referents(tracked_capsule) + + class IncrementalGCTests(unittest.TestCase): diff --git a/Misc/NEWS.d/next/Library/2024-09-25-18-34-48.gh-issue-124538.nXZk4R.rst b/Misc/NEWS.d/next/Library/2024-09-25-18-34-48.gh-issue-124538.nXZk4R.rst new file mode 100644 index 000000000000..33ae037ae56b --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-25-18-34-48.gh-issue-124538.nXZk4R.rst @@ -0,0 +1 @@ +Fixed crash when using :func:`gc.get_referents` on a capsule object. diff --git a/Objects/capsule.c b/Objects/capsule.c index 555979dab2b7..28965e0f21b7 100644 --- a/Objects/capsule.c +++ b/Objects/capsule.c @@ -317,10 +317,14 @@ static int capsule_traverse(PyCapsule *capsule, visitproc visit, void *arg) { // Capsule object is only tracked by the GC - // if _PyCapsule_SetTraverse() is called - assert(capsule->traverse_func != NULL); + // if _PyCapsule_SetTraverse() is called, but + // this can still be manually triggered by gc.get_referents() + + if (capsule->traverse_func != NULL) { + return capsule->traverse_func((PyObject*)capsule, visit, arg); + } - return capsule->traverse_func((PyObject*)capsule, visit, arg); + return 0; }