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

NIOCore: handle error description on Windows #2219

Merged
merged 2 commits into from
Jul 7, 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
49 changes: 49 additions & 0 deletions Sources/NIOCore/IO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,20 @@

#if os(Windows)
import ucrt
import func WinSDK.FormatMessageW
import func WinSDK.LocalFree
import let WinSDK.FORMAT_MESSAGE_ALLOCATE_BUFFER
import let WinSDK.FORMAT_MESSAGE_FROM_SYSTEM
import let WinSDK.FORMAT_MESSAGE_IGNORE_INSERTS
import let WinSDK.LANG_NEUTRAL
import let WinSDK.SUBLANG_DEFAULT
import typealias WinSDK.DWORD
import typealias WinSDK.WCHAR
import typealias WinSDK.WORD

internal func MAKELANGID(_ p: WORD, _ s: WORD) -> DWORD {
return DWORD((s << 10) | p)
}
#elseif os(Linux) || os(Android)
import Glibc
#elseif os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
Expand Down Expand Up @@ -107,13 +120,49 @@ private func reasonForError(errnoCode: CInt, reason: String) -> String {
}
}

#if os(Windows)
private func reasonForWinError(_ code: DWORD) -> String {
let dwFlags: DWORD = DWORD(FORMAT_MESSAGE_ALLOCATE_BUFFER)
| DWORD(FORMAT_MESSAGE_FROM_SYSTEM)
| DWORD(FORMAT_MESSAGE_IGNORE_INSERTS)

var buffer: UnsafeMutablePointer<WCHAR>?
// We use `FORMAT_MESSAGE_ALLOCATE_BUFFER` in flags which means that the
// buffer will be allocated by the call to `FormatMessageW`. The function
// expects a `LPWSTR` and expects the user to type-pun in this case.
let dwResult: DWORD = withUnsafeMutablePointer(to: &buffer) {
compnerd marked this conversation as resolved.
Show resolved Hide resolved
$0.withMemoryRebound(to: WCHAR.self, capacity: 2) {
FormatMessageW(dwFlags, nil, code,
MAKELANGID(WORD(LANG_NEUTRAL), WORD(SUBLANG_DEFAULT)),
$0, 0, nil)
}
}
guard dwResult > 0, let message = buffer else {
return "unknown error \(code)"
}
defer { LocalFree(buffer) }
return String(decodingCString: message, as: UTF16.self)
}
#endif

extension IOError: CustomStringConvertible {
public var description: String {
return self.localizedDescription
}

public var localizedDescription: String {
#if os(Windows)
switch self.error {
case .errno(let errno):
return reasonForError(errnoCode: errno, reason: self.failureDescription)
case .windows(let code):
return reasonForWinError(code)
case .winsock(let code):
return reasonForWinError(DWORD(code))
}
#else
return reasonForError(errnoCode: self.errnoCode, reason: self.failureDescription)
#endif
}
}

Expand Down