diff --git a/Lib/test/test_buffer.py b/Lib/test/test_buffer.py index f42a71cea319b63..756580c52a74c0f 100644 --- a/Lib/test/test_buffer.py +++ b/Lib/test/test_buffer.py @@ -4906,5 +4906,22 @@ def __release_buffer__(self, view): b.extend(A()) +@unittest.skipIf(ctypes is None or ndarray is None, + "requires ctypes and _testbuffer") +class TestPyObjectCopyData(unittest.TestCase): + def test_mismatched_shape(self): + copy_data = ctypes.pythonapi.PyObject_CopyData + copy_data.argtypes = (ctypes.py_object, ctypes.py_object) + copy_data.restype = ctypes.c_int + + source = ndarray(list(range(7)), shape=(2, 2), strides=(4, 2), + format='B') + destination = ndarray([0] * 8, shape=(2, 4), format='B', + flags=ND_WRITABLE) + + with self.assertRaisesRegex(BufferError, "same shape"): + copy_data(destination, source) + + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/C_API/2026-11-07-01-10-00.gh-issue-161081.6wq7KJ.rst b/Misc/NEWS.d/next/C_API/2026-11-07-01-10-00.gh-issue-161081.6wq7KJ.rst new file mode 100644 index 000000000000000..34e53e52ee5d4eb --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-11-07-01-10-00.gh-issue-161081.6wq7KJ.rst @@ -0,0 +1,2 @@ +Fix :c:func:`PyObject_CopyData` corrupting memory when copying between +non-contiguous buffers with different shapes. diff --git a/Objects/abstract.c b/Objects/abstract.c index da2a0b0c285b52b..d93b9bb7cfb6d2e 100644 --- a/Objects/abstract.c +++ b/Objects/abstract.c @@ -719,6 +719,23 @@ int PyObject_CopyData(PyObject *dest, PyObject *src) /* Otherwise a more elaborate copy scheme is needed */ + if (view_dest.ndim != view_src.ndim) { + PyErr_SetString(PyExc_BufferError, + "destination and source buffers must have the same shape"); + PyBuffer_Release(&view_dest); + PyBuffer_Release(&view_src); + return -1; + } + for (k = 0; k < view_src.ndim; k++) { + if (view_dest.shape[k] != view_src.shape[k]) { + PyErr_SetString(PyExc_BufferError, + "destination and source buffers must have the same shape"); + PyBuffer_Release(&view_dest); + PyBuffer_Release(&view_src); + return -1; + } + } + /* XXX(nnorwitz): need to check for overflow! */ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim); if (indices == NULL) {