Skip to content

Commit 237467f

Browse files
miss-islingtonVanshAgarwal24036vstinner
authored
[3.14] gh-144100: Fix crash for POINTER(str) used in ctypes argtypes (GH-144108) (#144244)
gh-144100: Fix crash for POINTER(str) used in ctypes argtypes (GH-144108) (cherry picked from commit 8f45925) Co-authored-by: VanshAgarwal24036 <148854295+VanshAgarwal24036@users.noreply.github.com> Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent 7ae9a47 commit 237467f

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

Lib/test/test_ctypes/test_pointers.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,16 @@ class Cls(Structure):
403403
self.assertEqual(len(ws_typ), 0, ws_typ)
404404
self.assertEqual(len(ws_ptr), 0, ws_ptr)
405405

406+
def test_pointer_proto_missing_argtypes_error(self):
407+
class BadType(ctypes._Pointer):
408+
# _type_ is intentionally missing
409+
pass
410+
411+
func = ctypes.pythonapi.Py_GetVersion
412+
func.argtypes = (BadType,)
413+
414+
with self.assertRaises(ctypes.ArgumentError):
415+
func(object())
406416

407417
class PointerTypeCacheTestCase(unittest.TestCase):
408418
# dummy tests to check warnings and base behavior
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed a crash in ctypes when using a deprecated ``POINTER(str)`` type in
2+
``argtypes``. Instead of aborting, ctypes now raises a proper Python
3+
exception when the pointer target type is unresolved.

Modules/_ctypes/_ctypes.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1413,7 +1413,13 @@ PyCPointerType_from_param_impl(PyObject *type, PyTypeObject *cls,
14131413
/* If we expect POINTER(<type>), but receive a <type> instance, accept
14141414
it by calling byref(<type>).
14151415
*/
1416-
assert(typeinfo->proto);
1416+
if (typeinfo->proto == NULL) {
1417+
PyErr_SetString(
1418+
PyExc_TypeError,
1419+
"cannot convert argument: POINTER _type_ type is not set"
1420+
);
1421+
return NULL;
1422+
}
14171423
switch (PyObject_IsInstance(value, typeinfo->proto)) {
14181424
case 1:
14191425
Py_INCREF(value); /* _byref steals a refcount */

0 commit comments

Comments
 (0)