Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Crash if MQTTSession stream is created and disposed of quickly #33

Closed
paulw11 opened this issue Aug 28, 2018 · 5 comments
Closed

Crash if MQTTSession stream is created and disposed of quickly #33

paulw11 opened this issue Aug 28, 2018 · 5 comments

Comments

@paulw11
Copy link
Contributor

paulw11 commented Aug 28, 2018

I was getting a crash in SwiftMQTT if there was a short period between the creation and dispose of an MQTTSessionStream - the problem is that the [weak self] has been released before the async block executes on the sessionQueue. The following check addresses the issue:

sessionQueue.async { [weak self] in
if self != nil {
let currentRunLoop = RunLoop.current
inputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode)
outputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode)
inputStream?.open()
outputStream?.open()
if ssl {
let securityLevel = StreamSocketSecurityLevel.negotiatedSSL.rawValue
inputStream?.setProperty(securityLevel, forKey: .socketSecurityLevelKey)
outputStream?.setProperty(securityLevel, forKey: .socketSecurityLevelKey)
}
if timeout > 0 {
DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {
self?.connectTimeout()
}
}

			currentRunLoop.run()
		}
	}
}
@paulw11
Copy link
Contributor Author

paulw11 commented Aug 28, 2018

Actually this code doesn't fix it :(

@paulw11 paulw11 closed this as completed Aug 28, 2018
@paulw11 paulw11 reopened this Aug 28, 2018
@adolfo
Copy link
Collaborator

adolfo commented Aug 28, 2018

@paulw11 could you write a failing test that reproduces this issue? A PR that fixes the problem is also appreciated if you find the solution.

@Jeffkenly88
Copy link

@adolfo Hi, I'm having the same issue, it happens not regularly, I just had to restart the app multiple times and it happens 1 time out of 10. It crashed with BAD_ACCESS exception on currentRunLoop.run()

@Kerry50407
Copy link

I simply moved the let currentRunLoop = RunLoop.current out of the queue scope,
Like this..

let currentRunLoop = RunLoop.current
sessionQueue.async { [weak self] in
inputStream?.schedule(in: currentRunLoop, forMode: .defaultRunLoopMode)
.....
currentRunLoop.run()
}

The app stop crashing.
I guess it happened due to the currentRunLoop is released. (not sure for the root cause)

Hope it helps!

@adolfo
Copy link
Collaborator

adolfo commented Apr 11, 2019

Resolved in #40

@adolfo adolfo closed this as completed Apr 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants