From 65ed553398308d24551fb561be432d531c6786cc Mon Sep 17 00:00:00 2001 From: Phil Blundell Date: Mon, 4 Jan 2021 12:39:26 +0000 Subject: [PATCH] MessageProtocol: Add concurrency protection for callback functions onBodyComplete() will be called on the transport thread, but setXXHandler() will be called on other threads. We must not delete the function call object while it's being invoked or bad things will happen. Add a mutex to protect against this. --- src/dbus_messageprotocol.cpp | 5 +++++ src/dbus_messageprotocol.h | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/dbus_messageprotocol.cpp b/src/dbus_messageprotocol.cpp index 405a5ad..c4ebdb1 100644 --- a/src/dbus_messageprotocol.cpp +++ b/src/dbus_messageprotocol.cpp @@ -73,24 +73,28 @@ void DBus::MessageProtocol::reset() { startMessage(); } void DBus::MessageProtocol::setMethodCallHandler( const DBus::Message::CallbackFunctionMethodCall& callback) { + std::lock_guard lock(m_CallbackMutex); m_MethodCallCallback = callback; } void DBus::MessageProtocol::setMethodReturnHandler( const DBus::Message::CallbackFunctionMethodReturn& callback) { + std::lock_guard lock(m_CallbackMutex); m_MethodReturnCallback = callback; } void DBus::MessageProtocol::setErrorHandler( const DBus::Message::CallbackFunctionError& callback) { + std::lock_guard lock(m_CallbackMutex); m_ErrorCallback = callback; } void DBus::MessageProtocol::setSignalHandler( const DBus::Message::CallbackFunctionSignal& callback) { + std::lock_guard lock(m_CallbackMutex); m_SignalCallback = callback; } @@ -211,6 +215,7 @@ void DBus::MessageProtocol::onBodyComplete(const std::string& body) try { uint8_t type = Type::asByte(m_HeaderStruct[1]); + std::lock_guard lock(m_CallbackMutex); switch (type) { case TYPE_METHOD: m_MethodCallCallback(Message::MethodCall(m_HeaderStruct, body)); diff --git a/src/dbus_messageprotocol.h b/src/dbus_messageprotocol.h index c6a4a97..fea8128 100644 --- a/src/dbus_messageprotocol.h +++ b/src/dbus_messageprotocol.h @@ -18,6 +18,7 @@ #ifndef DBUS_MESSAGEPROTOCOL #define DBUS_MESSAGEPROTOCOL +#include #include "dbus_message.h" #include "dbus_octetbuffer.h" #include "dbus_type_struct.h" @@ -61,6 +62,7 @@ class MessageProtocol { std::basic_string m_octetCache; // + std::recursive_mutex m_CallbackMutex; Message::CallbackFunctionMethodCall m_MethodCallCallback; Message::CallbackFunctionMethodReturn m_MethodReturnCallback; Message::CallbackFunctionError m_ErrorCallback;