Skip to content

Commit 24cc9a2

Browse files
pytorchbotlucylq
andauthored
Check for buffer overflow in prim_ops::et_copy_index() (#12827)
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * __->__ #12697 ^ Test on top of D78676341. Differential Revision: [D78701418](https://our.internmc.facebook.com/intern/diff/D78701418/) Co-authored-by: lucylq <[email protected]>
1 parent e934e6a commit 24cc9a2

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
@@ -131,7 +131,7 @@ TEST_F(RegisterPrimOpsTest, TestETCopyIndex) {
131131
Tensor copy_to = tf.make({2, 2}, {0, 0, 0, 0});
132132
#else
133133
std::vector<int> buf(4);
134-
SizesType expected_output_size[2] = {0, 0};
134+
SizesType expected_output_size[2] = {0, 2};
135135
Tensor copy_to =
136136
tf.make({2, 2}, {0, 0, 0, 0}, {}, TensorShapeDynamism::DYNAMIC_BOUND);
137137
// Resize the tensor to 0 size for the tests.

0 commit comments

Comments
 (0)