libbinder: RPC factor out BinderNode erase

In preparation for adding an invariant here.

Bug: 183140903
Test: binderRpcTest
Change-Id: I541f7c3e5bcb5ee049fabe34acb9784cfeed0d0c
diff --git a/libs/binder/RpcState.cpp b/libs/binder/RpcState.cpp
index 1f97293..6e7088f 100644
--- a/libs/binder/RpcState.cpp
+++ b/libs/binder/RpcState.cpp
@@ -458,9 +458,8 @@
                             addr.toString().c_str());
 
         it->second.timesRecd--;
-        if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
-            mNodeForAddress.erase(it);
-        }
+        LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
+                            "Bad state. RpcState shouldn't own received binder");
     }
 
     RpcWireHeader cmd = {
@@ -799,22 +798,26 @@
     LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
                         addr.toString().c_str());
 
-    sp<IBinder> tempHold;
-
     it->second.timesSent--;
+    sp<IBinder> tempHold = tryEraseNode(it);
+    _l.unlock();
+    tempHold = nullptr; // destructor may make binder calls on this session
+
+    return OK;
+}
+
+sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
+    sp<IBinder> ref;
+
     if (it->second.timesSent == 0) {
-        tempHold = it->second.sentRef;
-        it->second.sentRef = nullptr;
+        ref = std::move(it->second.sentRef);
 
         if (it->second.timesRecd == 0) {
             mNodeForAddress.erase(it);
         }
     }
 
-    _l.unlock();
-    tempHold = nullptr; // destructor may make binder calls on this session
-
-    return OK;
+    return ref;
 }
 
 } // namespace android