Skip to content

Commit c88a9f4

Browse files
validate backup size in BlackboardRestore (#1182)
1 parent 879522c commit c88a9f4

2 files changed

Lines changed: 47 additions & 1 deletion

File tree

‎src/bt_factory.cpp‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -773,7 +773,12 @@ NodeStatus Tree::tickRoot(TickOption opt, std::chrono::milliseconds sleep_time)
773773

774774
void BlackboardRestore(const std::vector<Blackboard::Ptr>& backup, Tree& tree)
775775
{
776-
assert(backup.size() == tree.subtrees.size());
776+
if(backup.size() != tree.subtrees.size())
777+
{
778+
throw RuntimeError("BlackboardRestore: the backup contains ",
779+
std::to_string(backup.size()), " blackboards, but the tree has ",
780+
std::to_string(tree.subtrees.size()), " subtrees");
781+
}
777782
for(size_t i = 0; i < tree.subtrees.size(); i++)
778783
{
779784
backup[i]->cloneInto(*(tree.subtrees[i]->blackboard));

‎tests/gtest_blackboard.cpp‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,47 @@ TEST(BlackboardTest, BlackboardBackup)
542542
ASSERT_EQ(status, BT::NodeStatus::SUCCESS);
543543
}
544544

545+
TEST(BlackboardTest, BlackboardRestoreSizeMismatch)
546+
{
547+
BT::BehaviorTreeFactory factory;
548+
549+
const std::string one_subtree = R"(
550+
<root BTCPP_format="4" main_tree_to_execute="SmallTree">
551+
<BehaviorTree ID="SmallTree">
552+
<AlwaysSuccess />
553+
</BehaviorTree>
554+
</root> )";
555+
556+
const std::string four_subtrees = R"(
557+
<root BTCPP_format="4" main_tree_to_execute="BigTree">
558+
<BehaviorTree ID="MySubtree">
559+
<AlwaysSuccess />
560+
</BehaviorTree>
561+
<BehaviorTree ID="BigTree">
562+
<Sequence>
563+
<SubTree ID="MySubtree" />
564+
<SubTree ID="MySubtree" name="second" />
565+
<SubTree ID="MySubtree" name="third" />
566+
</Sequence>
567+
</BehaviorTree>
568+
</root> )";
569+
570+
auto small_tree = factory.createTreeFromText(one_subtree);
571+
const auto bb_backup = BlackboardBackup(small_tree);
572+
ASSERT_EQ(bb_backup.size(), 1u);
573+
574+
auto big_tree = factory.createTreeFromText(four_subtrees);
575+
ASSERT_EQ(big_tree.subtrees.size(), 4u);
576+
577+
// The backup is shorter than the number of subtrees: reject it instead of
578+
// indexing past the end of the vector.
579+
ASSERT_THROW(BlackboardRestore(bb_backup, big_tree), BT::RuntimeError);
580+
581+
// A backup taken from the same tree must still be accepted.
582+
const auto big_backup = BlackboardBackup(big_tree);
583+
ASSERT_NO_THROW(BlackboardRestore(big_backup, big_tree));
584+
}
585+
545586
TEST(BlackboardTest, RootBlackboard)
546587
{
547588
BT::BehaviorTreeFactory factory;

0 commit comments

Comments
 (0)