diff --git a/Lib/test/test_ctypes/test_callbacks.py b/Lib/test/test_ctypes/test_callbacks.py index 7d746749130db25..4e85eddabdfdc1f 100644 --- a/Lib/test/test_ctypes/test_callbacks.py +++ b/Lib/test/test_ctypes/test_callbacks.py @@ -141,6 +141,72 @@ def __del__(self): gc.collect() CFUNCTYPE(None)(lambda x=Nasty(): None) + @unittest.skipUnless(sys.platform == 'win32', + 'COM callback argument handling is Windows-only') + def test_argument_conversion_error_does_not_leak(self): + import weakref + + marker = '_needs_com_addref_' + + class PoisonedKey: + def __hash__(self): + return hash(marker) + + def __eq__(self, other): + if type(other) is str and other == marker: + raise RuntimeError('injected lookup failure') + return NotImplemented + + refs = [] + finalized_values = [] + track = False + + def init(arg): + if track: + refs.append(weakref.ref(arg)) + arg.temporary = True + + def finalize(arg): + if getattr(arg, 'temporary', False): + finalized_values.append(arg.value) + + with self.assertWarnsRegex(RuntimeWarning, 'non-string key'): + Arg = type('Arg', (ctypes.c_void_p,), { + '__init__': init, + '__del__': finalize, + PoisonedKey(): True, + }) + + # Verify that the COM marker lookup can fail. + with self.assertRaises(RuntimeError): + marker in vars(Arg) + + calls = 0 + + def callback(arg): + nonlocal calls + calls += 1 + + c_callback = CFUNCTYPE(None, Arg)(callback) + source = Arg() + # The finalizer records the pointer without dereferencing it. + source.value = 1 + old_hook = sys.unraisablehook + try: + sys.unraisablehook = lambda unraisable: None + track = True + for _ in range(32): + c_callback(source) + finally: + track = False + sys.unraisablehook = old_hook + + gc.collect() + self.assertEqual(calls, 0) + self.assertEqual(len(refs), 32) + self.assertTrue(all(ref() is None for ref in refs)) + self.assertEqual(finalized_values, [None] * 32) + @unittest.skipUnless(hasattr(ctypes, 'WINFUNCTYPE'), 'ctypes.WINFUNCTYPE is required') def test_i38748_stackCorruption(self): diff --git a/Misc/NEWS.d/next/Library/2026-11-22-12-20-43.gh-issue-162412.CtCbRf.rst b/Misc/NEWS.d/next/Library/2026-11-22-12-20-43.gh-issue-162412.CtCbRf.rst new file mode 100644 index 000000000000000..2b51c2745177fb0 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-22-12-20-43.gh-issue-162412.CtCbRf.rst @@ -0,0 +1 @@ +Fix a reference leak in :mod:`ctypes` on Windows when converting a callback argument fails during the COM reference-count lookup. diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c index e54111b8a4fab44..cebdea85e6a348e 100644 --- a/Modules/_ctypes/callbacks.c +++ b/Modules/_ctypes/callbacks.c @@ -83,22 +83,13 @@ PyType_Spec cthunk_spec = { * slower. */ static int -TryAddRef(PyObject *cnv, CDataObject *obj) +NeedsComAddRef(PyObject *cnv) { - IUnknown *punk; PyObject *attrdict = _PyType_GetDict((PyTypeObject *)cnv); if (!attrdict) { return 0; } - int r = PyDict_Contains(attrdict, &_Py_ID(_needs_com_addref_)); - if (r <= 0) { - return r; - } - - punk = *(IUnknown **)obj->b_ptr; - if (punk) - punk->lpVtbl->AddRef(punk); - return 0; + return PyDict_Contains(attrdict, &_Py_ID(_needs_com_addref_)); } #endif @@ -177,13 +168,23 @@ static void _CallPythonObject(ctypes_state *st, Py_DECREF(obj); goto Error; } - memcpy(obj->b_ptr, *pArgs, info->size); - args[i] = (PyObject *)obj; #ifdef MS_WIN32 - if (TryAddRef(cnv, obj) < 0) { + int needs_addref = NeedsComAddRef(cnv); + if (needs_addref < 0) { + Py_DECREF(obj); goto Error; } #endif + memcpy(obj->b_ptr, *pArgs, info->size); +#ifdef MS_WIN32 + if (needs_addref) { + IUnknown *punk = *(IUnknown **)obj->b_ptr; + if (punk) { + punk->lpVtbl->AddRef(punk); + } + } +#endif + args[i] = (PyObject *)obj; } else { PyErr_Format(PyExc_TypeError, "cannot build parameter of type %R", cnv);