From 730713e47fff3fad8969b15a1355d26c5aeeff1c Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Thu, 12 Sep 2024 13:18:25 +0100 Subject: [PATCH] Add support for WASILibc (#2671) Dispatch is not supported on WASI, and only Unix domain sockets are supported, which means we have to exclude those APIs on this platform. There's work in progress to enable tests for this on CI, but nothing I can provide for this PR at the current moment. --------- Co-authored-by: Franz Busch --- Package.swift | 19 +++++++--- Sources/CNIOSHA1/c_nio_sha1.c | 2 +- Sources/CNIOWASI/CNIOWASI.c | 13 +++++++ Sources/CNIOWASI/include/CNIOWASI.h | 32 ++++++++++++++++ Sources/NIOConcurrencyHelpers/NIOLock.swift | 13 +++++-- Sources/NIOConcurrencyHelpers/atomics.swift | 2 + Sources/NIOConcurrencyHelpers/lock.swift | 37 +++++++++++++------ Sources/NIOCore/AsyncAwaitSupport.swift | 2 + Sources/NIOCore/BSDSocketAPI.swift | 15 +++++++- Sources/NIOCore/ByteBuffer-aux.swift | 11 +++++- Sources/NIOCore/ByteBuffer-conversions.swift | 4 ++ Sources/NIOCore/ByteBuffer-core.swift | 2 + Sources/NIOCore/Channel.swift | 2 + .../NIOCore/ConvenienceOptionSupport.swift | 2 + .../NIOCore/DispatchQueue+WithFuture.swift | 2 + Sources/NIOCore/EventLoop.swift | 23 +++++++++++- Sources/NIOCore/EventLoopFuture.swift | 7 +++- Sources/NIOCore/FileHandle.swift | 14 ++++++- Sources/NIOCore/FileRegion.swift | 2 + Sources/NIOCore/GlobalSingletons.swift | 2 + Sources/NIOCore/IO.swift | 2 + Sources/NIOCore/Interfaces.swift | 17 ++++++--- Sources/NIOCore/MulticastChannel.swift | 8 ++-- Sources/NIOCore/SocketAddresses.swift | 25 ++++++++++++- Sources/NIOCore/SocketOptionProvider.swift | 22 ++++++++++- Sources/NIOCore/SystemCallHelpers.swift | 14 ++++++- Sources/NIOCore/Utilities.swift | 6 ++- Sources/NIOEmbedded/AsyncTestingChannel.swift | 2 + .../NIOEmbedded/AsyncTestingEventLoop.swift | 2 + Sources/NIOEmbedded/Embedded.swift | 7 +++- Sources/NIOPosix/GetaddrinfoResolver.swift | 5 ++- .../MultiThreadedEventLoopGroup.swift | 5 ++- Sources/NIOPosix/NIOThreadPool.swift | 5 ++- Sources/_NIODataStructures/Heap.swift | 2 + 34 files changed, 280 insertions(+), 48 deletions(-) create mode 100644 Sources/CNIOWASI/CNIOWASI.c create mode 100644 Sources/CNIOWASI/include/CNIOWASI.h diff --git a/Package.swift b/Package.swift index 7ced7843d..c5edd5ebf 100644 --- a/Package.swift +++ b/Package.swift @@ -27,6 +27,10 @@ let swiftSystem: PackageDescription.Target.Dependency = .product( condition: .when(platforms: [.macOS, .iOS, .tvOS, .watchOS, .linux, .android]) ) +// These platforms require a depdency on `NIOPosix` from `NIOHTTP1` to maintain backward +// compatibility with previous NIO versions. +let historicalNIOPosixDependencyRequired: [Platform] = [.macOS, .iOS, .tvOS, .watchOS, .linux, .android] + let strictConcurrencyDevelopment = false let strictConcurrencySettings: [SwiftSetting] = { @@ -82,6 +86,7 @@ let package = Package( "CNIODarwin", "CNIOLinux", "CNIOWindows", + "CNIOWASI", "_NIODataStructures", swiftCollections, swiftAtomics, @@ -130,14 +135,14 @@ let package = Package( .target( name: "_NIOConcurrency", dependencies: [ - "NIO", + .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", ] ), .target( name: "NIOFoundationCompat", dependencies: [ - "NIO", + .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", ] ), @@ -170,6 +175,10 @@ let package = Package( name: "CNIOWindows", dependencies: [] ), + .target( + name: "CNIOWASI", + dependencies: [] + ), .target( name: "NIOConcurrencyHelpers", dependencies: [ @@ -180,7 +189,7 @@ let package = Package( .target( name: "NIOHTTP1", dependencies: [ - "NIO", + .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", "NIOConcurrencyHelpers", "CNIOLLHTTP", @@ -190,7 +199,7 @@ let package = Package( .target( name: "NIOWebSocket", dependencies: [ - "NIO", + .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", "NIOHTTP1", "CNIOSHA1", @@ -207,7 +216,7 @@ let package = Package( .target( name: "NIOTLS", dependencies: [ - "NIO", + .target(name: "NIO", condition: .when(platforms: historicalNIOPosixDependencyRequired)), "NIOCore", swiftCollections, ] diff --git a/Sources/CNIOSHA1/c_nio_sha1.c b/Sources/CNIOSHA1/c_nio_sha1.c index 30b61c879..2e4fa45bb 100644 --- a/Sources/CNIOSHA1/c_nio_sha1.c +++ b/Sources/CNIOSHA1/c_nio_sha1.c @@ -54,7 +54,7 @@ #endif #ifdef __ANDROID__ #include -#elif defined(__linux__) || defined(__APPLE__) +#elif defined(__linux__) || defined(__APPLE__) || defined(__wasm32__) #include #endif diff --git a/Sources/CNIOWASI/CNIOWASI.c b/Sources/CNIOWASI/CNIOWASI.c new file mode 100644 index 000000000..f5c4f842f --- /dev/null +++ b/Sources/CNIOWASI/CNIOWASI.c @@ -0,0 +1,13 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// diff --git a/Sources/CNIOWASI/include/CNIOWASI.h b/Sources/CNIOWASI/include/CNIOWASI.h new file mode 100644 index 000000000..4e2f1202a --- /dev/null +++ b/Sources/CNIOWASI/include/CNIOWASI.h @@ -0,0 +1,32 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) YEARS Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#pragma once + +#if __wasi__ + +#include +#include + +static inline void CNIOWASI_gettime(struct timespec *tv) { + // ClangImporter doesn't support `CLOCK_MONOTONIC` declaration in WASILibc, thus we have to define a bridge manually + clock_gettime(CLOCK_MONOTONIC, tv); +} + +static inline int CNIOWASI_O_CREAT() { + // ClangImporter doesn't support `O_CREATE` declaration in WASILibc, thus we have to define a bridge manually + return O_CREAT; +} + +#endif diff --git a/Sources/NIOConcurrencyHelpers/NIOLock.swift b/Sources/NIOConcurrencyHelpers/NIOLock.swift index 21902e27d..70e64a97c 100644 --- a/Sources/NIOConcurrencyHelpers/NIOLock.swift +++ b/Sources/NIOConcurrencyHelpers/NIOLock.swift @@ -23,6 +23,11 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc +#if canImport(wasi_pthread) +import wasi_pthread +#endif #else #error("The concurrency NIOLock module was unable to identify your C library.") #endif @@ -45,7 +50,7 @@ extension LockOperations { #if os(Windows) InitializeSRWLock(mutex) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) debugOnly { @@ -63,7 +68,7 @@ extension LockOperations { #if os(Windows) // SRWLOCK does not need to be free'd - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_mutex_destroy(mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif @@ -75,7 +80,7 @@ extension LockOperations { #if os(Windows) AcquireSRWLockExclusive(mutex) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_mutex_lock(mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif @@ -87,7 +92,7 @@ extension LockOperations { #if os(Windows) ReleaseSRWLockExclusive(mutex) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_mutex_unlock(mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif diff --git a/Sources/NIOConcurrencyHelpers/atomics.swift b/Sources/NIOConcurrencyHelpers/atomics.swift index afc8e25c8..1b9c7b773 100644 --- a/Sources/NIOConcurrencyHelpers/atomics.swift +++ b/Sources/NIOConcurrencyHelpers/atomics.swift @@ -32,6 +32,8 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc #else #error("The concurrency atomics module was unable to identify your C library.") #endif diff --git a/Sources/NIOConcurrencyHelpers/lock.swift b/Sources/NIOConcurrencyHelpers/lock.swift index e11c78d63..44845e828 100644 --- a/Sources/NIOConcurrencyHelpers/lock.swift +++ b/Sources/NIOConcurrencyHelpers/lock.swift @@ -23,6 +23,11 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc +#if canImport(wasi_pthread) +import wasi_pthread +#endif #else #error("The concurrency lock module was unable to identify your C library.") #endif @@ -47,7 +52,7 @@ public final class Lock { public init() { #if os(Windows) InitializeSRWLock(self.mutex) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) debugOnly { @@ -62,7 +67,7 @@ public final class Lock { deinit { #if os(Windows) // SRWLOCK does not need to be free'd - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_mutex_destroy(self.mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif @@ -76,7 +81,7 @@ public final class Lock { public func lock() { #if os(Windows) AcquireSRWLockExclusive(self.mutex) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_mutex_lock(self.mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif @@ -89,7 +94,7 @@ public final class Lock { public func unlock() { #if os(Windows) ReleaseSRWLockExclusive(self.mutex) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_mutex_unlock(self.mutex) precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") #endif @@ -129,7 +134,7 @@ public final class ConditionLock { #if os(Windows) private let cond: UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: 1) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) private let cond: UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: 1) #endif @@ -142,7 +147,7 @@ public final class ConditionLock { self.mutex = NIOLock() #if os(Windows) InitializeConditionVariable(self.cond) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_cond_init(self.cond, nil) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif @@ -151,11 +156,13 @@ public final class ConditionLock { deinit { #if os(Windows) // condition variables do not need to be explicitly destroyed - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_cond_destroy(self.cond) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif + #if compiler(>=6.1) && _runtime(_multithreaded) self.cond.deallocate() + #endif } /// Acquire the lock, regardless of the value of the state variable. @@ -195,7 +202,7 @@ public final class ConditionLock { #if os(Windows) let result = SleepConditionVariableSRW(self.cond, mutex, INFINITE, 0) precondition(result, "\(#function) failed in SleepConditionVariableSRW with error \(GetLastError())") - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_cond_wait(self.cond, mutex) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif @@ -241,7 +248,7 @@ public final class ConditionLock { // NOTE: this may be a spurious wakeup, adjust the timeout accordingly dwMilliseconds = dwMilliseconds - (timeGetTime() - dwWaitStart) } - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let nsecPerSec: Int64 = 1_000_000_000 self.lock() // the timeout as a (seconds, nano seconds) pair @@ -251,8 +258,14 @@ public final class ConditionLock { gettimeofday(&curTime, nil) let allNSecs: Int64 = timeoutNS + Int64(curTime.tv_usec) * 1000 + #if canImport(wasi_pthread) + let tvSec = curTime.tv_sec + (allNSecs / nsecPerSec) + #else + let tvSec = curTime.tv_sec + Int((allNSecs / nsecPerSec)) + #endif + var timeoutAbs = timespec( - tv_sec: curTime.tv_sec + Int((allNSecs / nsecPerSec)), + tv_sec: tvSec, tv_nsec: Int(allNSecs % nsecPerSec) ) assert(timeoutAbs.tv_nsec >= 0 && timeoutAbs.tv_nsec < Int(nsecPerSec)) @@ -273,6 +286,8 @@ public final class ConditionLock { } } } + #else + return true #endif } @@ -285,7 +300,7 @@ public final class ConditionLock { self.unlock() #if os(Windows) WakeAllConditionVariable(self.cond) - #else + #elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded)) let err = pthread_cond_broadcast(self.cond) precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif diff --git a/Sources/NIOCore/AsyncAwaitSupport.swift b/Sources/NIOCore/AsyncAwaitSupport.swift index 05e806171..5cc6b6ace 100644 --- a/Sources/NIOCore/AsyncAwaitSupport.swift +++ b/Sources/NIOCore/AsyncAwaitSupport.swift @@ -33,6 +33,7 @@ extension EventLoopFuture { } } +#if canImport(Dispatch) extension EventLoopGroup { /// Shuts down the event loop gracefully. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -49,6 +50,7 @@ extension EventLoopGroup { } } } +#endif extension EventLoopPromise { /// Complete a future with the result (or error) of the `async` function `body`. diff --git a/Sources/NIOCore/BSDSocketAPI.swift b/Sources/NIOCore/BSDSocketAPI.swift index ec8d16b2e..13f28b010 100644 --- a/Sources/NIOCore/BSDSocketAPI.swift +++ b/Sources/NIOCore/BSDSocketAPI.swift @@ -83,6 +83,13 @@ private let sysInet_pton: @convention(c) (CInt, UnsafePointer?, UnsafeMut #elseif canImport(Darwin) import Darwin +private let sysInet_ntop: + @convention(c) (CInt, UnsafeRawPointer?, UnsafeMutablePointer?, socklen_t) -> UnsafePointer? = + inet_ntop +private let sysInet_pton: @convention(c) (CInt, UnsafePointer?, UnsafeMutableRawPointer?) -> CInt = inet_pton +#elseif canImport(WASILibc) +import WASILibc + private let sysInet_ntop: @convention(c) (CInt, UnsafeRawPointer?, UnsafeMutablePointer?, socklen_t) -> UnsafePointer? = inet_ntop @@ -212,12 +219,14 @@ extension NIOBSDSocket.ProtocolFamily { public static let inet6: NIOBSDSocket.ProtocolFamily = NIOBSDSocket.ProtocolFamily(rawValue: PF_INET6) + #if !os(WASI) /// UNIX local to the host. public static let unix: NIOBSDSocket.ProtocolFamily = NIOBSDSocket.ProtocolFamily(rawValue: PF_UNIX) + #endif } -#if !os(Windows) +#if !os(Windows) && !os(WASI) extension NIOBSDSocket.ProtocolFamily { /// UNIX local to the host, alias for `PF_UNIX` (`.unix`) public static let local: NIOBSDSocket.ProtocolFamily = @@ -382,6 +391,7 @@ extension NIOBSDSocket.Option { public static let mptcp_info = NIOBSDSocket.Option(rawValue: 1) } +#if !os(WASI) // Socket Options extension NIOBSDSocket.Option { /// Get the error status and clear. @@ -405,8 +415,9 @@ extension NIOBSDSocket.Option { /// Allows the socket to send broadcast messages. public static let so_broadcast = Self(rawValue: SO_BROADCAST) } +#endif -#if !os(Windows) +#if !os(Windows) && !os(WASI) extension NIOBSDSocket.Option { /// Indicate when to generate timestamps. public static let so_timestamp: NIOBSDSocket.Option = diff --git a/Sources/NIOCore/ByteBuffer-aux.swift b/Sources/NIOCore/ByteBuffer-aux.swift index fcfa74ce3..3b00cfa45 100644 --- a/Sources/NIOCore/ByteBuffer-aux.swift +++ b/Sources/NIOCore/ByteBuffer-aux.swift @@ -12,9 +12,12 @@ // //===----------------------------------------------------------------------===// -import Dispatch import _NIOBase64 +#if canImport(Dispatch) +import Dispatch +#endif + extension ByteBuffer { // MARK: Bytes ([UInt8]) APIs @@ -273,6 +276,7 @@ extension ByteBuffer { } } + #if canImport(Dispatch) // MARK: DispatchData APIs /// Write `dispatchData` into this `ByteBuffer`, moving the writer index forward appropriately. /// @@ -337,6 +341,7 @@ extension ByteBuffer { self._moveReaderIndex(forwardBy: length) return result } + #endif // MARK: Other APIs @@ -674,6 +679,7 @@ extension ByteBuffer { self = ByteBufferAllocator().buffer(buffer: buffer) } + #if canImport(Dispatch) /// Create a fresh `ByteBuffer` containing the bytes contained in the given `DispatchData`. /// /// This will allocate a new `ByteBuffer` with enough space to fit the bytes of the `DispatchData` and potentially @@ -688,6 +694,7 @@ extension ByteBuffer { public init(dispatchData: DispatchData) { self = ByteBufferAllocator().buffer(dispatchData: dispatchData) } + #endif } extension ByteBuffer: Codable { @@ -801,6 +808,7 @@ extension ByteBufferAllocator { return newBuffer } + #if canImport(Dispatch) /// Create a fresh `ByteBuffer` containing the bytes contained in the given `DispatchData`. /// /// This will allocate a new `ByteBuffer` with enough space to fit the bytes of the `DispatchData` and potentially @@ -813,6 +821,7 @@ extension ByteBufferAllocator { buffer.writeDispatchData(dispatchData) return buffer } + #endif } extension Optional where Wrapped == ByteBuffer { diff --git a/Sources/NIOCore/ByteBuffer-conversions.swift b/Sources/NIOCore/ByteBuffer-conversions.swift index d1f4f0eef..8c3aed70e 100644 --- a/Sources/NIOCore/ByteBuffer-conversions.swift +++ b/Sources/NIOCore/ByteBuffer-conversions.swift @@ -12,7 +12,9 @@ // //===----------------------------------------------------------------------===// +#if canImport(Dispatch) import Dispatch +#endif extension Array where Element == UInt8 { @@ -48,6 +50,7 @@ extension String { } } +#if canImport(Dispatch) extension DispatchData { /// Creates a `DispatchData` from a given `ByteBuffer`. The entire readable portion of the buffer will be read. @@ -59,3 +62,4 @@ extension DispatchData { } } +#endif diff --git a/Sources/NIOCore/ByteBuffer-core.swift b/Sources/NIOCore/ByteBuffer-core.swift index 1729469fe..2696b18a8 100644 --- a/Sources/NIOCore/ByteBuffer-core.swift +++ b/Sources/NIOCore/ByteBuffer-core.swift @@ -22,6 +22,8 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc #else #error("The Byte Buffer module was unable to identify your C library.") #endif diff --git a/Sources/NIOCore/Channel.swift b/Sources/NIOCore/Channel.swift index 7b2a49c6f..d8fdc4669 100644 --- a/Sources/NIOCore/Channel.swift +++ b/Sources/NIOCore/Channel.swift @@ -360,9 +360,11 @@ public enum ChannelError: Error { /// address. case illegalMulticastAddress(SocketAddress) + #if !os(WASI) /// Multicast is not supported on Interface @available(*, deprecated, renamed: "NIOMulticastNotSupportedError") case multicastNotSupported(NIONetworkInterface) + #endif /// An operation that was inappropriate given the current `Channel` state was attempted. case inappropriateOperationForState diff --git a/Sources/NIOCore/ConvenienceOptionSupport.swift b/Sources/NIOCore/ConvenienceOptionSupport.swift index 69a5439b8..09a6ad7f0 100644 --- a/Sources/NIOCore/ConvenienceOptionSupport.swift +++ b/Sources/NIOCore/ConvenienceOptionSupport.swift @@ -175,9 +175,11 @@ extension ChannelOptions { mutating func applyFallbackMapping(_ universalBootstrap: NIOClientTCPBootstrap) -> NIOClientTCPBootstrap { var result = universalBootstrap + #if !os(WASI) if self.consumeAllowLocalEndpointReuse().isSet { result = result.channelOption(.socketOption(.so_reuseaddr), value: 1) } + #endif if self.consumeAllowRemoteHalfClosure().isSet { result = result.channelOption(.allowRemoteHalfClosure, value: true) } diff --git a/Sources/NIOCore/DispatchQueue+WithFuture.swift b/Sources/NIOCore/DispatchQueue+WithFuture.swift index f85ea96db..593380aa2 100644 --- a/Sources/NIOCore/DispatchQueue+WithFuture.swift +++ b/Sources/NIOCore/DispatchQueue+WithFuture.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +#if canImport(Dispatch) import Dispatch extension DispatchQueue { @@ -45,3 +46,4 @@ extension DispatchQueue { return promise.futureResult } } +#endif diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index 1f38c73a3..7b9e0c68e 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -12,9 +12,17 @@ // //===----------------------------------------------------------------------===// -import Dispatch import NIOConcurrencyHelpers +#if canImport(Dispatch) +import Dispatch +#endif + +#if canImport(WASILibc) +import WASILibc +import CNIOWASI +#endif + #if os(Linux) import CNIOLinux #endif // os(Linux) @@ -616,7 +624,14 @@ public struct NIODeadline: Equatable, Hashable, Sendable { /// and the odds that this code will still be running 530 years from now is very, very low, /// so as a practical matter this will never overflow. return UInt64(ts.tv_sec) &* 1_000_000_000 &+ UInt64(ts.tv_nsec) - #else // os(Linux) + #elseif os(WASI) + var ts = timespec() + CNIOWASI_gettime(&ts) + /// We use unsafe arithmetic here because `UInt64.max` nanoseconds is more than 580 years, + /// and the odds that this code will still be running 530 years from now is very, very low, + /// so as a practical matter this will never overflow. + return UInt64(ts.tv_sec) &* 1_000_000_000 &+ UInt64(ts.tv_nsec) + #else return DispatchTime.now().uptimeNanoseconds #endif // os(Linux) } @@ -1148,11 +1163,13 @@ public protocol EventLoopGroup: AnyObject, _NIOPreconcurrencySendable { /// future or kick off some operation, use `any()`. func any() -> EventLoop + #if canImport(Dispatch) /// Shuts down the eventloop gracefully. This function is clearly an outlier in that it uses a completion /// callback instead of an EventLoopFuture. The reason for that is that NIO's EventLoopFutures will call back on an event loop. /// The virtue of this function is to shut the event loop down. To work around that we call back on a DispatchQueue /// instead. @preconcurrency func shutdownGracefully(queue: DispatchQueue, _ callback: @Sendable @escaping (Error?) -> Void) + #endif /// Returns an `EventLoopIterator` over the `EventLoop`s in this `EventLoopGroup`. /// @@ -1174,6 +1191,7 @@ extension EventLoopGroup { } } +#if canImport(Dispatch) extension EventLoopGroup { @preconcurrency public func shutdownGracefully(_ callback: @escaping @Sendable (Error?) -> Void) { self.shutdownGracefully(queue: .global(), callback) @@ -1208,6 +1226,7 @@ extension EventLoopGroup { return } } +#endif /// This type is intended to be used by libraries which use NIO, and offer their users either the option /// to `.share` an existing event loop group or create (and manage) a new one (`.createNew`) and let it be diff --git a/Sources/NIOCore/EventLoopFuture.swift b/Sources/NIOCore/EventLoopFuture.swift index 6a8b47af3..a6aee1b2c 100644 --- a/Sources/NIOCore/EventLoopFuture.swift +++ b/Sources/NIOCore/EventLoopFuture.swift @@ -12,9 +12,12 @@ // //===----------------------------------------------------------------------===// -import Dispatch import NIOConcurrencyHelpers +#if canImport(Dispatch) +import Dispatch +#endif + /// Internal list of callbacks. /// /// Most of these are closures that pull a value from one future, call a user callback, push the @@ -1666,6 +1669,7 @@ extension EventLoopFuture { // MARK: may block +#if canImport(Dispatch) extension EventLoopFuture { /// Chain an `EventLoopFuture` providing the result of a IO / task that may block. For example: /// @@ -1764,6 +1768,7 @@ extension EventLoopFuture { } } } +#endif // MARK: assertion diff --git a/Sources/NIOCore/FileHandle.swift b/Sources/NIOCore/FileHandle.swift index bbba5b0db..82500b9fb 100644 --- a/Sources/NIOCore/FileHandle.swift +++ b/Sources/NIOCore/FileHandle.swift @@ -21,6 +21,9 @@ import Glibc import Musl #elseif canImport(Android) import Android +#elseif canImport(WASILibc) +import WASILibc +import CNIOWASI #else #error("The File Handle module was unable to identify your C library.") #endif @@ -59,6 +62,7 @@ public final class NIOFileHandle: FileDescriptor { ) } + #if !os(WASI) /// Duplicates this `NIOFileHandle`. This means that a new `NIOFileHandle` object with a new underlying file descriptor /// is returned. The caller takes ownership of the returned `NIOFileHandle` and is responsible for closing it. /// @@ -70,6 +74,7 @@ public final class NIOFileHandle: FileDescriptor { NIOFileHandle(descriptor: try SystemCalls.dup(descriptor: fd)) } } + #endif /// Take the ownership of the underlying file descriptor. This is similar to `close()` but the underlying file /// descriptor remains open. The caller is responsible for closing the file descriptor by some other means. @@ -139,6 +144,8 @@ extension NIOFileHandle { #if os(Windows) public static let defaultPermissions = _S_IREAD | _S_IWRITE + #elseif os(WASI) + public static let defaultPermissions = WASILibc.S_IWUSR | WASILibc.S_IRUSR | WASILibc.S_IRGRP | WASILibc.S_IROTH #else public static let defaultPermissions = S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH #endif @@ -148,7 +155,12 @@ extension NIOFileHandle { /// - parameters: /// - posixMode: `file mode` applied when file is created. Default permissions are: read and write for fileowner, read for owners group and others. public static func allowFileCreation(posixMode: NIOPOSIXFileMode = defaultPermissions) -> Flags { - Flags(posixMode: posixMode, posixFlags: O_CREAT) + #if os(WASI) + let flags = CNIOWASI_O_CREAT() + #else + let flags = O_CREAT + #endif + return Flags(posixMode: posixMode, posixFlags: flags) } /// Allows the specification of POSIX flags (e.g. `O_TRUNC`) and mode (e.g. `S_IWUSR`) diff --git a/Sources/NIOCore/FileRegion.swift b/Sources/NIOCore/FileRegion.swift index a9d1e09b6..646487293 100644 --- a/Sources/NIOCore/FileRegion.swift +++ b/Sources/NIOCore/FileRegion.swift @@ -21,6 +21,8 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc #else #error("The File Region module was unable to identify your C library.") #endif diff --git a/Sources/NIOCore/GlobalSingletons.swift b/Sources/NIOCore/GlobalSingletons.swift index a3f1e610f..50865e07b 100644 --- a/Sources/NIOCore/GlobalSingletons.swift +++ b/Sources/NIOCore/GlobalSingletons.swift @@ -25,6 +25,8 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc #else #error("Unsupported C library") #endif diff --git a/Sources/NIOCore/IO.swift b/Sources/NIOCore/IO.swift index f2d61bdba..3b8ef1ed2 100644 --- a/Sources/NIOCore/IO.swift +++ b/Sources/NIOCore/IO.swift @@ -34,6 +34,8 @@ import Glibc import Musl #elseif canImport(Bionic) import Bionic +#elseif canImport(WASILibc) +import WASILibc #elseif canImport(Darwin) import Darwin #else diff --git a/Sources/NIOCore/Interfaces.swift b/Sources/NIOCore/Interfaces.swift index 6030acdcb..858431cb6 100644 --- a/Sources/NIOCore/Interfaces.swift +++ b/Sources/NIOCore/Interfaces.swift @@ -22,6 +22,8 @@ import Bionic import CNIOLinux #elseif canImport(Darwin) import Darwin +#elseif canImport(WASILibc) +import WASILibc #elseif os(Windows) import let WinSDK.AF_INET import let WinSDK.AF_INET6 @@ -44,7 +46,7 @@ import typealias WinSDK.UINT8 #error("The Core interfaces module was unable to identify your C library.") #endif -#if !os(Windows) +#if !os(Windows) && !os(WASI) extension ifaddrs { fileprivate var dstaddr: UnsafeMutablePointer? { #if os(Linux) || os(Android) @@ -95,6 +97,11 @@ public final class NIONetworkInterface: Sendable { /// The index of the interface, as provided by `if_nametoindex`. public let interfaceIndex: Int + #if os(WASI) + @available(*, unavailable) + init() { fatalError() } + #endif + #if os(Windows) internal init?( _ pAdapter: UnsafeMutablePointer, @@ -127,7 +134,7 @@ public final class NIONetworkInterface: Sendable { self.pointToPointDestinationAddress = nil self.multicastSupported = false } - #else + #elseif !os(WASI) internal init?(_ caddr: ifaddrs) { self.name = String(cString: caddr.ifa_name!) @@ -308,7 +315,7 @@ public struct NIONetworkDevice { } self.backing = backing } - #else + #elseif !os(WASI) internal init?(_ caddr: ifaddrs) { guard let backing = Backing(caddr) else { return nil @@ -318,7 +325,7 @@ public struct NIONetworkDevice { } #endif - #if !os(Windows) + #if !os(Windows) && !os(WASI) /// Convert a `NIONetworkInterface` to a `NIONetworkDevice`. As `NIONetworkDevice`s are a superset of `NIONetworkInterface`s, /// it is always possible to perform this conversion. @available(*, deprecated, message: "This is a compatibility helper, and will be removed in a future release") @@ -424,7 +431,7 @@ extension NIONetworkDevice { self.pointToPointDestinationAddress = nil self.multicastSupported = false } - #else + #elseif !os(WASI) internal init?(_ caddr: ifaddrs) { self.name = String(cString: caddr.ifa_name!) self.address = caddr.ifa_addr.flatMap { $0.convert() } diff --git a/Sources/NIOCore/MulticastChannel.swift b/Sources/NIOCore/MulticastChannel.swift index 129fe6f46..45b2a6880 100644 --- a/Sources/NIOCore/MulticastChannel.swift +++ b/Sources/NIOCore/MulticastChannel.swift @@ -25,7 +25,7 @@ public protocol MulticastChannel: Channel { /// `nil` if you are not interested in the result of the operation. func joinGroup(_ group: SocketAddress, promise: EventLoopPromise?) - #if !os(Windows) + #if !os(Windows) && !os(WASI) /// Request that the `MulticastChannel` join the multicast group given by `group` on the interface /// given by `interface`. /// @@ -56,7 +56,7 @@ public protocol MulticastChannel: Channel { /// `nil` if you are not interested in the result of the operation. func leaveGroup(_ group: SocketAddress, promise: EventLoopPromise?) - #if !os(Windows) + #if !os(Windows) && !os(WASI) /// Request that the `MulticastChannel` leave the multicast group given by `group` on the interface /// given by `interface`. /// @@ -92,7 +92,7 @@ extension MulticastChannel { return promise.futureResult } - #if !os(Windows) + #if !os(Windows) && !os(WASI) @available(*, deprecated, renamed: "joinGroup(_:device:)") public func joinGroup(_ group: SocketAddress, interface: NIONetworkInterface?) -> EventLoopFuture { let promise = self.eventLoop.makePromise(of: Void.self) @@ -117,7 +117,7 @@ extension MulticastChannel { return promise.futureResult } - #if !os(Windows) + #if !os(Windows) && !os(WASI) @available(*, deprecated, renamed: "leaveGroup(_:device:)") public func leaveGroup(_ group: SocketAddress, interface: NIONetworkInterface?) -> EventLoopFuture { let promise = self.eventLoop.makePromise(of: Void.self) diff --git a/Sources/NIOCore/SocketAddresses.swift b/Sources/NIOCore/SocketAddresses.swift index 6e36b3986..22479a3ba 100644 --- a/Sources/NIOCore/SocketAddresses.swift +++ b/Sources/NIOCore/SocketAddresses.swift @@ -52,6 +52,8 @@ import Musl import Android #endif import CNIOLinux +#elseif canImport(WASILibc) +import WASILibc #else #error("The Socket Addresses module was unable to identify your C library.") #endif @@ -178,7 +180,11 @@ public enum SocketAddress: CustomStringConvertible, Sendable { case .v6: return .inet6 case .unixDomainSocket: + #if os(WASI) + fatalError("unix domain sockets are currently not supported by WASILibc") + #else return .unix + #endif } } @@ -197,7 +203,6 @@ public enum SocketAddress: CustomStringConvertible, Sendable { return nil } } - /// Get and set the port associated with the address, if defined. /// When setting to `nil` the port will default to `0` for compatible sockets. The rationale for this is that both `nil` and `0` can /// be interpreted as "no preference". @@ -233,6 +238,9 @@ public enum SocketAddress: CustomStringConvertible, Sendable { /// Get the pathname of a UNIX domain socket as a string public var pathname: String? { + #if os(WASI) + return nil + #else switch self { case .v4: return nil @@ -248,6 +256,7 @@ public enum SocketAddress: CustomStringConvertible, Sendable { } return pathname } + #endif } /// Calls the given function with a pointer to a `sockaddr` structure and the associated size @@ -321,11 +330,13 @@ public enum SocketAddress: CustomStringConvertible, Sendable { var addr = sockaddr_un() addr.sun_family = sa_family_t(NIOBSDSocket.AddressFamily.unix.rawValue) + #if !os(WASI) pathBytes.withUnsafeBytes { srcBuffer in withUnsafeMutableBytes(of: &addr.sun_path) { dstPtr in dstPtr.copyMemory(from: srcBuffer) } } + #endif self = .unixDomainSocket(.init(address: addr)) } @@ -457,6 +468,10 @@ public enum SocketAddress: CustomStringConvertible, Sendable { /// - returns: the `SocketAddress` for the host / port pair. /// - throws: a `SocketAddressError.unknown` if we could not resolve the `host`, or `SocketAddressError.unsupported` if the address itself is not supported (yet). public static func makeAddressResolvingHost(_ host: String, port: Int) throws -> SocketAddress { + #if os(WASI) + throw SocketAddressError.unsupported + #endif + #if os(Windows) return try host.withCString(encodedAs: UTF16.self) { wszHost in try String(port).withCString(encodedAs: UTF16.self) { wszPort in @@ -484,7 +499,7 @@ public enum SocketAddress: CustomStringConvertible, Sendable { throw SocketAddressError.unsupported } } - #else + #elseif !os(WASI) var info: UnsafeMutablePointer? // FIXME: this is blocking! @@ -549,6 +564,9 @@ extension SocketAddress: Equatable { return false } + #if os(WASI) + return true + #else let bufferSize = MemoryLayout.size(ofValue: addr1.address.sun_path) // Swift implicitly binds the memory for homogeneous tuples to both the tuple type and the element type. @@ -563,6 +581,7 @@ extension SocketAddress: Equatable { return strncmp(typedSunpath1, typedSunpath2, bufferSize) == 0 } } + #endif case (.v4, _), (.v6, _), (.unixDomainSocket, _): return false } @@ -581,6 +600,7 @@ extension SocketAddress: Hashable { hasher.combine(0) hasher.combine(uds.address.sun_family) + #if !os(WASI) let pathSize = MemoryLayout.size(ofValue: uds.address.sun_path) // Swift implicitly binds the memory of homogeneous tuples to both the tuple type and the element type. @@ -593,6 +613,7 @@ extension SocketAddress: Hashable { let bytes = UnsafeRawBufferPointer(start: UnsafeRawPointer(typedPathPointer), count: length) hasher.combine(bytes: bytes) } + #endif case .v4(let v4Addr): hasher.combine(1) hasher.combine(v4Addr.address.sin_family) diff --git a/Sources/NIOCore/SocketOptionProvider.swift b/Sources/NIOCore/SocketOptionProvider.swift index 772f709b1..1050dbfa8 100644 --- a/Sources/NIOCore/SocketOptionProvider.swift +++ b/Sources/NIOCore/SocketOptionProvider.swift @@ -24,6 +24,8 @@ import Bionic import CNIOLinux #elseif os(Windows) import WinSDK +#elseif canImport(WASILibc) +import WASILibc #else #error("The Socket Option provider module was unable to identify your C library.") #endif @@ -156,6 +158,16 @@ extension SocketOptionProvider { } #endif +enum SocketOptionProviderError: Swift.Error { + case unsupported +} + +#if canImport(WASILibc) +public typealias NIOLinger = Never +#else +public typealias NIOLinger = linger +#endif + // MARK:- Safe helper methods. // Hello code reader! All the methods in this extension are "safe" wrapper methods that define the correct // types for `setSocketOption` and `getSocketOption` and call those methods on behalf of the user. These @@ -171,15 +183,23 @@ extension SocketOptionProvider { /// - returns: An `EventLoopFuture` that fires when the option has been set, /// or if an error has occurred. public func setSoLinger(_ value: linger) -> EventLoopFuture { + #if os(WASI) + self.eventLoop.makeFailedFuture(SocketOptionProviderError.unsupported) + #else self.unsafeSetSocketOption(level: .socket, name: .so_linger, value: value) + #endif } /// Gets the value of the socket option SO_LINGER. /// /// - returns: An `EventLoopFuture` containing the value of the socket option, or /// any error that occurred while retrieving the socket option. - public func getSoLinger() -> EventLoopFuture { + public func getSoLinger() -> EventLoopFuture { + #if os(WASI) + self.eventLoop.makeFailedFuture(SocketOptionProviderError.unsupported) + #else self.unsafeGetSocketOption(level: .socket, name: .so_linger) + #endif } /// Sets the socket option IP_MULTICAST_IF to `value`. diff --git a/Sources/NIOCore/SystemCallHelpers.swift b/Sources/NIOCore/SystemCallHelpers.swift index 1749cd643..159b2f10b 100644 --- a/Sources/NIOCore/SystemCallHelpers.swift +++ b/Sources/NIOCore/SystemCallHelpers.swift @@ -25,6 +25,8 @@ import Darwin.C import Glibc #elseif canImport(Musl) import Musl +#elseif canImport(WASILibc) +import WASILibc #elseif os(Windows) import CNIOWindows #elseif canImport(Android) @@ -39,7 +41,9 @@ private let sysClose: @convention(c) (CInt) -> CInt = _close private let sysLseek: @convention(c) (CInt, off_t, CInt) -> off_t = _lseek private let sysRead: @convention(c) (CInt, UnsafeMutableRawPointer?, CUnsignedInt) -> CInt = _read #else +#if !os(WASI) private let sysDup: @convention(c) (CInt) -> CInt = dup +#endif private let sysClose: @convention(c) (CInt) -> CInt = close private let sysOpenWithMode: @convention(c) (UnsafePointer, CInt, NIOPOSIXFileMode) -> CInt = open private let sysLseek: @convention(c) (CInt, off_t, CInt) -> off_t = lseek @@ -49,7 +53,7 @@ private let sysRead: @convention(c) (CInt, UnsafeMutableRawPointer?, size_t) -> #if os(Android) private let sysIfNameToIndex: @convention(c) (UnsafePointer) -> CUnsignedInt = if_nametoindex private let sysGetifaddrs: @convention(c) (UnsafeMutablePointer?>) -> CInt = getifaddrs -#else +#elseif !os(WASI) private let sysIfNameToIndex: @convention(c) (UnsafePointer?) -> CUnsignedInt = if_nametoindex #if !os(Windows) private let sysGetifaddrs: @convention(c) (UnsafeMutablePointer?>?) -> CInt = getifaddrs @@ -97,8 +101,10 @@ internal func syscall( switch (err, blocking) { case (EINTR, _): continue + #if !os(WASI) case (EWOULDBLOCK, true): return .wouldBlock(0) + #endif default: preconditionIsNotUnacceptableErrno(err: err, where: function) throw IOError(errnoCode: err, reason: function) @@ -109,6 +115,7 @@ internal func syscall( } enum SystemCalls { + #if !os(WASI) @discardableResult @inline(never) internal static func dup(descriptor: CInt) throws -> CInt { @@ -116,6 +123,7 @@ enum SystemCalls { sysDup(descriptor) }.result } + #endif @inline(never) internal static func close(descriptor: CInt) throws { @@ -179,7 +187,7 @@ enum SystemCalls { sysRead(descriptor, pointer, size) } } - #else + #elseif !os(WASI) @inline(never) internal static func read( descriptor: CInt, @@ -192,6 +200,7 @@ enum SystemCalls { } #endif + #if !os(WASI) @inline(never) internal static func if_nametoindex(_ name: UnsafePointer?) throws -> CUnsignedInt { try syscall(blocking: false) { @@ -207,4 +216,5 @@ enum SystemCalls { } } #endif + #endif // !os(WASI) } diff --git a/Sources/NIOCore/Utilities.swift b/Sources/NIOCore/Utilities.swift index 730a3a370..6184c388c 100644 --- a/Sources/NIOCore/Utilities.swift +++ b/Sources/NIOCore/Utilities.swift @@ -38,6 +38,8 @@ import struct WinSDK.ULONG import typealias WinSDK.DWORD #elseif canImport(Darwin) import Darwin +#elseif canImport(WASILibc) +import WASILibc #else #error("The Core utilities module was unable to identify your C library.") #endif @@ -129,7 +131,7 @@ public enum System { #endif } - #if !os(Windows) + #if !os(Windows) && !os(WASI) /// A utility function that enumerates the available network interfaces on this machine. /// /// This function returns values that are true for a brief snapshot in time. These results can @@ -211,7 +213,7 @@ public enum System { } pAdapter = pAdapter!.pointee.Next } - #else + #elseif !os(WASI) var interface: UnsafeMutablePointer? = nil try SystemCalls.getifaddrs(&interface) let originalInterface = interface diff --git a/Sources/NIOEmbedded/AsyncTestingChannel.swift b/Sources/NIOEmbedded/AsyncTestingChannel.swift index 11900d835..087f9a0ea 100644 --- a/Sources/NIOEmbedded/AsyncTestingChannel.swift +++ b/Sources/NIOEmbedded/AsyncTestingChannel.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +#if canImport(Dispatch) import NIOConcurrencyHelpers import NIOCore @@ -661,3 +662,4 @@ extension NIOAsyncTestingChannel.LeftOverState: @unchecked Sendable {} @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension NIOAsyncTestingChannel.BufferState: @unchecked Sendable {} +#endif diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 3b9ed67de..9085e7864 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +#if canImport(Dispatch) import Atomics import Dispatch import NIOConcurrencyHelpers @@ -405,3 +406,4 @@ private class PromiseCreationStore { precondition(self.promiseCreationStore.isEmpty, "NIOAsyncTestingEventLoop freed with uncompleted promises!") } } +#endif diff --git a/Sources/NIOEmbedded/Embedded.swift b/Sources/NIOEmbedded/Embedded.swift index d95b25821..c7199093a 100644 --- a/Sources/NIOEmbedded/Embedded.swift +++ b/Sources/NIOEmbedded/Embedded.swift @@ -14,11 +14,14 @@ import Atomics import DequeModule -import Dispatch import NIOConcurrencyHelpers import NIOCore import _NIODataStructures +#if canImport(Dispatch) +import Dispatch +#endif + internal struct EmbeddedScheduledTask { let id: UInt64 let task: () -> Void @@ -216,6 +219,7 @@ public final class EmbeddedEventLoop: EventLoop { } } + #if canImport(Dispatch) /// - see: `EventLoop.shutdownGracefully` public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) { self.state = .closing @@ -226,6 +230,7 @@ public final class EmbeddedEventLoop: EventLoop { callback(nil) } } + #endif public func _preconditionSafeToWait(file: StaticString, line: UInt) { // EmbeddedEventLoop always allows a wait, as waiting will essentially always block diff --git a/Sources/NIOPosix/GetaddrinfoResolver.swift b/Sources/NIOPosix/GetaddrinfoResolver.swift index c5a7e5bfa..fc07d59a5 100644 --- a/Sources/NIOPosix/GetaddrinfoResolver.swift +++ b/Sources/NIOPosix/GetaddrinfoResolver.swift @@ -12,9 +12,12 @@ // //===----------------------------------------------------------------------===// -import Dispatch import NIOCore +#if canImport(Dispatch) +import Dispatch +#endif + /// A DNS resolver built on top of the libc `getaddrinfo` function. /// /// This is the lowest-common-denominator resolver available to NIO. It's not really a very good diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index 6e245b386..9f9266fa8 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -13,10 +13,13 @@ //===----------------------------------------------------------------------===// import Atomics -import Dispatch import NIOConcurrencyHelpers import NIOCore +#if canImport(Dispatch) +import Dispatch +#endif + struct NIORegistration: Registration { enum ChannelType { case serverSocketChannel(ServerSocketChannel) diff --git a/Sources/NIOPosix/NIOThreadPool.swift b/Sources/NIOPosix/NIOThreadPool.swift index 5f4ed1e04..c5817601f 100644 --- a/Sources/NIOPosix/NIOThreadPool.swift +++ b/Sources/NIOPosix/NIOThreadPool.swift @@ -14,10 +14,13 @@ import Atomics import DequeModule -import Dispatch import NIOConcurrencyHelpers import NIOCore +#if canImport(Dispatch) +import Dispatch +#endif + /// Errors that may be thrown when executing work on a `NIOThreadPool` public enum NIOThreadPoolError { diff --git a/Sources/_NIODataStructures/Heap.swift b/Sources/_NIODataStructures/Heap.swift index 29a95a18c..7fab52653 100644 --- a/Sources/_NIODataStructures/Heap.swift +++ b/Sources/_NIODataStructures/Heap.swift @@ -17,6 +17,8 @@ import Darwin.C import Glibc #elseif canImport(Musl) import Musl +#elseif canImport(WASILibc) +import WASILibc #elseif os(Windows) import ucrt #elseif canImport(Bionic)