Add workaround for sdevent OOM error

Process all outstanding bus events before the loop to make sure we don't
hit OOM errors.

Change-Id: I52e0a018d9c89dc0c5fdfba441d0ec3d5800fdcf
Signed-off-by: Willy Tu <wltu@google.com>
diff --git a/main.cpp b/main.cpp
index fce2a8f..fd8f4b6 100644
--- a/main.cpp
+++ b/main.cpp
@@ -330,17 +330,30 @@
                 std::bind_front(PostCodeEventHandler, &reporter, verbose));
         }
         // Enable bus to handle incoming IO and bus events
+        bool done = false;
         bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
-        auto intCb = [](sdeventplus::source::Signal& source,
-                        const struct signalfd_siginfo*) {
+        auto intCb = [&done](sdeventplus::source::Signal& source,
+                             const struct signalfd_siginfo*) {
             source.get_event().exit(0);
+            done = true;
         };
         stdplus::signal::block(SIGINT);
         sdeventplus::source::Signal(event, SIGINT, intCb).set_floating(true);
         stdplus::signal::block(SIGTERM);
         sdeventplus::source::Signal(event, SIGTERM, std::move(intCb))
             .set_floating(true);
-        rc = event.loop();
+
+        while (!done)
+        {
+            // Process all outstanding bus events before running the loop.
+            // This prevents the sd-bus handling logic from leaking memory.
+            // TODO: Remove when upstream fixes this bug
+            while (bus.process_discard() > 0)
+                ;
+
+            // Run and never timeout
+            rc = event.run(std::nullopt);
+        }
     }
     catch (const std::exception& e)
     {