Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test for case of undefined behaviour and throw error if found #52707

Merged
merged 1 commit into from
Dec 17, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions tensorflow/core/kernels/sequence_ops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,18 @@ class RangeOp : public OpKernel {
errors::InvalidArgument(
"Requires start >= limit when delta < 0: ", start, "/", limit));
}
int64_t size = 0;
if (std::is_integral<T>::value) {
size = static_cast<int64_t>(
(std::abs(limit - start) + std::abs(delta) - 1) / std::abs(delta));
} else {
size = static_cast<int64_t>(std::ceil(std::abs((limit - start) / delta)));
}
auto size_auto = (std::is_integral<T>::value
? (Eigen::numext::abs(limit - start) +
Eigen::numext::abs(delta) - T(1)) /
Eigen::numext::abs(delta)
: Eigen::numext::ceil(
Eigen::numext::abs((limit - start) / delta)));
OP_REQUIRES(context, size_auto <= std::numeric_limits<int64_t>::max(),
errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
std::numeric_limits<int64_t>::max()));

int64_t size = static_cast<int64_t>(size_auto);

TensorShape shape;
OP_REQUIRES_OK(context, shape.AddDimWithStatus(size));
Tensor* out = nullptr;
Expand Down
7 changes: 7 additions & 0 deletions tensorflow/core/ops/math_ops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,13 @@ Status RangeSize(const Tensor* start_t, const Tensor* limit_t,
Eigen::numext::abs(delta))
: (Eigen::numext::ceil(
Eigen::numext::abs((limit - start) / delta))));

// Undefined behaviour if size will not fit into int64_t
if (size > std::numeric_limits<int64_t>::max()) {
return errors::InvalidArgument(
"Requires ((limit - start) / delta) <= ", std::numeric_limits<int64_t>::max());
}

c->set_output(0, c->Vector(static_cast<int64_t>(size)));
return Status::OK();
}
Expand Down
2 changes: 1 addition & 1 deletion tensorflow/python/kernel_tests/array_ops/init_ops_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ def testLargeLimits(self):
def testLargeStarts(self):
# Test case for GitHub issue 46899.
with self.session():
with self.assertRaises(errors_impl.InvalidArgumentError):
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
v = math_ops.range(start=-1e+38, limit=1)
self.evaluate(v)

Expand Down