CocoaAsyncSocket icon indicating copy to clipboard operation
CocoaAsyncSocket copied to clipboard

GCDAsyncSocket never deallocs

Open peternlewis opened this issue 13 years ago • 12 comments

GCDAsyncSocket will never deallocate because the dispatch_source_set_event_handler holds a reference to a block which holds a reference to the GCDAsyncSocket self.

This results in the inability to close and then reopen a GCDAsyncSocket listener as the address is already in use.

This can be resolved by changing the reference to a weak reference. Before the dispatch_source_set_event_handler, add the line:

__weak GCDAsyncSocket* weakSelf = self;

and then using weakSelf instead of self to call doAccept.

while ([weakSelf doAccept:socketFD] && (++i < numPendingConnections));

You need to repeat this twice, once for ipv4 and once for ipv6.

At this point, you'll discover that it is a good thing GCDAsyncSocket is never dealloced because it crashes immediately the dealloc is run. This is because dealloc calls closeWithError, which in turn calls the delegate socketDidDisconnect, passing the GCDAsyncSocket self as a parameter. ARC promptly retains the GCDAsyncSocket which crashes as the GCDAsyncSocket is currently being deallocate.

This can be resolved by moving the "delegate = nil" to the start of the dealloc, which you may as well do as it is impossible to call the delegate safely at that point (well, it is impossible if you want to be able to pass the GCDAsyncSocket, which you can no longer do). An alternative would be to call socketDidDisconnect:nil in this case.

Either way, it means that socketDidDisconnect will not be called, or alternatively, will not be called with the appropriate GCDAsyncSocket as a parameter, which may break the API contract, but is unavoidable at this point.

A better API would be to have some sort of "Kill" method call to kill the GCDAsyncSocket before the dealloc happens.

peternlewis avatar Apr 09 '13 08:04 peternlewis

+1 - The fix works. One can work around the missed disconnect call. Still - not cool :\

pkluz avatar Oct 17 '13 22:10 pkluz

Hi, I have got a similar issue with GCDAsyncSocket library. I have a TCP client that use a specific source port to send message to a server. My client uses:[socket connectToHost:destIp onPort: destPort viaInterface: @":12345" withTimeout: -1 error: &err] method to connect to a server. This client can connect to the server, transmit message and receive echo message back from server with no problem for the first time. The issue is that after I called [socket setDelegate:nil delegateQueue:NULL]; [socket disconnect]; socket = nil; then if I need to connect to server again with the same source port ( [socket connectToHost:destIp onPort: destPort viaInterface: @":12345" withTimeout: -1 error: &err] ; ) , I got : Socket Error: [Error Domain=NSPOSIXErrorDomain Code = 48 "Address already in use" UserInfo=0x178268b80 {NSLocalizedDescription=Address already in use, NSLocalizedFailureReason=Error in connected() function}]

I used peternlewis's approach. But it seems this doesn't solve my issue. I used __weak GCDAsyncSocket weakSelf = self; for the blocks as suggested. In my case, I also changed all the self to weakSelf for the block in: " -(BOOL) connectToHost:(NSString *)inHost onPort:(uint16_t)port viaInterface: (NSString *)inInterface withTimeout:(NSTimeInterval)timeout error:(NSError *)errPtr " method and "-(BOOL) connectToAddress:(NSData )inRemoteAddr viaInterface:(NSString *)inInterface withTimeout:(NSTimeInterval)timeout error:(NSError *)errPtr" method. I am running out of ideas on what might still holding on the reference to the GCDAsyncSocket. Just wondering if anyone can help here. Thanks a lot.

pengyanb avatar Dec 02 '13 10:12 pengyanb

If you email me (support at stairways will work), I'm happy to email you a copy of the GCDAsyncSocket files I am currently using (absolutely no guarantees about anything at this point, they are bashed thoroughly).

I like the idea behind GCDAsyncSocket, but I have resigned myself to finding or writing an alternative.

peternlewis avatar Dec 03 '13 04:12 peternlewis

Hi Peter, thanks for your reply. Could you please email me a copy of your GCDAsyncSocket files, my email address is [email protected]

pengyanb avatar Dec 03 '13 20:12 pengyanb

