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
17 changes: 17 additions & 0 deletions Lib/test/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :c:func:`PyObject_CopyData` corrupting memory when copying between
non-contiguous buffers with different shapes.
17 changes: 17 additions & 0 deletions Objects/abstract.c
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading