Skip to content

Commit 9b8d89f

Browse files
committed
Swift: correct dispatch source construction on Win32
Windows uses handles internally for the dispatch sources. Convert the `fileDescriptor` parameter on the incoming point to `HANDLE`s when building the `DispatchSource`. This fixes passing invalid parameters to the Windows system functions.
1 parent a3bff44 commit 9b8d89f

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/swift/Source.swift

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212

1313
import CDispatch
1414
import _SwiftDispatchOverlayShims
15+
#if os(Windows)
16+
import WinSDK
17+
#endif
1518

1619
extension DispatchSourceProtocol {
1720

@@ -179,7 +182,13 @@ extension DispatchSource {
179182
#endif
180183

181184
public class func makeReadSource(fileDescriptor: Int32, queue: DispatchQueue? = nil) -> DispatchSourceRead {
182-
let source = dispatch_source_create(_swift_dispatch_source_type_READ(), UInt(fileDescriptor), 0, queue?.__wrapped)
185+
#if os(Windows)
186+
let handle: UInt = UInt(_get_osfhandle(fileDescriptor))
187+
if handle == UInt(bitPattern: INVALID_HANDLE_VALUE) { fatalError("unable to get underlying handle from file descriptor") }
188+
#else
189+
let handle: UInt = UInt(fileDescriptor)
190+
#endif
191+
let source = dispatch_source_create(_swift_dispatch_source_type_READ(), handle, 0, queue?.__wrapped)
183192
return DispatchSource(source: source) as DispatchSourceRead
184193
}
185194

@@ -216,7 +225,13 @@ extension DispatchSource {
216225
#endif
217226

218227
public class func makeWriteSource(fileDescriptor: Int32, queue: DispatchQueue? = nil) -> DispatchSourceWrite {
219-
let source = dispatch_source_create(_swift_dispatch_source_type_WRITE(), UInt(fileDescriptor), 0, queue?.__wrapped)
228+
#if os(Windows)
229+
let handle: UInt = UInt(_get_osfhandle(fileDescriptor))
230+
if handle == UInt(bitPattern: INVALID_HANDLE_VALUE) { fatalError("unable to get underlying handle from file descriptor") }
231+
#else
232+
let handle: UInt = UInt(fileDescriptor)
233+
#endif
234+
let source = dispatch_source_create(_swift_dispatch_source_type_WRITE(), handle, 0, queue?.__wrapped)
220235
return DispatchSource(source: source) as DispatchSourceWrite
221236
}
222237
}

0 commit comments

Comments
 (0)