fix(uavcan): free the node only after Run() has stopped (#29275)

* fix(uavcan): free the node only after Run() has stopped

uavcan stop deleted the node and left the wait for Run() to the destructor. The destructor freed the firmware and node ID servers before that wait, while Run() on wq:uavcan still used them, and after 50 ms freed the rest regardless, leaving _instance pointing at freed memory for the bus event interrupt, uavcan status and uavcan start. stop() now waits for Run() to clear _instance before deleting the node, and leaves the node allocated if Run() never gets there.

Assisted-by: Claude:claude-opus-5-5

* fix(uavcan): clear the node instance before descheduling it

Run() descheduled itself and then cleared _instance. A bus event interrupt in between still saw the instance and queued Run() again; if that run blocked, the shell's stop() saw _instance clear and freed the node under it.

Assisted-by: Claude:claude-opus-5-5
This commit is contained in:
Jacob Dahl authored and GitHub committed 2026-10-16 17:26:42 -06:00
1 parent 55e3d0ab22
commit 0262f30251
2 files changed
+32 -22

No files matched your search

+31 -22
View File
@@ -135,25 +135,6 @@ UavcanNode::~UavcanNode()
_servers = nullptr;
}
if (_instance) {
/* tell the task we want it to go away */
_task_should_exit.store(true);
ScheduleNow();
unsigned i = 10;
do {
/* wait 5ms - it should wake every 10ms or so worst-case */
usleep(5000);
if (--i == 0) {
break;
}
} while (_instance);
}
// Removing the sensor bridges
_sensor_bridges.clear();
@@ -461,6 +442,33 @@ UavcanNode::start(uavcan::NodeID node_id, uint32_t bitrate)
return OK;
}
int
UavcanNode::stop()
{
UavcanNode *const inst = _instance;
if (inst == nullptr) {
return -1;
}
inst->_task_should_exit.store(true);
inst->ScheduleNow();
// Run() clears _instance once the node and its outputs are off the work queue
for (int i = 0; i < 500 && _instance != nullptr; i++) {
px4_usleep(10000);
}
if (_instance != nullptr) {
// Run() may still be using it, so freeing it is not safe
PX4_ERR("Node did not stop, not freeing it");
return -1;
}
delete inst;
return OK;
}
void
UavcanNode::fill_node_info()
{
@@ -1032,8 +1040,10 @@ UavcanNode::Run()
_mixing_interface_servo.mixingOutput().unregister();
_mixing_interface_servo.ScheduleClear();
#endif
ScheduleClear();
// Cleared first: a bus event interrupt between the two would queue one more Run() that
// stop() does not wait for
_instance = nullptr;
ScheduleClear();
}
}
@@ -1704,8 +1714,7 @@ extern "C" __EXPORT int uavcan_main(int argc, char *argv[])
}
if (!std::strcmp(argv[1], "stop")) {
delete inst;
return 0;
return UavcanNode::stop();
}
print_usage();
+1
View File
@@ -221,6 +221,7 @@ public:
virtual ~UavcanNode();
static int start(uavcan::NodeID node_id, uint32_t bitrate);
static int stop();
uavcan::Node<> &get_node() { return _node; }