diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 742ceaa..33ddaa7 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..7f774e6 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 @@ -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")]), ], - swiftLanguageVersions: [.v5] + swiftLanguageModes: [.v5] ) diff --git a/Proposals/0007-FileDescriptor-dup3-pipe2.md b/Proposals/0007-FileDescriptor-dup3-pipe2.md new file mode 100644 index 0000000..6cb25ac --- /dev/null +++ b/Proposals/0007-FileDescriptor-dup3-pipe2.md @@ -0,0 +1,182 @@ +# 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 + +- **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. + +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) + + /// 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 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 and + /// close-on-fork flags. + /// + /// 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: PipeOptions + + /// 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 system closes the + /// file descriptor when replacing this process with another process. + /// + /// 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`. + 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 system closes the file + /// descriptor when forking this process into another process. + /// + /// 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`. + 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) + + /// 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 system closes the + /// file descriptor when replacing this process with another process. + /// + /// 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`. + 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 system closes the file + /// descriptor when forking this process into another process. + /// + /// 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`. + public static var closeOnFork: DuplicateOptions + } +} +``` + +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`. + +`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. 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.) diff --git a/Sources/CSystem/CMakeLists.txt b/Sources/CSystem/CMakeLists.txt index faf730e..0088ad1 100644 --- a/Sources/CSystem/CMakeLists.txt +++ b/Sources/CSystem/CMakeLists.txt @@ -1,20 +1,22 @@ #[[ 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 #]] -add_library(CSystem INTERFACE) -target_include_directories(CSystem INTERFACE +add_library(CSystem STATIC shims.c) +target_include_directories(CSystem PUBLIC "$" $) 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/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/Sources/CSystem/include/CSystemShared.h b/Sources/CSystem/include/CSystemShared.h new file mode 100644 index 0000000..1ee3a6a --- /dev/null +++ b/Sources/CSystem/include/CSystemShared.h @@ -0,0 +1,14 @@ +/* + 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(_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/include/module.modulemap b/Sources/CSystem/include/module.modulemap index 6e8b89e..38c2d46 100644 --- a/Sources/CSystem/include/module.modulemap +++ b/Sources/CSystem/include/module.modulemap @@ -1,6 +1,8 @@ module CSystem { + header "CSystemShared.h" 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 f492a2a..eb9126b 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -1,18 +1,54 @@ /* 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 */ +#if defined(__FreeBSD__) || defined(__OpenBSD__) +#define __BSD_VISIBLE +#include +#endif + +#if defined(__FreeBSD__) +#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 + +#if !defined(_WIN32) +extern int csystem_posix_pipe2(int fildes[2], int flag) { + #ifdef HAVE_PIPE2_DUP3 + return pipe2(fildes, flag); + #else + errno = ENOSYS; + 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); + #else + errno = ENOSYS; + return -1; + #endif +} diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index d5f5883..7155fa3 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 @@ -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`. @@ -324,6 +322,138 @@ extension FileDescriptor { #endif } + /// Options that specify behavior for a newly-created pipe. + @frozen + @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: PipeOptions { .init(rawValue: _O_NONBLOCK) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "nonBlocking") + public static var O_NONBLOCK: PipeOptions { nonBlocking } +#endif // !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 system closes the file + /// descriptor when replacing this process with another process. + /// + /// 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`. + @_alwaysEmitIntoClient + public static var closeOnExec: PipeOptions { .init(rawValue: _O_CLOEXEC) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnExec") + public static var O_CLOEXEC: PipeOptions { closeOnExec } + +#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 + /// across calls to the `fork(2)` function. + /// If you specify this option, the system closes the file + /// descriptor when forking this process into another process. + /// + /// 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`. + @_alwaysEmitIntoClient + public static var closeOnFork: PipeOptions { .init(rawValue: _O_CLOFORK) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnFork") + public static var O_CLOFORK: PipeOptions { closeOnFork } +#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 system closes the file + /// descriptor when replacing this process with another process. + /// + /// 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`. + @_alwaysEmitIntoClient + public static var closeOnExec: DuplicateOptions { .init(rawValue: _O_CLOEXEC) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnExec") + public static var O_CLOEXEC: DuplicateOptions { 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 system closes the file + /// descriptor when forking this process into another process. + /// + /// 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`. + @_alwaysEmitIntoClient + public static var closeOnFork: DuplicateOptions { .init(rawValue: _O_CLOFORK) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "closeOnFork") + public static var O_CLOFORK: DuplicateOptions { 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..df2a819 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, *) @@ -406,17 +405,82 @@ extension FileDescriptor { try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get() } + /// 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 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 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 + /// 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 and + /// close-on-fork flags. + /// + /// The corresponding C function is `dup3`. + @discardableResult + @_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(Errno) -> FileDescriptor { + try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get() + } + @available(System 0.0.2, *) @usableFromInline internal func _duplicate( as target: FileDescriptor?, retryOnInterrupt: Bool - ) throws -> Result { + ) -> Result { valueOrErrno(retryOnInterrupt: retryOnInterrupt) { - if let target = target { - return system_dup2(self.rawValue, target.rawValue) + if let target { + system_dup2(self.rawValue, target.rawValue) + } else { + system_dup(self.rawValue) } - return 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 + ) -> Result { + valueOrErrno(retryOnInterrupt: retryOnInterrupt) { + system_dup3(self.rawValue, target.rawValue, options) }.map(FileDescriptor.init(rawValue:)) } @@ -431,26 +495,61 @@ extension FileDescriptor { public func dup2() throws -> FileDescriptor { fatalError("Not implemented") } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "duplicate") + public func dup3() throws -> FileDescriptor { + fatalError("Not implemented") + } } #endif #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. /// /// The corresponding C function is `pipe`. @_alwaysEmitIntoClient @available(System 1.1.0, *) - public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { + public static func pipe( + ) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { try _pipe().get() } + /// 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. + /// + /// - Returns: The pair of file descriptors. + /// + /// The corresponding C function is `pipe2`. + @_alwaysEmitIntoClient + @available(macOS, unavailable) + @available(iOS, unavailable) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + @available(visionOS, unavailable) + 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() -> 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 @@ -460,6 +559,31 @@ extension FileDescriptor { } } } + + @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])) } + } + } + } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "pipe") + public static func pipe2() throws -> FileDescriptor { + fatalError("Not implemented") + } } #endif 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 { diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 17be792..4a388c4 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..dcb71e4 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -41,6 +41,33 @@ 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 + 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 +227,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 +358,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 +480,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 +802,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 +831,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 +852,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/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index b026c97..fa76713 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 @@ -619,9 +619,26 @@ internal var _O_DIRECTORY: CInt { internal var _O_SYMLINK: CInt { O_SYMLINK } #endif +@_alwaysEmitIntoClient +internal var _O_CLOEXEC: CInt { + #if os(Windows) + O_NOINHERIT + #else + O_CLOEXEC + #endif +} + #if !os(Windows) @_alwaysEmitIntoClient -internal var _O_CLOEXEC: CInt { O_CLOEXEC } +internal var _O_CLOFORK: CInt { + #if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD) + O_CLOFORK + #elseif os(FreeBSD) + FREEBSD_O_CLOFORK + #else + 0 + #endif +} #endif @_alwaysEmitIntoClient diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index f6eb533..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 @@ -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 { diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index e4e98cd..3c6055e 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -201,11 +201,18 @@ 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); } +@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) 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 diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index 9dd4c2b..abc4ecd 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -176,7 +176,105 @@ 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) + + #if !os(Windows) + 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) + } + } + } + } + #endif // !os(Windows) + + #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. 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