Skip to content

Commit fa7c37a

Browse files
gpsheadynkdir
andauthored
[3.11] gh-99952: fix refcount issues in ctypes.Structure from_param() result (#101339)
[3.11] gh-99952: [ctypes] fix refcount issues in from_param() result. (GH-100169) Fixes a reference counting issue with `ctypes.Structure` when a `from_param()` method call is used and the structure size is larger than a C pointer `sizeof(void*)`. This problem existed for a very long time, but became more apparent in 3.8+ by change likely due to garbage collection cleanup timing changes.. (cherry picked from commit dfad678) Co-authored-by: Yukihiro Nakadaira <[email protected]>
1 parent cd0fe5b commit fa7c37a

File tree

4 files changed

+63
-0
lines changed

4 files changed

+63
-0
lines changed

Lib/ctypes/test/test_parameters.py

+52
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,58 @@ def test_parameter_repr(self):
244244
self.assertRegex(repr(c_wchar_p.from_param('hihi')), r"^<cparam 'Z' \(0x[A-Fa-f0-9]+\)>$")
245245
self.assertRegex(repr(c_void_p.from_param(0x12)), r"^<cparam 'P' \(0x0*12\)>$")
246246

247+
@test.support.cpython_only
248+
def test_from_param_result_refcount(self):
249+
# Issue #99952
250+
import _ctypes_test
251+
from ctypes import PyDLL, c_int, c_void_p, py_object, Structure
252+
253+
class X(Structure):
254+
"""This struct size is <= sizeof(void*)."""
255+
_fields_ = [("a", c_void_p)]
256+
257+
def __del__(self):
258+
trace.append(4)
259+
260+
@classmethod
261+
def from_param(cls, value):
262+
trace.append(2)
263+
return cls()
264+
265+
PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
266+
PyList_Append.restype = c_int
267+
PyList_Append.argtypes = [py_object, py_object, X]
268+
269+
trace = []
270+
trace.append(1)
271+
PyList_Append(trace, 3, "dummy")
272+
trace.append(5)
273+
274+
self.assertEqual(trace, [1, 2, 3, 4, 5])
275+
276+
class Y(Structure):
277+
"""This struct size is > sizeof(void*)."""
278+
_fields_ = [("a", c_void_p), ("b", c_void_p)]
279+
280+
def __del__(self):
281+
trace.append(4)
282+
283+
@classmethod
284+
def from_param(cls, value):
285+
trace.append(2)
286+
return cls()
287+
288+
PyList_Append = PyDLL(_ctypes_test.__file__)._testfunc_pylist_append
289+
PyList_Append.restype = c_int
290+
PyList_Append.argtypes = [py_object, py_object, Y]
291+
292+
trace = []
293+
trace.append(1)
294+
PyList_Append(trace, 3, "dummy")
295+
trace.append(5)
296+
297+
self.assertEqual(trace, [1, 2, 3, 4, 5])
298+
247299
################################################################
248300

249301
if __name__ == '__main__':
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a reference undercounting issue in :class:`ctypes.Structure` with ``from_param()``
2+
results larger than a C pointer.

Modules/_ctypes/_ctypes.c

+3
Original file line numberDiff line numberDiff line change
@@ -416,13 +416,15 @@ _ctypes_alloc_format_string_with_shape(int ndim, const Py_ssize_t *shape,
416416
typedef struct {
417417
PyObject_HEAD
418418
void *ptr;
419+
PyObject *keep; // If set, a reference to the original CDataObject.
419420
} StructParamObject;
420421

421422

422423
static void
423424
StructParam_dealloc(PyObject *myself)
424425
{
425426
StructParamObject *self = (StructParamObject *)myself;
427+
Py_XDECREF(self->keep);
426428
PyMem_Free(self->ptr);
427429
Py_TYPE(self)->tp_free(myself);
428430
}
@@ -470,6 +472,7 @@ StructUnionType_paramfunc(CDataObject *self)
470472

471473
StructParamObject *struct_param = (StructParamObject *)obj;
472474
struct_param->ptr = ptr;
475+
struct_param->keep = Py_NewRef(self);
473476
} else {
474477
ptr = self->b_ptr;
475478
obj = (PyObject *)self;

Modules/_ctypes/_ctypes_test.c

+6
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,12 @@ EXPORT (HRESULT) KeepObject(IUnknown *punk)
10341034

10351035
#endif
10361036

1037+
EXPORT(int)
1038+
_testfunc_pylist_append(PyObject *list, PyObject *item)
1039+
{
1040+
return PyList_Append(list, item);
1041+
}
1042+
10371043
static struct PyModuleDef_Slot _ctypes_test_slots[] = {
10381044
{0, NULL}
10391045
};

0 commit comments

Comments
 (0)