Hi, it is possible to safely call the delegate from -dealloc, it's just not that trivial. Try this ;)

--- Downloads/CocoaAsyncSocket-master/GCD/GCDAsyncSocket.m  2013-12-26 17:20:56.000000000 +0100
+++ MyPrograms/dynimg-ios/ios-app/dynlib/layer_3/GCDAsyncSocket.m   2013-12-26 17:39:38.000000000 +0100
@@ -220,10 +220,11 @@
 - (void)didConnect:(int)aConnectIndex;
 - (void)didNotConnect:(int)aConnectIndex error:(NSError *)error;

 // Disconnect
 - (void)closeWithError:(NSError *)error;
+- (void)closeWithError:(NSError *)error callDelegate:(BOOL)doCallDelegate;
 - (void)maybeClose;

 // Errors
 - (NSError *)badConfigError:(NSString *)msg;
 - (NSError *)badParamError:(NSString *)msg;
@@ -1087,20 +1088,36 @@

 - (void)dealloc
 {
    LogInfo(@"%@ - %@ (start)", THIS_METHOD, self);

+    BOOL shouldCallDelegate = (flags & kSocketStarted);
+    
    if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
    {
-       [self closeWithError:nil];
+       [self closeWithError:nil callDelegate:NO];
    }
    else
    {
        dispatch_sync(socketQueue, ^{
-           [self closeWithError:nil];
+           [self closeWithError:nil callDelegate:NO];
        });
    }
+    
+    if(shouldCallDelegate && delegate)
+    {
+        if([delegate respondsToSelector:@selector(socketDidDisconnect:withError:)])
+        {
+            if(!delegateQueue || dispatch_get_current_queue() == delegateQueue) {
+                [delegate socketDidDisconnect:self withError:nil];
+            } else {
+                dispatch_sync(delegateQueue, ^{
+                    [delegate socketDidDisconnect:self withError:nil];
+                });
+            }
+        }
+    }

    delegate = nil;

    #if !OS_OBJECT_USE_OBJC
    if (delegateQueue) dispatch_release(delegateQueue);
@@ -2630,10 +2647,15 @@
 #pragma mark Disconnecting
 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 - (void)closeWithError:(NSError *)error
 {
+    [self closeWithError:error callDelegate:YES];
+}
+
+- (void)closeWithError:(NSError *)error callDelegate:(BOOL)callDelegate
+{
    LogTrace();

    NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");


@@ -2764,11 +2786,11 @@
        socket6FD = SOCKET_NULL;
    }

    // If the client has passed the connect/accept method, then the connection has at least begun.
    // Notify delegate that it is now ending.
-   BOOL shouldCallDelegate = (flags & kSocketStarted);
+   BOOL shouldCallDelegate = (flags & kSocketStarted) && callDelegate;

    // Clear stored socket info and all flags (config remains as is)
    socketFDBytesAvailable = 0;
    flags = 0;

michaelpeternell avatar Dec 26 '13 16:12 michaelpeternell

I wanna explain...

It is totally allowed to call -retain and -release (or any other method) on an object that is being deallocated, as long as you follow two rules:

  1. after -dealloc finishes, the retainCount has to be 0.
  2. after -dealloc finishes, the object must not be accessed in any way.

this means that the delegate has to be informed about the closing of the socket before -dealloc returns. One way to achieve this would be to change the dispatch_async call in -closeWithError: to a dispatch_sync call, but that would produce a deadlock situation in cases where the socket is deallocated from the same thread as the delegateQueue. Therefore we have to check in -dealloc if we are in the delegate queue, and if so, just inform the delegate, and if not so, inform the delegate synchronously via dispatch_sync.

With this method, you can still produce a deadlock situation, but you would have to try hard...

michaelpeternell avatar Dec 27 '13 12:12 michaelpeternell

Unfortunately, if you read the documentation on dispatch_get_current_queue it includes this lovely little nugget:

The code must not assume that synchronous execution onto a queue is safe from deadlock if that queue is not the one returned by dispatch_get_current_queue().

and

This function is deprecated and will be removed in a future release.

peternlewis avatar Dec 30 '13 06:12 peternlewis

damn ;-D so we have multiple options which are all broken in one way or the other... i will probably keep my code until i see it breaking, because i know how to avoid deadlock, and the deprecation will be a compile time error when it happens. but i totally understand that you wouldn't want to put such code into an official release...

michaelpeternell avatar Dec 30 '13 10:12 michaelpeternell

GCDAsyncSocket will never deallocate because the dispatch_source_set_event_handler holds a reference to a block which holds a reference to the GCDAsyncSocket self.

Correct. And this is unacceptable.

This can be resolved by changing the reference to a weak reference.

Yup, but there are actually 7 such instances where dispatch_source_set_event_handler holds a reference. And 2 places where a reference is being held via a dispatch_async on a globalConcurrentQueue.

I've fixed all such instances. In addition, I've wrapped the offending block implementations with the following "compiler helper":

dispatch_source_set_event_handler(source, ^{ @autoreleasepool {
#pragma clang diagnostic push
#pragma clang diagnostic warning "-Wimplicit-retain-self"

// Now the compiler will warn us better

#pragma clang diagnostic pop
}});

This can be resolved by [not invoking the socketDidDisconnect delegate method]. An alternative would be to call socketDidDisconnect:nil in this case.

When considering these options it's important to keep in mind the scenarios that bring them about in the first place. In almost all cases, the delegate of a socket is also its owner. And so the following two cases are the most common scenarios:

  1. The delegate/owner is deallocated, and doesn't bother cleaning up the socket
  2. The delegate/owner explicitly invokes asyncSocket = nil without disconnecting it first

If we take the route of not invoking socketDidDisconnect, then scenario 1 is unaffected. This is because the delegate is being deallocated, and thus its weak reference will return nil, and it won't be invoked anyway. However, scenario 2 is affected. The extent of which depends upon the code. However I can easily imagine a situation in which the socketDidDisconnect method is the only code path that properly notifies something.

If we take the route of invoking the socketDidDisconnect method, but with a nil parameter, then again scenario 1 is unaffected. (Delegate is being deallocated, thus weak reference == nil) Scenario 2 is also affected, though I would argue to a much lesser extent. Here's why:

If the delegate/owner has but one asyncSocket instance, then it may not even inspect the sending parameter. If it does inspect the sending parameter, and finds it to be nil, then this will likely prompt the developer to investigate why. (If he/she is confused by this, or it proves to be a problem.) Long story short, the absence of a method invocation is likely harder to detect then a method invocation with a nil parameter (which may not even be an issue).

I do not doubt that some developers may argue otherwise. When it comes down to it, it is likely a product of how one usually architects their state machines surrounding the socket code. However, if one strongly feels that their socketDidDisconnect delegate method should not be invoked, then it is a simple thing to achieve:

asyncSocket.delegate = nil; // don't invoke socketDidDisconnect delegate method
asyncSocket = nil; // implicitly disconnect and deallocate socket

robbiehanson avatar Apr 10 '14 18:04 robbiehanson

A note for future readers. If you encounter this error, my guess is that you did one of the things @robbiehanson lists above:

  1. The delegate/owner is deallocated, and doesn't bother cleaning up the socket
  2. The delegate/owner explicitly invokes asyncSocket = nil without disconnecting it first

With ARC I'd gotten used to not having to implement dealloc. So, when my GCDAsyncSocketDelegate was destroyed, I wasn't disconnecting the socket. Doing the following in my delegate - which is the owner of the socket instance - solved the problem:

- (void)dealloc {
    [self.server disconnect];
    self.server.delegate = nil;
    self.server = nil;
}

ExoticObjects avatar Dec 18 '15 21:12 ExoticObjects

Hi @robbiehanson, Is there a solution for this ?

Double-Dude avatar Jul 07 '17 04:07 Double-Dude

This worked for me: send a close() command to the socket, wait for it to close, and in the close delegate clean the client:

    /// will kill the client, if exists
    func killClient() {
        self.client?.close()
    }
/// disconnected
    func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
        delegate.onUdpClientDisconnected(error: error)
        cleanClient()
    }
/// will reset (allocate) the client
    private func cleanClient() {
        self.client?.setDelegateQueue(nil)
        self.client?.setDelegate(nil)
        self.client?.pauseReceiving()
        self.client = nil
    }

osfunapps avatar Aug 12 '19 09:08 osfunapps