Revert "Revert "Allow proxies to be compared.""

This reverts commit 7c238ef97977204a5a5ff65a39f602ceb44ed307.

(originally reverted due to merge conflicts)

Bug: 32172906
Test: hidl_test

Change-Id: I590c60ed529847742dede590e1e9a152a7650da0
diff --git a/transport/include/hidl/HidlBinderSupport.h b/transport/include/hidl/HidlBinderSupport.h
index 6f82dbc..47ff581 100644
--- a/transport/include/hidl/HidlBinderSupport.h
+++ b/transport/include/hidl/HidlBinderSupport.h
@@ -306,25 +306,42 @@
 // Otherwise, the smallest possible BnChild is found where IChild is a subclass of IType
 // and iface is of class IChild. BnChild will be used to wrapped the given iface.
 // Return nullptr if iface is null or any failure.
-template <typename IType, typename ProxyType>
+template <typename IType>
 sp<IBinder> toBinder(sp<IType> iface) {
     IType *ifacePtr = iface.get();
     if (ifacePtr == nullptr) {
         return nullptr;
     }
     if (ifacePtr->isRemote()) {
-        return ::android::hardware::IInterface::asBinder(static_cast<ProxyType *>(ifacePtr));
+        return ::android::hardware::IInterface::asBinder(
+            static_cast<BpInterface<IType>*>(ifacePtr));
     } else {
         std::string myDescriptor = details::getDescriptor(ifacePtr);
         if (myDescriptor.empty()) {
             // interfaceDescriptor fails
             return nullptr;
         }
-        auto func = details::gBnConstructorMap.get(myDescriptor, nullptr);
-        if (!func) {
-            return nullptr;
+
+        // for get + set
+        std::unique_lock<std::mutex> _lock = details::gBnMap.lock();
+
+        wp<BHwBinder> wBnObj = details::gBnMap.getLocked(ifacePtr, nullptr);
+        sp<IBinder> sBnObj = wBnObj.promote();
+
+        if (sBnObj == nullptr) {
+            auto func = details::gBnConstructorMap.get(myDescriptor, nullptr);
+            if (!func) {
+                return nullptr;
+            }
+
+            sBnObj = sp<IBinder>(func(static_cast<void*>(ifacePtr)));
+
+            if (sBnObj != nullptr) {
+                details::gBnMap.setLocked(ifacePtr, static_cast<BHwBinder*>(sBnObj.get()));
+            }
         }
-        return sp<IBinder>(func(static_cast<void *>(ifacePtr)));
+
+        return sBnObj;
     }
 }