From e65f5a6cadcd6b025855f32e8e9d9f0675c29591 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 3 Dec 2025 16:45:46 -0800 Subject: [PATCH 01/28] dup3 wrapper proposal Improve a sentence. --- Proposals/0007-FileDescriptor-dup3-pipe2.md | 175 ++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 Proposals/0007-FileDescriptor-dup3-pipe2.md diff --git a/Proposals/0007-FileDescriptor-dup3-pipe2.md b/Proposals/0007-FileDescriptor-dup3-pipe2.md new file mode 100644 index 0000000..269231a --- /dev/null +++ b/Proposals/0007-FileDescriptor-dup3-pipe2.md @@ -0,0 +1,175 @@ +# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor` + +* Proposal: SYS-0007 +- Author(s): Jake Petroules , Guillaume Lessard + +* Other Reviews: [Swift Forums Pitch](https://forums.swift.org/t/82486) + +##### Revision history + +* **v1** Initial version + +## Introduction + +Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively. + +This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD and Android. + +## Motivation + +It is considered best practice to set the `O_CLOEXEC` (close-on-exec) bit on newly created file descriptors to prevent them from being inherited by subprocesses. + +Some POSIX functions such as `open` provide a "flags" parameter allowing this the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`. + +POSIX 2024 corrects this deficiency for `dup2` and `pipe` by introducing `dup3` and `pipe2` variants that allow the close-on-exec bit to be set atomically. + +While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defence in depth with respect to opened file descriptors. + +## Proposed solution + +This proposal adds new overloads to `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` that will wrap the functionality of the `dup3` and `pipe2` functions. + +## Example usage + +```swift +import System + +let fd0 = try FileDescriptor.open("/tmp/test.txt", .readOnly) +let fd1 = FileDescriptor(rawValue: 731) +let fd2 = fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec]) +``` + +## Detailed design + +`FileDescriptor` will add the following overloads and types: + +```swift +struct FileDescriptor { + /// Creates a unidirectional data channel, which can be used for + /// interprocess communication. + /// + /// - Parameters: + /// - options: The behavior for creating the pipe. + /// + /// - Returns: The pair of file descriptors. + /// + /// The corresponding C function is `pipe2`. + public static func pipe( + options: PipeOptions + ) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) + + /// Duplicates this file descriptor and return the newly created copy. + /// + /// - Parameters: + /// - `target`: The desired target file descriptor. + /// - `options`: The behavior for creating the target file descriptor. + /// - retryOnInterrupt: Whether to retry the write operation + /// if it throws ``Errno/interrupted``. The default is `true`. + /// Pass `false` to try only once and throw an error upon interruption. + /// - Returns: The new file descriptor. + /// + /// If the `target` descriptor is already in use, then it is first + /// deallocated as if a close(2) call had been done first. + /// + /// File descriptors are merely references to some underlying system resource. + /// The system does not distinguish between the original and the new file + /// descriptor in any way. For example, read, write and seek operations on + /// one of them also affect the logical file position in the other, and + /// append mode, non-blocking I/O and asynchronous I/O options are shared + /// between the references. If a separate pointer into the file is desired, + /// a different object reference to the file must be obtained by issuing an + /// additional call to `open`. + /// + /// However, each file descriptor maintains its own close-on-exec flag. + /// + /// The corresponding C function is `dup3`. + @discardableResult + public func duplicate( + as target: FileDescriptor, + options: DuplicateOptions, + retryOnInterrupt: Bool = true + ) throws(Errno) -> FileDescriptor + + /// Options that specify behavior for a newly-created pipe. + public struct PipeOptions: OptionSet, Sendable, Hashable, Codable { + /// The raw C options. + public var rawValue: CInt + + /// Create a strongly-typed options value from raw C options. + public init(rawValue: CInt) + + /// Indicates that all subsequent input and output operations + /// on the pipe's file descriptors will be nonblocking. + /// + /// The corresponding C constant is `O_NONBLOCK`. + public static var nonBlocking: OpenOptions + + /// Indicates that executing a program closes the file. + /// + /// Normally, file descriptors remain open across calls to the `exec(2)` + /// family of functions. If you specify this option, the file descriptor + /// is closed when replacing this process with another process. + /// + /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOEXEC`. + public static var closeOnExec: PipeOptions + + /// Indicates that forking a program closes the file. + /// + /// Normally, file descriptors remain open across calls to the `fork(2)` + /// function. If you specify this option, the file descriptor is closed + /// when forking this process into another process. + /// + /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOFORK`. + public static var closeOnFork: PipeOptions + } + + /// Options that specify behavior for a duplicated file descriptor. + public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable { + /// The raw C options. + public var rawValue: CInt + + /// Create a strongly-typed options value from raw C options. + public init(rawValue: CInt) + + /// Normally, file descriptors remain open across calls to the `exec(2)` + /// family of functions. If you specify this option, the file descriptor + /// is closed when replacing this process with another process. + /// + /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOEXEC`. + public static var closeOnExec: DuplicateOptions + + /// Indicates that forking a program closes the file. + /// + /// Normally, file descriptors remain open across calls to the `fork(2)` + /// function. If you specify this option, the file descriptor is closed + /// when forking this process into another process. + /// + /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOFORK`. + public static var closeOnFork: DuplicateOptions + } +} +``` + +These API additions are unavailable on Windows and Darwin, as the underlying `dup3` and `pipe2` APIs do not exist. + +`closeOnFork` is unavailable on Linux and Android, as the underlying `O_CLOFORK` constant does not exist. + +## Impact on existing code + +This change will have no impact on existing code, as it is purely additive. + +## Alternatives considered + +None. The underlying POSIX API are additions that help C developers follow best practices, and these overloads provide the same value to Swift developers. From 097805e8695f04a70198e74bb7be5a89f9fcc31c Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 6 Jan 2026 16:57:33 -0800 Subject: [PATCH 02/28] require Swift 6.1 - and exclude 6.0 toolchains from executing in CI --- .github/workflows/pull_request.yml | 4 +++- Package.swift | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index e706a36..e83adc5 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -19,6 +19,7 @@ jobs: [ {"swift_version": "5.9"}, {"swift_version": "5.10"}, + {"swift_version": "6.0"}, {"os_version": "focal", "swift_version": "nightly-6.2"}, {"os_version": "focal", "swift_version": "6.2"}, {"os_version": "focal", "swift_version": "nightly-6.3"}, @@ -31,7 +32,8 @@ jobs: windows_exclude_swift_versions: | [ {"swift_version": "5.9"}, - {"swift_version": "5.10"} + {"swift_version": "5.10"}, + {"swift_version": "6.0"}, ] enable_linux_static_sdk_build: true linux_static_sdk_exclude_swift_versions: | diff --git a/Package.swift b/Package.swift index c7621c0..b624a59 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.0 +// swift-tools-version:6.1 //===----------------------------------------------------------------------===// // // This source file is part of the Swift System open source project @@ -142,5 +142,5 @@ let package = Package( cSettings: cSettings, swiftSettings: swiftSettings), ], - swiftLanguageVersions: [.v5] + swiftLanguageModes: [.v5] ) From 4d2c21f6b36daf7e53947e8250213d5a127497f3 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 19 May 2026 18:28:14 -0700 Subject: [PATCH 03/28] fix a few more inconsistencies --- Proposals/0007-FileDescriptor-dup3-pipe2.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Proposals/0007-FileDescriptor-dup3-pipe2.md b/Proposals/0007-FileDescriptor-dup3-pipe2.md index 269231a..9989ce6 100644 --- a/Proposals/0007-FileDescriptor-dup3-pipe2.md +++ b/Proposals/0007-FileDescriptor-dup3-pipe2.md @@ -58,12 +58,12 @@ struct FileDescriptor { options: PipeOptions ) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) - /// Duplicates this file descriptor and return the newly created copy. + /// Duplicate this file descriptor and return the newly created copy. /// /// - Parameters: - /// - `target`: The desired target file descriptor. - /// - `options`: The behavior for creating the target file descriptor. - /// - retryOnInterrupt: Whether to retry the write operation + /// - target: The desired target file descriptor. + /// - options: The behavior for creating the target file descriptor. + /// - retryOnInterrupt: Whether to retry the operation /// if it throws ``Errno/interrupted``. The default is `true`. /// Pass `false` to try only once and throw an error upon interruption. /// - Returns: The new file descriptor. @@ -80,7 +80,8 @@ struct FileDescriptor { /// a different object reference to the file must be obtained by issuing an /// additional call to `open`. /// - /// However, each file descriptor maintains its own close-on-exec flag. + /// However, each file descriptor maintains its own close-on-exec and + /// close-on-fork flags. /// /// The corresponding C function is `dup3`. @discardableResult @@ -102,7 +103,7 @@ struct FileDescriptor { /// on the pipe's file descriptors will be nonblocking. /// /// The corresponding C constant is `O_NONBLOCK`. - public static var nonBlocking: OpenOptions + public static var nonBlocking: PipeOptions /// Indicates that executing a program closes the file. /// @@ -137,6 +138,8 @@ struct FileDescriptor { /// Create a strongly-typed options value from raw C options. public init(rawValue: CInt) + /// Indicates that executing a program closes the file. + /// /// Normally, file descriptors remain open across calls to the `exec(2)` /// family of functions. If you specify this option, the file descriptor /// is closed when replacing this process with another process. From 0323dff7db7ef4b83d0bcbb002e471a36996ba02 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 19 May 2026 18:40:04 -0700 Subject: [PATCH 04/28] Rephrase using active voice --- Proposals/0007-FileDescriptor-dup3-pipe2.md | 24 ++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Proposals/0007-FileDescriptor-dup3-pipe2.md b/Proposals/0007-FileDescriptor-dup3-pipe2.md index 9989ce6..5e159de 100644 --- a/Proposals/0007-FileDescriptor-dup3-pipe2.md +++ b/Proposals/0007-FileDescriptor-dup3-pipe2.md @@ -108,10 +108,10 @@ struct FileDescriptor { /// Indicates that executing a program closes the file. /// /// Normally, file descriptors remain open across calls to the `exec(2)` - /// family of functions. If you specify this option, the file descriptor - /// is closed when replacing this process with another process. + /// family of functions. If you specify this option, the system closes the + /// file descriptor when replacing this process with another process. /// - /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOEXEC`. @@ -120,10 +120,10 @@ struct FileDescriptor { /// Indicates that forking a program closes the file. /// /// Normally, file descriptors remain open across calls to the `fork(2)` - /// function. If you specify this option, the file descriptor is closed - /// when forking this process into another process. + /// function. If you specify this option, the system closes the file + /// descriptor when forking this process into another process. /// - /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOFORK`. @@ -141,10 +141,10 @@ struct FileDescriptor { /// Indicates that executing a program closes the file. /// /// Normally, file descriptors remain open across calls to the `exec(2)` - /// family of functions. If you specify this option, the file descriptor - /// is closed when replacing this process with another process. + /// family of functions. If you specify this option, the system closes the + /// file descriptor when replacing this process with another process. /// - /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOEXEC`. @@ -153,10 +153,10 @@ struct FileDescriptor { /// Indicates that forking a program closes the file. /// /// Normally, file descriptors remain open across calls to the `fork(2)` - /// function. If you specify this option, the file descriptor is closed - /// when forking this process into another process. + /// function. If you specify this option, the system closes the file + /// descriptor when forking this process into another process. /// - /// The state of the file descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOFORK`. From 348b497836426600ca6a81c971c05f0cf178a98b Mon Sep 17 00:00:00 2001 From: Jake Petroules Date: Thu, 2 Oct 2025 11:04:19 -0700 Subject: [PATCH 05/28] Add overloads to cover dup3 and pipe2 POSIX APIs This follows the existing pattern of wrapping dup/dup2 and pipe with FileDescriptor.duplicate and FileDescriptor.pipe, with additional overloads for passing the O_CLOEXEC and similar flags. --- Sources/CSystem/CMakeLists.txt | 1 + Sources/CSystem/include/CSystemShared.h | 2 + Sources/CSystem/include/module.modulemap | 1 + Sources/CSystem/shims.c | 32 +++++- Sources/System/FileDescriptor.swift | 135 +++++++++++++++++++++++ Sources/System/FileOperations.swift | 88 ++++++++++++++- Sources/System/Internals/Constants.swift | 9 ++ Sources/System/Internals/Syscalls.swift | 17 ++- 8 files changed, 277 insertions(+), 8 deletions(-) create mode 100644 Sources/CSystem/include/CSystemShared.h diff --git a/Sources/CSystem/CMakeLists.txt b/Sources/CSystem/CMakeLists.txt index faf730e..36656ae 100644 --- a/Sources/CSystem/CMakeLists.txt +++ b/Sources/CSystem/CMakeLists.txt @@ -14,6 +14,7 @@ target_include_directories(CSystem INTERFACE install(FILES include/CSystemLinux.h + include/CSystemShared.h include/CSystemWindows.h include/module.modulemap DESTINATION include/CSystem) diff --git a/Sources/CSystem/include/CSystemShared.h b/Sources/CSystem/include/CSystemShared.h new file mode 100644 index 0000000..edcb5cc --- /dev/null +++ b/Sources/CSystem/include/CSystemShared.h @@ -0,0 +1,2 @@ +extern int csystem_posix_pipe2(int fildes[2], int flag); +extern int csystem_posix_dup3(int fildes, int fildes2, int flag); diff --git a/Sources/CSystem/include/module.modulemap b/Sources/CSystem/include/module.modulemap index 6e8b89e..73b1004 100644 --- a/Sources/CSystem/include/module.modulemap +++ b/Sources/CSystem/include/module.modulemap @@ -1,4 +1,5 @@ module CSystem { + header "CSystemShared.h" header "CSystemLinux.h" header "CSystemWASI.h" header "CSystemWindows.h" diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index f492a2a..69e994e 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -7,12 +7,40 @@ See https://swift.org/LICENSE.txt for license information */ +#if defined(__FreeBSD__) || defined(__OpenBSD__) +#define __BSD_VISIBLE +#include +#endif + #ifdef __linux__ - +#define _GNU_SOURCE #include - #endif #if defined(_WIN32) #include #endif + +#include + +#if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__) +#define HAVE_PIPE2_DUP3 +#endif + +// Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h +extern int csystem_posix_pipe2(int fildes[2], int flag) { + #ifdef HAVE_PIPE2_DUP3 + return pipe2(fildes, flag); + #else + errno = ENOSYS; + return -1; + #endif +} +extern int csystem_posix_dup3(int fildes, int fildes2, int flag) { + #ifdef HAVE_PIPE2_DUP3 + return dup3(fildes, fildes2, flag); + #else + errno = ENOSYS; + return -1; + #endif +} diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index d5f5883..86d8fc6 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -324,6 +324,141 @@ extension FileDescriptor { #endif } + /// Options that specify behavior for a newly-created pipe. + @frozen + @available(Windows, unavailable) + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + public struct PipeOptions: OptionSet, Sendable, Hashable, Codable { + /// The raw C options. + @_alwaysEmitIntoClient + public var rawValue: CInt + + /// Create a strongly-typed options value from raw C options. + @_alwaysEmitIntoClient + public init(rawValue: CInt) { self.rawValue = rawValue } + +#if !os(Windows) + /// Indicates that all + /// subsequent input and output operations on the pipe's file descriptors will be nonblocking. + /// + /// The corresponding C constant is `O_NONBLOCK`. + @_alwaysEmitIntoClient + public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "nonBlocking") + public static var O_NONBLOCK: OpenOptions { nonBlocking } + + /// Indicates that executing a program closes the file. + /// + /// Normally, file descriptors remain open + /// across calls to the `exec(2)` family of functions. + /// If you specify this option, + /// the file descriptor is closed when replacing this process + /// with another process. + /// + /// The state of the file + /// descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOEXEC`. + @_alwaysEmitIntoClient + public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnExec") + public static var O_CLOEXEC: OpenOptions { closeOnExec } + +#if !os(WASI) && !os(Linux) && !os(Android) + /// Indicates that forking a program closes the file. + /// + /// Normally, file descriptors remain open + /// across calls to the `fork(2)` function. + /// If you specify this option, + /// the file descriptor is closed when forking this process + /// into another process. + /// + /// The state of the file + /// descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOFORK`. + @_alwaysEmitIntoClient + public static var closeOnFork: OpenOptions { .init(rawValue: _O_CLOFORK) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnFork") + public static var O_CLOFORK: OpenOptions { closeOnFork } +#endif +#endif + } + + /// Options that specify behavior for a duplicated file descriptor. + @frozen + @available(Windows, unavailable) + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable { + /// The raw C options. + @_alwaysEmitIntoClient + public var rawValue: CInt + + /// Create a strongly-typed options value from raw C options. + @_alwaysEmitIntoClient + public init(rawValue: CInt) { self.rawValue = rawValue } + +#if !os(Windows) + /// Indicates that executing a program closes the file. + /// + /// Normally, file descriptors remain open + /// across calls to the `exec(2)` family of functions. + /// If you specify this option, + /// the file descriptor is closed when replacing this process + /// with another process. + /// + /// The state of the file + /// descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOEXEC`. + @_alwaysEmitIntoClient + public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnExec") + public static var O_CLOEXEC: OpenOptions { closeOnExec } + +#if !os(WASI) && !os(Linux) && !os(Android) + /// Indicates that forking a program closes the file. + /// + /// Normally, file descriptors remain open + /// across calls to the `fork(2)` function. + /// If you specify this option, + /// the file descriptor is closed when forking this process + /// into another process. + /// + /// The state of the file + /// descriptor flags can be inspected using `F_GETFD`, + /// as described in the `fcntl(2)` man page. + /// + /// The corresponding C constant is `O_CLOFORK`. + @_alwaysEmitIntoClient + public static var closeOnFork: OpenOptions { .init(rawValue: _O_CLOFORK) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnFork") + public static var O_CLOFORK: OpenOptions { closeOnFork } +#endif +#endif + } + /// Options for specifying what a file descriptor's offset is relative to. @frozen @available(System 0.0.1, *) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index 9ddc16c..df1f353 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -403,17 +403,62 @@ extension FileDescriptor { as target: FileDescriptor? = nil, retryOnInterrupt: Bool = true ) throws -> FileDescriptor { - try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get() + try _duplicate(as: target, options: 0, retryOnInterrupt: retryOnInterrupt).get() + } + + /// Duplicates this file descriptor and return the newly created copy. + /// + /// - Parameters: + /// - `target`: The desired target file descriptor. + /// - `options`: The behavior for creating the target file descriptor. + /// - retryOnInterrupt: Whether to retry the write operation + /// if it throws ``Errno/interrupted``. The default is `true`. + /// Pass `false` to try only once and throw an error upon interruption. + /// - Returns: The new file descriptor. + /// + /// If the `target` descriptor is already in use, then it is first + /// deallocated as if a close(2) call had been done first. + /// + /// File descriptors are merely references to some underlying system resource. + /// The system does not distinguish between the original and the new file + /// descriptor in any way. For example, read, write and seek operations on + /// one of them also affect the logical file position in the other, and + /// append mode, non-blocking I/O and asynchronous I/O options are shared + /// between the references. If a separate pointer into the file is desired, + /// a different object reference to the file must be obtained by issuing an + /// additional call to `open`. + /// + /// However, each file descriptor maintains its own close-on-exec flag. + /// + /// + /// The corresponding C function is `dup3`. + @_alwaysEmitIntoClient + @available(Windows, unavailable) + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + public func duplicate( + as target: FileDescriptor, + options: DuplicateOptions, + retryOnInterrupt: Bool = true + ) throws -> FileDescriptor { + try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get() } @available(System 0.0.2, *) @usableFromInline internal func _duplicate( as target: FileDescriptor?, + options: Int32, retryOnInterrupt: Bool ) throws -> Result { valueOrErrno(retryOnInterrupt: retryOnInterrupt) { if let target = target { + if options != 0 { + return system_dup3(self.rawValue, target.rawValue, options) + } return system_dup2(self.rawValue, target.rawValue) } return system_dup(self.rawValue) @@ -431,6 +476,12 @@ extension FileDescriptor { public func dup2() throws -> FileDescriptor { fatalError("Not implemented") } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "duplicate") + public func dup3() throws -> FileDescriptor { + fatalError("Not implemented") + } } #endif @@ -445,21 +496,48 @@ extension FileDescriptor { @_alwaysEmitIntoClient @available(System 1.1.0, *) public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { - try _pipe().get() + try _pipe(options: 0).get() + } + + /// Creates a unidirectional data channel, which can be used for interprocess communication. + /// + /// - Parameters: + /// - options: The behavior for creating the pipe. + /// + /// - Returns: The pair of file descriptors. + /// + /// The corresponding C function is `pipe2`. + @_alwaysEmitIntoClient + @available(Windows, unavailable) + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + public static func pipe(options: PipeOptions) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { + try _pipe(options: options.rawValue).get() } - @available(System 1.1.0, *) @usableFromInline - internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { + internal static func _pipe(options: Int32) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { var fds: (Int32, Int32) = (-1, -1) return withUnsafeMutablePointer(to: &fds) { pointer in pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in valueOrErrno(retryOnInterrupt: false) { - system_pipe(fds) + if options != 0 { + return system_pipe2(fds, options) + } + return system_pipe(fds) }.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) } } } } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "pipe") + public func pipe2() throws -> FileDescriptor { + fatalError("Not implemented") + } } #endif diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index b026c97..607b2e6 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -622,6 +622,15 @@ internal var _O_SYMLINK: CInt { O_SYMLINK } #if !os(Windows) @_alwaysEmitIntoClient internal var _O_CLOEXEC: CInt { O_CLOEXEC } + +@_alwaysEmitIntoClient +internal var _O_CLOFORK: CInt { + #if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) + O_CLOFORK + #else + 0 + #endif +} #endif @_alwaysEmitIntoClient diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index f6eb533..2803424 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -14,7 +14,6 @@ import Glibc #elseif canImport(Musl) import Musl #elseif canImport(WASILibc) -import CSystem import WASILibc #elseif os(Windows) import ucrt @@ -24,6 +23,8 @@ import Android #error("Unsupported Platform") #endif +import CSystem + // Interacting with the mocking system, tracing, etc., is a potentially significant // amount of code size, so we hand outline that code for every syscall @@ -139,6 +140,13 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 { #endif return dup2(fd, fd2) } + +internal func system_dup3(_ fd: Int32, _ fd2: Int32, _ oflag: Int32) -> Int32 { + #if ENABLE_MOCKING + if mockingEnabled { return _mock(fd, fd2, oflag) } + #endif + return csystem_posix_dup3(fd, fd2, oflag) +} #endif #if !os(WASI) @@ -148,6 +156,13 @@ internal func system_pipe(_ fds: UnsafeMutablePointer) -> CInt { #endif return pipe(fds) } + +internal func system_pipe2(_ fds: UnsafeMutablePointer, _ oflag: Int32) -> CInt { +#if ENABLE_MOCKING + if mockingEnabled { return _mock(fds, oflag) } +#endif + return csystem_posix_pipe2(fds, oflag) +} #endif internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { From cc4afd1a71dfdc09a20c0781894bb6e11aa4bff9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 19 May 2026 19:13:45 -0700 Subject: [PATCH 06/28] Fix types of new static members of option sets --- Sources/System/FileDescriptor.swift | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 86d8fc6..6f21317 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -347,11 +347,11 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_NONBLOCK`. @_alwaysEmitIntoClient - public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) } + public static var nonBlocking: PipeOptions { .init(rawValue: _O_NONBLOCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "nonBlocking") - public static var O_NONBLOCK: OpenOptions { nonBlocking } + public static var O_NONBLOCK: PipeOptions { nonBlocking } /// Indicates that executing a program closes the file. /// @@ -367,11 +367,11 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_CLOEXEC`. @_alwaysEmitIntoClient - public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) } + public static var closeOnExec: PipeOptions { .init(rawValue: _O_CLOEXEC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnExec") - public static var O_CLOEXEC: OpenOptions { closeOnExec } + public static var O_CLOEXEC: PipeOptions { closeOnExec } #if !os(WASI) && !os(Linux) && !os(Android) /// Indicates that forking a program closes the file. @@ -388,11 +388,11 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_CLOFORK`. @_alwaysEmitIntoClient - public static var closeOnFork: OpenOptions { .init(rawValue: _O_CLOFORK) } + public static var closeOnFork: PipeOptions { .init(rawValue: _O_CLOFORK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnFork") - public static var O_CLOFORK: OpenOptions { closeOnFork } + public static var O_CLOFORK: PipeOptions { closeOnFork } #endif #endif } @@ -429,11 +429,11 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_CLOEXEC`. @_alwaysEmitIntoClient - public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) } + public static var closeOnExec: DuplicateOptions { .init(rawValue: _O_CLOEXEC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnExec") - public static var O_CLOEXEC: OpenOptions { closeOnExec } + public static var O_CLOEXEC: DuplicateOptions { closeOnExec } #if !os(WASI) && !os(Linux) && !os(Android) /// Indicates that forking a program closes the file. @@ -450,11 +450,11 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_CLOFORK`. @_alwaysEmitIntoClient - public static var closeOnFork: OpenOptions { .init(rawValue: _O_CLOFORK) } + public static var closeOnFork: DuplicateOptions { .init(rawValue: _O_CLOFORK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnFork") - public static var O_CLOFORK: OpenOptions { closeOnFork } + public static var O_CLOFORK: DuplicateOptions { closeOnFork } #endif #endif } From 61280ab3656a5c21ee7ae643a924e591d0a34278 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 19 May 2026 19:16:35 -0700 Subject: [PATCH 07/28] Fix declaration inconsistencies --- Sources/System/FileOperations.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index df1f353..c52c4d3 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -432,6 +432,7 @@ extension FileDescriptor { /// /// /// The corresponding C function is `dup3`. + @discardableResult @_alwaysEmitIntoClient @available(Windows, unavailable) @available(macOS, unavailable) @@ -443,7 +444,7 @@ extension FileDescriptor { as target: FileDescriptor, options: DuplicateOptions, retryOnInterrupt: Bool = true - ) throws -> FileDescriptor { + ) throws(Errno) -> FileDescriptor { try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get() } @@ -514,7 +515,7 @@ extension FileDescriptor { @available(tvOS, unavailable) @available(watchOS, unavailable) @available(visionOS, unavailable) - public static func pipe(options: PipeOptions) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { + public static func pipe(options: PipeOptions) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { try _pipe(options: options.rawValue).get() } @@ -535,7 +536,7 @@ extension FileDescriptor { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "pipe") - public func pipe2() throws -> FileDescriptor { + public static func pipe2() throws -> FileDescriptor { fatalError("Not implemented") } } From 814d09c7ea874badbe57236d2441e200e76f0557 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 19 May 2026 19:17:40 -0700 Subject: [PATCH 08/28] Improve doc-comments --- Sources/System/FileDescriptor.swift | 44 +++++++++++------------------ Sources/System/FileOperations.swift | 15 +++++----- 2 files changed, 25 insertions(+), 34 deletions(-) diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 6f21317..5ebf9b1 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -306,12 +306,10 @@ extension FileDescriptor { /// /// Normally, file descriptors remain open /// across calls to the `exec(2)` family of functions. - /// If you specify this option, - /// the file descriptor is closed when replacing this process - /// with another process. + /// If you specify this option, the system closes the file + /// descriptor when replacing this process with another process. /// - /// The state of the file - /// descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOEXEC`. @@ -342,8 +340,8 @@ extension FileDescriptor { public init(rawValue: CInt) { self.rawValue = rawValue } #if !os(Windows) - /// Indicates that all - /// subsequent input and output operations on the pipe's file descriptors will be nonblocking. + /// Indicates that all subsequent input and output operations + /// on the pipe's file descriptors will be nonblocking. /// /// The corresponding C constant is `O_NONBLOCK`. @_alwaysEmitIntoClient @@ -357,12 +355,10 @@ extension FileDescriptor { /// /// Normally, file descriptors remain open /// across calls to the `exec(2)` family of functions. - /// If you specify this option, - /// the file descriptor is closed when replacing this process - /// with another process. + /// If you specify this option, the system closes the file + /// descriptor when replacing this process with another process. /// - /// The state of the file - /// descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOEXEC`. @@ -378,12 +374,10 @@ extension FileDescriptor { /// /// Normally, file descriptors remain open /// across calls to the `fork(2)` function. - /// If you specify this option, - /// the file descriptor is closed when forking this process - /// into another process. + /// If you specify this option, the system closes the file + /// descriptor when forking this process into another process. /// - /// The state of the file - /// descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOFORK`. @@ -419,12 +413,10 @@ extension FileDescriptor { /// /// Normally, file descriptors remain open /// across calls to the `exec(2)` family of functions. - /// If you specify this option, - /// the file descriptor is closed when replacing this process - /// with another process. + /// If you specify this option, the system closes the file + /// descriptor when replacing this process with another process. /// - /// The state of the file - /// descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOEXEC`. @@ -440,12 +432,10 @@ extension FileDescriptor { /// /// Normally, file descriptors remain open /// across calls to the `fork(2)` function. - /// If you specify this option, - /// the file descriptor is closed when forking this process - /// into another process. + /// If you specify this option, the system closes the file + /// descriptor when forking this process into another process. /// - /// The state of the file - /// descriptor flags can be inspected using `F_GETFD`, + /// You can inspect the file descriptor flag state using `F_GETFD`, /// as described in the `fcntl(2)` man page. /// /// The corresponding C constant is `O_CLOFORK`. diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index c52c4d3..fb32e3d 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -406,12 +406,12 @@ extension FileDescriptor { try _duplicate(as: target, options: 0, retryOnInterrupt: retryOnInterrupt).get() } - /// Duplicates this file descriptor and return the newly created copy. + /// Duplicate this file descriptor and return the newly created copy. /// /// - Parameters: - /// - `target`: The desired target file descriptor. - /// - `options`: The behavior for creating the target file descriptor. - /// - retryOnInterrupt: Whether to retry the write operation + /// - target: The desired target file descriptor. + /// - options: The behavior for creating the target file descriptor. + /// - retryOnInterrupt: Whether to retry the operation /// if it throws ``Errno/interrupted``. The default is `true`. /// Pass `false` to try only once and throw an error upon interruption. /// - Returns: The new file descriptor. @@ -428,8 +428,8 @@ extension FileDescriptor { /// a different object reference to the file must be obtained by issuing an /// additional call to `open`. /// - /// However, each file descriptor maintains its own close-on-exec flag. - /// + /// However, each file descriptor maintains its own close-on-exec and + /// close-on-fork flags. /// /// The corresponding C function is `dup3`. @discardableResult @@ -500,7 +500,8 @@ extension FileDescriptor { try _pipe(options: 0).get() } - /// Creates a unidirectional data channel, which can be used for interprocess communication. + /// Creates a unidirectional data channel, which can be used for + /// interprocess communication. /// /// - Parameters: /// - options: The behavior for creating the pipe. From 491b97c7c0c22a92bed0b1af2ba4dbfcc438b0cb Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 20 May 2026 09:58:40 -0700 Subject: [PATCH 09/28] Complete implementation of SYS-0007 --- Sources/System/FileDescriptor.swift | 2 +- Sources/System/FileOperations.swift | 73 +++++++++++++++++++++-------- 2 files changed, 55 insertions(+), 20 deletions(-) diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 5ebf9b1..86f36bb 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 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 diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index fb32e3d..f69374f 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 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 @@ -395,7 +395,6 @@ extension FileDescriptor { /// /// However, each file descriptor maintains its own close-on-exec flag. /// - /// /// The corresponding C functions are `dup` and `dup2`. @_alwaysEmitIntoClient @available(System 0.0.2, *) @@ -403,7 +402,7 @@ extension FileDescriptor { as target: FileDescriptor? = nil, retryOnInterrupt: Bool = true ) throws -> FileDescriptor { - try _duplicate(as: target, options: 0, retryOnInterrupt: retryOnInterrupt).get() + try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get() } /// Duplicate this file descriptor and return the newly created copy. @@ -452,17 +451,31 @@ extension FileDescriptor { @usableFromInline internal func _duplicate( as target: FileDescriptor?, + retryOnInterrupt: Bool + ) -> Result { + valueOrErrno(retryOnInterrupt: retryOnInterrupt) { + if let target { + system_dup2(self.rawValue, target.rawValue) + } else { + system_dup(self.rawValue) + } + }.map(FileDescriptor.init(rawValue:)) + } + + @available(Windows, unavailable) + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + @usableFromInline + internal func _duplicate( + as target: FileDescriptor, options: Int32, retryOnInterrupt: Bool - ) throws -> Result { + ) -> Result { valueOrErrno(retryOnInterrupt: retryOnInterrupt) { - if let target = target { - if options != 0 { - return system_dup3(self.rawValue, target.rawValue, options) - } - return system_dup2(self.rawValue, target.rawValue) - } - return system_dup(self.rawValue) + system_dup3(self.rawValue, target.rawValue, options) }.map(FileDescriptor.init(rawValue:)) } @@ -496,8 +509,9 @@ extension FileDescriptor { /// The corresponding C function is `pipe`. @_alwaysEmitIntoClient @available(System 1.1.0, *) - public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { - try _pipe(options: 0).get() + public static func pipe( + ) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { + try _pipe().get() } /// Creates a unidirectional data channel, which can be used for @@ -516,20 +530,41 @@ extension FileDescriptor { @available(tvOS, unavailable) @available(watchOS, unavailable) @available(visionOS, unavailable) - public static func pipe(options: PipeOptions) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { + public static func pipe( + options: PipeOptions + ) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { try _pipe(options: options.rawValue).get() } + @available(System 1.1.0, *) @usableFromInline - internal static func _pipe(options: Int32) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { + internal static func _pipe( + ) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { var fds: (Int32, Int32) = (-1, -1) return withUnsafeMutablePointer(to: &fds) { pointer in pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in valueOrErrno(retryOnInterrupt: false) { - if options != 0 { - return system_pipe2(fds, options) - } - return system_pipe(fds) + system_pipe(fds) + }.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) } + } + } + } + + @available(Windows, unavailable) + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + @usableFromInline + internal static func _pipe( + options: Int32, + ) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { + var fds: (Int32, Int32) = (-1, -1) + return withUnsafeMutablePointer(to: &fds) { pointer in + pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in + valueOrErrno(retryOnInterrupt: false) { + system_pipe2(fds, options) }.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) } } } From de8779fb3d36a772a28d27ae1ec4e360ced5e82a Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 26 May 2026 16:19:09 -0700 Subject: [PATCH 10/28] Update copyright headers --- Sources/CSystem/CMakeLists.txt | 2 +- Sources/CSystem/include/CSystemShared.h | 9 +++++++++ Sources/CSystem/shims.c | 2 +- Sources/System/Internals/Constants.swift | 2 +- Sources/System/Internals/Syscalls.swift | 2 +- 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Sources/CSystem/CMakeLists.txt b/Sources/CSystem/CMakeLists.txt index 36656ae..617802c 100644 --- a/Sources/CSystem/CMakeLists.txt +++ b/Sources/CSystem/CMakeLists.txt @@ -1,7 +1,7 @@ #[[ This source file is part of the Swift System open source project -Copyright (c) 2020 Apple Inc. and the Swift System project authors +Copyright (c) 2020 - 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 diff --git a/Sources/CSystem/include/CSystemShared.h b/Sources/CSystem/include/CSystemShared.h index edcb5cc..ccc05b1 100644 --- a/Sources/CSystem/include/CSystemShared.h +++ b/Sources/CSystem/include/CSystemShared.h @@ -1,2 +1,11 @@ +/* + 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 +*/ + extern int csystem_posix_pipe2(int fildes[2], int flag); extern int csystem_posix_dup3(int fildes, int fildes2, int flag); diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index 69e994e..433cc78 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 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 diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 607b2e6..8f9fc48 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 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 diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 2803424..7deae4d 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 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 From 26f8c4f19583eaca93b7fa88a2ba83910b7a2bcb Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 26 May 2026 16:36:06 -0700 Subject: [PATCH 11/28] [ci] update workflows library to latest version --- .github/workflows/pull_request.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 1e58db4..5eb9b35 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.7 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10 with: swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI" enable_linux_checks: true @@ -58,7 +58,7 @@ jobs: build-abi-stable: name: Build ABI Stable - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.7 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10 with: enable_linux_checks: false enable_macos_checks: true @@ -71,7 +71,7 @@ jobs: soundness: name: Soundness - uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7 + uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10 with: license_header_check_project_name: "Swift.org" # https://github.com/apple/swift-system/issues/224 From 56dad9d66e95f62827969a14ec4afa6c15418fea Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 26 May 2026 16:36:06 -0700 Subject: [PATCH 12/28] [ci] update workflows library to latest version --- .github/workflows/pull_request.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 1e58db4..5eb9b35 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.7 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10 with: swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI" enable_linux_checks: true @@ -58,7 +58,7 @@ jobs: build-abi-stable: name: Build ABI Stable - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.7 + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10 with: enable_linux_checks: false enable_macos_checks: true @@ -71,7 +71,7 @@ jobs: soundness: name: Soundness - uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.7 + uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10 with: license_header_check_project_name: "Swift.org" # https://github.com/apple/swift-system/issues/224 From 34f4970c1cdff8d6c4816b43280323275ece055c Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Fri, 29 May 2026 12:48:43 -0600 Subject: [PATCH 13/28] Build CSystem as a static library in CMake so shims.c is compiled --- Sources/CSystem/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/CSystem/CMakeLists.txt b/Sources/CSystem/CMakeLists.txt index 617802c..6bde43c 100644 --- a/Sources/CSystem/CMakeLists.txt +++ b/Sources/CSystem/CMakeLists.txt @@ -7,8 +7,8 @@ Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information #]] -add_library(CSystem INTERFACE) -target_include_directories(CSystem INTERFACE +add_library(CSystem STATIC shims.c) +target_include_directories(CSystem PUBLIC "$" $) From 2cae953181a6771cf73597bc3da553d1843004b5 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 4 Jun 2026 11:32:59 -0700 Subject: [PATCH 14/28] Fix a crash when work is interleaved between prepare and submit in IORing --- Sources/System/IORing/IORequest.swift | 23 ++------ Sources/System/IORing/IORing.swift | 59 +++++++++++++++++-- Sources/System/IORing/RawIORequest.swift | 1 - Tests/SystemTests/IORequestTests.swift | 3 +- Tests/SystemTests/IORingTests.swift | 75 ++++++++++++++++++++++++ 5 files changed, 136 insertions(+), 25 deletions(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 7e433f9..d642a0a 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -388,7 +388,9 @@ extension IORing.Request { } @inline(__always) @inlinable - internal consuming func makeRawRequest() -> RawIORequest { + internal consuming func makeRawRequest( + pathBuffers: PendingPathBuffers + ) -> RawIORequest { var request = RawIORequest() switch extractCore() { case .nop: @@ -400,27 +402,19 @@ extension IORing.Request { request.operation = .openAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( - UInt( - bitPattern: path.withPlatformString { ptr in - ptr //this is unsavory, but we keep it alive by storing path alongside it in the request - })) + UInt(bitPattern: pathBuffers.pin(path))) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.file_index = UInt32(fileSlot.index + 1) - request.path = path request.rawValue.user_data = context case .openat( let atDirectory, let path, let mode, let options, let permissions, let context): request.operation = .openAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( - UInt( - bitPattern: path.withPlatformString { ptr in - ptr //this is unsavory, but we keep it alive by storing path alongside it in the request - })) + UInt(bitPattern: pathBuffers.pin(path))) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 - request.path = path request.rawValue.user_data = context case .write(let file, let buffer, let offset, let context): request.operation = .writeFixed @@ -466,12 +460,7 @@ extension IORing.Request { request.operation = .unlinkAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( - UInt( - bitPattern: path.withPlatformString { ptr in - ptr //this is unsavory, but we keep it alive by storing path alongside it in the request - }) - ) - request.path = path + UInt(bitPattern: pathBuffers.pin(path))) request.rawValue.user_data = context case .cancelContext(let flags, let targetContext): request.operation = .asyncCancel diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 16c85a0..3570da6 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -41,6 +41,32 @@ extension UnsafeMutableRawBufferPointer { } } +/// Owns the FilePaths whose interior pointers have been written into pending +/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to +/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap +@usableFromInline +internal final class PendingPathBuffers { + @usableFromInline + var paths: [FilePath] = [] + + init(reservedCapacity: Int) { + paths.reserveCapacity(reservedCapacity) + } + + @usableFromInline + func pin(_ path: FilePath) -> UnsafePointer { + paths.append(path) + // Safe to escape: `paths` keeps the FilePath (and its underlying + // [SystemChar] buffer) alive until clear() or class deinit. + return paths.last!.withPlatformString { $0 } + } + + @usableFromInline + func clear() { + paths.removeAll(keepingCapacity: true) + } +} + // all pointers in this struct reference kernel-visible memory @usableFromInline struct SQRing: ~Copyable { @usableFromInline let kernelHead: UnsafePointer> @@ -200,7 +226,14 @@ private func setUpRing( throw err } - if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0 + // We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced + // pathnames (and other inline data) out of userspace before io_uring_enter + // returns; the path-buffer side store on IORing relies on this to free + // path buffers as soon as a submission completes. + let requiredFeatures = + IORing.Features.nonDroppingCompletions.rawValue + | IORing.Features.stableSubmissions.rawValue + if params.features & requiredFeatures != requiredFeatures { close(ringDescriptor) throw Errno.invalidArgument @@ -324,6 +357,8 @@ public struct IORing: ~Copyable { @usableFromInline var _registeredFiles: [UInt32] @usableFromInline var _registeredBuffers: [iovec] + @usableFromInline let _pendingPathBuffers: PendingPathBuffers + var features = Features(rawValue: 0) /// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them. @@ -444,6 +479,7 @@ public struct IORing: ~Copyable { self.completionRingSize = tmpCQSize self._registeredFiles = [] self._registeredBuffers = [] + self._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries)) self.submissionRing = submissionRing self.completionRing = completionRing self.submissionQueueEntries = submissionQueueEntries @@ -765,6 +801,10 @@ public struct IORing: ~Copyable { @inlinable public func submitPreparedRequests() throws(Errno) { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) + // IORING_FEAT_SUBMIT_STABLE guarantees the kernel has copied any + // SQE-referenced data (e.g. openat/unlinkAt pathnames) before + // io_uring_enter returns; safe to release path storage now. + _pendingPathBuffers.clear() } /// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available. @@ -790,9 +830,14 @@ public struct IORing: ~Copyable { /// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request @inlinable public mutating func prepare(request: __owned Request) -> Bool { - var raw: RawIORequest? = request.makeRawRequest() - return _tryWriteRequest( + guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else { + return false + } + var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers) + let ok = _tryWriteRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + assert(ok) + return ok } /// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. @@ -806,18 +851,20 @@ public struct IORing: ~Copyable { return false } let last = linkedRequests.last! + var allAdded = true for req in linkedRequests.dropLast() { - var raw = req.makeRawRequest() + var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers) raw.linkToNextRequest() let successfullyAdded = _tryWriteRequest( raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) assert(successfullyAdded) + allAdded = allAdded && successfullyAdded } let successfullyAdded = _tryWriteRequest( - last.makeRawRequest(), ring: &submissionRing, + last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) assert(successfullyAdded) - return true + return allAdded && successfullyAdded } /// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space. diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index 0bc4029..c9b80dc 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -8,7 +8,6 @@ internal struct RawIORequest: ~Copyable { // swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where // IORing is supported (currently requires kernel version >= 5.15). @usableFromInline var rawValue: swift_io_uring_sqe - @usableFromInline var path: FilePath? //buffer owner for the path pointer that the sqe may have @inlinable public init() { self.rawValue = swift_io_uring_sqe() diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 9246d39..773a90c 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -22,7 +22,8 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { // which are known to work correctly. final class IORequestTests: XCTestCase { func testNop() { - let req = IORing.Request.nop().makeRawRequest() + let req = IORing.Request.nop().makeRawRequest( + pathBuffers: PendingPathBuffers(reservedCapacity: 0)) let sourceBytes = requestBytes(req) // convenient property of nop: it's all zeros! // for some unknown reason, liburing sets the fd field to -1. diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index c5d54d4..e001e69 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -127,6 +127,81 @@ final class IORingTests: XCTestCase { efdBuf.deallocate() rawBuffer.deallocate() } + + // Prior to the fix this is testing, prepare() escaped a pointer obtained + // inside `path.withPlatformString { ... }` into the SQE and dropped the + // owning FilePath before submit, so io_uring_enter handed the kernel a + // 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 } + let (parent, _) = try makeHelloWorldFile() + var ring = try IORing(queueDepth: 6) + + func enqueueOpen() { + let path: FilePath = "/tmp/IORingTests/test.txt" + let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly)) + XCTAssertTrue(ok) + } + enqueueOpen() + + var churn: [UnsafeMutableRawBufferPointer] = [] + for _ in 0..<256 { + let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1) + memset(buf.baseAddress!, 0x41, 64) + churn.append(buf) + } + for buf in churn { buf.deallocate() } + churn.removeAll() + + try ring.submitPreparedRequests() + let completion = try ring.blockingConsumeCompletion() + XCTAssertGreaterThanOrEqual( + completion.result, 0, + "open should succeed; got \(completion.result)") + + if completion.result >= 0 { + let fd = FileDescriptor(rawValue: Int32(completion.result)) + try fd.close() + } + try cleanUpHelloWorldFile(parent) + } + + func testPathBufferLifetimeAcrossLinkedRequests() throws { + guard try 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]) + + func enqueueLinkedReadback() { + let path: FilePath = "/tmp/IORingTests/test.txt" + let ok = ring.prepare(linkedRequests: + .open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly), + .read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]), + .close(ring.registeredFileSlots[0])) + XCTAssertTrue(ok) + } + enqueueLinkedReadback() + + var churn: [UnsafeMutableRawBufferPointer] = [] + for _ in 0..<256 { + let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1) + memset(buf.baseAddress!, 0x41, 64) + churn.append(buf) + } + for buf in churn { buf.deallocate() } + + try ring.submitPreparedRequests() + _ = try ring.blockingConsumeCompletion() // open + _ = try ring.blockingConsumeCompletion() // read + _ = try ring.blockingConsumeCompletion() // close + + let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) + XCTAssertEqual(result, "Hello, World!") + + try cleanUpHelloWorldFile(parent) + rawBuffer.deallocate() + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From 6fa5c8a6c10b82e5abf42fcd743f09ffe666ecf1 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 4 Jun 2026 15:56:58 -0700 Subject: [PATCH 15/28] Explain why this is a class --- Sources/System/IORing/IORing.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 3570da6..dcb71e4 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -44,6 +44,7 @@ extension UnsafeMutableRawBufferPointer { /// Owns the FilePaths whose interior pointers have been written into pending /// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to /// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap +/// This is a class purely to avoid making methods calling `pin` mutating, which would be an API break @usableFromInline internal final class PendingPathBuffers { @usableFromInline From e59002fa14dea846fb6abb20ebda63ca6a1017ce Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 9 Jun 2026 13:56:14 -0700 Subject: [PATCH 16/28] Add option-taking pipe() implementation for Windows --- Sources/CSystem/include/CSystemShared.h | 3 +++ Sources/CSystem/shims.c | 4 ++++ Sources/System/FileDescriptor.swift | 11 ++++++++--- Sources/System/FileOperations.swift | 2 -- Sources/System/Internals/Constants.swift | 10 ++++++++-- Sources/System/Internals/WindowsSyscallAdapters.swift | 7 +++++++ 6 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Sources/CSystem/include/CSystemShared.h b/Sources/CSystem/include/CSystemShared.h index ccc05b1..1ee3a6a 100644 --- a/Sources/CSystem/include/CSystemShared.h +++ b/Sources/CSystem/include/CSystemShared.h @@ -7,5 +7,8 @@ See https://swift.org/LICENSE.txt for license information */ +#if !defined(_WIN32) extern int csystem_posix_pipe2(int fildes[2], int flag); +#endif + extern int csystem_posix_dup3(int fildes, int fildes2, int flag); diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index 433cc78..4130582 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -28,6 +28,8 @@ #endif // Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h + +#if !defined(_WIN32) extern int csystem_posix_pipe2(int fildes[2], int flag) { #ifdef HAVE_PIPE2_DUP3 return pipe2(fildes, flag); @@ -36,6 +38,8 @@ extern int csystem_posix_pipe2(int fildes[2], int flag) { return -1; #endif } +#endif // !defined(_WIN32) + extern int csystem_posix_dup3(int fildes, int fildes2, int flag) { #ifdef HAVE_PIPE2_DUP3 return dup3(fildes, fildes2, flag); diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 86f36bb..7155fa3 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -324,7 +324,6 @@ extension FileDescriptor { /// Options that specify behavior for a newly-created pipe. @frozen - @available(Windows, unavailable) @available(macOS, unavailable) @available(iOS, unavailable) @available(tvOS, unavailable) @@ -350,6 +349,7 @@ extension FileDescriptor { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "nonBlocking") public static var O_NONBLOCK: PipeOptions { nonBlocking } +#endif // !os(Windows) /// Indicates that executing a program closes the file. /// @@ -369,7 +369,13 @@ extension FileDescriptor { @available(*, unavailable, renamed: "closeOnExec") public static var O_CLOEXEC: PipeOptions { closeOnExec } -#if !os(WASI) && !os(Linux) && !os(Android) +#if os(Windows) + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnExec") + public static var O_NOINHERIT: PipeOptions { closeOnExec } +#endif + +#if !os(Windows) && !os(WASI) && !os(Linux) && !os(Android) /// Indicates that forking a program closes the file. /// /// Normally, file descriptors remain open @@ -387,7 +393,6 @@ extension FileDescriptor { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnFork") public static var O_CLOFORK: PipeOptions { closeOnFork } -#endif #endif } diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index f69374f..7dfcb9e 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -524,7 +524,6 @@ extension FileDescriptor { /// /// The corresponding C function is `pipe2`. @_alwaysEmitIntoClient - @available(Windows, unavailable) @available(macOS, unavailable) @available(iOS, unavailable) @available(tvOS, unavailable) @@ -550,7 +549,6 @@ extension FileDescriptor { } } - @available(Windows, unavailable) @available(macOS, unavailable) @available(iOS, unavailable) @available(tvOS, unavailable) diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 8f9fc48..477fc9a 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -619,10 +619,16 @@ internal var _O_DIRECTORY: CInt { internal var _O_SYMLINK: CInt { O_SYMLINK } #endif -#if !os(Windows) @_alwaysEmitIntoClient -internal var _O_CLOEXEC: CInt { O_CLOEXEC } +internal var _O_CLOEXEC: CInt { + #if os(Windows) + O_NOINHERIT + #else + O_CLOEXEC + #endif +} +#if !os(Windows) @_alwaysEmitIntoClient internal var _O_CLOFORK: CInt { #if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index ca9b42d..c649aa3 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -206,6 +206,13 @@ internal func pipe( return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT); } +@inline(__always) +internal func csystem_posix_pipe2( + _ fds: UnsafeMutablePointer, bytesReserved: UInt32 = 0, _ oflag: Int32 +) -> CInt { + return _pipe(fds, bytesReserved, _O_BINARY | oflag) +} + @inline(__always) internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { let handle: intptr_t = _get_osfhandle(fd) From 2cc89c12b30109613c694283b0b43da2d71810e9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 9 Jun 2026 13:56:55 -0700 Subject: [PATCH 17/28] Defer pipe buffering decision to the OS on Windows --- Sources/System/Internals/WindowsSyscallAdapters.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index c649aa3..4883140 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -201,7 +201,7 @@ internal func pwrite( @inline(__always) internal func pipe( - _ fds: UnsafeMutablePointer, bytesReserved: UInt32 = 4096 + _ fds: UnsafeMutablePointer, bytesReserved: UInt32 = 0 ) -> CInt { return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT); } From a2bc5f06250bca1a2a2ab1e14ad9e6ada456b668 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 9 Jun 2026 14:19:02 -0700 Subject: [PATCH 18/28] Add tests specific to dup2 and dup3 --- Tests/SystemTests/FileOperationsTest.swift | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index 9dd4c2b..eb2713f 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -178,6 +178,79 @@ final class FileOperationsTest: XCTestCase { } #endif + func testAdHocDuplicate2() throws { + try withTemporaryFilePath(basename: "test") { + let path = $0.appending("foo2.txt") + let fd1 = try FileDescriptor.open(path, .readWrite, + options: [.create, .truncate], + permissions: .ownerReadWrite) + + let fd2 = FileDescriptor(rawValue: 731) + let fd3 = try fd1.duplicate(as: fd2) + XCTAssertEqual(fd2, fd3) + + try fd2.close() + do { + try fd3.close() + XCTFail("Should be unreachable") + } catch { + if let error = try? XCTUnwrap(error as? Errno) { + XCTAssertEqual(error, .badFileDescriptor) + } + } + + // dup2() accepts two equal parameters. + let fd4 = try fd1.duplicate(as: fd1) + XCTAssertEqual(fd4, fd1) + + try fd1.close() + do { + try fd4.close() + XCTFail("Should be unreachable") + } catch { + if let error = try? XCTUnwrap(error as? Errno) { + XCTAssertEqual(error, .badFileDescriptor) + } + } + } + } + + #if !SYSTEM_PACKAGE_DARWIN && !os(Windows) + func testAdHocDuplicate3() throws { + + try withTemporaryFilePath(basename: "test") { + let path = $0.appending("foo3.txt") + + let fd1 = try FileDescriptor.open(path, .readWrite, + options: [.create, .truncate], + permissions: .ownerReadWrite) + + let fd2 = FileDescriptor(rawValue: 731) + let fd3 = try fd1.duplicate(as: fd2, options: [.closeOnExec]) + XCTAssertEqual(fd2, fd3) + + try fd2.close() + do { + try fd3.close() + } catch { + if let error = try? XCTUnwrap(error as? Errno) { + XCTAssertEqual(error, .badFileDescriptor) + } + } + + // dup3() does not accept two equal parameters. + do { + _ = try fd1.duplicate(as: fd1, options: []) + XCTFail("Should be unreachable") + } catch { + if let error = try? XCTUnwrap(error as? Errno) { + XCTAssertEqual(error, .invalidArgument) + } + } + } + } + #endif // !SYSTEM_PACKAGE_DARWIN && !os(Windows) + func testAdHocOpen() { // Ad-hoc test touching a file system. do { From 3e0b3181761d39aa22f7c2addbb805b6d6aeb769 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 9 Jun 2026 14:19:20 -0700 Subject: [PATCH 19/28] Add a test for pipe2 --- Tests/SystemTests/FileOperationsTest.swift | 25 +++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index eb2713f..91ac5f1 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -176,7 +176,30 @@ final class FileOperationsTest: XCTestCase { } } } - #endif + + #if !SYSTEM_PACKAGE_DARWIN + func testAdHocPipeWithOptions() throws { + // Ad-hoc test testing `Pipe` functionality. + // We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`. + let options: FileDescriptor.PipeOptions = [.closeOnExec] + let pipe: (readEnd: FileDescriptor, writeEnd: FileDescriptor) + pipe = try FileDescriptor.pipe(options: options) + try pipe.readEnd.closeAfter { + try pipe.writeEnd.closeAfter { + var abc = "abc" + try abc.withUTF8 { + _ = try pipe.writeEnd.write(UnsafeRawBufferPointer($0)) + } + let readLen = 3 + let readBytes = try Array(unsafeUninitializedCapacity: readLen) { buf, count in + count = try pipe.readEnd.read(into: UnsafeMutableRawBufferPointer(buf)) + } + XCTAssertEqual(readBytes, Array(abc.utf8)) + } + } + } + #endif // !SYSTEM_PACKAGE_DARWIN + #endif // !os(WASI) func testAdHocDuplicate2() throws { try withTemporaryFilePath(basename: "test") { From 4fdc665a0f71aa18b7fd0f168ba036e3c2b492d9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 9 Jun 2026 16:39:56 -0700 Subject: [PATCH 20/28] Compile out testAdHocDuplicate2 on Windows --- Tests/SystemTests/FileOperationsTest.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index 91ac5f1..abc4ecd 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -201,6 +201,7 @@ final class FileOperationsTest: XCTestCase { #endif // !SYSTEM_PACKAGE_DARWIN #endif // !os(WASI) + #if !os(Windows) func testAdHocDuplicate2() throws { try withTemporaryFilePath(basename: "test") { let path = $0.appending("foo2.txt") @@ -237,6 +238,7 @@ final class FileOperationsTest: XCTestCase { } } } + #endif // !os(Windows) #if !SYSTEM_PACKAGE_DARWIN && !os(Windows) func testAdHocDuplicate3() throws { From b7b66845da26ef99063e7ea8539e559aab2da1e8 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 10 Jun 2026 09:56:17 -0700 Subject: [PATCH 21/28] Update proposal with Windows change --- Proposals/0007-FileDescriptor-dup3-pipe2.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Proposals/0007-FileDescriptor-dup3-pipe2.md b/Proposals/0007-FileDescriptor-dup3-pipe2.md index 5e159de..a94d781 100644 --- a/Proposals/0007-FileDescriptor-dup3-pipe2.md +++ b/Proposals/0007-FileDescriptor-dup3-pipe2.md @@ -9,6 +9,8 @@ * **v1** Initial version +- **v2** Add Windows version of `pipe(options:)` + ## Introduction Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively. @@ -165,7 +167,9 @@ struct FileDescriptor { } ``` -These API additions are unavailable on Windows and Darwin, as the underlying `dup3` and `pipe2` APIs do not exist. +These API additions are unavailable Darwin, as the underlying `dup3` and `pipe2` APIs do not exist. + +`pipe(options:)` is added for Windows with the option `.closeOnExec`, but `duplicate(as:options:)` is not added because the underlying API does not match `dup3`. `closeOnFork` is unavailable on Linux and Android, as the underlying `O_CLOFORK` constant does not exist. From e60d362adab401b2aa0b7ada0dcba0cb6bd63236 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 10 Jun 2026 10:44:38 -0700 Subject: [PATCH 22/28] fix typo --- Proposals/0007-FileDescriptor-dup3-pipe2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Proposals/0007-FileDescriptor-dup3-pipe2.md b/Proposals/0007-FileDescriptor-dup3-pipe2.md index a94d781..6cb25ac 100644 --- a/Proposals/0007-FileDescriptor-dup3-pipe2.md +++ b/Proposals/0007-FileDescriptor-dup3-pipe2.md @@ -167,7 +167,7 @@ struct FileDescriptor { } ``` -These API additions are unavailable Darwin, as the underlying `dup3` and `pipe2` APIs do not exist. +These API additions are unavailable on Darwin, as the underlying `dup3` and `pipe2` APIs do not exist. `pipe(options:)` is added for Windows with the option `.closeOnExec`, but `duplicate(as:options:)` is not added because the underlying API does not match `dup3`. From d937d1573571b23bba210c48015262bd448dd15d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 11 Jun 2026 13:22:29 -0700 Subject: [PATCH 23/28] Add clarifications to the doc-comments of the new overloads. --- Sources/System/FileOperations.swift | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index 7dfcb9e..df2a819 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -415,9 +415,14 @@ extension FileDescriptor { /// Pass `false` to try only once and throw an error upon interruption. /// - Returns: The new file descriptor. /// + /// If the `target` descriptor the same as `self`, then EINVAL is thrown. /// If the `target` descriptor is already in use, then it is first /// deallocated as if a close(2) call had been done first. /// + /// NOTE: This overload called with an empty option set is not necessarily + /// equivalent to calling the overload with no options, because `dup3` with + /// no set options is not required to behave identically to `dup2`. + /// /// File descriptors are merely references to some underlying system resource. /// The system does not distinguish between the original and the new file /// descriptor in any way. For example, read, write and seek operations on @@ -502,7 +507,8 @@ extension FileDescriptor { #if !os(WASI) @available(System 1.1.0, *) extension FileDescriptor { - /// Creates a unidirectional data channel, which can be used for interprocess communication. + /// Creates a unidirectional data channel, which can be used for + /// interprocess communication. /// /// - Returns: The pair of file descriptors. /// @@ -517,6 +523,11 @@ extension FileDescriptor { /// Creates a unidirectional data channel, which can be used for /// interprocess communication. /// + /// NOTE: This overload called with an empty option set is not necessarily + /// equivalent to calling the overload with no options. On Windows, this + /// overload with empty options disables the `closeOnExec` behaviour, + /// which is enabled by the overload without options. + /// /// - Parameters: /// - options: The behavior for creating the pipe. /// From 7e888c0cb44f110f240505554b0660b61ad478c7 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Sun, 31 May 2026 13:28:03 -0700 Subject: [PATCH 24/28] System: remove unnecessary type casting The compiler now imports these as their canonical type, allowing us to directly use without the explicit type cast. Due to the floor of Swift 6.3, we must preserve the type cast values. Introduce an overlay to explicitly cast the values in the older compilers. --- .../System/FilePath/FilePathTempWindows.swift | 4 +- Sources/System/FilePath/FilePathWindows.swift | 2 +- .../Internals/WindowsSyscallAdapters.swift | 96 ++-- Sources/System/WinSDK+Overlay.swift | 439 ++++++++++++++++++ .../FileOperationsTestWindows.swift | 58 +-- 5 files changed, 522 insertions(+), 77 deletions(-) create mode 100644 Sources/System/WinSDK+Overlay.swift diff --git a/Sources/System/FilePath/FilePathTempWindows.swift b/Sources/System/FilePath/FilePathTempWindows.swift index 259aaaf..0321d52 100644 --- a/Sources/System/FilePath/FilePathTempWindows.swift +++ b/Sources/System/FilePath/FilePathTempWindows.swift @@ -73,7 +73,7 @@ internal func _recursiveRemove( ) throws { // First, deal with subdirectories try forEachFile(at: path) { findData in - if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 { + if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 { let name = withUnsafeBytes(of: findData.cFileName) { return SystemString(platformString: $0.assumingMemoryBound( to: CInterop.PlatformChar.self).baseAddress!) @@ -94,7 +94,7 @@ internal func _recursiveRemove( let component = FilePath.Component(name)! let subpath = path.appending(component) - if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 { + if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 { try subpath.withPlatformString { subpath in if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) { throw Errno(windowsError: GetLastError()) diff --git a/Sources/System/FilePath/FilePathWindows.swift b/Sources/System/FilePath/FilePathWindows.swift index 875c1c6..d892795 100644 --- a/Sources/System/FilePath/FilePathWindows.swift +++ b/Sources/System/FilePath/FilePathWindows.swift @@ -529,7 +529,7 @@ fileprivate func SUCCEEDED(_ hr: HRESULT) -> Bool { // an HRESULT to a Win32 error code. @inline(__always) fileprivate func WIN32_FROM_HRESULT(_ hr: HRESULT) -> DWORD { - if SUCCEEDED(hr) { return DWORD(ERROR_SUCCESS) } + if SUCCEEDED(hr) { return ERROR_SUCCESS } if HRESULT_FACILITY(hr) == FACILITY_WIN32 { return HRESULT_CODE(hr) } diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index ca9b42d..e4e98cd 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -38,9 +38,9 @@ internal func open( guard let hFile = try? path.withCanonicalPathRepresentation({ path in CreateFileW(path, decodedFlags.dwDesiredAccess, - DWORD(FILE_SHARE_DELETE - | FILE_SHARE_READ - | FILE_SHARE_WRITE), + FILE_SHARE_DELETE + | FILE_SHARE_READ + | FILE_SHARE_WRITE, &saAttrs, decodedFlags.dwCreationDisposition, decodedFlags.dwFlagsAndAttributes, @@ -80,9 +80,9 @@ internal func open( guard let hFile = try? path.withCanonicalPathRepresentation({ path in CreateFileW(path, decodedFlags.dwDesiredAccess, - DWORD(FILE_SHARE_DELETE - | FILE_SHARE_READ - | FILE_SHARE_WRITE), + FILE_SHARE_DELETE + | FILE_SHARE_READ + | FILE_SHARE_WRITE, &saAttrs, decodedFlags.dwCreationDisposition, decodedFlags.dwFlagsAndAttributes, @@ -218,16 +218,16 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { // Save the current position and restore it when we're done if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset, - DWORD(FILE_CURRENT)) { + FILE_CURRENT) { ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } defer { - _ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN)); + _ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN); } // Truncate (or extend) the file - if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN)) + if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN) || !SetEndOfFile(hFile) { ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 @@ -279,7 +279,7 @@ internal func rmdir( } internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { - switch Int32(errorCode) { + switch errorCode { case ERROR_SUCCESS: return 0 case ERROR_INVALID_FUNCTION, @@ -358,28 +358,28 @@ fileprivate func rightsFromModeBits( var rights: DWORD = 0 if (bits & 0o4) != 0 { - rights |= DWORD(FILE_READ_ATTRIBUTES - | FILE_READ_DATA - | FILE_READ_EA - | STANDARD_RIGHTS_READ - | SYNCHRONIZE) + rights |= (FILE_READ_ATTRIBUTES + | FILE_READ_DATA + | FILE_READ_EA + | STANDARD_RIGHTS_READ + | SYNCHRONIZE) } if (bits & 0o2) != 0 { - rights |= DWORD(FILE_APPEND_DATA - | FILE_WRITE_ATTRIBUTES - | FILE_WRITE_DATA - | FILE_WRITE_EA - | STANDARD_RIGHTS_WRITE - | SYNCHRONIZE) + rights |= (FILE_APPEND_DATA + | FILE_WRITE_ATTRIBUTES + | FILE_WRITE_DATA + | FILE_WRITE_EA + | STANDARD_RIGHTS_WRITE + | SYNCHRONIZE) if fileOrDirectory == .directory && !sticky { - rights |= DWORD(FILE_DELETE_CHILD) + rights |= FILE_DELETE_CHILD } } if (bits & 0o1) != 0 { - rights |= DWORD(FILE_EXECUTE - | FILE_READ_ATTRIBUTES - | STANDARD_RIGHTS_EXECUTE - | SYNCHRONIZE) + rights |= (FILE_EXECUTE + | FILE_READ_ATTRIBUTES + | STANDARD_RIGHTS_EXECUTE + | SYNCHRONIZE) } return rights @@ -447,7 +447,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, var everyone: PSID? = nil guard AllocateAndInitializeSid(&SIDAuthWorld, 1, - DWORD(SECURITY_WORLD_RID), + SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyone) else { return nil @@ -488,7 +488,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, EXPLICIT_ACCESS_W( grfAccessPermissions: ownerRights, grfAccessMode: GRANT_ACCESS, - grfInheritance: DWORD(NO_INHERITANCE), + grfInheritance: NO_INHERITANCE, Trustee: TRUSTEE_W( pMultipleTrustee: nil, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, @@ -501,7 +501,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, EXPLICIT_ACCESS_W( grfAccessPermissions: groupRights, grfAccessMode: GRANT_ACCESS, - grfInheritance: DWORD(NO_INHERITANCE), + grfInheritance: NO_INHERITANCE, Trustee: TRUSTEE_W( pMultipleTrustee: nil, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, @@ -514,7 +514,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, EXPLICIT_ACCESS_W( grfAccessPermissions: otherRights, grfAccessMode: GRANT_ACCESS, - grfInheritance: DWORD(NO_INHERITANCE), + grfInheritance: NO_INHERITANCE, Trustee: TRUSTEE_W( pMultipleTrustee: nil, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, @@ -531,7 +531,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, EXPLICIT_ACCESS_W( grfAccessPermissions: ownerDenyRights, grfAccessMode: DENY_ACCESS, - grfInheritance: DWORD(NO_INHERITANCE), + grfInheritance: NO_INHERITANCE, Trustee: TRUSTEE_W( pMultipleTrustee: nil, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, @@ -549,7 +549,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, EXPLICIT_ACCESS_W( grfAccessPermissions: groupDenyRights, grfAccessMode: DENY_ACCESS, - grfInheritance: DWORD(NO_INHERITANCE), + grfInheritance: NO_INHERITANCE, Trustee: TRUSTEE_W( pMultipleTrustee: nil, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, @@ -578,13 +578,13 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode, var descriptor = SECURITY_DESCRIPTOR() guard InitializeSecurityDescriptor(&descriptor, - DWORD(SECURITY_DESCRIPTOR_REVISION)) else { + SECURITY_DESCRIPTOR_REVISION) else { return nil } guard SetSecurityDescriptorControl(&descriptor, - SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED), - SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED)) + SE_DACL_PROTECTED, + SE_DACL_PROTECTED) && SetSecurityDescriptorOwner(&descriptor, user, false) && SetSecurityDescriptorGroup(&descriptor, group, false) && SetSecurityDescriptorDacl(&descriptor, @@ -624,15 +624,15 @@ fileprivate struct DecodedOpenFlags { init(_ oflag: Int32) { switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) { case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC: - dwCreationDisposition = DWORD(CREATE_NEW) + dwCreationDisposition = CREATE_NEW case _O_CREAT: - dwCreationDisposition = DWORD(OPEN_ALWAYS) + dwCreationDisposition = OPEN_ALWAYS case _O_CREAT | _O_TRUNC: - dwCreationDisposition = DWORD(CREATE_ALWAYS) + dwCreationDisposition = CREATE_ALWAYS case _O_TRUNC: - dwCreationDisposition = DWORD(TRUNCATE_EXISTING) + dwCreationDisposition = TRUNCATE_EXISTING default: - dwCreationDisposition = DWORD(OPEN_EXISTING) + dwCreationDisposition = OPEN_EXISTING } // The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping @@ -641,11 +641,11 @@ fileprivate struct DecodedOpenFlags { dwDesiredAccess = 0 switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) { case _O_RDONLY: - dwDesiredAccess |= DWORD(GENERIC_READ) + dwDesiredAccess |= GENERIC_READ case _O_WRONLY: - dwDesiredAccess |= DWORD(GENERIC_WRITE) + dwDesiredAccess |= GENERIC_WRITE case _O_RDWR: - dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE) + dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE default: break } @@ -654,19 +654,19 @@ fileprivate struct DecodedOpenFlags { dwFlagsAndAttributes = 0 if (oflag & _O_SEQUENTIAL) != 0 { - dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN) + dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN } if (oflag & _O_RANDOM) != 0 { - dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS) + dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS } if (oflag & _O_TEMPORARY) != 0 { - dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE) + dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE } if (oflag & _O_SHORT_LIVED) != 0 { - dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY) + dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY } else { - dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL) + dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL } } } diff --git a/Sources/System/WinSDK+Overlay.swift b/Sources/System/WinSDK+Overlay.swift new file mode 100644 index 0000000..41a292c --- /dev/null +++ b/Sources/System/WinSDK+Overlay.swift @@ -0,0 +1,439 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 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 os(Windows) + +import WinSDK + +@_transparent +internal var CREATE_ALWAYS: DWORD { + DWORD(WinSDK.CREATE_ALWAYS) +} + +@_transparent +internal var CREATE_NEW: DWORD { + DWORD(WinSDK.CREATE_NEW) +} + +@_transparent +internal var ERROR_ACCESS_DENIED: DWORD { + DWORD(WinSDK.ERROR_ACCESS_DENIED) +} + +@_transparent +internal var ERROR_ALREADY_EXISTS: DWORD { + DWORD(WinSDK.ERROR_ALREADY_EXISTS) +} + +@_transparent +internal var ERROR_ARENA_TRASHED: DWORD { + DWORD(WinSDK.ERROR_ARENA_TRASHED) +} + +@_transparent +internal var ERROR_BAD_ENVIRONMENT: DWORD { + DWORD(WinSDK.ERROR_BAD_ENVIRONMENT) +} + +@_transparent +internal var ERROR_BAD_FORMAT: DWORD { + DWORD(WinSDK.ERROR_BAD_FORMAT) +} + +@_transparent +internal var ERROR_BAD_NET_NAME: DWORD { + DWORD(WinSDK.ERROR_BAD_NET_NAME) +} + +@_transparent +internal var ERROR_BAD_NETPATH: DWORD { + DWORD(WinSDK.ERROR_BAD_NETPATH) +} + +@_transparent +internal var ERROR_BAD_PATHNAME: DWORD { + DWORD(WinSDK.ERROR_BAD_PATHNAME) +} + +@_transparent +internal var ERROR_BROKEN_PIPE: DWORD { + DWORD(WinSDK.ERROR_BROKEN_PIPE) +} + +@_transparent +internal var ERROR_CANNOT_MAKE: DWORD { + DWORD(WinSDK.ERROR_CANNOT_MAKE) +} + +@_transparent +internal var ERROR_CHILD_NOT_COMPLETE: DWORD { + DWORD(WinSDK.ERROR_CHILD_NOT_COMPLETE) +} + +@_transparent +internal var ERROR_CURRENT_DIRECTORY: DWORD { + DWORD(WinSDK.ERROR_CURRENT_DIRECTORY) +} + +@_transparent +internal var ERROR_DIR_NOT_EMPTY: DWORD { + DWORD(WinSDK.ERROR_DIR_NOT_EMPTY) +} + +@_transparent +internal var ERROR_DISK_FULL: DWORD { + DWORD(WinSDK.ERROR_DISK_FULL) +} + +@_transparent +internal var ERROR_DRIVE_LOCKED: DWORD { + DWORD(WinSDK.ERROR_DRIVE_LOCKED) +} + +@_transparent +internal var ERROR_DIRECT_ACCESS_HANDLE: DWORD { + DWORD(WinSDK.ERROR_DIRECT_ACCESS_HANDLE) +} + +@_transparent +internal var ERROR_FILE_EXISTS: DWORD { + DWORD(WinSDK.ERROR_FILE_EXISTS) +} + +@_transparent +internal var ERROR_FILE_NOT_FOUND: DWORD { + DWORD(WinSDK.ERROR_FILE_NOT_FOUND) +} + +@_transparent +internal var ERROR_FAIL_I24: DWORD { + DWORD(WinSDK.ERROR_FAIL_I24) +} + +@_transparent +internal var ERROR_FILENAME_EXCED_RANGE: DWORD { + DWORD(WinSDK.ERROR_FILENAME_EXCED_RANGE) +} + +@_transparent +internal var ERROR_NEGATIVE_SEEK: DWORD { + DWORD(WinSDK.ERROR_NEGATIVE_SEEK) +} + +@_transparent +internal var ERROR_NO_MORE_FILES: DWORD { + DWORD(WinSDK.ERROR_NO_MORE_FILES) +} + +@_transparent +internal var ERROR_NO_UNICODE_TRANSLATION: DWORD { + DWORD(WinSDK.ERROR_NO_UNICODE_TRANSLATION) +} + +@_transparent +internal var ERROR_NOT_ENOUGH_MEMORY: DWORD { + DWORD(WinSDK.ERROR_NOT_ENOUGH_MEMORY) +} + +@_transparent +internal var ERROR_INVALID_ACCESS: DWORD { + DWORD(WinSDK.ERROR_INVALID_ACCESS) +} + +@_transparent +internal var ERROR_INVALID_BLOCK: DWORD { + DWORD(WinSDK.ERROR_INVALID_BLOCK) +} + +@_transparent +internal var ERROR_INVALID_DATA: DWORD { + DWORD(WinSDK.ERROR_INVALID_DATA) +} + +@_transparent +internal var ERROR_INVALID_DRIVE: DWORD { + DWORD(WinSDK.ERROR_INVALID_DRIVE) +} + +@_transparent +internal var ERROR_INVALID_FUNCTION: DWORD { + DWORD(WinSDK.ERROR_INVALID_FUNCTION) +} + +@_transparent +internal var ERROR_INVALID_HANDLE: DWORD { + DWORD(WinSDK.ERROR_INVALID_HANDLE) +} + +@_transparent +internal var ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD { + DWORD(WinSDK.ERROR_INFLOOP_IN_RELOC_CHAIN) +} + +@_transparent +internal var ERROR_INVALID_PARAMETER: DWORD { + DWORD(WinSDK.ERROR_INVALID_PARAMETER) +} + +@_transparent +internal var ERROR_INVALID_STARTING_CODESEG: DWORD { + DWORD(WinSDK.ERROR_INVALID_STARTING_CODESEG) +} + +@_transparent +internal var ERROR_INVALID_TARGET_HANDLE: DWORD { + DWORD(WinSDK.ERROR_INVALID_TARGET_HANDLE) +} + +@_transparent +internal var ERROR_LOCK_FAILED: DWORD { + DWORD(WinSDK.ERROR_LOCK_FAILED) +} + +@_transparent +internal var ERROR_LOCK_VIOLATION: DWORD { + DWORD(WinSDK.ERROR_LOCK_VIOLATION) +} + +@_transparent +internal var ERROR_MAX_THRDS_REACHED: DWORD { + DWORD(WinSDK.ERROR_MAX_THRDS_REACHED) +} + +@_transparent +internal var ERROR_NESTING_NOT_ALLOWED: DWORD { + DWORD(WinSDK.ERROR_NESTING_NOT_ALLOWED) +} + +@_transparent +internal var ERROR_NETWORK_ACCESS_DENIED: DWORD { + DWORD(WinSDK.ERROR_NETWORK_ACCESS_DENIED) +} + +@_transparent +internal var ERROR_NO_PROC_SLOTS: DWORD { + DWORD(WinSDK.ERROR_NO_PROC_SLOTS) +} + +@_transparent +internal var ERROR_NOT_ENOUGH_QUOTA: DWORD { + DWORD(WinSDK.ERROR_NOT_ENOUGH_QUOTA) +} + +@_transparent +internal var ERROR_NOT_LOCKED: DWORD { + DWORD(WinSDK.ERROR_NOT_LOCKED) +} + +@_transparent +internal var ERROR_NOT_SAME_DEVICE: DWORD { + DWORD(WinSDK.ERROR_NOT_SAME_DEVICE) +} + +@_transparent +internal var ERROR_PATH_NOT_FOUND: DWORD { + DWORD(WinSDK.ERROR_PATH_NOT_FOUND) +} + +@_transparent +internal var ERROR_SEEK_ON_DEVICE: DWORD { + DWORD(WinSDK.ERROR_SEEK_ON_DEVICE) +} + +@_transparent +internal var ERROR_SHARING_BUFFER_EXCEEDED: DWORD { + DWORD(WinSDK.ERROR_SHARING_BUFFER_EXCEEDED) +} + +@_transparent +internal var ERROR_SUCCESS: DWORD { + DWORD(WinSDK.ERROR_SUCCESS) +} + +@_transparent +internal var ERROR_WAIT_NO_CHILDREN: DWORD { + DWORD(WinSDK.ERROR_WAIT_NO_CHILDREN) +} + +@_transparent +internal var ERROR_WRITE_PROTECT: DWORD { + DWORD(WinSDK.ERROR_WRITE_PROTECT) +} + +@_transparent +internal var ERROR_TOO_MANY_OPEN_FILES: DWORD { + DWORD(WinSDK.ERROR_TOO_MANY_OPEN_FILES) +} + +@_transparent +internal var FILE_APPEND_DATA: DWORD { + DWORD(WinSDK.FILE_APPEND_DATA) +} + +@_transparent +internal var FILE_ATTRIBUTE_DIRECTORY: DWORD { + DWORD(WinSDK.FILE_ATTRIBUTE_DIRECTORY) +} + +@_transparent +internal var FILE_ATTRIBUTE_NORMAL: DWORD { + DWORD(WinSDK.FILE_ATTRIBUTE_NORMAL) +} + +@_transparent +internal var FILE_ATTRIBUTE_TEMPORARY: DWORD { + DWORD(WinSDK.FILE_ATTRIBUTE_TEMPORARY) +} + +@_transparent +internal var FILE_BEGIN: DWORD { + DWORD(WinSDK.FILE_BEGIN) +} + +@_transparent +internal var FILE_CURRENT: DWORD { + DWORD(WinSDK.FILE_CURRENT) +} + +@_transparent +internal var FILE_DELETE_CHILD: DWORD { + DWORD(WinSDK.FILE_DELETE_CHILD) +} + +@_transparent +package var FILE_EXECUTE: DWORD { + DWORD(WinSDK.FILE_EXECUTE) +} + +@_transparent +internal var FILE_FLAG_DELETE_ON_CLOSE: DWORD { + DWORD(WinSDK.FILE_FLAG_DELETE_ON_CLOSE) +} + +@_transparent +internal var FILE_FLAG_RANDOM_ACCESS: DWORD { + DWORD(WinSDK.FILE_FLAG_RANDOM_ACCESS) +} + +@_transparent +internal var FILE_FLAG_SEQUENTIAL_SCAN: DWORD { + DWORD(WinSDK.FILE_FLAG_SEQUENTIAL_SCAN) +} + +@_transparent +package var FILE_READ_ATTRIBUTES: DWORD { + DWORD(WinSDK.FILE_READ_ATTRIBUTES) +} + +@_transparent +internal var FILE_READ_DATA: DWORD { + DWORD(WinSDK.FILE_READ_DATA) +} + +@_transparent +internal var FILE_READ_EA: DWORD { + DWORD(WinSDK.FILE_READ_EA) +} + +@_transparent +internal var FILE_SHARE_DELETE: DWORD { + DWORD(WinSDK.FILE_SHARE_DELETE) +} + +@_transparent +internal var FILE_SHARE_READ: DWORD { + DWORD(WinSDK.FILE_SHARE_READ) +} + +@_transparent +internal var FILE_SHARE_WRITE: DWORD { + DWORD(WinSDK.FILE_SHARE_WRITE) +} + +@_transparent +package var FILE_WRITE_ATTRIBUTES: DWORD { + DWORD(WinSDK.FILE_WRITE_ATTRIBUTES) +} + +@_transparent +internal var FILE_WRITE_DATA: DWORD { + DWORD(WinSDK.FILE_WRITE_DATA) +} + +@_transparent +internal var FILE_WRITE_EA: DWORD { + DWORD(WinSDK.FILE_WRITE_EA) +} + +@_transparent +internal var GENERIC_READ: DWORD { + DWORD(WinSDK.GENERIC_READ) +} + +@_transparent +internal var GENERIC_WRITE: DWORD { + DWORD(WinSDK.GENERIC_WRITE) +} + +@_transparent +internal var NO_INHERITANCE: DWORD { + DWORD(WinSDK.NO_INHERITANCE) +} + +@_transparent +internal var OPEN_ALWAYS: DWORD { + DWORD(WinSDK.OPEN_ALWAYS) +} + +@_transparent +internal var OPEN_EXISTING: DWORD { + DWORD(WinSDK.OPEN_EXISTING) +} + +@_transparent +internal var SE_DACL_PROTECTED: SECURITY_DESCRIPTOR_CONTROL { + SECURITY_DESCRIPTOR_CONTROL(WinSDK.SE_DACL_PROTECTED) +} + +@_transparent +internal var SECURITY_DESCRIPTOR_REVISION: DWORD { + DWORD(WinSDK.SECURITY_DESCRIPTOR_REVISION) +} + +@_transparent +internal var SECURITY_WORLD_RID: DWORD { + DWORD(WinSDK.SECURITY_WORLD_RID) +} + +@_transparent +internal var STANDARD_RIGHTS_READ: DWORD { + DWORD(WinSDK.STANDARD_RIGHTS_READ) +} + +@_transparent +internal var STANDARD_RIGHTS_EXECUTE: DWORD { + DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE) +} + +@_transparent +internal var STANDARD_RIGHTS_WRITE: DWORD { + DWORD(WinSDK.STANDARD_RIGHTS_WRITE) +} + +@_transparent +internal var SYNCHRONIZE: DWORD { + DWORD(WinSDK.SYNCHRONIZE) +} + +@_transparent +internal var TRUNCATE_EXISTING: DWORD { + DWORD(WinSDK.TRUNCATE_EXISTING) +} + +#endif diff --git a/Tests/SystemTests/FileOperationsTestWindows.swift b/Tests/SystemTests/FileOperationsTestWindows.swift index f43521b..fbba7b5 100644 --- a/Tests/SystemTests/FileOperationsTestWindows.swift +++ b/Tests/SystemTests/FileOperationsTestWindows.swift @@ -19,6 +19,10 @@ import XCTest import WinSDK +private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA) +private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE) +private let FILE_READ_ATTRIBUTES = DWORD(WinSDK.FILE_READ_ATTRIBUTES) + @available(iOS 8, *) final class FileOperationsTestWindows: XCTestCase { private let r = ACCESS_MASK( @@ -43,6 +47,8 @@ final class FileOperationsTestWindows: XCTestCase { | SYNCHRONIZE ) + private let none = ACCESS_MASK(0) + private struct Test { var permissions: CModeT var ownerAccess: ACCESS_MASK @@ -72,7 +78,7 @@ final class FileOperationsTestWindows: XCTestCase { var psidEveryone: PSID? = nil XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1, - DWORD(SECURITY_WORLD_RID), + SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &psidEveryone)) defer { @@ -106,7 +112,7 @@ final class FileOperationsTestWindows: XCTestCase { &psidGroup, &pDacl, nil, - &pSD), DWORD(ERROR_SUCCESS)) + &pSD), ERROR_SUCCESS) defer { LocalFree(pSD) } @@ -135,15 +141,15 @@ final class FileOperationsTestWindows: XCTestCase { XCTAssertEqual(GetEffectiveRightsFromAclW( pDacl, &owner, - &ownerAccess), DWORD(ERROR_SUCCESS)) + &ownerAccess), ERROR_SUCCESS) XCTAssertEqual(GetEffectiveRightsFromAclW( pDacl, &group, - &groupAccess), DWORD(ERROR_SUCCESS)) + &groupAccess), ERROR_SUCCESS) XCTAssertEqual(GetEffectiveRightsFromAclW( pDacl, &everyone, - &otherAccess), DWORD(ERROR_SUCCESS)) + &otherAccess), ERROR_SUCCESS) return (ownerAccess, groupAccess, otherAccess) } @@ -182,9 +188,9 @@ final class FileOperationsTestWindows: XCTestCase { try withTemporaryFilePath(basename: "testUmask") { path in let tests = [ - Test(0o000, 0, 0, 0), - Test(0o700, r|w|x, 0, 0), - Test(0o770, r|w|x, r|x, 0), + Test(0o000, none, none, none), + Test(0o700, r|w|x, none, none), + Test(0o770, r|w|x, r|x, none), Test(0o777, r|w|x, r|x, r|x) ] @@ -195,9 +201,9 @@ final class FileOperationsTestWindows: XCTestCase { .otherWrite, .otherExecute]) { try withTemporaryFilePath(basename: "testUmask") { path in let tests = [ - Test(0o000, 0, 0, 0), - Test(0o700, r|w|x, 0, 0), - Test(0o770, r|w|x, r, 0), + Test(0o000, none, none, none), + Test(0o700, r|w|x, none, none), + Test(0o770, r|w|x, r, none), Test(0o777, r|w|x, r, r) ] @@ -214,28 +220,28 @@ final class FileOperationsTestWindows: XCTestCase { try FilePermissions.withCreationMask([]) { try withTemporaryFilePath(basename: "testPermissions") { path in let tests = [ - Test(0o000, 0, 0, 0), + Test(0o000, none, none, none), - Test(0o400, r, 0, 0), - Test(0o200, w, 0, 0), - Test(0o100, x, 0, 0), - Test(0o040, 0, r, 0), - Test(0o020, 0, w, 0), - Test(0o010, 0, x, 0), - Test(0o004, 0, 0, r), - Test(0o002, 0, 0, w), - Test(0o001, 0, 0, x), + Test(0o400, r, none, none), + Test(0o200, w, none, none), + Test(0o100, x, none, none), + Test(0o040, none, r, none), + Test(0o020, none, w, none), + Test(0o010, none, x, none), + Test(0o004, none, none, r), + Test(0o002, none, none, w), + Test(0o001, none, none, x), - Test(0o700, r|w|x, 0, 0), - Test(0o770, r|w|x, r|w|x, 0), + Test(0o700, r|w|x, none, none), + Test(0o770, r|w|x, r|w|x, none), Test(0o777, r|w|x, r|w|x, r|w|x), Test(0o755, r|w|x, r|x, r|x), Test(0o644, r|w, r, r), - Test(0o007, 0, 0, r|w|x), - Test(0o070, 0, r|w|x, 0), - Test(0o077, 0, r|w|x, r|w|x), + Test(0o007, none, none, r|w|x), + Test(0o070, none, r|w|x, none), + Test(0o077, none, r|w|x, r|w|x), ] try runTests(tests, at: path) From 360e6f70f034b90f82dbafda66bfc6919ab428d4 Mon Sep 17 00:00:00 2001 From: Kenta Kubo <601636+kkebo@users.noreply.github.com> Date: Fri, 12 Jun 2026 22:31:04 +0900 Subject: [PATCH 25/28] Fix missing `O_CLOFORK` on older FreeBSD --- Sources/CSystem/CMakeLists.txt | 1 + Sources/CSystem/include/CSystemFreeBSD.h | 21 +++++++++++++++++++++ Sources/CSystem/include/module.modulemap | 1 + Sources/CSystem/shims.c | 4 ++++ Sources/System/Internals/Constants.swift | 4 +++- 5 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 Sources/CSystem/include/CSystemFreeBSD.h diff --git a/Sources/CSystem/CMakeLists.txt b/Sources/CSystem/CMakeLists.txt index 6bde43c..0088ad1 100644 --- a/Sources/CSystem/CMakeLists.txt +++ b/Sources/CSystem/CMakeLists.txt @@ -16,6 +16,7 @@ install(FILES include/CSystemLinux.h include/CSystemShared.h include/CSystemWindows.h + include/CSystemFreeBSD.h include/module.modulemap DESTINATION include/CSystem) set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem) diff --git a/Sources/CSystem/include/CSystemFreeBSD.h b/Sources/CSystem/include/CSystemFreeBSD.h new file mode 100644 index 0000000..158f0b4 --- /dev/null +++ b/Sources/CSystem/include/CSystemFreeBSD.h @@ -0,0 +1,21 @@ +/* + 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 defined(__FreeBSD__) + +#include + +#ifdef O_CLOFORK +#define FREEBSD_O_CLOFORK O_CLOFORK +#else +#define FREEBSD_O_CLOFORK 0 +#endif + +#endif + diff --git a/Sources/CSystem/include/module.modulemap b/Sources/CSystem/include/module.modulemap index 73b1004..38c2d46 100644 --- a/Sources/CSystem/include/module.modulemap +++ b/Sources/CSystem/include/module.modulemap @@ -3,5 +3,6 @@ module CSystem { header "CSystemLinux.h" header "CSystemWASI.h" header "CSystemWindows.h" + header "CSystemFreeBSD.h" export * } diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index 4130582..eb9126b 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -12,6 +12,10 @@ #include #endif +#if defined(__FreeBSD__) +#include +#endif + #ifdef __linux__ #define _GNU_SOURCE #include diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 477fc9a..fa76713 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -631,8 +631,10 @@ internal var _O_CLOEXEC: CInt { #if !os(Windows) @_alwaysEmitIntoClient internal var _O_CLOFORK: CInt { - #if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) + #if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD) O_CLOFORK + #elseif os(FreeBSD) + FREEBSD_O_CLOFORK #else 0 #endif From c50ad26d0608df2b5291c0862d32deb1758aaad1 Mon Sep 17 00:00:00 2001 From: Sarunas <3808892+vsarunas@users.noreply.github.com> Date: Fri, 12 Jun 2026 09:26:21 +0300 Subject: [PATCH 26/28] fix: build with MemberImportVisibility --- Sources/System/FilePath/FilePathTempPosix.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Sources/System/FilePath/FilePathTempPosix.swift b/Sources/System/FilePath/FilePathTempPosix.swift index e8713c2..2ac7098 100644 --- a/Sources/System/FilePath/FilePathTempPosix.swift +++ b/Sources/System/FilePath/FilePathTempPosix.swift @@ -9,6 +9,23 @@ #if !os(Windows) +#if SYSTEM_PACKAGE_DARWIN +import Darwin +#elseif canImport(Glibc) +import CSystem +import Glibc +#elseif canImport(Musl) +import CSystem +import Musl +#elseif canImport(WASILibc) +import WASILibc +#elseif canImport(Android) +import CSystem +import Android +#else +#error("Unsupported Platform") +#endif + /// Get the path to the system temporary directory. internal func _getTemporaryDirectory() throws -> FilePath { guard let tmp = system_getenv("TMPDIR") else { From 0a3460f369300549b672b382f99d0314aa7ad990 Mon Sep 17 00:00:00 2001 From: Jonathan Flat <50605158+jrflat@users.noreply.github.com> Date: Fri, 12 Jun 2026 18:21:14 -0400 Subject: [PATCH 27/28] [1.7.0] Fix Stat MemberImportVisibility regression and add test (#320) * Fix Stat MemberImportVisibility regression and add test * Remove Android from the MIV test --- Package.swift | 6 ++++ Sources/CSystem/include/CSystemLinux.h | 2 -- Tests/MemberImportVisibility/Probe.swift | 45 ++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 Tests/MemberImportVisibility/Probe.swift diff --git a/Package.swift b/Package.swift index b624a59..7f774e6 100644 --- a/Package.swift +++ b/Package.swift @@ -141,6 +141,12 @@ let package = Package( exclude: testsToExclude, cSettings: cSettings, swiftSettings: swiftSettings), + // Builds a SystemPackage consumer with MemberImportVisibility enabled. + // Fails if a C member of a vended type is attributed to the CSystem module. + .testTarget( + name: "MemberImportVisibility", + dependencies: ["SystemPackage"], + swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]), ], swiftLanguageModes: [.v5] ) diff --git a/Sources/CSystem/include/CSystemLinux.h b/Sources/CSystem/include/CSystemLinux.h index 6489c4f..815e142 100644 --- a/Sources/CSystem/include/CSystemLinux.h +++ b/Sources/CSystem/include/CSystemLinux.h @@ -11,13 +11,11 @@ #include #include -#include #include #include #include #include #include -#include #include #include #include diff --git a/Tests/MemberImportVisibility/Probe.swift b/Tests/MemberImportVisibility/Probe.swift new file mode 100644 index 0000000..d08503b --- /dev/null +++ b/Tests/MemberImportVisibility/Probe.swift @@ -0,0 +1,45 @@ +/* + 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 +*/ + +// Compile-only canary for MemberImportVisibility regressions: this file fails +// to build if a C member of a type SystemPackage vends is attributed to the +// private CSystem module. +// +// For new type wrappers introduced to System, access their C members here: +// - Import the platform overlay (Glibc/Musl), as consumers do. +// - Access raw C members of vended types (e.g. CInterop.Stat) as a downstream +// consumer would. Don't go through the Swift (e.g. Stat) wrapper since its +// accesses happen inside System, where importing CSystem is fine. +// - Touch every direct member the public API exposes. One field is not always +// a safe proxy for the rest. + +#if canImport(Glibc) || canImport(Musl) +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif +import SystemPackage + +func _mivProbe(_ s: CInterop.Stat) { + _ = s.st_dev + _ = s.st_ino + _ = s.st_mode + _ = s.st_nlink + _ = s.st_uid + _ = s.st_gid + _ = s.st_rdev + _ = s.st_size + _ = s.st_blksize + _ = s.st_blocks + _ = s.st_atim + _ = s.st_mtim + _ = s.st_ctim +} +#endif From 7502b711c92a17741fa625d722b0ccbd595d8ed1 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 12 Jun 2026 15:16:19 -0700 Subject: [PATCH 28/28] Update README to indicate 1.7.x is the latest version --- README.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 0b75fd0..3958cd9 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ To use the `SystemPackage` library in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file: ```swift -.package(url: "https://github.com/apple/swift-system", from: "1.6.1"), +.package(url: "https://github.com/apple/swift-system", from: "1.7.1"), ``` Finally, include `"SystemPackage"` as a dependency for your executable target: @@ -41,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target: let package = Package( // name, platforms, products, etc. dependencies: [ - .package(url: "https://github.com/apple/swift-system", from: "1.6.1"), + .package(url: "https://github.com/apple/swift-system", from: "1.7.1"), // other dependencies ], targets: [ @@ -88,6 +88,7 @@ The following table maps existing package releases to their minimum required Swi | ----------------------- | --------------- | ------------- | | swift-system 1.3.x | >= Swift 5.8 | >= Xcode 14.3 | | swift-system 1.4.x through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 | +| swift-system 1.7.x | >= Swift 6.1 | >= Xcode 16.3 | We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so. @@ -107,15 +108,16 @@ We maintain separate branches for each active minor version of the package: | Package version | Branch | | ----------------------- | ----------- | -| swift-system 1.3.x | release/1.3 | -| swift-system 1.4.x | release/1.4 | -| swift-system 1.5.x | release/1.5 | -| swift-system 1.6.x | release/1.6 | -| swift-system 1.7.x (unreleased) | main | +| swift-system 1.3.x | release/1.3.0 | +| swift-system 1.4.x | release/1.4.0 | +| swift-system 1.5.x | release/1.5.0 | +| swift-system 1.6.x | release/1.6.0 | +| swift-system 1.7.x | release/1.7.0 | +| swift-system 1.8.x (unreleased) | main | Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction: -`release/1.3` → `release/1.4` → `main` +`release/1.6.0` → `release/1.7.0` → `main` For example, anything landing on `release/1.3` will eventually appear on `release/1.4` and then `main` too; there is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.)