Skip to content

Commit fb27e62

Browse files
committed
gh-161081: Reject mismatched non-contiguous buffers in PyObject_CopyData
1 parent d900c8f commit fb27e62

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎Lib/test/test_buffer.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4906,5 +4906,22 @@ def __release_buffer__(self, view):
49064906
b.extend(A())
49074907

49084908

4909+
@unittest.skipIf(ctypes is None or ndarray is None,
4910+
"requires ctypes and _testbuffer")
4911+
class TestPyObjectCopyData(unittest.TestCase):
4912+
def test_mismatched_shape(self):
4913+
copy_data = ctypes.pythonapi.PyObject_CopyData
4914+
copy_data.argtypes = (ctypes.py_object, ctypes.py_object)
4915+
copy_data.restype = ctypes.c_int
4916+
4917+
source = ndarray(list(range(7)), shape=(2, 2), strides=(4, 2),
4918+
format='B')
4919+
destination = ndarray([0] * 8, shape=(2, 4), format='B',
4920+
flags=ND_WRITABLE)
4921+
4922+
with self.assertRaisesRegex(BufferError, "same shape"):
4923+
copy_data(destination, source)
4924+
4925+
49094926
if __name__ == "__main__":
49104927
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :c:func:`PyObject_CopyData` corrupting memory when copying between
2+
non-contiguous buffers with different shapes.

‎Objects/abstract.c‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,23 @@ int PyObject_CopyData(PyObject *dest, PyObject *src)
719719

720720
/* Otherwise a more elaborate copy scheme is needed */
721721

722+
if (view_dest.ndim != view_src.ndim) {
723+
PyErr_SetString(PyExc_BufferError,
724+
"destination and source buffers must have the same shape");
725+
PyBuffer_Release(&view_dest);
726+
PyBuffer_Release(&view_src);
727+
return -1;
728+
}
729+
for (k = 0; k < view_src.ndim; k++) {
730+
if (view_dest.shape[k] != view_src.shape[k]) {
731+
PyErr_SetString(PyExc_BufferError,
732+
"destination and source buffers must have the same shape");
733+
PyBuffer_Release(&view_dest);
734+
PyBuffer_Release(&view_src);
735+
return -1;
736+
}
737+
}
738+
722739
/* XXX(nnorwitz): need to check for overflow! */
723740
indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
724741
if (indices == NULL) {

0 commit comments

Comments
 (0)