libbinder: delete dead server objects

We can do more active cleanup, and we can do kinder cleanup, but for now
fix leaks (future considerations/TODOs left in code).

Bug: 185167543
Test: binderRpcTest
Change-Id: Ide06476aefd72cbc46ba5fba095244a5448e493b
diff --git a/libs/binder/RpcSession.cpp b/libs/binder/RpcSession.cpp
index 09ec20d..bf998c1 100644
--- a/libs/binder/RpcSession.cpp
+++ b/libs/binder/RpcSession.cpp
@@ -24,6 +24,7 @@
 #include <string_view>
 
 #include <binder/Parcel.h>
+#include <binder/RpcServer.h>
 #include <binder/Stability.h>
 #include <utils/String8.h>
 
@@ -168,6 +169,22 @@
                         "bad state: connection object guaranteed to be in list");
 }
 
+void RpcSession::terminateLocked() {
+    // TODO(b/185167543):
+    // - kindly notify other side of the connection of termination (can't be
+    // locked)
+    // - prevent new client/servers from being added
+    // - stop all threads which are currently reading/writing
+    // - terminate RpcState?
+
+    if (mTerminated) return;
+
+    sp<RpcServer> server = mForServer.promote();
+    if (server) {
+        server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
+    }
+}
+
 wp<RpcServer> RpcSession::server() {
     return mForServer;
 }
@@ -264,6 +281,9 @@
     std::lock_guard<std::mutex> _l(mMutex);
     if (auto it = std::find(mServers.begin(), mServers.end(), connection); it != mServers.end()) {
         mServers.erase(it);
+        if (mServers.size() == 0) {
+            terminateLocked();
+        }
         return true;
     }
     return false;