libpldmresponder: fix a potential pldm crash

In the current state, pldm does create the sensor/effecter even in the
absence of the underlying dbus resource. There is a bug in the responder
code due to which we emplace an empty dbus value map into the handler
with a sensor ID. And if the remote PLDM endpoint queries for the state
of the sensor, pldm would crash since it tries to read content from the
empty dbus value map. This commit would fix the crash by adding
necessary bound checks.

Testing:
1. Unit tests passed.
2. Functionally verified the fix by giving a dummy dbus object path and
making sure that the sensor/effecter is not created & also ensured that
pldm does not crash.

Change-Id: I5fb06677f6ae1bd74f9ec741b311f59737caf79d
Signed-off-by: Manojkiran Eda <manojkiran.eda@gmail.com>
diff --git a/libpldmresponder/pdr_state_sensor.hpp b/libpldmresponder/pdr_state_sensor.hpp
index aa29859..ea24497 100644
--- a/libpldmresponder/pdr_state_sensor.hpp
+++ b/libpldmresponder/pdr_state_sensor.hpp
@@ -73,7 +73,6 @@
         HTOLE16(pdr->hdr.length);
 
         pdr->terminus_handle = TERMINUS_HANDLE;
-        pdr->sensor_id = handler.getNextSensorId();
 
         try
         {
@@ -118,7 +117,6 @@
         pdr->composite_sensor_count = sensors.size();
 
         HTOLE16(pdr->terminus_handle);
-        HTOLE16(pdr->sensor_id);
         HTOLE16(pdr->entity_type);
         HTOLE16(pdr->entity_instance);
         HTOLE16(pdr->container_id);
@@ -173,21 +171,26 @@
                 error(
                     "Failed to create sensor PDR, D-Bus object '{PATH}' returned {ERROR}",
                     "PATH", objectPath, "ERROR", e);
-                continue;
+                break;
             }
-
             dbusMappings.emplace_back(std::move(dbusMapping));
             dbusValMaps.emplace_back(std::move(dbusIdToValMap));
         }
 
-        handler.addDbusObjMaps(
-            pdr->sensor_id,
-            std::make_tuple(std::move(dbusMappings), std::move(dbusValMaps)),
-            pldm::responder::pdr_utils::TypeId::PLDM_SENSOR_ID);
-        pldm::responder::pdr_utils::PdrEntry pdrEntry{};
-        pdrEntry.data = entry.data();
-        pdrEntry.size = pdrSize;
-        repo.addRecord(pdrEntry);
+        if (!(dbusMappings.empty() && dbusValMaps.empty()))
+        {
+            pdr->sensor_id = handler.getNextSensorId();
+            HTOLE16(pdr->sensor_id);
+            handler.addDbusObjMaps(
+                pdr->sensor_id,
+                std::make_tuple(std::move(dbusMappings),
+                                std::move(dbusValMaps)),
+                pldm::responder::pdr_utils::TypeId::PLDM_SENSOR_ID);
+            pldm::responder::pdr_utils::PdrEntry pdrEntry{};
+            pdrEntry.data = entry.data();
+            pdrEntry.size = pdrSize;
+            repo.addRecord(pdrEntry);
+        }
     }
 }