summaryrefslogtreecommitdiffstats
path: root/libsysutils/src
diff options
context:
space:
mode:
authorBrad Fitzpatrick <bradfitz@android.com>2011-03-29 08:45:04 -0700
committerAndroid Git Automerger <android-git-automerger@android.com>2011-03-29 08:45:04 -0700
commit4fecade5f21d5d062ebe1c70535367d3407bb68f (patch)
tree8997c814b16a593c8915a36e5f3e0d2db430bfec /libsysutils/src
parent15b15c4b4acede0b999e6a7af9ce797c6a58a62a (diff)
parentcb1e616e3c108a9c8b159bb95c3356acf5797ba2 (diff)
downloadsystem_core-4fecade5f21d5d062ebe1c70535367d3407bb68f.zip
system_core-4fecade5f21d5d062ebe1c70535367d3407bb68f.tar.gz
system_core-4fecade5f21d5d062ebe1c70535367d3407bb68f.tar.bz2
am cb1e616e: am 7c556549: Merge changes Icdefb5ff,Icd7f5f03
* commit 'cb1e616e3c108a9c8b159bb95c3356acf5797ba2': Fix potential race introduced in Icd7f5f03 SocketClient: add optional reference counting
Diffstat (limited to 'libsysutils/src')
-rw-r--r--libsysutils/src/SocketClient.cpp24
-rw-r--r--libsysutils/src/SocketListener.cpp9
2 files changed, 30 insertions, 3 deletions
diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp
index a6aed26..90ca52e 100644
--- a/libsysutils/src/SocketClient.cpp
+++ b/libsysutils/src/SocketClient.cpp
@@ -15,8 +15,10 @@ SocketClient::SocketClient(int socket)
, 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,25 @@ int SocketClient::sendData(const void* data, int len) {
pthread_mutex_unlock(&mWriteMutex);
return 0;
}
+
+void SocketClient::incRef() {
+ pthread_mutex_lock(&mRefCountMutex);
+ mRefCount++;
+ pthread_mutex_unlock(&mRefCountMutex);
+}
+
+bool SocketClient::decRef() {
+ bool deleteSelf = false;
+ pthread_mutex_lock(&mRefCountMutex);
+ mRefCount--;
+ if (mRefCount == 0) {
+ deleteSelf = true;
+ } else if (mRefCount < 0) {
+ SLOGE("SocketClient refcount went negative!");
+ }
+ pthread_mutex_unlock(&mRefCountMutex);
+ if (deleteSelf) {
+ delete this;
+ }
+ return deleteSelf;
+}
diff --git a/libsysutils/src/SocketListener.cpp b/libsysutils/src/SocketListener.cpp
index 611d5fe..69ed79e 100644
--- a/libsysutils/src/SocketListener.cpp
+++ b/libsysutils/src/SocketListener.cpp
@@ -55,7 +55,7 @@ SocketListener::~SocketListener() {
}
SocketClientCollection::iterator it;
for (it = mClients->begin(); it != mClients->end();) {
- delete (*it);
+ (*it)->decRef();
it = mClients->erase(it);
}
delete mClients;
@@ -225,8 +225,11 @@ void SocketListener::runListener() {
}
pthread_mutex_unlock(&mClientsLock);
/* Destroy the client */
- close(c->getSocket());
- delete c;
+ int socket = c->getSocket();
+ if (c->decRef()) {
+ // Note: 'c' is deleted memory at this point.
+ close(socket);
+ }
}
}
}