Skip to content

Commit 33318db

Browse files
lucylqfacebook-github-bot
authored andcommitted
Add checks for compute_slice (#15647)
Summary: Add safety checks to compute_slice, to ensure that we: 1. Do not read outside of the src tensor bounds 2. Do not write outside of the output tensor bounds Differential Revision: D86433966
1 parent f83227c commit 33318db

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

kernels/portable/cpu/util/slice_util.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,14 @@ void compute_slice(
156156
int64_t length,
157157
int64_t step,
158158
Tensor& out) {
159+
ET_CHECK_MSG(
160+
dim < in.dim(),
161+
"Requested dim is larger than input tensor dim; dim = %" PRId64,
162+
dim);
163+
ET_CHECK_MSG(start < dim, "Requested start is larger than the dim size.");
164+
ET_CHECK_MSG(
165+
length * step < dim,
166+
"Requested length * step is larger than the dim size.");
159167
size_t dim_length = in.size(dim);
160168

161169
size_t leading_dims = getLeadingDims(in, dim);
@@ -170,6 +178,9 @@ void compute_slice(
170178
const char* input_data = in.const_data_ptr<char>();
171179
char* dest = out.mutable_data_ptr<char>();
172180

181+
ET_CHECK_MSG(
182+
out.nbytes() >= (length * leading_dims * length_per_step),
183+
"out.nbytes() is smaller than the expected slice size.");
173184
for (const auto i : c10::irange(leading_dims)) {
174185
const char* src = input_data + (i * dim_length + start) * length_per_step;
175186
for ([[maybe_unused]] const auto j : c10::irange(length)) {

0 commit comments

Comments
 (0)