From cf21866a47ebf8809a9a3cc1452796605b5d3a8f Mon Sep 17 00:00:00 2001 From: Guo-Rong <5484552+gkoh@users.noreply.github.com> Date: Wed, 25 Dec 2024 11:36:32 +1030 Subject: [PATCH] Fix disconnect race crash. It was possible for the Target object to be destructed before it stopped. This manifested as a crash when freed memory was accessed. Add a flag to wait and check. --- include/FurbleControl.h | 2 ++ src/FurbleControl.cpp | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/include/FurbleControl.h b/include/FurbleControl.h index c5d09a5..edbafb1 100644 --- a/include/FurbleControl.h +++ b/include/FurbleControl.h @@ -50,6 +50,8 @@ class Control { protected: Target(Camera *camera); + volatile bool m_Stopped = false; + private: static constexpr UBaseType_t m_QueueLength = 8; diff --git a/src/FurbleControl.cpp b/src/FurbleControl.cpp index f92642e..169a5e5 100644 --- a/src/FurbleControl.cpp +++ b/src/FurbleControl.cpp @@ -75,6 +75,7 @@ void Control::Target::task(void) { } } task_exit: + m_Stopped = true; vTaskDelete(NULL); } @@ -212,10 +213,18 @@ void Control::disconnect(void) { const std::lock_guard lock(m_Mutex); + // send disconnect for (const auto &target : m_Targets) { target->sendCommand(CMD_DISCONNECT); } + // wait for tasks to finish + for (const auto &target : m_Targets) { + do { + vTaskDelay(pdMS_TO_TICKS(1)); + } while (!target.get()->m_Stopped); + } + m_Targets.clear(); m_State = STATE_IDLE; }