Skip to content

Process: correct a subtle runLoopSource lifetime issue #3125

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

Merged
merged 2 commits into from
Jan 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 25 additions & 31 deletions Sources/Foundation/Process.swift
Original file line number Diff line number Diff line change
Expand Up @@ -642,18 +642,8 @@ open class Process: NSObject {
process._terminationReason = .exit
}

if let handler = process.terminationHandler {
let thread: Thread = Thread { handler(process) }
thread.start()
}

process.isRunning = false

// Invalidate the source and wake up the run loop, if it is available
CFRunLoopSourceInvalidate(process.runLoopSource)
if let runloop = process.runLoop {
CFRunLoopWakeUp(runloop._cfRunLoop)
}
// Signal waitUntilExit() and optionally invoke termination handler.
process.terminateRunLoop()

CFSocketInvalidate(socket)
}, &context)
Expand Down Expand Up @@ -829,28 +819,12 @@ open class Process: NSObject {
process._terminationReason = .exit
}

// Set the running flag to false
process.isRunning = false

// If a termination handler has been set, invoke it on a background thread

if let terminationHandler = process.terminationHandler {
let thread = Thread {
terminationHandler(process)
}
thread.start()
}

// Invalidate the source and wake up the run loop, if it's available

CFRunLoopSourceInvalidate(process.runLoopSource)
if let runLoop = process.runLoop {
CFRunLoopWakeUp(runLoop._cfRunLoop)
}
// Signal waitUntilExit() and optionally invoke termination handler.
process.terminateRunLoop()

CFSocketInvalidate( socket )

}, &context )
}, &context )

CFSocketSetSocketFlags( socket, CFOptionFlags(kCFSocketCloseOnInvalidate))

Expand Down Expand Up @@ -1165,6 +1139,26 @@ open class Process: NSObject {
self.runLoop = nil
self.runLoopSource = nil
}

private func terminateRunLoop() {
// Ensure that the run loop source is invalidated before we mark the process
// as no longer running. This serves as a semaphore to
// `waitUntilExit` to decrement the `runLoopSource` retain count,
// potentially releasing it.
CFRunLoopSourceInvalidate(self.runLoopSource)
let runloopToWakeup = self.runLoop
self.isRunning = false

// Wake up the run loop, *AFTER* clearing .isRunning to avoid an extra time out period.
if let cfRunLoop = runloopToWakeup?._cfRunLoop {
CFRunLoopWakeUp(cfRunLoop)
}

if let handler = self.terminationHandler {
let thread: Thread = Thread { handler(self) }
thread.start()
}
}
}

extension Process {
Expand Down