Skip to content

Commit a8ff3d7

Browse files
author
Github Executorch
committed
Fix integer overflow in compute_numel() (TOB-EXECUTORCH-19)
compute_numel() multiplies tensor dimensions without overflow protection. The result is used for size calculations in make_tensor_ptr() and clone_tensor_ptr(), so an overflow could lead to undersized allocations and subsequent buffer overflows. Add an ET_CHECK_MSG before each multiplication to verify that numel * sizes[i] will not exceed SSIZE_MAX. This PR was authored with the assistance of Claude.
1 parent 15e8bf7 commit a8ff3d7

1 file changed

Lines changed: 7 additions & 0 deletions

File tree

runtime/core/portable_type/tensor_impl.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <executorch/runtime/core/portable_type/tensor_impl.h>
1010

1111
#include <algorithm>
12+
#include <climits>
1213
#include <cstdint>
1314

1415
#include <c10/util/irange.h>
@@ -38,6 +39,12 @@ ssize_t compute_numel(const TensorImpl::SizesType* sizes, ssize_t dim) {
3839
"Size must be non-negative, got %zd at dimension %zd",
3940
static_cast<ssize_t>(sizes[i]),
4041
i);
42+
ET_CHECK_MSG(
43+
sizes[i] == 0 || numel <= SSIZE_MAX / sizes[i],
44+
"Overflow computing numel: %zd * %zd would overflow ssize_t at dimension %zd",
45+
numel,
46+
static_cast<ssize_t>(sizes[i]),
47+
i);
4148
numel *= sizes[i];
4249
}
4350
return numel;

0 commit comments

Comments
 (0)