diff --git a/Lib/test/test_ctypes/test_funcptr.py b/Lib/test/test_ctypes/test_funcptr.py index be641da30eadae..90b8826292eb7e 100644 --- a/Lib/test/test_ctypes/test_funcptr.py +++ b/Lib/test/test_ctypes/test_funcptr.py @@ -130,6 +130,14 @@ def c_string(init): def test_abstract(self): self.assertRaises(TypeError, _CFuncPtr, 13, "name", 42, "iid") + def test_invalid_argtypes(self): + libc = CDLL(None) + + PRINTF_PROTO = CFUNCTYPE(c_int, ctypes.c_char_p) + c_printf = PRINTF_PROTO(("printf", libc), ((1,),)) + c_printf.argtypes = (c_char_p, c_int) + with self.assertRaises(TypeError): + c_printf(b"Hello\n") if __name__ == '__main__': unittest.main() diff --git a/Misc/NEWS.d/next/Library/2025-08-27-01-04-38.gh-issue-138008.iCEhZ9.rst b/Misc/NEWS.d/next/Library/2025-08-27-01-04-38.gh-issue-138008.iCEhZ9.rst new file mode 100644 index 00000000000000..53e394547de84a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-08-27-01-04-38.gh-issue-138008.iCEhZ9.rst @@ -0,0 +1 @@ +Fix segfaults in _cyptes during _build_callargs. diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 4bd3e380b3bc4b..5ea19b79a99035 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -4374,7 +4374,11 @@ _build_callargs(ctypes_state *st, PyCFuncPtrObject *self, PyObject *argtypes, callargs = PyTuple_New(len); /* the argument tuple we build */ if (callargs == NULL) return NULL; - + if (!_validate_paramflags(st, Py_TYPE(self), argtypes)) { + PyErr_SetString(PyExc_TypeError, + "the current argument is invalid"); + goto error; + } #ifdef MS_WIN32 /* For a COM method, skip the first arg */ if (self->index) {