Skip to content

Check for buffer overflow in prim_ops::et_copy_index() #12697

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 24, 2025
Merged
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
19 changes: 13 additions & 6 deletions kernels/prim_ops/et_copy_index.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,9 @@ void et_copy_index(KernelRuntimeContext& context, EValue** stack) {
// If we're copying past the first index then the shape of
// copy_from and copy_to without the leading dimension should be
// the same. i.e. copy_to.size[1:] == copy_from.size[:].
if (index > 0) {
ET_CHECK_MSG(
copy_to.sizes()[i + 1] == copy_from.sizes()[i],
"Mismatch in shape between copy_to and copy_from tensors");
}
ET_CHECK_MSG(
copy_to.sizes()[i + 1] == copy_from.sizes()[i],
"Mismatch in shape between copy_to and copy_from tensors");
expected_output_size[i + 1] = copy_from.sizes()[i];
}

Expand All @@ -111,8 +109,17 @@ void et_copy_index(KernelRuntimeContext& context, EValue** stack) {
// If we've reached here, it means the copy_to tensor has been
// successfully resized so we can now copy over the data from
// copy_from into the copy_to tensor.

// Check that the destination has enough space for the copy.
size_t offset = index * size_copy_from;
size_t copy_to_size = copy_to.element_size() * copy_to.numel();
ET_CHECK_MSG(
offset + size_copy_from <= copy_to_size,
"Buffer overflow: copy_to tensor is smaller than copy_from tensor.");

memcpy(
(void*)((uintptr_t)copy_to_ptr + index * size_copy_from),
// NOLINTNEXTLINE(performance-no-int-to-ptr)
(void*)((uintptr_t)copy_to_ptr + offset),
copy_from_ptr,
size_copy_from);
}
Expand Down
2 changes: 1 addition & 1 deletion kernels/prim_ops/test/prim_ops_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ TEST_F(RegisterPrimOpsTest, TestETCopyIndex) {
Tensor copy_to = tf.make({2, 2}, {0, 0, 0, 0});
#else
std::vector<int> buf(4);
SizesType expected_output_size[2] = {0, 0};
SizesType expected_output_size[2] = {0, 2};
Tensor copy_to =
tf.make({2, 2}, {0, 0, 0, 0}, {}, TensorShapeDynamism::DYNAMIC_BOUND);
// Resize the tensor to 0 size for the tests.
Expand Down
Loading