Skip to content

Commit a7a0014

Browse files
fix null _p access in the TestNode async_delay timer handler (#1243)
1 parent 17775ef commit a7a0014

2 files changed

Lines changed: 32 additions & 12 deletions

File tree

‎src/actions/test_node.cpp‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,10 @@ struct TestNode::PImpl
8484
ScriptFunction success_executor;
8585
ScriptFunction failure_executor;
8686
ScriptFunction post_executor;
87-
TimerQueue<> timer;
8887
std::atomic_bool completed = false;
88+
// Keep last: ~TimerQueue() joins the worker thread, so this must be destroyed
89+
// before completed, which the timer handler touches.
90+
TimerQueue<> timer;
8991
};
9092

9193
TestNode::TestNode(const std::string& name, const NodeConfig& config,
@@ -133,17 +135,20 @@ NodeStatus TestNode::onStart()
133135
// convert this in an asynchronous operation. Use another thread to count
134136
// a certain amount of time.
135137
_p->completed = false;
136-
_p->timer.add(std::chrono::milliseconds(_p->config->async_delay), [this](bool aborted) {
137-
if(!aborted)
138-
{
139-
_p->completed.store(true);
140-
this->emitWakeUpSignal();
141-
}
142-
else
143-
{
144-
_p->completed.store(false);
145-
}
146-
});
138+
// The handler must not read _p: ~TimerQueue() runs it (aborted) while the
139+
// PImpl is being deleted, and std::unique_ptr may already hold nullptr then.
140+
_p->timer.add(std::chrono::milliseconds(_p->config->async_delay),
141+
[this, p = _p.get()](bool aborted) {
142+
if(!aborted)
143+
{
144+
p->completed.store(true);
145+
this->emitWakeUpSignal();
146+
}
147+
else
148+
{
149+
p->completed.store(false);
150+
}
151+
});
147152
return NodeStatus::RUNNING;
148153
}
149154

‎tests/gtest_substitution.cpp‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,3 +589,18 @@ TEST(Substitution, IncompatibleTypeSubstitutionThrows)
589589
EXPECT_EQ(tree.tickWhileRunning(), NodeStatus::SUCCESS);
590590
}
591591
}
592+
593+
// Destroying a TestNode while its async_delay timer is pending makes
594+
// ~TimerQueue() run the handler (aborted) during the PImpl deletion. The
595+
// handler used to reach the PImpl through _p, which std::unique_ptr may have
596+
// already reset to nullptr at that point (libc++ does).
597+
TEST(Substitution, DestroyTestNodeWithPendingAsyncDelay)
598+
{
599+
auto test_config = std::make_shared<TestNodeConfig>();
600+
test_config->return_status = NodeStatus::SUCCESS;
601+
test_config->async_delay = std::chrono::milliseconds(10000);
602+
603+
auto node = std::make_unique<TestNode>("mock", NodeConfig{}, test_config);
604+
ASSERT_EQ(node->executeTick(), NodeStatus::RUNNING);
605+
node.reset();
606+
}

0 commit comments

Comments
 (0)