Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
66 changes: 66 additions & 0 deletions Lib/test/test_ctypes/test_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a reference leak in :mod:`ctypes` on Windows when converting a callback argument fails during the COM reference-count lookup.
29 changes: 15 additions & 14 deletions Modules/_ctypes/callbacks.c
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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);
Comment thread
manabeai marked this conversation as resolved.
Resolved
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);
Expand Down
Loading