Merge "RpcServer: be thread safe" am: 379dbd1ca4

Original change: https://android-review.googlesource.com/c/platform/frameworks/native/+/1683483

Change-Id: I36e04efbe183e0eea7d28fee2c998abc7ec807e8
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index 1fa37ba..6dc4f95 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -48,16 +48,20 @@
 
     auto connection = RpcConnection::make();
     connection->setForServer(sp<RpcServer>::fromExisting(this));
-    mConnections.push_back(connection);
+    {
+        std::lock_guard<std::mutex> _l(mLock);
+        mConnections.push_back(connection);
+    }
     return connection;
 }
 
 void RpcServer::setRootObject(const sp<IBinder>& binder) {
-    LOG_ALWAYS_FATAL_IF(mRootObject != nullptr, "There can only be one root object");
+    std::lock_guard<std::mutex> _l(mLock);
     mRootObject = binder;
 }
 
 sp<IBinder> RpcServer::getRootObject() {
+    std::lock_guard<std::mutex> _l(mLock);
     return mRootObject;
 }
 
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index d29b651..a665fad 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -21,6 +21,8 @@
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
 
+#include <mutex>
+
 // WARNING: This is a feature which is still in development, and it is subject
 // to radical change. Any production use of this may subject your code to any
 // number of problems.
@@ -30,9 +32,6 @@
 /**
  * This represents a server of an interface, which may be connected to by any
  * number of clients over sockets.
- *
- * This object is not (currently) thread safe. All calls to it are expected to
- * happen at process startup.
  */
 class RpcServer final : public virtual RefBase {
 public:
@@ -51,16 +50,8 @@
     sp<RpcConnection> addClientConnection();
 
     /**
-     * Allowing a server to explicitly drop clients would be easy to add here,
-     * but it is not currently implemented, since users of this functionality
-     * could not use similar functionality if they are running under real
-     * binder.
-     */
-    // void drop(const sp<RpcConnection>& connection);
-
-    /**
      * The root object can be retrieved by any client, without any
-     * authentication.
+     * authentication. TODO(b/183988761)
      */
     void setRootObject(const sp<IBinder>& binder);
 
@@ -77,8 +68,8 @@
 
     bool mAgreedExperimental = false;
 
+    std::mutex mLock;
     sp<IBinder> mRootObject;
-
     std::vector<sp<RpcConnection>> mConnections; // per-client
 };