From 58bce128cea4c9d003a95899becee84543ae3451 Mon Sep 17 00:00:00 2001 From: Minh Vu Date: Fri, 26 Jun 2026 04:54:56 +0200 Subject: [PATCH 01/14] Forward io_uring_enter2 size argument (#326) --- Sources/CSystem/include/io_uring.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index ce618f3..686bb77 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -235,7 +235,7 @@ static inline int io_uring_enter2(int fd, unsigned int to_submit, unsigned int m unsigned int flags, void *args, size_t sz) { return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, - flags, args, _NSIG / 8); + flags, args, sz); } static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, From e358151f96ca629ce1824f3e6275a4810a40ba32 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 25 Jun 2026 15:10:26 -0700 Subject: [PATCH 02/14] Improve existence/enablement test for io_uring --- Tests/SystemTests/IORingTests.swift | 88 +++++++++++++++++++++++------ 1 file changed, 72 insertions(+), 16 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index e001e69..b8a8ecd 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -3,6 +3,11 @@ import XCTest import CSystem //for eventfd +#if canImport(Glibc) +import Glibc // for errno +#elseif canImport(Musl) +import Musl // for errno +#endif #if SYSTEM_PACKAGE import SystemPackage @@ -10,29 +15,80 @@ import SystemPackage import System #endif -func uringEnabled() throws -> Bool { +// Cache `isUringEnabled()`. The probe is complex and the answer doesn't change +// during a test run. +let uringEnabled: Bool = { do { - let procPath = FilePath("/proc/sys/kernel/io_uring_disabled") - let fd = try FileDescriptor.open(procPath, .readOnly) - let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0) - _ = try fd.read(into: buffer) - if buffer.load(fromByteOffset: 0, as: Int.self) == 0 { - return true - } - } catch (_) { + return try isUringEnabled() + } catch { return false } - return false +}() + +func isUringEnabled() throws -> Bool { + // Even if the kernel supports io_uring, the SystemPackage build may have + // been compiled against older kernel headers that lack features it needs + // (gated on IORING_TIMEOUT_BOOTTIME in CSystem); in that configuration + // IORing.init throws ENOTSUP. Treat that as disabled so tests skip cleanly + // instead of failing. + do throws(Errno) { + _ = try IORing(queueDepth: 1, flags: []) + } catch { + switch error { + case .notSupported, .noFunction, .invalidArgument, + .notPermitted, .permissionDenied: + return false + default: + throw error + } + } + + // The ideal test uses /proc/sys/kernel/io_uring_disabled (Linux >= 6.6). + if let fd = try? FileDescriptor.open( + "/proc/sys/kernel/io_uring_disabled", .readOnly) + { + defer { try? fd.close() } + let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1, alignment: 1) + defer { buffer.deallocate() } + let n = try fd.read(into: buffer) + return n == 1 && (buffer.load(as: UInt8.self) == UInt8(ascii: "0")) + } + + // Fallback for older kernels: simply attempt io_uring_setup. + // - ENOSYS -> syscall doesn't exist (Linux < 5.1) -> disabled. + // - EPERM or EACCES -> treat as disabled + // - propagate any other error. + var params = io_uring_params() + let raw = io_uring_setup(1, ¶ms) + if raw < 0 { + let err = Errno(rawValue: errno) + switch err { + case .noFunction, .notPermitted, .permissionDenied: + return false + default: + throw err + } + } + try? FileDescriptor(rawValue: raw).close() + return true } final class IORingTests: XCTestCase { + func testIsUringEnabled() throws { + // If `isUringEnabled()` throws, it is incomplete in some way. + let enabled = try isUringEnabled() + if !enabled { + print("IORing tests will be skipped.") + } + } + func testInit() throws { - guard try uringEnabled() else { return } + guard uringEnabled else { return } _ = try IORing(queueDepth: 32, flags: []) } func testNop() throws { - guard try uringEnabled() else { return } + guard uringEnabled else { return } var ring = try IORing(queueDepth: 32, flags: []) _ = try ring.submit(linkedRequests: .nop()) let completion = try ring.blockingConsumeCompletion() @@ -68,7 +124,7 @@ final class IORingTests: XCTestCase { } func testUndersizedSubmissionQueue() throws { - guard try uringEnabled() else { return } + guard uringEnabled else { return } var ring: IORing = try IORing(queueDepth: 1) let enqueued = ring.prepare(linkedRequests: .nop(), .nop()) XCTAssertFalse(enqueued) @@ -76,7 +132,7 @@ final class IORingTests: XCTestCase { // Exercises opening, reading, closing, registered files, registered buffers, and eventfd func testOpenReadAndWriteFixedFile() throws { - guard try uringEnabled() else { return } + guard uringEnabled else { return } let (parent, path) = try makeHelloWorldFile() let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) @@ -134,7 +190,7 @@ final class IORingTests: XCTestCase { // dangling pointer. Here we deliberately let the FilePath go out of scope // between prepare and submit, then churn the heap to make UAFs observable. func testPathBufferLifetimeAcrossPrepareSubmit() throws { - guard try uringEnabled() else { return } + guard uringEnabled else { return } let (parent, _) = try makeHelloWorldFile() var ring = try IORing(queueDepth: 6) @@ -168,7 +224,7 @@ final class IORingTests: XCTestCase { } func testPathBufferLifetimeAcrossLinkedRequests() throws { - guard try uringEnabled() else { return } + guard uringEnabled else { return } let (parent, _) = try makeHelloWorldFile() let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) From 1494bb89fc004ccfb1ac34d2d9f0de5a6800d9fe Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 25 Jun 2026 16:58:42 -0700 Subject: [PATCH 03/14] Change the io_uring existence macros to integer values `true` and `false` import differently with C23 than before, so the swift-side test `(__SWIFT_IORING_SUPPORTED != 0)` became dependent on the toolchain. Integer constants are more reliable for this. --- Sources/CSystem/include/io_uring.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index 686bb77..3010bbc 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -81,7 +81,7 @@ #ifdef IORING_TIMEOUT_BOOTTIME // Kernel version >= 5.15, io_uring_sqe has file_index // and all current Swift operations are supported. -#define __SWIFT_IORING_SUPPORTED true +#define __SWIFT_IORING_SUPPORTED 1 typedef struct io_uring_sqe swift_io_uring_sqe; #else // io_uring_sqe is missing properties that IORequest expects. @@ -89,7 +89,7 @@ typedef struct io_uring_sqe swift_io_uring_sqe; // // Define a fallback struct to avoid build errors, but IORing // will throw ENOTSUP on initialization. -#define __SWIFT_IORING_SUPPORTED false +#define __SWIFT_IORING_SUPPORTED 0 typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe; #endif @@ -107,7 +107,7 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe; // Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK) #include -#define __SWIFT_IORING_SUPPORTED false +#define __SWIFT_IORING_SUPPORTED 0 #define IORING_OFF_SQ_RING 0ULL #define IORING_OFF_CQ_RING 0x8000000ULL From e0aa78a94473a0703756710c85a0dcdac6e2b0d9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 22 Jun 2026 17:16:17 -0700 Subject: [PATCH 04/14] Test for an implementation bug --- Tests/SystemTests/IORingTests.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index b8a8ecd..1d897a1 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -258,6 +258,32 @@ final class IORingTests: XCTestCase { try cleanUpHelloWorldFile(parent) rawBuffer.deallocate() } + + // Timeout test for `blockingConsumeCompletion(timeout:)`: + func testBlockingConsumeCompletionWithTimeoutOnIdleRing() throws { + guard uringEnabled else { return } + let ring = try IORing(queueDepth: 4, flags: []) + guard ring.supportedFeatures.contains(.extendedArguments) else { + // Kernel < 5.11: timeouts in io_uring_enter aren't supported. + return + } + + let clock = ContinuousClock() + let start = clock.now + + var thrown: Errno? = nil + do throws(Errno) { + _ = try ring.blockingConsumeCompletion(timeout: .milliseconds(100)) + XCTFail("expected timeout, got a completion on an idle ring") + } catch { + thrown = error + } + + let elapsed = start.duration(to: clock.now) + + XCTAssertEqual(thrown, .timeout) + XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(50)) + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From 76a2dc6162afc84d4e373abce22176266c57ac7f Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 22 Jun 2026 17:30:21 -0700 Subject: [PATCH 05/14] Improve `_blockingConsumeCompletionGuts` --- Sources/CSystem/include/io_uring.h | 3 ++- Sources/System/IORing/IORing.swift | 26 ++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index 3010bbc..defc284 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -113,7 +113,8 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe; #define IORING_OFF_CQ_RING 0x8000000ULL #define IORING_OFF_SQES 0x10000000ULL -#define IORING_ENTER_GETEVENTS (1U << 0) +#define IORING_ENTER_GETEVENTS (1U << 0) +#define IORING_ENTER_EXT_ARG (1U << 3) #define IORING_FEAT_SINGLE_MMAP (1U << 0) #define IORING_FEAT_NODROP (1U << 1) diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index dcb71e4..0da0dea 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -517,14 +517,16 @@ public struct IORing: ~Copyable { if count < minimumCount { while count < minimumCount { var sz = 0 + var flags = IORING_ENTER_GETEVENTS if extraArgs != nil { sz = MemoryLayout.size + flags |= IORING_ENTER_EXT_ARG } let res = io_uring_enter2( ringDescriptor, 0, minimumCount, - IORING_ENTER_GETEVENTS, + flags, extraArgs, sz ) @@ -536,14 +538,30 @@ public struct IORing: ~Copyable { // EFAULT (bad address for argument from library, fatal) // EBUSY (not enough space for events; implies events filled // by kernel between kernelTail load and now) - if res >= 0 || res == -EBUSY { + // ETIME (timeout from extraArgs.ts elapsed before + // minimumCount completions arrived) + if res >= 0 { break - } else if res == -EAGAIN || res == -EINTR { + } + let err: Errno + #if canImport(Glibc) + err = Errno(rawValue: Glibc.errno) + #elseif canImport(Musl) + err = Errno(rawValue: Musl.errno) + #endif + if err == .resourceBusy { + break + } + if err == .resourceTemporarilyUnavailable || err == .interrupted { continue } + if err == .timeout { + try consumer(nil, err, true) + return + } fatalError( "fatal error in receiving requests: " - + Errno(rawValue: -res).debugDescription + + err.debugDescription ) } var count = 0 From 1cfd5105b2f7541cad8ee1d41b4fa42c2c1449a5 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 26 Jun 2026 17:09:27 -0700 Subject: [PATCH 06/14] [gardening] remove a forgotten print statement --- Tests/SystemTests/IORingTests.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 1d897a1..ee1f4ab 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -173,7 +173,6 @@ final class IORingTests: XCTestCase { _ = try ring.blockingConsumeCompletion() //close memset(rawBuffer.baseAddress!, 0, rawBuffer.count) //Verify using a non-ring IO method that what we wrote matches our expectations - print("about to open") let nonRingFD = try FileDescriptor.open(path, .readOnly) let bytesRead = try nonRingFD.read(into: rawBuffer) XCTAssert(bytesRead == 13) From a7e7c56fec933a1e84c1a97b7ed9379fa964b46e Mon Sep 17 00:00:00 2001 From: Jake Petroules Date: Fri, 26 Jun 2026 21:04:06 -0700 Subject: [PATCH 07/14] Enable .closeOnExec for FileDescriptor.open on Windows Make OpenOptions.closeOnExec available on Windows, where it maps to _O_CLOEXEC (O_NOINHERIT). The Windows open adapter already decodes O_NOINHERIT into a non-inheritable handle, so this produces the expected close-on-exec semantics. Also add the deprecated O_NOINHERIT alias, matching the PipeOptions treatment from #312. --- Sources/System/FileDescriptor.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 7155fa3..b7a9505 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -301,7 +301,6 @@ extension FileDescriptor { public static var O_EVTONLY: OpenOptions { eventOnly } #endif -#if !os(Windows) /// Indicates that executing a program closes the file. /// /// Normally, file descriptors remain open @@ -319,6 +318,11 @@ extension FileDescriptor { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnExec") public static var O_CLOEXEC: OpenOptions { closeOnExec } + +#if os(Windows) + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnExec") + public static var O_NOINHERIT: OpenOptions { closeOnExec } #endif } From 0b7fc03c76e27c85c44bbf4dc159d58abc3e2f73 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 6 Jul 2026 11:26:24 -0700 Subject: [PATCH 08/14] Add test of OpenOptions.closeOnExec for Windows --- .../FileOperationsTestWindows.swift | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Tests/SystemTests/FileOperationsTestWindows.swift b/Tests/SystemTests/FileOperationsTestWindows.swift index fbba7b5..856d74d 100644 --- a/Tests/SystemTests/FileOperationsTestWindows.swift +++ b/Tests/SystemTests/FileOperationsTestWindows.swift @@ -18,6 +18,7 @@ import XCTest #endif import WinSDK +import ucrt private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA) private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE) @@ -295,6 +296,38 @@ final class FileOperationsTestWindows: XCTestCase { // We can't easily test this without allocating 4GB, but the boundary is correct } } + + func testCloseOnExecOpenOption() throws { + try withTemporaryFilePath(basename: "testCloseOnExec") { path in + + func hasInheritFlag(of fd: FileDescriptor) throws -> Bool { + let osfHandle = _get_osfhandle(fd.rawValue) + let handle = try XCTUnwrap(HANDLE(bitPattern: osfHandle)) + var flags: DWORD = 0 + XCTAssertTrue(GetHandleInformation(handle, &flags)) + return flags & DWORD(HANDLE_FLAG_INHERIT) == DWORD(HANDLE_FLAG_INHERIT) + } + + var fd: FileDescriptor + fd = try FileDescriptor.open( + path.appending("wontinherit.txt"), .readWrite, + options: [.create, .truncate, .closeOnExec], + permissions: .ownerReadWrite + ) + try fd.closeAfter { + XCTAssertEqual(try hasInheritFlag(of: fd), false) + } + + fd = try FileDescriptor.open( + path.appending("inheritable.txt"), .readWrite, + options: [.create, .truncate], + permissions: .ownerReadWrite + ) + try fd.closeAfter { + XCTAssertEqual(try hasInheritFlag(of: fd), true) + } + } + } } #endif // os(Windows) From 636e14a3d2f2c7f8e0fee144829d337a697e2df6 Mon Sep 17 00:00:00 2001 From: finagolfin Date: Fri, 3 Jul 2026 11:45:09 +0530 Subject: [PATCH 09/14] Update CI to latest version of official workflows --- .github/workflows/pull_request.yml | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 5eb9b35..14354cb 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -10,7 +10,7 @@ on: jobs: tests: name: Test - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.12 with: swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI" enable_linux_checks: true @@ -24,6 +24,8 @@ jobs: {"os_version": "focal", "swift_version": "6.2"}, {"os_version": "focal", "swift_version": "nightly-6.3"}, {"os_version": "focal", "swift_version": "6.3"}, + {"os_version": "focal", "swift_version": "nightly-6.4.x"}, + {"os_version": "focal", "swift_version": "6.4.x"}, {"os_version": "focal", "swift_version": "nightly-main"}, ] enable_macos_checks: true @@ -42,6 +44,8 @@ jobs: {"os_version": "focal", "swift_version": "6.2"}, {"os_version": "focal", "swift_version": "nightly-6.3"}, {"os_version": "focal", "swift_version": "6.3"}, + {"os_version": "focal", "swift_version": "nightly-6.4.x"}, + {"os_version": "focal", "swift_version": "6.4.x"}, {"os_version": "focal", "swift_version": "nightly-main"}, ] enable_wasm_sdk_build: true @@ -51,6 +55,8 @@ jobs: {"os_version": "focal", "swift_version": "6.2"}, {"os_version": "focal", "swift_version": "nightly-6.3"}, {"os_version": "focal", "swift_version": "6.3"}, + {"os_version": "focal", "swift_version": "nightly-6.4.x"}, + {"os_version": "focal", "swift_version": "6.4.x"}, {"os_version": "focal", "swift_version": "nightly-main"}, ] enable_android_sdk_build: true @@ -58,7 +64,7 @@ jobs: build-abi-stable: name: Build ABI Stable - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.12 with: enable_linux_checks: false enable_macos_checks: true @@ -71,7 +77,7 @@ jobs: soundness: name: Soundness - uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10 + uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.12 with: license_header_check_project_name: "Swift.org" # https://github.com/apple/swift-system/issues/224 From d7ca4a9e4c1a93f214e529369c319921874df1fd Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 26 Jun 2026 05:22:56 -0700 Subject: [PATCH 10/14] improve Errno handling for io_uring_enter2 --- Sources/System/IORing/IORing+Util.swift | 43 ++++++++++++++++++++++ Sources/System/IORing/IORing.swift | 48 +++++++++++-------------- 2 files changed, 63 insertions(+), 28 deletions(-) create mode 100644 Sources/System/IORing/IORing+Util.swift diff --git a/Sources/System/IORing/IORing+Util.swift b/Sources/System/IORing/IORing+Util.swift new file mode 100644 index 0000000..7e78e86 --- /dev/null +++ b/Sources/System/IORing/IORing+Util.swift @@ -0,0 +1,43 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2026 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +#if compiler(>=6.2) && $Lifetimes +#if os(Linux) + +import CSystem +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif + +/// Throwing wrapper around the `io_uring_enter2` shim. +/// +/// On success returns the syscall's non-negative result (the number of SQEs +/// consumed by the kernel). On failure, reads `errno` and throws the matching +/// `Errno`. `EINTR` is retried automatically. +@usableFromInline +internal func _ioUringEnter2( + ringDescriptor: Int32, + toSubmit: UInt32, + minComplete: UInt32, + flags: UInt32, + args: UnsafeMutablePointer?, + argsSize: Int +) throws(Errno) -> Int32 { + let result = valueOrErrno(retryOnInterrupt: true) { + io_uring_enter2( + ringDescriptor, toSubmit, minComplete, flags, args, argsSize + ) + } + return try result.get() +} + +#endif // os(Linux) +#endif // compiler(>=6.2) && $Lifetimes diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 0da0dea..3d07877 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -522,16 +522,18 @@ public struct IORing: ~Copyable { sz = MemoryLayout.size flags |= IORING_ENTER_EXT_ARG } - let res = io_uring_enter2( - ringDescriptor, - 0, - minimumCount, - flags, - extraArgs, - sz - ) + do { + _ = try _ioUringEnter2( + ringDescriptor: ringDescriptor, + toSubmit: 0, + minComplete: minimumCount, + flags: flags, + args: extraArgs, + argsSize: sz + ) + break // error handling: - // EAGAIN / EINTR (try again), + // EAGAIN (try again), // EBADF / EBADFD / EOPNOTSUPP / ENXIO // (failure in ring lifetime management, fatal), // EINVAL (bad constant flag?, fatal), @@ -540,29 +542,19 @@ public struct IORing: ~Copyable { // by kernel between kernelTail load and now) // ETIME (timeout from extraArgs.ts elapsed before // minimumCount completions arrived) - if res >= 0 { + } catch Errno.resourceBusy { break - } - let err: Errno - #if canImport(Glibc) - err = Errno(rawValue: Glibc.errno) - #elseif canImport(Musl) - err = Errno(rawValue: Musl.errno) - #endif - if err == .resourceBusy { - break - } - if err == .resourceTemporarilyUnavailable || err == .interrupted { + } catch Errno.resourceTemporarilyUnavailable { continue - } - if err == .timeout { - try consumer(nil, err, true) + } catch Errno.timeout { + try consumer(nil, .timeout, true) return + } catch { + fatalError( + "fatal error in receiving requests: " + + error.debugDescription + ) } - fatalError( - "fatal error in receiving requests: " - + err.debugDescription - ) } var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { From 124e17164ce28c477b1da29184b9fc775ae78966 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 26 Jun 2026 05:40:40 -0700 Subject: [PATCH 11/14] improve Errno handling for io_uring_enter --- Sources/System/IORing/IORing+Util.swift | 19 +++++++++++++++++ Sources/System/IORing/IORing.swift | 27 ++++++++++++++++--------- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/Sources/System/IORing/IORing+Util.swift b/Sources/System/IORing/IORing+Util.swift index 7e78e86..d667541 100644 --- a/Sources/System/IORing/IORing+Util.swift +++ b/Sources/System/IORing/IORing+Util.swift @@ -39,5 +39,24 @@ internal func _ioUringEnter2( return try result.get() } +/// Throwing wrapper around the `io_uring_enter` shim. +/// +/// On success returns the syscall's non-negative result (the number of SQEs +/// consumed by the kernel). On failure, reads `errno` and throws the matching +/// `Errno`. `EINTR` is retried automatically. +@usableFromInline +internal func _ioUringEnter( + ringDescriptor: Int32, + toSubmit: UInt32, + minComplete: UInt32, + flags: UInt32, + sig: UnsafeMutablePointer? +) throws(Errno) -> Int32 { + let result = valueOrErrno(retryOnInterrupt: true) { + io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig) + } + return try result.get() +} + #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 3d07877..88e52c3 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -128,23 +128,30 @@ internal func _enter( // Ring always needs enter right now; // TODO: support SQPOLL here while true { - let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil) + do { + let ret = try _ioUringEnter( + ringDescriptor: ringDescriptor, + toSubmit: numEvents, + minComplete: minCompletions, + flags: flags, + sig: nil + ) + if _getSubmissionQueueCount(ring: ring) > 0 { + // See https://github.com/axboe/liburing/issues/309, + // in some cases not all pending requests are submitted + continue + } + return ret // error handling: - // EAGAIN / EINTR (try again), + // EAGAIN (try again), // EBADF / EBADFD / EOPNOTSUPP / ENXIO // (failure in ring lifetime management, fatal), // EINVAL (bad constant flag?, fatal), // EFAULT (bad address for argument from library, fatal) - if ret == -EAGAIN || ret == -EINTR { + } catch Errno.resourceTemporarilyUnavailable { //TODO: should we wait a bit on AGAIN? + //alternatively we could treat EAGAIN the same as EINTR in the wrapper continue - } else if ret < 0 { - throw(Errno(rawValue: -ret)) - } else if _getSubmissionQueueCount(ring: ring) > 0 { - // See https://github.com/axboe/liburing/issues/309, in some cases not all pending requests are submitted - continue - } else { - return ret } } } From 73da907161a4986c16d556997ba23249a2884cce Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 26 Jun 2026 05:50:55 -0700 Subject: [PATCH 12/14] improve Errno handling for io_uring_register --- Sources/System/IORing/IORing+Util.swift | 17 +++++ Sources/System/IORing/IORing.swift | 91 +++++++++---------------- 2 files changed, 50 insertions(+), 58 deletions(-) diff --git a/Sources/System/IORing/IORing+Util.swift b/Sources/System/IORing/IORing+Util.swift index d667541..be25886 100644 --- a/Sources/System/IORing/IORing+Util.swift +++ b/Sources/System/IORing/IORing+Util.swift @@ -58,5 +58,22 @@ internal func _ioUringEnter( return try result.get() } +/// Throwing wrapper around the `io_uring_register` shim. +/// +/// On success returns the syscall's non-negative result. On failure, reads +/// `errno` and throws the matching `Errno`. `EINTR` is retried automatically. +@usableFromInline +internal func _ioUringRegister( + ringDescriptor: Int32, + opcode: UInt32, + arg: UnsafeMutableRawPointer?, + nrArgs: UInt32 +) throws(Errno) -> Int32 { + let result = valueOrErrno(retryOnInterrupt: true) { + io_uring_register(ringDescriptor, opcode, arg, nrArgs) + } + return try result.get() +} + #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 88e52c3..94d1fd5 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -677,31 +677,22 @@ public struct IORing: ~Copyable { /// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information. public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) { var rawfd = descriptor.rawValue - let result = withUnsafePointer(to: &rawfd) { fdptr in - let result = io_uring_register( - ringDescriptor, - RegistrationOps.registerEventFD.rawValue, - UnsafeMutableRawPointer(mutating: fdptr), - 1 - ) - return result >= 0 ? nil : Errno(rawValue: -result) - } - if let result { - throw result - } + _ = try _ioUringRegister( + ringDescriptor: ringDescriptor, + opcode: RegistrationOps.registerEventFD.rawValue, + arg: &rawfd, + nrArgs: 1 + ) } /// Removes a registered event file descriptor from the ring public mutating func unregisterEventFD() throws(Errno) { - let result = io_uring_register( - ringDescriptor, - RegistrationOps.unregisterEventFD.rawValue, - nil, - 0 + _ = try _ioUringRegister( + ringDescriptor: ringDescriptor, + opcode: RegistrationOps.unregisterEventFD.rawValue, + arg: nil, + nrArgs: 0 ) - if result < 0 { - throw Errno(rawValue: -result) - } } /// Registers `count` files with the ring for later use in IO operations @@ -710,18 +701,13 @@ public struct IORing: ~Copyable { precondition(count < UInt32.max) let files = [UInt32](repeating: UInt32.max, count: count) - let regResult = files.withUnsafeBufferPointer { bPtr in - let result = io_uring_register( - self.ringDescriptor, - RegistrationOps.registerFiles.rawValue, - UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), - UInt32(truncatingIfNeeded: count) + try files.withUnsafeBufferPointer { bPtr throws(Errno) in + _ = try _ioUringRegister( + ringDescriptor: self.ringDescriptor, + opcode: RegistrationOps.registerFiles.rawValue, + arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress), + nrArgs: UInt32(truncatingIfNeeded: count) ) - return result >= 0 ? nil : Errno(rawValue: -result) - } - - if let regResult { - throw regResult } _registeredFiles = files @@ -730,15 +716,12 @@ public struct IORing: ~Copyable { /// Removes registered files from the ring public func unregisterFiles() throws { - let result = io_uring_register( - ringDescriptor, - RegistrationOps.unregisterFiles.rawValue, - nil, - 0 + _ = try _ioUringRegister( + ringDescriptor: ringDescriptor, + opcode: RegistrationOps.unregisterFiles.rawValue, + arg: nil, + nrArgs: 0 ) - if result < 0 { - throw Errno(rawValue: -result) - } } /// Allows access to registered files by index @@ -754,18 +737,13 @@ public struct IORing: ~Copyable { precondition(buffers.count < UInt32.max) precondition(_registeredBuffers.isEmpty) let iovecs = buffers.map { $0.to_iovec() } - let regResult = iovecs.withUnsafeBufferPointer { bPtr in - let result = io_uring_register( - self.ringDescriptor, - RegistrationOps.registerBuffers.rawValue, - UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), - UInt32(truncatingIfNeeded: buffers.count) + try iovecs.withUnsafeBufferPointer { bPtr throws(Errno) in + _ = try _ioUringRegister( + ringDescriptor: self.ringDescriptor, + opcode: RegistrationOps.registerBuffers.rawValue, + arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress), + nrArgs: UInt32(truncatingIfNeeded: buffers.count) ) - return result >= 0 ? nil : Errno(rawValue: -result) - } - - if let regResult { - throw regResult } _registeredBuffers = iovecs @@ -804,15 +782,12 @@ public struct IORing: ~Copyable { } public func unregisterBuffers() throws { - let result = io_uring_register( - self.ringDescriptor, - RegistrationOps.unregisterBuffers.rawValue, - nil, - 0 + _ = try _ioUringRegister( + ringDescriptor: self.ringDescriptor, + opcode: RegistrationOps.unregisterBuffers.rawValue, + arg: nil, + nrArgs: 0 ) - guard result >= 0 else { - throw Errno(rawValue: -result) - } } /// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring. From efc401eb32b1f73dfee51b0036b2fea7f7fd6a29 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 6 Jul 2026 14:06:30 -0700 Subject: [PATCH 13/14] Add testing of throwing behaviour --- Tests/SystemTests/IORingTests.swift | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index ee1f4ab..97bf86c 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -283,6 +283,33 @@ final class IORingTests: XCTestCase { XCTAssertEqual(thrown, .timeout) XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(50)) } + + func testRegisterEventFDTwiceThrows() throws { + guard uringEnabled else { return } + var ring = try IORing(queueDepth: 4) + let efd = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE))) + defer { try? efd.close() } + + try ring.registerEventFD(efd) + do throws(Errno) { + try ring.registerEventFD(efd) // second registration -> EBUSY + XCTFail("expected second registerEventFD to throw") + } catch { + XCTAssertEqual(error, .resourceBusy) + } + } + + func testSubmitOnDisabledRingThrows() throws { + guard uringEnabled else { return } + var ring = try IORing(queueDepth: 4, flags: [.startDisabled]) + + do throws(Errno) { + _ = try ring.submit(linkedRequests: .nop()) + XCTFail("expected submit on a disabled ring to throw") + } catch { + XCTAssertEqual(error, Errno(rawValue: EBADFD)) + } + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From 41de235573ac1a32d4d9e165f963d64fafd6d6a8 Mon Sep 17 00:00:00 2001 From: Minh Vu Date: Tue, 7 Jul 2026 18:34:42 +0200 Subject: [PATCH 14/14] Add missing System CMake sources (#325) --- Sources/System/CMakeLists.txt | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 1f3420a..cb4f8d0 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -9,6 +9,7 @@ See https://swift.org/LICENSE.txt for license information add_library(SystemPackage Errno.swift + ErrnoWindows.swift FileDescriptor.swift FileHelpers.swift FileOperations.swift @@ -18,9 +19,12 @@ add_library(SystemPackage SystemString.swift Util.swift Util+StringArray.swift - UtilConsumers.swift) + UtilConsumers.swift + WinSDK+Overlay.swift) set_target_properties(SystemPackage PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) +target_compile_options(SystemPackage PRIVATE + -enable-experimental-feature Lifetimes) target_sources(SystemPackage PRIVATE FilePath/FilePath.swift FilePath/FilePathComponents.swift @@ -28,7 +32,23 @@ target_sources(SystemPackage PRIVATE FilePath/FilePathParsing.swift FilePath/FilePathString.swift FilePath/FilePathSyntax.swift + FilePath/FilePathTemp.swift + FilePath/FilePathTempPosix.swift + FilePath/FilePathTempWindows.swift FilePath/FilePathWindows.swift) +target_sources(SystemPackage PRIVATE + FileSystem/FileFlags.swift + FileSystem/FileMode.swift + FileSystem/FileType.swift + FileSystem/Identifiers.swift + FileSystem/Stat.swift) +if(CMAKE_SYSTEM_NAME STREQUAL Linux) + target_sources(SystemPackage PRIVATE + IORing/IOCompletion.swift + IORing/IORequest.swift + IORing/IORing.swift + IORing/RawIORequest.swift) +endif() target_sources(SystemPackage PRIVATE Internals/Backcompat.swift Internals/CInterop.swift