Compare commits

..
Author SHA1 Message Date
Franz Busch 1f070c0900 Add FD based write 2025-12-08 17:14:24 +01:00
Franz Busch 5b248a21c8 Add accept/connect APIs 2025-12-08 16:12:11 +01:00
Franz Busch e69d5c1f3c [IO_URING] Add support for pollAdd operation
## Motivation

To observe events on file descriptors IO_URING supports the `pollAdd` operation. This is useful when you want to observe a file descriptor becoming ready to read or write

## Modifications

This PR adds a new `IORing.Request.PollEvents` option set to model the poll masks. Furthermore, it adds a new `static func pollAdd` to the `IORing.Request`.

## Result

We can now use IO_URING to poll for events on file descriptors.
2025-12-08 12:05:48 +01:00
36 changed files with 400 additions and 1781 deletions

No files matched your search

+8 -13
View File
@@ -10,7 +10,7 @@ on:
jobs:
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
enable_linux_checks: true
@@ -19,11 +19,8 @@ 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"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_macos_checks: true
@@ -32,16 +29,13 @@ jobs:
windows_exclude_swift_versions: |
[
{"swift_version": "5.9"},
{"swift_version": "5.10"},
{"swift_version": "6.0"},
{"swift_version": "5.10"}
]
enable_linux_static_sdk_build: true
linux_static_sdk_exclude_swift_versions: |
[
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_wasm_sdk_build: true
@@ -49,16 +43,17 @@ jobs:
[
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_android_sdk_build: true
enable_android_sdk_checks: true
android_exclude_swift_versions: |
[
{"os_version": "focal", "swift_version": "nightly-main"},
]
build-abi-stable:
name: Build ABI Stable
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
enable_linux_checks: false
enable_macos_checks: true
@@ -71,7 +66,7 @@ jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "Swift.org"
# https://github.com/apple/swift-system/issues/224
+2 -8
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.1
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
@@ -141,12 +141,6 @@ 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]
swiftLanguageVersions: [.v5]
)
+1 -1
View File
@@ -417,7 +417,7 @@ public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
### Stat
`Stat` can be initialized from a `FilePath`, `UnsafePointer<CChar>`, or `FileDescriptor`. This proposal also includes functions on `FileDescriptor` and `FilePath` for creating a `Stat` object, seen in the section below.
`Stat` can be initialized from a `FilePath`, `UnsafePointer<CChar>`, or `FileDescriptor`. This proposal also includes functions on `FileDescriptor` and `FilePath` for creating a `Stat` object, seen in the section below.
The initializer accepting a `FileDescriptor` corresponds to `fstat()`. If the file descriptor points to a symlink, this will return information about the symlink itself.
-182
View File
@@ -1,182 +0,0 @@
# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor`
* Proposal: SYS-0007
- Author(s): Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
* 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.
-262
View File
@@ -1,262 +0,0 @@
# Back-Deploy CInterop.stat for Migration Compatibility
* Proposal: SYS-0008
* Author: [Jonathan Flat](https://github.com/jrflat)
* Status: **Awaiting review**
* Implementation: [apple/swift-system#299](https://github.com/apple/swift-system/pull/299)
* Review: ([pitch](https://forums.swift.org/t/pitch-back-deploy-system-cinterop-stat-for-migration-compatibility/84930))
#### Revision history
* **v1** Initial version
* **v2** Clarify that `CInterop.stat(_:_:)` is a new function
* **v3** Explain why this proposal should not set a precedence for future System APIs
## Introduction
This proposal introduces `CInterop.stat(_:_:)` and back-deploys the `CInterop.Stat` typealias from System to make them available on older OS versions, enabling a migration path for clients who may encounter naming conflicts with `FilePath.stat()` or `FileDescriptor.stat()` when System's new `Stat` API ships.
## Motivation
The introduction of `FilePath.stat()` and `FileDescriptor.stat()` in [SYS-0006](0006-system-stat.md) creates a potential source compatibility issue for a small number of clients. While we estimate this affects an exceedingly rare set of developers (1 case found in public GitHub repositories), we want to provide a clear migration path.
### Compatibility scenario
Some clients may have extended `FilePath` or `FileDescriptor` with custom functions that use `Darwin.stat()` and `Darwin.stat(_:_:)` **without** the `Darwin.` (or other libc) module qualification inside the function body:
```swift
extension FilePath {
func isRegularFile() -> Bool {
var s = stat() // Calls Darwin.stat(_:_:) - unqualified!
guard stat(self.string, &s) == 0 else { // Calls Darwin.stat(_:_:) - unqualified!
return false
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
When the new `FilePath.stat()` API from SYS-0006 ships, these unqualified calls to `stat()` and `stat(_:_:)` will refer to the new instance method, causing build errors:
```
error: Call can throw, but it is not marked with 'try' and the error is not handled
error: Use of 'stat' refers to instance method rather than global function 'stat' in module 'Darwin'
```
### Why not just use `Darwin.stat`?
Clients could resolve the ambiguity by qualifying their calls with `Darwin.`, `Glibc.`, etc. However, this approach has several limitations:
1. **Cross-platform code**: Clients writing code for multiple platforms would need platform-specific `#if` blocks with code for each platform's libc module.
2. **Awkward syntax**: Due to the overload between the `stat` type and `stat(_:_:)` function, clients must use the verbose `Darwin.stat(_:_:)(path, &s)` syntax to call the function, which is unintuitive.
3. **Older deployment targets**: Clients supporting older deployment targets can't use the new `System.Stat` API on older OS versions but still need to avoid build breakage when compiled with an SDK that includes the new `FilePath.stat()`
By back-deploying `CInterop.stat(_:_:)` to `System 0.0.2 (macOS 12.0, iOS 15.0)`, we provide a cross-platform, ergonomic solution: clients can replace `stat(_:_:)` with `CInterop.stat(_:_:)` for older deployment targets, and use the new `Stat` API moving forward.
## Proposed solution
Back-deploy `CInterop.Stat` and `CInterop.stat(_:_:)` to `@available(System 0.0.2, *)`, making them available on `macOS 12.0, iOS 15.0` and aligned. Note that `System 0.0.2` already maps to earliest source availability when System is used as a package, so the back-deployment is only relevant for System as an OS framework.
### API Overview
```swift
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
public typealias Stat = stat
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32
}
#endif
```
The implementation uses `@_alwaysEmitIntoClient` to make the function available on older OS versions by embedding the implementation in client code. This makes sense for a widely-available and standardized C function like `stat()`.
### Migration guidance
If you have `FilePath` or `FileDescriptor` extensions that use unqualified `stat()` calls and need to support older deployment targets, migrate to `CInterop.Stat` (type) and `CInterop.stat(_:_:)` (function):
#### Before:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
var s = stat()
guard stat(self.string, &s) == 0 else {
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
#### After:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
var s = CInterop.Stat() // stat() --> CInterop.Stat()
guard CInterop.stat(self.string, &s) == 0 else { // stat(_:_:) --> CInterop.stat(_:_:)
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
#### Migrate to the new `Stat` API:
Migrate to the more ergonomic interface on newer OS versions using `if #available`:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
if #available(macOS X, iOS Y, *) {
return try stat().type == .regular // Calls FilePath.stat()
}
var s = CInterop.Stat()
guard CInterop.stat(self.string, &s) == 0 else {
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
Alternatively, you may use just the new API if your deployment target supports it.
#### Who should use `CInterop.stat(_:_:)`?
This scenario is rare and only occurs when a project meets **all** of the following conditions:
1. Has a custom extension on `FilePath` or `FileDescriptor`, that
2. Uses **unqualified** `stat()` or `stat(_:_:)` calls inside that method, and
3. Needs to support deployment targets older than the new `Stat` API availability
If your code uses qualified calls, e.g. `Darwin.stat()`, or uses a wrapper around `stat()` already, it is **not** affected by this issue and no migration is needed.
## Detailed design
### CInterop extension
```swift
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
/// The C `stat` struct.
public typealias Stat = stat
/// Calls the C `stat()` function.
///
/// This is a direct wrapper around the C `stat()` system call.
/// For a more ergonomic Swift API, use `Stat` instead.
///
/// - Warning: This API is primarily intended for migration purposes when
/// supporting older deployment targets. If your deployment target supports
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
/// type-safe, ergonomic access to file metadata in Swift.
///
/// - Parameters:
/// - path: A null-terminated C string representing the file path.
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
system_stat(path, &s)
}
}
#endif
```
### Internal wrapper
The `system_stat` wrapper is also marked `@_alwaysEmitIntoClient` so it can be inlined. `system_stat` calls the global `stat` function for the current platform.
```swift
#if !os(Windows)
@_alwaysEmitIntoClient
internal func system_stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
stat(path, &s)
}
#endif
```
## Source compatibility
This proposal is additive and source-compatible.
## ABI compatibility
This proposal is ABI-compatible. The use of `@_alwaysEmitIntoClient` ensures that the implementation is embedded in client code.
## Implications on adoption
Clients can adopt `CInterop.Stat` and `CInterop.stat(_:_:)` to support older deployment targets when building with the new SDK.
## Future directions
Once clients can raise their deployment targets to support the new `Stat` API introduced in SYS-0006, they should migrate to it, which provides:
- Type-safe, ergonomic Swift interfaces
- Strongly-typed wrappers (`FileType`, `FileMode`, `FilePermissions`, etc.)
- Proper error handling with typed throws
## Why this should not set a precedent for CInterop functions
We should not expose `CInterop` functions for most, if not all, other methods that shadow a global function. `stat` is a special case for a few reasons:
- Many other syscalls gain a more Swift-y API name, e.g. `dup/dup2` → `duplicate(as:)`, `ftruncate` → `resize(to:)`, `umask` → `FilePermissions.creationMask` if that becomes API, etc. Those renames mean user extensions are unlikely to collide with future System API. `stat` is one of the few syscalls whose C name is already clear and idiomatic enough to use directly as the Swift API name.
- Many syscalls that do keep their C name (e.g. `open`, `close`, `read`, `write`) have been in System since the beginning, so there was never a window where someone would have needed to create their own extension for that functionality.
- `stat` is both widely used and was missing from System for some time, which creates a better chance for migration friction.
- Other syscalls that could be added to System naturally disambiguate through parameter labels. Names like `rename`, `link`, and `unlink` would require non-optional arguments (e.g. `rename(to:)`, `link(to:)`), so their Swift signatures wouldn't collide with the bare C functions. `stat` is unusual in that it works as a zero-argument call on `FilePath`/`FileDescriptor` and has the same shape as the global C `stat()` struct initializer.
## Alternatives considered
### Do nothing
We could choose not to provide a migration path and let affected clients handle the ambiguity by:
1. Qualifying their calls with platform-specific modules (e.g. `Darwin.stat`)
2. Wrapping `stat()` in another function
3. Raising their deployment target to use the new `Stat` API
However, this creates an unnecessary burden for the (admittedly rare) affected clients, especially those who need to maintain backward compatibility with older OS versions.
### Use a different name for `FilePath.stat()`
We could use a different name such as `FilePath.statInfo()`, `FilePath.status()`, `FilePath.Stat()`, or `FilePath.fileInfo()`. However, considering the rarity of the issue, changing to a less concise, discoverable, and expressive function name is not preferrable when we can offer a migration solution.
### Create `stat()` overloads directly on `FilePath`
We could create `stat()` extensions on `FilePath` within System that guide a developer to use the new instance method via `try stat()`, e.g:
```swift
extension FilePath {
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
public func stat() -> CInterop.Stat {
CInterop.Stat()
}
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
public func stat(
_ path: UnsafePointer<CChar>,
_ s: inout CInterop.Stat
) -> Int32 {
system_stat(path, &s)
}
}
```
This is beneficial because it prevents any SDK breakage with only a System change. However, this is not a great long-term solution to have as public API because:
- It makes choosing the right `stat()` more confusing with 5 total overloads.
- It hurts discoverability for the new `Stat` API.
### Expose the internal `system_stat` wrapper directly
This would achieve the same effect as exposing `CInterop.stat(_:_:)`, but goes against the API naming/organization patterns in System. `CInterop` seems like a clear place for the direct C `stat` wrapper to belong.
### Back-deploy the full `Stat` API
Unlike functions and typealiases, types such as `Stat`, `FileType`, `FileMode`, etc. would require significant coordination and effort to back-deploy, making this alternative less desirable, especially considering it's not required to address the issue.
+8 -10
View File
@@ -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.7.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.6.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.7.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
// other dependencies
],
targets: [
@@ -88,7 +88,6 @@ 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.
@@ -108,16 +107,15 @@ We maintain separate branches for each active minor version of the package:
| Package version | Branch |
| ----------------------- | ----------- |
| 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 |
| 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 |
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.6.0` → `release/1.7.0` → `main`
`release/1.3` → `release/1.4` → `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.)
+3 -5
View File
@@ -1,22 +1,20 @@
#[[
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 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 STATIC shims.c)
target_include_directories(CSystem PUBLIC
add_library(CSystem INTERFACE)
target_include_directories(CSystem INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
$<INSTALL_INTERFACE:include/CSystem>)
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)
-21
View File
@@ -1,21 +0,0 @@
/*
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 <fcntl.h>
#ifdef O_CLOFORK
#define FREEBSD_O_CLOFORK O_CLOFORK
#else
#define FREEBSD_O_CLOFORK 0
#endif
#endif
+2
View File
@@ -11,11 +11,13 @@
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/sysinfo.h>
#include <sys/timerfd.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
-14
View File
@@ -1,14 +0,0 @@
/*
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);
+2
View File
@@ -134,6 +134,8 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
#define IORING_FEAT_RW_ATTR (1U << 16)
#define IORING_FEAT_NO_IOWAIT (1U << 17)
#define IORING_POLL_ADD_MULTI (1U << 0)
#if !defined(_ASM_GENERIC_INT_LL64_H) && !defined(_ASM_GENERIC_INT_L64_H) && !defined(_UAPI_ASM_GENERIC_INT_LL64_H) && !defined(_UAPI_ASM_GENERIC_INT_L64_H)
typedef uint8_t __u8;
typedef uint16_t __u16;
-2
View File
@@ -1,8 +1,6 @@
module CSystem {
header "CSystemShared.h"
header "CSystemLinux.h"
header "CSystemWASI.h"
header "CSystemWindows.h"
header "CSystemFreeBSD.h"
export *
}
+3 -39
View File
@@ -1,54 +1,18 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 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 <unistd.h>
#endif
#if defined(__FreeBSD__)
#include <CSystemFreeBSD.h>
#endif
#ifdef __linux__
#define _GNU_SOURCE
#include <CSystemLinux.h>
#endif
#if defined(_WIN32)
#include <CSystemWindows.h>
#endif
#include <errno.h>
#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
}
+1 -1
View File
@@ -160,7 +160,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
/// No child processes.
///
/// A `wait(2)` or `waitpid(2)` function was executed
/// by a process that doesn't have any existing child processes
/// by a process that dosn't have any existing child processes
/// or whose child processes are all already being waited for.
///
/// The corresponding C error is `ECHILD`.
+6 -136
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2021 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,10 +306,12 @@ extension FileDescriptor {
///
/// 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.
/// If you specify this option,
/// the file descriptor is closed when replacing this process
/// with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// 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`.
@@ -322,138 +324,6 @@ 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, *)
+9 -133
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2025 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,6 +395,7 @@ 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, *)
@@ -405,82 +406,17 @@ 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
) -> Result<FileDescriptor, Errno> {
) throws -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
if let target {
system_dup2(self.rawValue, target.rawValue)
} else {
system_dup(self.rawValue)
if let target = target {
return system_dup2(self.rawValue, target.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<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_dup3(self.rawValue, target.rawValue, options)
return system_dup(self.rawValue)
}.map(FileDescriptor.init(rawValue:))
}
@@ -495,61 +431,26 @@ 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
@@ -559,31 +460,6 @@ 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
@@ -9,23 +9,6 @@
#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 {
@@ -73,7 +73,7 @@ internal func _recursiveRemove(
) throws {
// First, deal with subdirectories
try forEachFile(at: path) { findData in
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 {
if (findData.dwFileAttributes & DWORD(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 & FILE_ATTRIBUTE_DIRECTORY) == 0 {
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 {
try subpath.withPlatformString { subpath in
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
throw Errno(windowsError: GetLastError())
@@ -517,7 +517,7 @@ fileprivate func HRESULT_CODE(_ hr: HRESULT) -> DWORD {
@inline(__always)
fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD {
DWORD(hr >> 16) & 0x1fff
DWORD(hr << 16) & 0x1fff
}
@inline(__always)
@@ -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 ERROR_SUCCESS }
if SUCCEEDED(hr) { return DWORD(ERROR_SUCCESS) }
if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
return HRESULT_CODE(hr)
}
+141 -9
View File
@@ -2,6 +2,7 @@
#if os(Linux)
import CSystem
import Glibc
@usableFromInline
internal enum IORequestCore {
@@ -23,6 +24,22 @@ internal enum IORequestCore {
intoSlot: IORing.RegisteredFile,
context: UInt64 = 0
)
case pollAdd(
file: FileDescriptor,
pollEvents: IORing.Request.PollEvents,
isMultiShot: Bool = true,
context: UInt64 = 0
)
case connect(
socketFD: FileDescriptor,
sockaddr: UnsafePointer<sockaddr>,
addrLen: socklen_t,
context: UInt64 = 0
)
case accept(
file: FileDescriptor,
context: UInt64 = 0
)
case read(
file: FileDescriptor,
buffer: IORing.RegisteredBuffer,
@@ -55,7 +72,7 @@ internal enum IORequestCore {
)
case writeUnregistered(
file: FileDescriptor,
buffer: UnsafeMutableRawBufferPointer,
buffer: UnsafeRawBufferPointer,
offset: UInt64 = 0,
context: UInt64 = 0
)
@@ -187,6 +204,88 @@ extension IORing.Request {
.init(core: .nop)
}
/// Adds a poll operation to monitor a file descriptor for specific I/O events.
///
/// This method creates an io_uring poll operation that monitors the specified file descriptor
/// for I/O readiness events. The operation completes when any of the requested events become
/// active on the file descriptor, such as data becoming available for reading or the descriptor
/// becoming ready for writing.
///
/// Poll operations are useful for implementing efficient I/O multiplexing, allowing you to
/// monitor multiple file descriptors concurrently within a single io_uring instance. When used
/// with multishot mode, a single poll operation can deliver multiple completion events without
/// needing to be resubmitted.
///
/// ## Multishot Behavior
///
/// When `isMultiShot` is `true`, the poll operation automatically rearms after each completion
/// event, continuing to monitor the file descriptor for subsequent events. This reduces
/// submission overhead for long-lived monitoring operations. The operation continues until
/// explicitly cancelled or the file descriptor is closed.
///
/// When `isMultiShot` is `false`, the poll operation completes once after the first matching
/// event occurs, requiring resubmission to continue monitoring.
///
/// ## Example Usage
///
/// ```swift
/// // Monitor a socket for incoming connections
/// let pollRequest = IORing.Request.pollAdd(
/// listenSocket,
/// pollEvents: .pollin,
/// isMultiShot: true,
/// context: 1
/// )
/// try ring.submit(pollRequest)
///
/// // Process completions
/// for completion in try ring.completions() {
/// if completion.context == 1 {
/// // Handle incoming connection
/// }
/// }
/// ```
///
/// - Parameters:
/// - file: The file descriptor to monitor for I/O events.
/// - pollEvents: The I/O events to monitor on the file descriptor.
/// - isMultiShot: If `true`, the poll operation automatically rearms after each event,
/// continuing to monitor the file descriptor. If `false`, the operation completes after
/// the first matching event. Defaults to `true`.
/// - context: An application-specific value passed through to the completion event,
/// allowing you to identify which operation completed. Defaults to `0`.
///
/// - Returns: An I/O ring request that monitors the file descriptor for the specified events.
///
/// ## See Also
///
/// - ``PollEvents``: The events that can be monitored.
/// - ``IORing/Request/cancel(_:matching:)``: Cancelling poll operations.
@inlinable public static func pollAdd(
_ file: FileDescriptor,
pollEvents: PollEvents,
isMultiShot: Bool = true,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .pollAdd(file: file, pollEvents: pollEvents, context: context))
}
@inlinable public static func accept(
_ file: FileDescriptor,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .accept(file: file, context: context))
}
@inlinable public static func connect(
socketFD: FileDescriptor,
sockAddr: UnsafePointer<sockaddr>,
addrLen: socklen_t,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .connect(socketFD: socketFD, sockaddr: sockAddr, addrLen: addrLen, context: context))
}
@inlinable public static func read(
_ file: IORing.RegisteredFile,
into buffer: IORing.RegisteredBuffer,
@@ -252,7 +351,7 @@ extension IORing.Request {
}
@inlinable public static func write(
_ buffer: UnsafeMutableRawBufferPointer,
_ buffer: UnsafeRawBufferPointer,
into file: FileDescriptor,
at offset: UInt64 = 0,
context: UInt64 = 0
@@ -388,9 +487,7 @@ extension IORing.Request {
}
@inline(__always) @inlinable
internal consuming func makeRawRequest(
pathBuffers: PendingPathBuffers
) -> RawIORequest {
internal consuming func makeRawRequest() -> RawIORequest {
var request = RawIORequest()
switch extractCore() {
case .nop:
@@ -402,19 +499,27 @@ extension IORing.Request {
request.operation = .openAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(bitPattern: pathBuffers.pin(path)))
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
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: pathBuffers.pin(path)))
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
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
@@ -427,7 +532,7 @@ extension IORing.Request {
case .writeUnregistered(let file, let buffer, let offset, let context):
request.operation = .write
return makeRawRequest_readWrite_unregistered(
file: file, buffer: buffer, offset: offset, context: context, request: request)
file: file, buffer: UnsafeMutableRawBufferPointer(mutating: buffer), offset: offset, context: context, request: request)
case .writeUnregisteredSlot(let file, let buffer, let offset, let context):
request.operation = .write
return makeRawRequest_readWrite_unregistered_slot(
@@ -460,7 +565,12 @@ extension IORing.Request {
request.operation = .unlinkAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(bitPattern: pathBuffers.pin(path)))
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
request.rawValue.user_data = context
case .cancelContext(let flags, let targetContext):
request.operation = .asyncCancel
@@ -477,6 +587,28 @@ extension IORing.Request {
case .cancel(let flags):
request.operation = .asyncCancel
request.cancel_flags = flags
case .pollAdd(let file, let pollEvents, let isMultiShot, let context):
request.operation = .pollAdd
request.fileDescriptor = file
request.rawValue.user_data = context
if isMultiShot {
request.rawValue.len = IORING_POLL_ADD_MULTI
}
request.rawValue.poll32_events = pollEvents.rawValue
case .connect(let socketFD, let sockaddrPtr, let addrLen, let context):
request.operation = .connect
request.fileDescriptor = socketFD
request.rawValue.user_data = context
request.rawValue.addr = UInt64(UInt(bitPattern: sockaddrPtr))
request.rawValue.addr2 = UInt64(MemoryLayout<sockaddr_in>.size)
case .accept(let file, let context):
request.operation = .accept
request.fileDescriptor = file
request.rawValue.user_data = context
// For accept, we can set addr and len to 0 to ignore client address
request.rawValue.addr = 0
request.rawValue.len = 0
request.rawValue.accept_flags = 0
}
return request
+6 -54
View File
@@ -41,33 +41,6 @@ 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<CInterop.PlatformChar> {
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<Atomic<UInt32>>
@@ -227,14 +200,7 @@ private func setUpRing(
throw err
}
// 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
if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0
{
close(ringDescriptor)
throw Errno.invalidArgument
@@ -358,8 +324,6 @@ 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.
@@ -480,7 +444,6 @@ 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
@@ -802,10 +765,6 @@ 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.
@@ -831,14 +790,9 @@ 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 {
guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else {
return false
}
var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers)
let ok = _tryWriteRequest(
var raw: RawIORequest? = request.makeRawRequest()
return _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.
@@ -852,20 +806,18 @@ public struct IORing: ~Copyable {
return false
}
let last = linkedRequests.last!
var allAdded = true
for req in linkedRequests.dropLast() {
var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers)
var raw = req.makeRawRequest()
raw.linkToNextRequest()
let successfullyAdded = _tryWriteRequest(
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
allAdded = allAdded && successfullyAdded
}
let successfullyAdded = _tryWriteRequest(
last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing,
last.makeRawRequest(), ring: &submissionRing,
submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
return allAdded && successfullyAdded
return true
}
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
+59
View File
@@ -0,0 +1,59 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
extension IORing.Request {
/// A set of I/O events that can be monitored on a file descriptor.
///
/// `PollEvents` represents the event mask used with io_uring poll operations to specify
/// which I/O conditions to monitor on a file descriptor. These events correspond to the
/// standard Posix poll events defined in the kernel's `poll.h` header.
///
/// Use `PollEvents` with ``IORing/Request/pollAdd(_:pollEvents:isMultiShot:context:)``
/// to register interest in specific I/O events. The poll operation completes when any of
/// the specified events become active on the file descriptor.
///
/// ## Usage
///
/// ```swift
/// // Monitor a socket for incoming data
/// let request = IORing.Request.pollAdd(
/// socketFD,
/// pollEvents: .pollin,
/// isMultiShot: true
/// )
/// ```
public struct PollEvents: OptionSet, Hashable, Codable {
public var rawValue: UInt32
@inlinable
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
/// An event indicating data is available for reading.
///
/// This event becomes active when data arrives on the file descriptor and can be read
/// without blocking. For sockets, this includes when a new connection is available on
/// a listening socket. Corresponds to the Posix `POLLIN` event flag.
@inlinable
public static var pollin: PollEvents { PollEvents(rawValue: 0x0001) }
/// An event indicating the file descriptor is ready for writing.
///
/// This event becomes active when writing to the file descriptor will not block. For
/// sockets, this indicates that send buffer space is available. Corresponds to the
/// Posix `POLLOUT` event flag.
@inlinable
public static var pollout: PollEvents { PollEvents(rawValue: 0x0004) }
}
}
#endif
#endif
+3
View File
@@ -8,6 +8,7 @@ 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()
@@ -29,8 +30,10 @@ extension RawIORequest {
case sendMessage = 9
case receiveMessage = 10
// ...
case accept = 13
case asyncCancel = 14
case link_timeout = 15
case connect = 16
// ...
case openAt = 18
case close = 19
+1 -25
View File
@@ -81,33 +81,9 @@ public enum CInterop {
}
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
/// The C `stat` struct.
public typealias Stat = stat
/// Calls the C `stat()` function.
///
/// This is a direct wrapper around the C `stat()` system call.
/// For a more ergonomic Swift API, use `Stat` instead.
///
/// - Warning: This API is primarily intended for migration purposes when
/// supporting older deployment targets. If your deployment target supports
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
/// type-safe, ergonomic access to file metadata in Swift.
///
/// - Parameters:
/// - path: A null-terminated C string representing the file path.
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
system_stat(path, &s)
}
}
@available(System 99, *)
extension CInterop {
public typealias Stat = stat
public typealias DeviceID = dev_t
public typealias Inode = ino_t
public typealias UserID = uid_t
+3 -21
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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
@@ -619,26 +619,9 @@ 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_CLOFORK: CInt {
#if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD)
O_CLOFORK
#elseif os(FreeBSD)
FREEBSD_O_CLOFORK
#else
0
#endif
}
internal var _O_CLOEXEC: CInt { O_CLOEXEC }
#endif
@_alwaysEmitIntoClient
@@ -710,9 +693,8 @@ internal var _S_IFLNK: mode_t { S_IFLNK }
internal var _S_IFSOCK: mode_t { S_IFSOCK }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
// `S_IFWHT` is `Int32` on FreeBSD.
@_alwaysEmitIntoClient
internal var _S_IFWHT: mode_t { .init(S_IFWHT) }
internal var _S_IFWHT: mode_t { S_IFWHT }
#endif
// MARK: - stat/chflags File Flags
+1 -2
View File
@@ -91,8 +91,7 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
}
#if !os(Windows)
@available(System 0.0.2, *)
@_alwaysEmitIntoClient
@available(System 99, *)
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
stat(p, &s)
}
+2 -17
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2025 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,6 +14,7 @@ import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
import CSystem
import WASILibc
#elseif os(Windows)
import ucrt
@@ -23,8 +24,6 @@ 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
@@ -140,13 +139,6 @@ 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)
@@ -156,13 +148,6 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#endif
return pipe(fds)
}
internal func system_pipe2(_ fds: UnsafeMutablePointer<Int32>, _ 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 {
@@ -38,9 +38,9 @@ internal func open(
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE,
DWORD(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,
FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
@@ -149,12 +149,6 @@ internal func pread(
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows ReadFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -177,12 +171,6 @@ internal func pwrite(
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows WriteFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -201,18 +189,11 @@ internal func pwrite(
@inline(__always)
internal func pipe(
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 4096
) -> CInt {
return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
}
@inline(__always)
internal func csystem_posix_pipe2(
_ fds: UnsafeMutablePointer<Int32>, 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)
@@ -225,16 +206,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,
FILE_CURRENT) {
DWORD(FILE_CURRENT)) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
defer {
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN);
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN));
}
// Truncate (or extend) the file
if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN)
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN))
|| !SetEndOfFile(hFile) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
@@ -286,7 +267,7 @@ internal func rmdir(
}
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
switch errorCode {
switch Int32(errorCode) {
case ERROR_SUCCESS:
return 0
case ERROR_INVALID_FUNCTION,
@@ -365,28 +346,28 @@ fileprivate func rightsFromModeBits(
var rights: DWORD = 0
if (bits & 0o4) != 0 {
rights |= (FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
rights |= DWORD(FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
}
if (bits & 0o2) != 0 {
rights |= (FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
rights |= DWORD(FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
if fileOrDirectory == .directory && !sticky {
rights |= FILE_DELETE_CHILD
rights |= DWORD(FILE_DELETE_CHILD)
}
}
if (bits & 0o1) != 0 {
rights |= (FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
rights |= DWORD(FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
}
return rights
@@ -454,7 +435,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var everyone: PSID? = nil
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
DWORD(SECURITY_WORLD_RID),
0, 0, 0, 0, 0, 0, 0,
&everyone) else {
return nil
@@ -495,7 +476,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -508,7 +489,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -521,7 +502,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: otherRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -538,7 +519,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -556,7 +537,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -585,13 +566,13 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var descriptor = SECURITY_DESCRIPTOR()
guard InitializeSecurityDescriptor(&descriptor,
SECURITY_DESCRIPTOR_REVISION) else {
DWORD(SECURITY_DESCRIPTOR_REVISION)) else {
return nil
}
guard SetSecurityDescriptorControl(&descriptor,
SE_DACL_PROTECTED,
SE_DACL_PROTECTED)
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED),
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED))
&& SetSecurityDescriptorOwner(&descriptor, user, false)
&& SetSecurityDescriptorGroup(&descriptor, group, false)
&& SetSecurityDescriptorDacl(&descriptor,
@@ -631,15 +612,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 = CREATE_NEW
dwCreationDisposition = DWORD(CREATE_NEW)
case _O_CREAT:
dwCreationDisposition = OPEN_ALWAYS
dwCreationDisposition = DWORD(OPEN_ALWAYS)
case _O_CREAT | _O_TRUNC:
dwCreationDisposition = CREATE_ALWAYS
dwCreationDisposition = DWORD(CREATE_ALWAYS)
case _O_TRUNC:
dwCreationDisposition = TRUNCATE_EXISTING
dwCreationDisposition = DWORD(TRUNCATE_EXISTING)
default:
dwCreationDisposition = OPEN_EXISTING
dwCreationDisposition = DWORD(OPEN_EXISTING)
}
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
@@ -648,11 +629,11 @@ fileprivate struct DecodedOpenFlags {
dwDesiredAccess = 0
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
case _O_RDONLY:
dwDesiredAccess |= GENERIC_READ
dwDesiredAccess |= DWORD(GENERIC_READ)
case _O_WRONLY:
dwDesiredAccess |= GENERIC_WRITE
dwDesiredAccess |= DWORD(GENERIC_WRITE)
case _O_RDWR:
dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE)
default:
break
}
@@ -661,19 +642,19 @@ fileprivate struct DecodedOpenFlags {
dwFlagsAndAttributes = 0
if (oflag & _O_SEQUENTIAL) != 0 {
dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN)
}
if (oflag & _O_RANDOM) != 0 {
dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS)
}
if (oflag & _O_TEMPORARY) != 0 {
dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE)
}
if (oflag & _O_SHORT_LIVED) != 0 {
dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY)
} else {
dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL)
}
}
}
+3 -2
View File
@@ -145,7 +145,6 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// The underlying port right will be automatically deallocated when
/// the Mach.Port object is destroyed.
@available(System 1.4.0, *)
public init(name: mach_port_name_t, context: mach_port_context_t) {
precondition(name != mach_port_name_t(MACH_PORT_NULL),
"Mach.Port cannot be initialized with MACH_PORT_NULL")
@@ -181,6 +180,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(System 1.4.0, *)
public consuming func relinquish(
) -> (name: mach_port_name_t, context: mach_port_context_t) {
@@ -322,7 +322,7 @@ extension Mach.Port where RightType == Mach.SendRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@available(System 1.4.0, *)
@inlinable
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
@@ -365,6 +365,7 @@ extension Mach.Port where RightType == Mach.SendOnceRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(System 1.4.0, *)
public consuming func relinquish() -> mach_port_name_t {
let name = _name
-439
View File
@@ -1,439 +0,0 @@
/*
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
-45
View File
@@ -1,45 +0,0 @@
/*
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
+1 -99
View File
@@ -176,105 +176,7 @@ final class FileOperationsTest: XCTestCase {
}
}
}
#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<UInt8>(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)
#endif
func testAdHocOpen() {
// Ad-hoc test touching a file system.
@@ -19,10 +19,6 @@ 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(
@@ -47,8 +43,6 @@ final class FileOperationsTestWindows: XCTestCase {
| SYNCHRONIZE
)
private let none = ACCESS_MASK(0)
private struct Test {
var permissions: CModeT
var ownerAccess: ACCESS_MASK
@@ -78,7 +72,7 @@ final class FileOperationsTestWindows: XCTestCase {
var psidEveryone: PSID? = nil
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
DWORD(SECURITY_WORLD_RID),
0, 0, 0, 0, 0, 0, 0,
&psidEveryone))
defer {
@@ -112,7 +106,7 @@ final class FileOperationsTestWindows: XCTestCase {
&psidGroup,
&pDacl,
nil,
&pSD), ERROR_SUCCESS)
&pSD), DWORD(ERROR_SUCCESS))
defer {
LocalFree(pSD)
}
@@ -141,15 +135,15 @@ final class FileOperationsTestWindows: XCTestCase {
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&owner,
&ownerAccess), ERROR_SUCCESS)
&ownerAccess), DWORD(ERROR_SUCCESS))
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&group,
&groupAccess), ERROR_SUCCESS)
&groupAccess), DWORD(ERROR_SUCCESS))
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&everyone,
&otherAccess), ERROR_SUCCESS)
&otherAccess), DWORD(ERROR_SUCCESS))
return (ownerAccess, groupAccess, otherAccess)
}
@@ -188,9 +182,9 @@ final class FileOperationsTestWindows: XCTestCase {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|x, none),
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|x, 0),
Test(0o777, r|w|x, r|x, r|x)
]
@@ -201,9 +195,9 @@ final class FileOperationsTestWindows: XCTestCase {
.otherWrite, .otherExecute]) {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r, none),
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r, 0),
Test(0o777, r|w|x, r, r)
]
@@ -220,81 +214,34 @@ final class FileOperationsTestWindows: XCTestCase {
try FilePermissions.withCreationMask([]) {
try withTemporaryFilePath(basename: "testPermissions") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o000, 0, 0, 0),
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(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(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|w|x, none),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|w|x, 0),
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, none, none, r|w|x),
Test(0o070, none, r|w|x, none),
Test(0o077, none, r|w|x, r|w|x),
Test(0o007, 0, 0, r|w|x),
Test(0o070, 0, r|w|x, 0),
Test(0o077, 0, r|w|x, r|w|x),
]
try runTests(tests, at: path)
}
}
}
/// Test that buffer sizes exceeding DWORD.max (4GB) are properly rejected
func testBufferSizeLimit() throws {
try withTemporaryFilePath(basename: "testBufferSizeLimit") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"),
.readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
defer { try? fd.close() }
// Write some data first
try fd.writeAll("test data".utf8)
// Allocate a small buffer for testing
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 1)
defer { buffer.deallocate() }
// Test that a count exceeding DWORD.max (UInt32.max = 4,294,967,295) returns EINVAL
// We use a buffer pointer but pass a count > DWORD.max
let oversizedCount = Int(DWORD.max) + 1
let oversizedBuffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress,
count: oversizedCount
)
// pread should fail with EINVAL
do {
_ = try fd.read(fromAbsoluteOffset: 0, into: oversizedBuffer)
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// pwrite should also fail with EINVAL
do {
_ = try fd.write(toAbsoluteOffset: 0, UnsafeRawBufferPointer(oversizedBuffer))
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// Verify that exactly DWORD.max works (if we had a buffer that large)
// We can't easily test this without allocating 4GB, but the boundary is correct
}
}
}
#endif // os(Windows)
+1 -2
View File
@@ -22,8 +22,7 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
// which are known to work correctly.
final class IORequestTests: XCTestCase {
func testNop() {
let req = IORing.Request.nop().makeRawRequest(
pathBuffers: PendingPathBuffers(reservedCapacity: 0))
let req = IORing.Request.nop().makeRawRequest()
let sourceBytes = requestBytes(req)
// convenient property of nop: it's all zeros!
// for some unknown reason, liburing sets the fd field to -1.
+44 -61
View File
@@ -122,85 +122,68 @@ final class IORingTests: XCTestCase {
let bytesRead = try nonRingFD.read(into: rawBuffer)
XCTAssert(bytesRead == 13)
let result2 = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result2, "Hello, World!")
XCTAssertEqual(result2, "Hello, World!")
try cleanUpHelloWorldFile(parent)
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 {
func testPollAddPollIn() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
var ring = try IORing(queueDepth: 6)
var ring = try IORing(queueDepth: 32, flags: [])
func enqueueOpen() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly))
XCTAssertTrue(ok)
// Test POLLIN: Create an eventfd to monitor for read readiness
let testEventFD = FileDescriptor(rawValue: eventfd(0, 0))
defer {
// Clean up
try! testEventFD.close()
}
enqueueOpen()
let pollInContext: UInt64 = 42
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
// Submit a pollAdd request to monitor for POLLIN events (data available for reading)
let enqueued = try ring.submit(linkedRequests:
.pollAdd(testEventFD, pollEvents: .pollin, isMultiShot: false, context: pollInContext))
XCTAssert(enqueued)
// Write to the eventfd to trigger the POLLIN event
var value: UInt64 = 1
withUnsafeBytes(of: &value) { bufferPtr in
_ = try? testEventFD.write(bufferPtr)
}
for buf in churn { buf.deallocate() }
churn.removeAll()
try ring.submitPreparedRequests()
// Consume the completion from the poll operation
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)
XCTAssertEqual(completion.context, pollInContext)
XCTAssertGreaterThan(completion.result, 0) // Poll should return mask of ready events
}
func testPathBufferLifetimeAcrossLinkedRequests() throws {
func testPollAddPollOut() 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])
var ring = try IORing(queueDepth: 32, flags: [])
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)
// Test POLLOUT: Create a pipe to monitor for write readiness
var pipeFDs: [Int32] = [0, 0]
let pipeResult = pipe(&pipeFDs)
XCTAssertEqual(pipeResult, 0)
let writeFD = FileDescriptor(rawValue: pipeFDs[1])
let readFD = FileDescriptor(rawValue: pipeFDs[0])
defer {
// Clean up
try! writeFD.close()
try! readFD.close()
}
enqueueLinkedReadback()
let pollOutContext: UInt64 = 43
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() }
// Submit a pollAdd request to monitor for POLLOUT events (ready for writing)
// Pipes are typically ready for writing when empty
let enqueuedOut = try ring.submit(linkedRequests:
.pollAdd(writeFD, pollEvents: .pollout, isMultiShot: false, context: pollOutContext))
XCTAssert(enqueuedOut)
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()
// Consume the completion from the poll operation
let completionOut = try ring.blockingConsumeCompletion()
XCTAssertEqual(completionOut.context, pollOutContext)
XCTAssertGreaterThan(completionOut.result, 0) // Poll should return mask of ready events
}
}
#endif // os(Linux)
+11 -10
View File
@@ -118,7 +118,7 @@ private struct StatTests {
#expect(targetStat.type == .regular)
#expect(symlinkStat.type == .symbolicLink)
#expect(symlinkStat.size < targetStat.size)
#expect(symlinkStat.sizeAllocated <= targetStat.sizeAllocated)
#expect(symlinkStat.sizeAllocated < targetStat.sizeAllocated)
// Set each .st_atim back to its original value for comparison
@@ -368,11 +368,14 @@ private struct StatTests {
]
#elseif os(FreeBSD)
let userSettableFlags: FileFlags = [
.noDump, .hidden, .offline,
.readOnly, .sparse, .system
// The following flags throw EPERM on ZFS.
// .userImmutable, .userAppend, .opaque,
// .userNoUnlink, .reparse,
.noDump, .userImmutable, .userAppend,
.opaque, .tracked, .hidden,
.userNoUnlink,
.offline,
.readOnly,
.reparse,
.sparse,
.system
]
#else // os(OpenBSD)
let userSettableFlags: FileFlags = [
@@ -381,15 +384,13 @@ private struct StatTests {
#endif
flags.insert(userSettableFlags)
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
try #require(fchflags(fd.rawValue, flags.rawValue) == 0, "\(Errno.current)")
stat = try fd.stat()
#expect(stat.flags == flags)
flags.remove(userSettableFlags)
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
try #require(fchflags(fd.rawValue, flags.rawValue) == 0, "\(Errno.current)")
stat = try fd.stat()
#expect(stat.flags == flags)