Skip to content

Commit

Permalink
MessageProtocol: Add concurrency protection for callback functions
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
philb authored and mikecrowe committed Jul 15, 2021
1 parent 46ed337 commit 65ed553
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/dbus_messageprotocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,24 +73,28 @@ void DBus::MessageProtocol::reset() { startMessage(); }
void DBus::MessageProtocol::setMethodCallHandler(
const DBus::Message::CallbackFunctionMethodCall& callback)
{
std::lock_guard<std::recursive_mutex> lock(m_CallbackMutex);
m_MethodCallCallback = callback;
}

void DBus::MessageProtocol::setMethodReturnHandler(
const DBus::Message::CallbackFunctionMethodReturn& callback)
{
std::lock_guard<std::recursive_mutex> lock(m_CallbackMutex);
m_MethodReturnCallback = callback;
}

void DBus::MessageProtocol::setErrorHandler(
const DBus::Message::CallbackFunctionError& callback)
{
std::lock_guard<std::recursive_mutex> lock(m_CallbackMutex);
m_ErrorCallback = callback;
}

void DBus::MessageProtocol::setSignalHandler(
const DBus::Message::CallbackFunctionSignal& callback)
{
std::lock_guard<std::recursive_mutex> lock(m_CallbackMutex);
m_SignalCallback = callback;
}

Expand Down Expand Up @@ -211,6 +215,7 @@ void DBus::MessageProtocol::onBodyComplete(const std::string& body)
try
{
uint8_t type = Type::asByte(m_HeaderStruct[1]);
std::lock_guard<std::recursive_mutex> lock(m_CallbackMutex);
switch (type) {
case TYPE_METHOD:
m_MethodCallCallback(Message::MethodCall(m_HeaderStruct, body));
Expand Down
2 changes: 2 additions & 0 deletions src/dbus_messageprotocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#ifndef DBUS_MESSAGEPROTOCOL
#define DBUS_MESSAGEPROTOCOL

#include <mutex>
#include "dbus_message.h"
#include "dbus_octetbuffer.h"
#include "dbus_type_struct.h"
Expand Down Expand Up @@ -61,6 +62,7 @@ class MessageProtocol {
std::basic_string<uint8_t> m_octetCache;

//
std::recursive_mutex m_CallbackMutex;
Message::CallbackFunctionMethodCall m_MethodCallCallback;
Message::CallbackFunctionMethodReturn m_MethodReturnCallback;
Message::CallbackFunctionError m_ErrorCallback;
Expand Down

0 comments on commit 65ed553

Please sign in to comment.