Skip to content

Commit 9483c72

Browse files
authored
Check for buffer overflow in prim_ops::et_copy_index() (#12822)
^ Test on top of D78676341. ghstack-source-id: 298161226 @exported-using-ghexport Differential Revision: [D78701418](https://our.internmc.facebook.com/intern/diff/D78701418/)
1 parent 9d92ff8 commit 9483c72

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

kernels/prim_ops/et_copy_index.cpp

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,11 +86,9 @@ void et_copy_index(KernelRuntimeContext& context, EValue** stack) {
8686
// If we're copying past the first index then the shape of
8787
// copy_from and copy_to without the leading dimension should be
8888
// the same. i.e. copy_to.size[1:] == copy_from.size[:].
89-
if (index > 0) {
90-
ET_CHECK_MSG(
91-
copy_to.sizes()[i + 1] == copy_from.sizes()[i],
92-
"Mismatch in shape between copy_to and copy_from tensors");
93-
}
89+
ET_CHECK_MSG(
90+
copy_to.sizes()[i + 1] == copy_from.sizes()[i],
91+
"Mismatch in shape between copy_to and copy_from tensors");
9492
expected_output_size[i + 1] = copy_from.sizes()[i];
9593
}
9694

@@ -111,8 +109,17 @@ void et_copy_index(KernelRuntimeContext& context, EValue** stack) {
111109
// If we've reached here, it means the copy_to tensor has been
112110
// successfully resized so we can now copy over the data from
113111
// copy_from into the copy_to tensor.
112+
113+
// Check that the destination has enough space for the copy.
114+
size_t offset = index * size_copy_from;
115+
size_t copy_to_size = copy_to.element_size() * copy_to.numel();
116+
ET_CHECK_MSG(
117+
offset + size_copy_from <= copy_to_size,
118+
"Buffer overflow: copy_to tensor is smaller than copy_from tensor.");
119+
114120
memcpy(
115-
(void*)((uintptr_t)copy_to_ptr + index * size_copy_from),
121+
// NOLINTNEXTLINE(performance-no-int-to-ptr)
122+
(void*)((uintptr_t)copy_to_ptr + offset),
116123
copy_from_ptr,
117124
size_copy_from);
118125
}

kernels/prim_ops/test/prim_ops_test.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ TEST_F(RegisterPrimOpsTest, TestETCopyIndex) {
215215
Tensor copy_to = tf.make({2, 2}, {0, 0, 0, 0});
216216
#else
217217
std::vector<int> buf(4);
218-
SizesType expected_output_size[2] = {0, 0};
218+
SizesType expected_output_size[2] = {0, 2};
219219
Tensor copy_to =
220220
tf.make({2, 2}, {0, 0, 0, 0}, {}, TensorShapeDynamism::DYNAMIC_BOUND);
221221
// Resize the tensor to 0 size for the tests.

0 commit comments

Comments
 (0)