Fix crashes when tracing enabled and Socket disposed during connect (#35964)
authorStephen Toub <stoub@microsoft.com>
Thu, 7 May 2020 16:38:33 +0000 (12:38 -0400)
committerGitHub <noreply@github.com>
Thu, 7 May 2020 16:38:33 +0000 (12:38 -0400)
Given the right (wrong) sequence of events, if tracing is enabled and a Socket is disposed of during a connect operation, the tracing code might try to access properties on the Socket that throw ObjectDisposedException, and these exceptions may propagate and crash the process.

src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs

index dd3f895..e8857e5 100644 (file)
@@ -690,7 +690,14 @@ namespace System.Net.Sockets
                     {
                         _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket!, _currentSocket._rightEndPoint!.Create(remoteSocketAddress));
 
-                        if (NetEventSource.IsEnabled) NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
+                        if (NetEventSource.IsEnabled)
+                        {
+                            try
+                            {
+                                NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
+                            }
+                            catch (ObjectDisposedException) { }
+                        }
                     }
                     else
                     {
@@ -704,7 +711,14 @@ namespace System.Net.Sockets
                     socketError = FinishOperationConnect();
                     if (socketError == SocketError.Success)
                     {
-                        if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket!, _currentSocket!.LocalEndPoint, _currentSocket.RemoteEndPoint);
+                        if (NetEventSource.IsEnabled)
+                        {
+                            try
+                            {
+                                NetEventSource.Connected(_currentSocket!, _currentSocket!.LocalEndPoint, _currentSocket.RemoteEndPoint);
+                            }
+                            catch (ObjectDisposedException) { }
+                        }
 
                         // Mark socket connected.
                         _currentSocket!.SetToConnected();