SocketClient: add optional reference counting

Needed to fix a race in netd.

Bug: 3438459
Change-Id: Icd7f5f035510235f733a25c0621479d3e644b152
diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp
index a6aed26..6d4dff4 100644
--- a/libsysutils/src/SocketClient.cpp
+++ b/libsysutils/src/SocketClient.cpp
@@ -15,8 +15,10 @@
         , mPid(-1)
         , mUid(-1)
         , mGid(-1)
+        , mRefCount(1)
 {
     pthread_mutex_init(&mWriteMutex, NULL);
+    pthread_mutex_init(&mRefCountMutex, NULL);
 
     struct ucred creds;
     socklen_t szCreds = sizeof(creds);
@@ -100,3 +102,22 @@
     pthread_mutex_unlock(&mWriteMutex);
     return 0;
 }
+
+void SocketClient::incRef() {
+  pthread_mutex_lock(&mRefCountMutex);
+  mRefCount++;
+  pthread_mutex_unlock(&mRefCountMutex);
+}
+
+void SocketClient::decRef() {
+  bool deleteSelf = false;
+  pthread_mutex_lock(&mRefCountMutex);
+  mRefCount--;
+  if (mRefCount == 0) {
+      deleteSelf = true;
+  }
+  pthread_mutex_unlock(&mRefCountMutex);
+  if (deleteSelf) {
+      delete this;
+  }
+}