Skip to content

Commit 18cf8e6

Browse files
lucylqfacebook-github-bot
authored andcommitted
Do not copy beyond out tensor bounds (pytorch#15648)
Summary: `set_all_to_value(out_data, out_step_len, value)` loops over the padding and copies a row at a time. Add some checks to make sure we do not exceed the out tensor (out_data) size when copying. Differential Revision: D86436435
1 parent f83227c commit 18cf8e6

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

kernels/portable/cpu/op_constant_pad_nd.cpp

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,17 @@ void apply_padding_to_dim(
5757
size_t out_step_len = out_strides[dim];
5858
size_t in_step_len = self_strides[dim];
5959

60-
for ([[maybe_unused]] const auto i : c10::irange(pad_before)) {
60+
// Do not copy padding beyond the out tensor bounds.
61+
if (pad_before > 0) {
62+
auto numel = 1;
63+
for (ET_UNUSED const auto i : c10::irange(out_sizes.size())) {
64+
numel *= out_sizes[i];
65+
}
66+
ET_CHECK_MSG(
67+
numel * sizeof(CTYPE) >= pad_before * out_step_len,
68+
"Out tensor is too small for the requested padding.");
69+
}
70+
for (ET_UNUSED const auto i : c10::irange(pad_before)) {
6171
set_all_to_value(out_data, out_step_len, value);
6272
out_data += out_step_len;
6373
}
@@ -76,7 +86,7 @@ void apply_padding_to_dim(
7686
}
7787
// Otherwise, call this function recursively
7888
else {
79-
for ([[maybe_unused]] const auto i : c10::irange(self_sizes[dim])) {
89+
for (ET_UNUSED const auto i : c10::irange(self_sizes[dim])) {
8090
apply_padding_to_dim(
8191
ndim,
8292
self_data,
@@ -95,7 +105,17 @@ void apply_padding_to_dim(
95105
}
96106
}
97107

98-
for ([[maybe_unused]] const auto i : c10::irange(pad_after)) {
108+
// Do not copy padding beyond the out tensor bounds.
109+
if (pad_after > 0) {
110+
auto numel = 1;
111+
for (ET_UNUSED const auto i : c10::irange(out_sizes.size())) {
112+
numel *= out_sizes[i];
113+
}
114+
ET_CHECK_MSG(
115+
numel * sizeof(CTYPE) >= pad_after * out_step_len,
116+
"Out tensor is too small for the requested padding.");
117+
}
118+
for (ET_UNUSED const auto i : c10::irange(pad_after)) {
99119
set_all_to_value(out_data, out_step_len, value);
100120
out_data += out_step_len;
101121
}

0 commit comments

Comments
 (0)