Skip to content
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
11 changes: 9 additions & 2 deletions runtime/core/portable_type/tensor_impl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <cstdint>

#include <c10/util/irange.h>
#include <c10/util/safe_numerics.h>

#include <executorch/runtime/core/exec_aten/util/dim_order_util.h>
#include <executorch/runtime/core/exec_aten/util/scalar_type_util.h>
Expand All @@ -38,7 +39,9 @@ ssize_t compute_numel(const TensorImpl::SizesType* sizes, ssize_t dim) {
"Size must be non-negative, got %zd at dimension %zd",
static_cast<ssize_t>(sizes[i]),
i);
numel *= sizes[i];
bool overflow =
c10::mul_overflows(numel, static_cast<ssize_t>(sizes[i]), &numel);
ET_CHECK_MSG(!overflow, "numel overflowed");
}
return numel;
}
Expand Down Expand Up @@ -66,7 +69,11 @@ TensorImpl::TensorImpl(
}

size_t TensorImpl::nbytes() const {
return numel_ * elementSize(type_);
size_t result;
bool overflow = c10::mul_overflows(
static_cast<size_t>(numel_), elementSize(type_), &result);
ET_CHECK_MSG(!overflow, "nbytes overflowed");
return result;
}

// Return the size of one element of the tensor
Expand Down
9 changes: 9 additions & 0 deletions runtime/core/portable_type/test/tensor_impl_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <executorch/runtime/core/portable_type/tensor_impl.h>

#include <gtest/gtest.h>
#include <cstdint>
#include <random>

#include <executorch/runtime/core/exec_aten/util/tensor_util.h>
Expand Down Expand Up @@ -449,3 +450,11 @@ TEST_F(TensorImplTest, TestResizingTensorToZeroAndBack) {
EXPECT_GT(t.numel(), 0);
EXPECT_EQ(t.data(), data);
}

TEST_F(TensorImplTest, TestNbytesOverflow) {
SizesType sizes[3] = {
static_cast<SizesType>(1 << 21),
static_cast<SizesType>(1 << 21),
static_cast<SizesType>(1 << 21)};
ET_EXPECT_DEATH(TensorImpl t(ScalarType::Float, 3, sizes), "");
}
Loading