From a5e94f07bfac9d29df26ff62797705da27d89369 Mon Sep 17 00:00:00 2001 From: Benjamin Kaufmann Date: Sat, 12 Jun 2021 13:02:17 +0200 Subject: [PATCH] Fix issue #135: Segfault in Message::peekType() * Add missing nullptr check in Message::peekType(). * According to its specification, sd_bus_message_peek_type() sets a given contents parameter to NULL if the next element in a message is not a container. Since assigning a nullptr to a std::string has undefined behaviour (typically resulting in an invalid memory access), Message::peekType() must not assign contentsSig unconditionally. --- src/Message.cpp | 2 +- tests/unittests/Message_test.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/Message.cpp b/src/Message.cpp index 5f89fe0..d59d0af 100644 --- a/src/Message.cpp +++ b/src/Message.cpp @@ -617,7 +617,7 @@ void Message::peekType(std::string& type, std::string& contents) const auto r = sd_bus_message_peek_type((sd_bus_message*)msg_, &typeSig, &contentsSig); SDBUS_THROW_ERROR_IF(r < 0, "Failed to peek message type", -r); type = typeSig; - contents = contentsSig; + contents = contentsSig ? contentsSig : ""; } bool Message::isValid() const diff --git a/tests/unittests/Message_test.cpp b/tests/unittests/Message_test.cpp index 755a4e9..01baf6d 100644 --- a/tests/unittests/Message_test.cpp +++ b/tests/unittests/Message_test.cpp @@ -238,3 +238,29 @@ TEST(AMessage, CanCarryAComplexType) ASSERT_THAT(dataRead, Eq(dataWritten)); } + +TEST(AMessage, CanPeekASimpleType) +{ + auto msg = sdbus::createPlainMessage(); + msg << 123; + msg.seal(); + + std::string type; + std::string contents; + msg.peekType(type, contents); + ASSERT_THAT(type, "i"); + ASSERT_THAT(contents, ""); +} + +TEST(AMessage, CanPeekContainerContents) +{ + auto msg = sdbus::createPlainMessage(); + msg << std::map{{1, "one"}, {2, "two"}}; + msg.seal(); + + std::string type; + std::string contents; + msg.peekType(type, contents); + ASSERT_THAT(type, "a"); + ASSERT_THAT(contents, "{is}"); +}