Skip to content

Commit d20f628

Browse files
fix overflow in the integer to floating point safe-cast checks (#1238)
1 parent 33c3673 commit d20f628

3 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎include/behaviortree_cpp/utils/convert_impl.hpp‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,11 @@ inline void checkTruncation(const From& from)
102102
}
103103
else
104104
{
105-
doesnt_fit = std::abs(static_cast<int64_t>(from)) > static_cast<int64_t>(max_exact);
105+
// Negate in unsigned arithmetic: std::abs(INT64_MIN) overflows.
106+
const auto value = static_cast<int64_t>(from);
107+
const uint64_t magnitude =
108+
value < 0 ? 0 - static_cast<uint64_t>(value) : static_cast<uint64_t>(value);
109+
doesnt_fit = magnitude > max_exact;
106110
}
107111
if(doesnt_fit)
108112
{

‎include/behaviortree_cpp/utils/safe_any.hpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,12 @@ inline bool ValidCast(const SRC& val)
259259
{
260260
// For integral to float, check if we can represent the value exactly
261261
TO as_float = static_cast<TO>(val);
262+
// as_float can round up to 2^digits (e.g. INT64_MAX -> 2^63), one past
263+
// the max of SRC. Casting that back to SRC would overflow.
264+
if(as_float >= std::ldexp(TO(1), std::numeric_limits<SRC>::digits))
265+
{
266+
return false;
267+
}
262268
SRC back_conv = static_cast<SRC>(as_float);
263269
return back_conv == val;
264270
}

‎tests/gtest_basic_types.cpp‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,25 @@ TEST(BasicTypes, DoubleToIntBoundary)
148148
EXPECT_NO_THROW(bb->set("k", in_range));
149149
}
150150

151+
TEST(BasicTypes, IntToDoubleBoundary)
152+
{
153+
// The precision check must not negate INT64_MIN (signed overflow, undefined
154+
// behavior). Its magnitude is above 2^53, so it is rejected like INT64_MAX.
155+
EXPECT_ANY_THROW((void)BT::Any(INT64_MIN).cast<double>());
156+
EXPECT_ANY_THROW((void)BT::Any(INT64_MAX).cast<double>());
157+
EXPECT_EQ(BT::Any(int64_t(-4503599627370496LL)).cast<double>(), -4503599627370496.0);
158+
159+
// Through Blackboard::set, INT64_MAX rounds up to 2^63 as a double, which must
160+
// not be cast back to int64_t. All three extremes are beyond 2^53.
161+
auto bb = BT::Blackboard::create();
162+
bb->set("d", 1.0); // lock the entry to double
163+
EXPECT_ANY_THROW(bb->set("d", INT64_MAX));
164+
EXPECT_ANY_THROW(bb->set("d", UINT64_MAX));
165+
EXPECT_ANY_THROW(bb->set("d", INT64_MIN));
166+
EXPECT_NO_THROW(bb->set("d", int64_t(1000)));
167+
EXPECT_EQ(bb->get<double>("d"), 1000.0);
168+
}
169+
151170
TEST(BasicTypes, ConvertFromString_Bool)
152171
{
153172
ASSERT_TRUE(convertFromString<bool>("true"));

0 commit comments

Comments
 (0)