mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
199
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff97796848 | ||
|
|
fc55a43b0c | ||
|
|
b01fd78b91 | ||
|
|
486d48c80f | ||
|
|
95ed6aa2a4 | ||
|
|
cbf57d4575 | ||
|
|
c3b7f2a48e | ||
|
|
74a7b6f618 | ||
|
|
e6796eb47d | ||
|
|
b0d4217c8c | ||
|
|
85e911cd30 | ||
|
|
65f43f5d57 | ||
|
|
b62bce1bc4 | ||
|
|
6843adad5a | ||
|
|
4699556133 | ||
|
|
1c80f27aef | ||
|
|
59b5659a1e | ||
|
|
dc65a924d9 | ||
|
|
3b8124e350 | ||
|
|
241fedcbbd | ||
|
|
1b452c2996 | ||
|
|
869129b7bf | ||
|
|
5c2854d7bd | ||
|
|
6dc13544bb | ||
|
|
d0ef8d091d | ||
|
|
79b7490ae9 | ||
|
|
c5c1a835d6 | ||
|
|
27bc5e7e8d | ||
|
|
c49268ed91 | ||
|
|
704705c5c5 | ||
|
|
16cfbd4f8b | ||
|
|
755a5b4b3d | ||
|
|
6485260369 | ||
|
|
d4e86324e9 | ||
|
|
29b14a3025 | ||
|
|
6a63f086f6 | ||
|
|
b9e0ecaa60 | ||
|
|
6e3259aec3 | ||
|
|
d4373e36f6 | ||
|
|
a6d4c153b7 | ||
|
|
4df226b098 | ||
|
|
a2ca84e281 | ||
|
|
980a71f20c | ||
|
|
bd49600d62 | ||
|
|
0ecb080d5c | ||
|
|
bed8e28860 | ||
|
|
2e81d94142 | ||
|
|
75c85d47e7 | ||
|
|
5b7e24a6b1 | ||
|
|
6baba54adb | ||
|
|
27b4a4a03a | ||
|
|
8ac955bde7 | ||
|
|
617edb8398 | ||
|
|
5db65c3086 | ||
|
|
2159235ef0 | ||
|
|
dd5313284d | ||
|
|
2a069e401b | ||
|
|
e775d1bf59 | ||
|
|
e4b352c650 | ||
|
|
ab11b74b39 | ||
|
|
353a48d98d | ||
|
|
aa7ed87b5f | ||
|
|
73067f8221 | ||
|
|
a352b4c224 | ||
|
|
cd18a372c0 | ||
|
|
0d9e29baa0 | ||
|
|
4966bcbf8b | ||
|
|
71be76265f | ||
|
|
90a174256e | ||
|
|
a9597cc068 | ||
|
|
50688cacbd | ||
|
|
bd155c104f | ||
|
|
52930bf6be | ||
|
|
7c072c0d97 | ||
|
|
5d61ccdc7e | ||
|
|
2b266acf85 | ||
|
|
101cc809ba | ||
|
|
0b30161977 | ||
|
|
b349ff8c05 | ||
|
|
7cb32eb7a4 | ||
|
|
a6515006f5 | ||
|
|
7edc09a749 | ||
|
|
03604ffcd9 | ||
|
|
2d0912acba | ||
|
|
16cdb0d008 | ||
|
|
e2ae946862 | ||
|
|
f05c1d815d | ||
|
|
0601f0edec | ||
|
|
a10991ab88 | ||
|
|
b5544ba79a | ||
|
|
dda389ed2b | ||
|
|
d3c632e868 | ||
|
|
326260ee3b | ||
|
|
d5f004e6f1 | ||
|
|
38cd4aaf65 | ||
|
|
41de235573 | ||
|
|
efc401eb32 | ||
|
|
73da907161 | ||
|
|
124e17164c | ||
|
|
d7ca4a9e4c | ||
|
|
4a55025558 | ||
|
|
8771bb6199 | ||
|
|
e927959165 | ||
|
|
f52438c1b8 | ||
|
|
636e14a3d2 | ||
|
|
7c504cabbf | ||
|
|
0b7fc03c76 | ||
|
|
a7e7c56fec | ||
|
|
c124911240 | ||
|
|
a17caca7af | ||
|
|
1cfd5105b2 | ||
|
|
76a2dc6162 | ||
|
|
e0aa78a944 | ||
|
|
1494bb89fc | ||
|
|
e358151f96 | ||
|
|
e7723528a1 | ||
|
|
58bce128ce | ||
|
|
5b670937e3 | ||
|
|
74bc402c95 | ||
|
|
96c5f3b852 | ||
|
|
776989a955 | ||
|
|
671bd1a573 | ||
|
|
69ba2cd76e | ||
|
|
ede51c41cb | ||
|
|
64545cfc87 | ||
|
|
7502b711c9 | ||
|
|
abcf8e31b3 | ||
|
|
0a3460f369 | ||
|
|
c50ad26d06 | ||
|
|
666fba77fc | ||
|
|
360e6f70f0 | ||
|
|
e402d5fa38 | ||
|
|
1bd796b6b9 | ||
|
|
7e888c0cb4 | ||
|
|
d937d15735 | ||
|
|
8af20f00ab | ||
|
|
9a8bef12be | ||
|
|
e60d362ada | ||
|
|
b7b66845da | ||
|
|
4fdc665a0f | ||
|
|
3e0b318176 | ||
|
|
a2bc5f0625 | ||
|
|
2cc89c12b3 | ||
|
|
e59002fa14 | ||
|
|
ebbbc31709 | ||
|
|
c6cc06d24d | ||
|
|
669763cfd5 | ||
|
|
6fa5c8a6c1 | ||
|
|
2cae953181 | ||
|
|
03453849a2 | ||
|
|
0d7feaa50c | ||
|
|
34f4970c1c | ||
|
|
2986958695 | ||
|
|
30d09ac188 | ||
|
|
686feb3a39 | ||
|
|
56dad9d66e | ||
|
|
929b835515 | ||
|
|
26f8c4f195 | ||
|
|
de8779fb3d | ||
|
|
491b97c7c0 | ||
|
|
814d09c7ea | ||
|
|
61280ab365 | ||
|
|
cc4afd1a71 | ||
|
|
348b497836 | ||
|
|
0323dff7db | ||
|
|
4d2c21f6b3 | ||
|
|
45e26e7cc1 | ||
|
|
9554473133 | ||
|
|
c0fa05b225 | ||
|
|
51d396093d | ||
|
|
6d25d11066 | ||
|
|
cb63c9a073 | ||
|
|
4471eaa313 | ||
|
|
f86edc7020 | ||
|
|
71db29e931 | ||
|
|
043bda4234 | ||
|
|
4278ed8d97 | ||
|
|
cf6956a19a | ||
|
|
91bd99f29a | ||
|
|
7c0af0ded6 | ||
|
|
7e474cb4bd | ||
|
|
b0e5ec8932 | ||
|
|
538ae25062 | ||
|
|
fb3c3abebf | ||
|
|
f6b96c3ba7 | ||
|
|
7c6ad0fc39 | ||
|
|
13851a3421 | ||
|
|
8f8d80a4fe | ||
|
|
608a75b962 | ||
|
|
0dbbab4aa1 | ||
|
|
2eb655e0b7 | ||
|
|
53afbde6ab | ||
|
|
07a3f090d7 | ||
|
|
dda2b535b7 | ||
|
|
0ed3416369 | ||
|
|
766415499c | ||
|
|
097805e869 | ||
|
|
e65f5a6cad | ||
|
|
0dcedcb7bb |
No files matched your search
@@ -10,7 +10,7 @@ on:
|
||||
jobs:
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.15
|
||||
with:
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
|
||||
enable_linux_checks: true
|
||||
@@ -19,10 +19,13 @@ 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-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_macos_checks: true
|
||||
@@ -31,7 +34,8 @@ jobs:
|
||||
windows_exclude_swift_versions: |
|
||||
[
|
||||
{"swift_version": "5.9"},
|
||||
{"swift_version": "5.10"}
|
||||
{"swift_version": "5.10"},
|
||||
{"swift_version": "6.0"},
|
||||
]
|
||||
enable_linux_static_sdk_build: true
|
||||
linux_static_sdk_exclude_swift_versions: |
|
||||
@@ -40,6 +44,8 @@ jobs:
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_wasm_sdk_build: true
|
||||
@@ -49,17 +55,17 @@ jobs:
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_android_sdk_build: true
|
||||
android_exclude_swift_versions: |
|
||||
[
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_android_sdk_checks: true
|
||||
enable_freebsd_checks: true
|
||||
|
||||
build-abi-stable:
|
||||
name: Build ABI Stable
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.15
|
||||
with:
|
||||
enable_linux_checks: false
|
||||
enable_macos_checks: true
|
||||
@@ -70,9 +76,43 @@ jobs:
|
||||
# Enable availability to match ABI stable verion of system.
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE"
|
||||
|
||||
cmake_build:
|
||||
name: CMake Validation
|
||||
runs-on: ubuntu-latest
|
||||
container: swiftlang/swift:nightly-main-noble
|
||||
steps:
|
||||
- name: Copy Sources
|
||||
uses: actions/checkout@v6
|
||||
- name: Install Dependencies
|
||||
shell: bash
|
||||
run: apt update && apt install -y cmake ninja-build jq
|
||||
- name: Configure Project
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p build/.cmake/api/v1/query
|
||||
touch build/.cmake/api/v1/query/codemodel-v2
|
||||
cmake -G 'Ninja' -B build -S . -DCMAKE_C_COMPILER=clang -DCMAKE_Swift_COMPILER=swiftc -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=YES
|
||||
- name: Validate CMake File Lists
|
||||
shell: bash
|
||||
run: |
|
||||
swift package describe --type json > /tmp/swiftpm.json
|
||||
cat build/.cmake/api/v1/reply/target-SystemPackage-*.json > /tmp/cmake.json
|
||||
jq '.targets[] | select(.name == "SystemPackage") | .sources[]' /tmp/swiftpm.json | sort > /tmp/swiftpm-list.txt
|
||||
jq '.sources[].path[15:]' /tmp/cmake.json | sort > /tmp/cmake-list.txt
|
||||
comm -23 /tmp/swiftpm-list.txt /tmp/cmake-list.txt > /tmp/missing.txt
|
||||
if [ -s /tmp/missing.txt ]; then
|
||||
echo "::error::SystemPackage CMakeLists.txt does not match SwiftPM. Missing sources:"
|
||||
cat /tmp/missing.txt
|
||||
exit 1
|
||||
fi
|
||||
echo "::notice::SystemPackage CMakeLists.txt matches SwiftPM"
|
||||
- name: Build Project with CMake
|
||||
shell: bash
|
||||
run: cmake --build build
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.15
|
||||
with:
|
||||
license_header_check_project_name: "Swift.org"
|
||||
# https://github.com/apple/swift-system/issues/224
|
||||
|
||||
@@ -13,6 +13,8 @@ project(SwiftSystem
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
set(CMAKE_Swift_LANGUAGE_VERSION 6)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
# Code of Conduct
|
||||
|
||||
To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.
|
||||
|
||||
To give clarity of what is expected of our members, this code of conduct is based on [contributor-covenant.org](http://contributor-covenant.org). This document is used across many open source communities, and we think it articulates our values well.
|
||||
|
||||
### Contributor Code of Conduct v1.4
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language (e.g., prefer non-gendered words like “folks” to “guys”, non-ableist words like “soundness check” to “sanity check”, etc.)
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others’ private information, such as a physical or electronic address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
This Code of Conduct applies within all project spaces managed by Swift.org, including (but not limited to) source code repositories, bug trackers, web sites, documentation, and online forums. It also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a member of the [Swift Core Team](https://swift.org/community/#community-structure) or by flagging the behavior for moderation (e.g., in the Forums), whether you are the target of that behavior or not. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. The site of the disputed behavior is usually not an acceptable place to discuss moderation decisions, and moderators may move or remove any such discussion.
|
||||
|
||||
Project maintainers are held to a higher standard, and project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
|
||||
If you disagree with a moderation action, you can appeal to the Core Team (or individual Core Team members) privately.
|
||||
|
||||
This policy is adapted from the Contributor Code of Conduct [version 1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/).
|
||||
+52
-43
@@ -1,9 +1,9 @@
|
||||
// swift-tools-version:6.0
|
||||
// swift-tools-version:6.1
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
@@ -12,57 +12,59 @@
|
||||
|
||||
import PackageDescription
|
||||
|
||||
struct Availability {
|
||||
struct Available {
|
||||
var name: String
|
||||
var version: String
|
||||
var osAvailability: String
|
||||
var sourceAvailability: String
|
||||
|
||||
var minSwiftPMVersions: String {
|
||||
"macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0"
|
||||
}
|
||||
var minSpanDeploymentVersions: String {
|
||||
"macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0"
|
||||
init(
|
||||
_ version: String,
|
||||
_ osAvailability: String
|
||||
) {
|
||||
self.name = "System"
|
||||
self.version = version
|
||||
self.osAvailability = osAvailability
|
||||
self.sourceAvailability = "macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0"
|
||||
}
|
||||
|
||||
var isStandardAvailability: Bool { name == "System" }
|
||||
var swiftSetting: SwiftSetting {
|
||||
#if SYSTEM_ABI_STABLE
|
||||
// Use availability matching Darwin API.
|
||||
let availability = self.osAvailability
|
||||
#else
|
||||
// Use availability matching SwiftPM default.
|
||||
let availability = self.sourceAvailability
|
||||
#endif
|
||||
return .enableExperimentalFeature(
|
||||
"AvailabilityMacro=\(self.name) \(version):\(availability)")
|
||||
}
|
||||
}
|
||||
|
||||
let availabilityMap: [(String, String)] = [
|
||||
("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
|
||||
("0.0.2", "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0"),
|
||||
("1.1.0", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
|
||||
("1.2.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
let availability: [Available] = [
|
||||
Available("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
|
||||
|
||||
("99", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("0.0.2", "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0"),
|
||||
|
||||
Available("0.0.3", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
|
||||
Available("1.1.0", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
|
||||
|
||||
Available("1.1.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
Available("1.2.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
|
||||
Available("1.2.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
Available("1.3.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
|
||||
|
||||
Available("1.3.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
Available("1.3.2", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
Available("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
|
||||
Available("1.7.0", "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0"),
|
||||
|
||||
Available("199", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
]
|
||||
|
||||
let availabilities: [Availability] =
|
||||
availabilityMap.map {
|
||||
Availability(name: "System", version: $0.0, osAvailability: $0.1)
|
||||
} + availabilityMap.prefix(5).map {
|
||||
Availability(name: "SystemWithSpan", version: $0.0, osAvailability: $0.1)
|
||||
}
|
||||
|
||||
let swiftSettingsAvailability = availabilities.map {
|
||||
availability -> SwiftSetting in
|
||||
let osVersionList: String
|
||||
#if SYSTEM_ABI_STABLE
|
||||
// Use availability matching Darwin API.
|
||||
osVersionList = availability.osAvailability
|
||||
#else
|
||||
if availability.isStandardAvailability {
|
||||
// Use availability matching SwiftPM minimum.
|
||||
osVersionList = availability.minSwiftPMVersions
|
||||
} else {
|
||||
// Use availability matching Span deployment minimum.
|
||||
osVersionList = availability.minSpanDeploymentVersions
|
||||
}
|
||||
#endif
|
||||
return .enableExperimentalFeature(
|
||||
"AvailabilityMacro=\(availability.name) \(availability.version):\(osVersionList)"
|
||||
)
|
||||
}
|
||||
let swiftSettingsAvailability = availability.map(\.swiftSetting)
|
||||
|
||||
#if SYSTEM_CI
|
||||
let swiftSettingsCI: [SwiftSetting] = [
|
||||
@@ -79,6 +81,7 @@ let swiftSettings = swiftSettingsAvailability + swiftSettingsCI + [
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug)),
|
||||
.enableExperimentalFeature("Lifetimes"),
|
||||
.enableUpcomingFeature("MemberImportVisibility"),
|
||||
]
|
||||
|
||||
let cSettings: [CSetting] = [
|
||||
@@ -139,6 +142,12 @@ let package = Package(
|
||||
exclude: testsToExclude,
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
// Builds a SystemPackage consumer with MemberImportVisibility enabled.
|
||||
// Fails if a C member of a vended type is attributed to the CSystem module.
|
||||
.testTarget(
|
||||
name: "MemberImportVisibility",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]),
|
||||
.target(
|
||||
name: "SystemSockets",
|
||||
dependencies: ["SystemPackage", "CSystem"],
|
||||
@@ -160,5 +169,5 @@ let package = Package(
|
||||
path: "Sources/Samples",
|
||||
swiftSettings: swiftSettings),
|
||||
],
|
||||
swiftLanguageVersions: [.v5]
|
||||
swiftLanguageModes: [.v6]
|
||||
)
|
||||
@@ -79,7 +79,7 @@ These initializers use a typed `throws(Errno)` and require Swift 6.0 or later.
|
||||
|
||||
See the **Appendix** section at the end of this proposal for a table view of Swift API to C mappings.
|
||||
|
||||
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability.
|
||||
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability, except `Stat`'s `==` and `hash(into:)`, which are ordinary `public` API.
|
||||
|
||||
### FileType
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -693,24 +693,27 @@ public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number is used to distinguish between different files
|
||||
/// that have used the same inode over time.
|
||||
/// The file generation number may be used to distinguish between different
|
||||
/// files that have used the same inode over time.
|
||||
///
|
||||
/// The corresponding C property is `st_gen`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
public var generationNumber: Int { get set }
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
|
||||
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
|
||||
public var generationNumber: UInt64 { get set }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
extension Stat: Equatable {
|
||||
/// Compares the raw bytes of two `Stat` structs for equality.
|
||||
/// Compares the meaningful file-metadata fields of two `Stat` values.
|
||||
///
|
||||
/// Alignment padding and platform reserved/"spare" fields are not compared.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool
|
||||
}
|
||||
|
||||
extension Stat: Hashable {
|
||||
/// Hashes the raw bytes of this `Stat` struct.
|
||||
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
|
||||
public func hash(into hasher: inout Hasher)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor`
|
||||
|
||||
* Proposal: SYS-0007
|
||||
* Authors: 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:)`
|
||||
* **v3** Add Darwin versions of `dup3` and `pipe2` wrappers
|
||||
|
||||
## 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, Android, and the Apple operating systems based on Darwin 27.0 or newer; `pipe(options:)` will also be available on Windows.
|
||||
|
||||
## 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 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 defense 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 = try 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.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options. On Windows, the
|
||||
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
|
||||
/// but this overload disables it when called with an empty option set.
|
||||
///
|
||||
/// - 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 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
|
||||
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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`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.
|
||||
@@ -0,0 +1,262 @@
|
||||
# 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.
|
||||
@@ -32,7 +32,7 @@ To use the `SystemPackage` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.8.0"),
|
||||
```
|
||||
|
||||
Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
@@ -41,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.8.0"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
@@ -87,7 +87,8 @@ The following table maps existing package releases to their minimum required Swi
|
||||
| Package version | Swift version | Xcode release |
|
||||
| ----------------------- | --------------- | ------------- |
|
||||
| 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.4.0 through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 |
|
||||
| swift-system 1.7.0 through 1.8.x | >= Swift 6.1 | >= Xcode 16.3 |
|
||||
|
||||
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so.
|
||||
|
||||
@@ -107,20 +108,22 @@ We maintain separate branches for each active minor version of the package:
|
||||
|
||||
| Package version | Branch |
|
||||
| ----------------------- | ----------- |
|
||||
| swift-system 1.3.x | release/1.3 |
|
||||
| swift-system 1.4.x | release/1.4 |
|
||||
| swift-system 1.5.x | release/1.5 |
|
||||
| swift-system 1.6.x | release/1.6 |
|
||||
| swift-system 1.7.x (unreleased) | main |
|
||||
| swift-system 1.3.x | release/1.3.0 |
|
||||
| swift-system 1.4.x | release/1.4.0 |
|
||||
| swift-system 1.5.x | release/1.5.0 |
|
||||
| swift-system 1.6.x | release/1.6.0 |
|
||||
| swift-system 1.7.x | release/1.7.0 |
|
||||
| swift-system 1.8.x | release/1.8.x |
|
||||
| swift-system 1.9.x (unreleased) | |
|
||||
|
||||
Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction:
|
||||
|
||||
`release/1.3` → `release/1.4` → `main`
|
||||
`release/1.7.0` → `release/1.8.x` → `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.)
|
||||
For example, anything landing on `release/1.6.0` will eventually appear on `release/1.7.0`, then `release/1.8.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.)
|
||||
|
||||
### Code of Conduct
|
||||
|
||||
Like all Swift.org projects, we would like the Swift System project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc].
|
||||
|
||||
[coc]: CODE_OF_CONDUCT.md
|
||||
[coc]: https://github.com/apple/.github/blob/main/CODE_OF_CONDUCT.md
|
||||
@@ -1,20 +1,25 @@
|
||||
#[[
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(CSystem INTERFACE)
|
||||
target_include_directories(CSystem INTERFACE
|
||||
add_library(CSystem STATIC shims.c)
|
||||
target_include_directories(CSystem PUBLIC
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
||||
$<INSTALL_INTERFACE:include/CSystem>)
|
||||
|
||||
install(FILES
|
||||
include/CSystemDarwin.h
|
||||
include/CSystemLinux.h
|
||||
include/CSystemShared.h
|
||||
include/CSystemWASI.h
|
||||
include/CSystemWindows.h
|
||||
include/CSystemFreeBSD.h
|
||||
include/io_uring.h
|
||||
include/module.modulemap
|
||||
DESTINATION include/CSystem)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
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(__APPLE__)
|
||||
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifdef O_CLOFORK
|
||||
#define COMPATIBILITY_O_CLOFORK O_CLOFORK
|
||||
#else
|
||||
#define COMPATIBILITY_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#endif // defined(__APPLE__)
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
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 COMPATIBILITY_O_CLOFORK O_CLOFORK
|
||||
#else
|
||||
#define COMPATIBILITY_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#endif // defined(__FreeBSD__)
|
||||
@@ -11,13 +11,11 @@
|
||||
|
||||
#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>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if !defined(_WIN32)
|
||||
extern int csystem_posix_pipe2(int fildes[2], int flag);
|
||||
#endif
|
||||
|
||||
extern int csystem_posix_dup3(int fildes, int fildes2, int flag);
|
||||
@@ -81,7 +81,7 @@
|
||||
#ifdef IORING_TIMEOUT_BOOTTIME
|
||||
// Kernel version >= 5.15, io_uring_sqe has file_index
|
||||
// and all current Swift operations are supported.
|
||||
#define __SWIFT_IORING_SUPPORTED true
|
||||
#define __SWIFT_IORING_SUPPORTED 1
|
||||
typedef struct io_uring_sqe swift_io_uring_sqe;
|
||||
#else
|
||||
// io_uring_sqe is missing properties that IORequest expects.
|
||||
@@ -89,7 +89,7 @@ typedef struct io_uring_sqe swift_io_uring_sqe;
|
||||
//
|
||||
// Define a fallback struct to avoid build errors, but IORing
|
||||
// will throw ENOTSUP on initialization.
|
||||
#define __SWIFT_IORING_SUPPORTED false
|
||||
#define __SWIFT_IORING_SUPPORTED 0
|
||||
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
#endif
|
||||
|
||||
@@ -107,13 +107,14 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
// Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK)
|
||||
#include <stdint.h>
|
||||
|
||||
#define __SWIFT_IORING_SUPPORTED false
|
||||
#define __SWIFT_IORING_SUPPORTED 0
|
||||
|
||||
#define IORING_OFF_SQ_RING 0ULL
|
||||
#define IORING_OFF_CQ_RING 0x8000000ULL
|
||||
#define IORING_OFF_SQES 0x10000000ULL
|
||||
|
||||
#define IORING_ENTER_GETEVENTS (1U << 0)
|
||||
#define IORING_ENTER_GETEVENTS (1U << 0)
|
||||
#define IORING_ENTER_EXT_ARG (1U << 3)
|
||||
|
||||
#define IORING_FEAT_SINGLE_MMAP (1U << 0)
|
||||
#define IORING_FEAT_NODROP (1U << 1)
|
||||
@@ -235,7 +236,7 @@ static inline int io_uring_enter2(int fd, unsigned int to_submit, unsigned int m
|
||||
unsigned int flags, void *args, size_t sz)
|
||||
{
|
||||
return syscall(__NR_io_uring_enter, fd, to_submit, min_complete,
|
||||
flags, args, _NSIG / 8);
|
||||
flags, args, sz);
|
||||
}
|
||||
|
||||
static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
module CSystem {
|
||||
header "CSystemShared.h"
|
||||
header "CSystemDarwin.h"
|
||||
header "CSystemLinux.h"
|
||||
header "CSystemWASI.h"
|
||||
header "CSystemWindows.h"
|
||||
header "CSystemFreeBSD.h"
|
||||
export *
|
||||
}
|
||||
+57
-3
@@ -1,18 +1,72 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if defined(__FreeBSD__)
|
||||
#define __BSD_VISIBLE
|
||||
#endif
|
||||
#if defined(__FreeBSD__) || defined(__OpenBSD__)
|
||||
#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
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#include <Availability.h>
|
||||
#if defined(__MAC_27_0)
|
||||
#include <unistd.h>
|
||||
#define HAVE_PIPE2_DUP3
|
||||
#endif
|
||||
#endif // defined(__APPLE__)
|
||||
|
||||
// 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) {
|
||||
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
|
||||
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
|
||||
return pipe2(fildes, flag);
|
||||
__builtin_trap();
|
||||
#elif defined(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) {
|
||||
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
|
||||
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
|
||||
return dup3(fildes, fildes2, flag);
|
||||
__builtin_trap();
|
||||
#elif defined(HAVE_PIPE2_DUP3)
|
||||
return dup3(fildes, fildes2, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
@@ -24,7 +24,6 @@ struct Connect: ParsableCommand {
|
||||
@Option(name: .shortAndLong, help: "Message to send")
|
||||
var message: String = "Hello from swift-system sockets!"
|
||||
|
||||
@available(System 99, *)
|
||||
func run() throws {
|
||||
print("Resolving \(host)...")
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ struct Listen: ParsableCommand {
|
||||
@Option(name: .shortAndLong, help: "Maximum number of connections to accept (0 for unlimited)")
|
||||
var maxConnections: Int = 0
|
||||
|
||||
@available(System 99, *)
|
||||
func run() throws {
|
||||
// Create socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
|
||||
@@ -27,7 +27,6 @@ struct Resolve: ParsableCommand {
|
||||
@Flag(name: .long, help: "Show only IPv6 addresses")
|
||||
var ipv6Only: Bool = false
|
||||
|
||||
@available(System 99, *)
|
||||
func run() throws {
|
||||
let family: SocketDescriptor.Domain?
|
||||
if ipv4Only {
|
||||
@@ -74,7 +73,6 @@ struct Resolve: ParsableCommand {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
private func familyName(_ domain: SocketDescriptor.Domain) -> String {
|
||||
switch domain {
|
||||
case .ipv4: return "IPv4"
|
||||
@@ -84,7 +82,6 @@ struct Resolve: ParsableCommand {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
private func typeName(_ type: SocketDescriptor.ConnectionType) -> String {
|
||||
switch type {
|
||||
case .stream: return "Stream (TCP)"
|
||||
@@ -94,7 +91,6 @@ struct Resolve: ParsableCommand {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
private func protocolName(_ proto: SocketDescriptor.ProtocolID) -> String {
|
||||
switch proto {
|
||||
case .tcp: return "TCP"
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
@available(System 99, *)
|
||||
struct ReverseResolve: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Reverse resolve an IP address to a hostname using getnameinfo"
|
||||
|
||||
@@ -13,11 +13,12 @@ import SystemSockets
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
// Glibc declares `stdin`, `stdout` and `stderr` as mutable globals.
|
||||
@preconcurrency import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
@preconcurrency import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
@preconcurrency import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -36,7 +37,6 @@ internal func complain(_ message: String) {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress.ResolvedAddress {
|
||||
var niceDescription: String {
|
||||
var proto = ""
|
||||
@@ -49,7 +49,6 @@ extension SocketAddress.ResolvedAddress {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
var niceDescription: String {
|
||||
if let ipv4 = self.ipv4 { return ipv4.description }
|
||||
@@ -59,7 +58,6 @@ extension SocketAddress {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor.ConnectionType {
|
||||
var isConnectionless: Bool {
|
||||
self == .datagram || self == .reliablyDeliveredMessage
|
||||
|
||||
@@ -10,9 +10,7 @@
|
||||
import ArgumentParser
|
||||
|
||||
struct SystemSamples: ParsableCommand {
|
||||
|
||||
@available(System 99, *)
|
||||
static var configuration = CommandConfiguration(
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "system-samples",
|
||||
abstract: "A collection of little programs exercising some System features.",
|
||||
subcommands: [
|
||||
|
||||
@@ -9,6 +9,7 @@ See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
add_library(SystemPackage
|
||||
Errno.swift
|
||||
ErrnoWindows.swift
|
||||
FileDescriptor.swift
|
||||
FileHelpers.swift
|
||||
FileOperations.swift
|
||||
@@ -18,9 +19,32 @@ add_library(SystemPackage
|
||||
SystemString.swift
|
||||
Util.swift
|
||||
Util+StringArray.swift
|
||||
UtilConsumers.swift)
|
||||
UtilConsumers.swift
|
||||
WinSDK+Overlay.swift)
|
||||
set_target_properties(SystemPackage PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
# Availability macro definitions.
|
||||
# Should stay in sync with the `availability` array in Package.swift,
|
||||
# matching `sourceAvailability`, which is the minimum Swift availability.
|
||||
# Availability support for Darwin platforms is omitted.
|
||||
set(SWIFT_SYSTEM_AVAILABILITY_VERSIONS
|
||||
0.0.1 0.0.2 0.0.3
|
||||
1.1.0 1.1.1 1.2.0 1.2.1 1.3.0 1.3.1 1.3.2 1.4.0
|
||||
1.7.0
|
||||
199)
|
||||
set(SWIFT_SYSTEM_SOURCE_AVAILABILITY
|
||||
"macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0")
|
||||
set(SWIFT_SYSTEM_AVAILABILITY_MACRO)
|
||||
foreach(version IN LISTS SWIFT_SYSTEM_AVAILABILITY_VERSIONS)
|
||||
list(APPEND SWIFT_SYSTEM_AVAILABILITY_MACRO
|
||||
"SHELL:-enable-experimental-feature \"AvailabilityMacro=System ${version}:${SWIFT_SYSTEM_SOURCE_AVAILABILITY}\"")
|
||||
endforeach()
|
||||
|
||||
target_compile_options(SystemPackage PRIVATE
|
||||
-enable-experimental-feature Lifetimes
|
||||
${SWIFT_SYSTEM_AVAILABILITY_MACRO}
|
||||
"SHELL:-package-name swift-system")
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePath.swift
|
||||
FilePath/FilePathComponents.swift
|
||||
@@ -28,7 +52,25 @@ target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePathParsing.swift
|
||||
FilePath/FilePathString.swift
|
||||
FilePath/FilePathSyntax.swift
|
||||
FilePath/FilePathTemp.swift
|
||||
FilePath/FilePathTempPosix.swift
|
||||
FilePath/FilePathTempWindows.swift
|
||||
FilePath/FilePathWindows.swift)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FileSystem/FileFlags.swift
|
||||
FileSystem/FileMode.swift
|
||||
FileSystem/FileType.swift
|
||||
FileSystem/Identifiers.swift
|
||||
FileSystem/Stat.swift)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
IORing/IOCompletion.swift
|
||||
IORing/IORequest.swift
|
||||
IORing/IORing.swift
|
||||
IORing/IORing+Util.swift
|
||||
IORing/PollEvents.swift
|
||||
IORing/RawIORequest.swift)
|
||||
endif()
|
||||
target_sources(SystemPackage PRIVATE
|
||||
Internals/Backcompat.swift
|
||||
Internals/CInterop.swift
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2024 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
|
||||
@@ -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 dosn't have any existing child processes
|
||||
/// by a process that doesn't have any existing child processes
|
||||
/// or whose child processes are all already being waited for.
|
||||
///
|
||||
/// The corresponding C error is `ECHILD`.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -301,17 +301,14 @@ extension FileDescriptor {
|
||||
public static var O_EVTONLY: OpenOptions { eventOnly }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
/// across calls to the `exec(2)` family of functions.
|
||||
/// If you specify this option,
|
||||
/// the file descriptor is closed when replacing this process
|
||||
/// with another process.
|
||||
/// If you specify this option, the system closes the file
|
||||
/// descriptor when replacing this process with another process.
|
||||
///
|
||||
/// The state of the file
|
||||
/// descriptor flags can be inspected using `F_GETFD`,
|
||||
/// You can inspect the file descriptor flag state using `F_GETFD`,
|
||||
/// as described in the `fcntl(2)` man page.
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
@@ -321,6 +318,135 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_CLOEXEC: OpenOptions { closeOnExec }
|
||||
|
||||
#if os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_NOINHERIT: OpenOptions { closeOnExec }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Options that specify behavior for a newly-created pipe.
|
||||
@frozen
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
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 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -398,7 +524,6 @@ extension FileDescriptor {
|
||||
@available(*, unavailable, renamed: "nextData")
|
||||
public static var SEEK_DATA: SeekOrigin { nextData }
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 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
|
||||
@@ -20,7 +20,6 @@ extension FileDescriptor {
|
||||
/// If `body` throws an error
|
||||
/// or an error occurs while closing the file descriptor,
|
||||
/// this method rethrows that error.
|
||||
@available(System 0.0.1, *)
|
||||
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
|
||||
// No underscore helper, since the closure's throw isn't necessarily typed.
|
||||
let result: R
|
||||
@@ -50,7 +49,6 @@ extension FileDescriptor {
|
||||
/// If `sequence` doesn't implement
|
||||
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
|
||||
/// temporary space will be allocated as needed.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func writeAll<S: Sequence>(
|
||||
@@ -64,25 +62,18 @@ extension FileDescriptor {
|
||||
_ sequence: S
|
||||
) -> Result<Int, Errno> where S.Element == UInt8 {
|
||||
sequence._withRawBufferPointer { buffer in
|
||||
_writeAllBuffer(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _writeAllBuffer(
|
||||
_ buffer: UnsafeRawBufferPointer
|
||||
) -> Result<Int, Errno> {
|
||||
var idx = 0
|
||||
while idx < buffer.count {
|
||||
switch _write(
|
||||
UnsafeRawBufferPointer(rebasing: buffer[idx...]), retryOnInterrupt: true
|
||||
) {
|
||||
case .success(let numBytes): idx += numBytes
|
||||
case .failure(let err): return .failure(err)
|
||||
var idx = 0
|
||||
while idx < buffer.count {
|
||||
switch _write(
|
||||
UnsafeRawBufferPointer(rebasing: buffer[idx...]), retryOnInterrupt: true
|
||||
) {
|
||||
case .success(let numBytes): idx += numBytes
|
||||
case .failure(let err): return .failure(err)
|
||||
}
|
||||
}
|
||||
assert(idx == buffer.count)
|
||||
return .success(buffer.count)
|
||||
}
|
||||
assert(idx == buffer.count)
|
||||
return .success(buffer.count)
|
||||
}
|
||||
|
||||
/// Writes a sequence of bytes to the given offset.
|
||||
@@ -100,7 +91,6 @@ extension FileDescriptor {
|
||||
/// If `sequence` doesn't implement
|
||||
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
|
||||
/// temporary space will be allocated as needed.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func writeAll<S: Sequence>(
|
||||
@@ -109,159 +99,24 @@ extension FileDescriptor {
|
||||
try _writeAll(toAbsoluteOffset: offset, sequence).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal func _writeAll<S: Sequence>(
|
||||
toAbsoluteOffset offset: Int64, _ sequence: S
|
||||
) -> Result<Int, Errno> where S.Element == UInt8 {
|
||||
sequence._withRawBufferPointer { buffer in
|
||||
_writeAllBuffer(toAbsoluteOffset: offset, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _writeAllBuffer(
|
||||
toAbsoluteOffset offset: Int64, _ buffer: UnsafeRawBufferPointer
|
||||
) -> Result<Int, Errno> {
|
||||
var idx = 0
|
||||
while idx < buffer.count {
|
||||
switch _write(
|
||||
toAbsoluteOffset: offset + Int64(idx),
|
||||
UnsafeRawBufferPointer(rebasing: buffer[idx...]),
|
||||
retryOnInterrupt: true
|
||||
) {
|
||||
case .success(let numBytes): idx += numBytes
|
||||
case .failure(let err): return .failure(err)
|
||||
var idx = 0
|
||||
while idx < buffer.count {
|
||||
switch _write(
|
||||
toAbsoluteOffset: offset + Int64(idx),
|
||||
UnsafeRawBufferPointer(rebasing: buffer[idx...]),
|
||||
retryOnInterrupt: true
|
||||
) {
|
||||
case .success(let numBytes): idx += numBytes
|
||||
case .failure(let err): return .failure(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(idx == buffer.count)
|
||||
return .success(buffer.count)
|
||||
}
|
||||
|
||||
#if compiler(>=6.2)
|
||||
/// Writes the entire contents of a buffer, retrying on partial writes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: The region of memory that contains the data being written.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were written.
|
||||
///
|
||||
/// After writing,
|
||||
/// this method increments the file's offset by the number of bytes written.
|
||||
/// To change the file's offset,
|
||||
/// call the ``seek(offset:from:)`` method.
|
||||
///
|
||||
/// The corresponding C function is `write`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func writeAll(
|
||||
_ data: RawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
try data.withUnsafeBytes { buffer throws(Errno) -> Int in
|
||||
try _writeAllBuffer(buffer).get()
|
||||
assert(idx == buffer.count)
|
||||
return .success(buffer.count)
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the entire contents of a buffer at the specified offset,
|
||||
/// retrying on partial writes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The file offset where writing begins.
|
||||
/// - data: The region of memory that contains the data being written.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were written.
|
||||
///
|
||||
/// Unlike ``writeAll(_:retryOnInterrupt:)``,
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pwrite`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func writeAll(
|
||||
toAbsoluteOffset offset: Int64,
|
||||
_ data: RawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
try data.withUnsafeBytes { buffer throws(Errno) -> Int in
|
||||
try _writeAllBuffer(toAbsoluteOffset: offset, buffer).get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads bytes into a buffer, retrying until it is full.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The region of memory to read into.
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// After reading,
|
||||
/// this method increments the file's offset by the number of bytes read.
|
||||
/// To change the file's offset,
|
||||
/// call the ``seek(offset:from:)`` method.
|
||||
///
|
||||
/// The corresponding C function is `read`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func read(
|
||||
filling buffer: inout OutputRawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
let originalCapacity = buffer.freeCapacity
|
||||
while buffer.freeCapacity > 0 {
|
||||
let bytesRead = try read(into: &buffer, retryOnInterrupt: retryOnInterrupt)
|
||||
if bytesRead == 0 {
|
||||
break // EOF
|
||||
}
|
||||
}
|
||||
return originalCapacity - buffer.freeCapacity
|
||||
}
|
||||
|
||||
/// Reads bytes at the specified offset into a buffer,
|
||||
/// retrying until it is full.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The file offset where reading begins.
|
||||
/// - buffer: The region of memory to read into.
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// Unlike ``read(filling:retryOnInterrupt:)``,
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pread`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func read(
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
filling buffer: inout OutputRawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
let originalCapacity = buffer.freeCapacity
|
||||
var currentOffset = offset
|
||||
while buffer.freeCapacity > 0 {
|
||||
let bytesRead = try read(fromAbsoluteOffset: currentOffset, into: &buffer, retryOnInterrupt: retryOnInterrupt)
|
||||
if bytesRead == 0 {
|
||||
break // EOF
|
||||
}
|
||||
currentOffset += Int64(bytesRead)
|
||||
}
|
||||
return originalCapacity - buffer.freeCapacity
|
||||
}
|
||||
#endif // swift(>=6.2)
|
||||
}
|
||||
+135
-176
@@ -16,6 +16,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -23,7 +25,6 @@ extension FileDescriptor {
|
||||
/// - Returns: A file descriptor for the open file
|
||||
///
|
||||
/// The corresponding C function is `open`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ path: FilePath,
|
||||
@@ -56,6 +57,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -63,7 +66,6 @@ extension FileDescriptor {
|
||||
/// - Returns: A file descriptor for the open file
|
||||
///
|
||||
/// The corresponding C function is `open`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
@@ -77,7 +79,6 @@ extension FileDescriptor {
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal static func _open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
@@ -91,8 +92,10 @@ extension FileDescriptor {
|
||||
if let permissions = permissions {
|
||||
return system_open(path, oFlag, permissions.rawValue)
|
||||
}
|
||||
precondition(!options.contains(.create),
|
||||
"Create must be given permissions")
|
||||
if options.contains(.create) {
|
||||
fatalError(
|
||||
"FileDescriptor.open: 'permissions' must not be nil when 'options' contains '.create'")
|
||||
}
|
||||
return system_open(path, oFlag)
|
||||
}
|
||||
return descOrError.map { FileDescriptor(rawValue: $0) }
|
||||
@@ -105,6 +108,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -151,7 +156,6 @@ extension FileDescriptor {
|
||||
/// the object will be deactivated.
|
||||
///
|
||||
/// The corresponding C function is `close`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func close() throws { try _close().get() }
|
||||
|
||||
@@ -169,7 +173,6 @@ extension FileDescriptor {
|
||||
/// in bytes from the beginning of the file.
|
||||
///
|
||||
/// The corresponding C function is `lseek`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func seek(
|
||||
@@ -178,7 +181,6 @@ extension FileDescriptor {
|
||||
try _seek(offset: offset, from: whence).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal func _seek(
|
||||
offset: Int64, from whence: FileDescriptor.SeekOrigin
|
||||
@@ -216,7 +218,6 @@ extension FileDescriptor {
|
||||
/// call the ``seek(offset:from:)`` method.
|
||||
///
|
||||
/// The corresponding C function is `read`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func read(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
@@ -225,12 +226,11 @@ extension FileDescriptor {
|
||||
try _read(into: buffer, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal func _read(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<Int, Errno> {
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_read(self.rawValue, buffer.baseAddress, buffer.count)
|
||||
}
|
||||
@@ -254,7 +254,6 @@ extension FileDescriptor {
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pread`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func read(
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
@@ -268,7 +267,6 @@ extension FileDescriptor {
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal func _read(
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
@@ -309,7 +307,6 @@ extension FileDescriptor {
|
||||
/// call the ``seek(offset:from:)`` method.
|
||||
///
|
||||
/// The corresponding C function is `write`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func write(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
@@ -318,7 +315,6 @@ extension FileDescriptor {
|
||||
try _write(buffer, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal func _write(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
@@ -344,7 +340,6 @@ extension FileDescriptor {
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pwrite`.
|
||||
@available(System 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func write(
|
||||
toAbsoluteOffset offset: Int64,
|
||||
@@ -354,7 +349,6 @@ extension FileDescriptor {
|
||||
try _write(toAbsoluteOffset: offset, buffer, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
@usableFromInline
|
||||
internal func _write(
|
||||
toAbsoluteOffset offset: Int64,
|
||||
@@ -379,164 +373,18 @@ extension FileDescriptor {
|
||||
buffer,
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
#if compiler(>=6.2)
|
||||
/// Writes the contents of a buffer at the current file offset.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: The region of memory that contains the data being written.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were written.
|
||||
///
|
||||
/// After writing,
|
||||
/// this method increments the file's offset by the number of bytes written.
|
||||
/// To change the file's offset,
|
||||
/// call the ``seek(offset:from:)`` method.
|
||||
///
|
||||
/// The corresponding C function is `write`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func write(
|
||||
_ data: RawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
try data.withUnsafeBytes { bytes throws(Errno) -> Int in
|
||||
try _write(bytes, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the contents of a buffer at the specified offset.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The file offset where writing begins.
|
||||
/// - data: The region of memory that contains the data being written.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were written.
|
||||
///
|
||||
/// Unlike ``write(_:retryOnInterrupt:)``,
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pwrite`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func write(
|
||||
toAbsoluteOffset offset: Int64,
|
||||
_ data: RawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
try data.withUnsafeBytes { bytes throws(Errno) -> Int in
|
||||
try _write(toAbsoluteOffset: offset, bytes, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _readIntoOutputBuffer(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
initializedCount: inout Int,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
// Read into the uninitialized portion (starting at offset 'initializedCount')
|
||||
let uninitializedPortion = UnsafeMutableRawBufferPointer(
|
||||
start: buffer.baseAddress?.advanced(by: initializedCount),
|
||||
count: buffer.count - initializedCount
|
||||
)
|
||||
do {
|
||||
let result = try _read(into: uninitializedPortion, retryOnInterrupt: retryOnInterrupt)
|
||||
if case .success(let bytesRead) = result {
|
||||
initializedCount += bytesRead // Add to existing count, don't replace it!
|
||||
}
|
||||
return result
|
||||
} catch {
|
||||
fatalError("Unexpected error from _read")
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads bytes at the current file offset into a buffer.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The region of memory to read into.
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// After reading,
|
||||
/// this method increments the file's offset by the number of bytes read.
|
||||
/// To change the file's offset,
|
||||
/// call the ``seek(offset:from:)`` method.
|
||||
///
|
||||
/// The corresponding C function is `read`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func read(
|
||||
into buffer: inout OutputRawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
try buffer.withUnsafeMutableBytes { buf, count throws(Errno) -> Int in
|
||||
try _readIntoOutputBuffer(buf, initializedCount: &count, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads bytes at the specified offset into a buffer.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The file offset where reading begins.
|
||||
/// - buffer: The region of memory to read into.
|
||||
/// - retryOnInterrupt: Whether to retry the read operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// Unlike ``read(into:retryOnInterrupt:)``,
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pread`.
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func read(
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
into buffer: inout OutputRawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
do {
|
||||
return try buffer.withUnsafeMutableBytes { buf, count in
|
||||
// Read into the uninitialized portion (starting at offset 'count')
|
||||
let uninitializedPortion = UnsafeMutableRawBufferPointer(
|
||||
start: buf.baseAddress?.advanced(by: count),
|
||||
count: buf.count - count
|
||||
)
|
||||
let bytesRead = try read(fromAbsoluteOffset: offset, into: uninitializedPortion, retryOnInterrupt: retryOnInterrupt)
|
||||
count += bytesRead // Add to existing count, don't replace it!
|
||||
return bytesRead
|
||||
}
|
||||
} catch let error as Errno {
|
||||
throw error
|
||||
} catch {
|
||||
fatalError("Unexpected error type")
|
||||
}
|
||||
}
|
||||
#endif // compiler(>=6.2)
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@available(System 0.0.2, *)
|
||||
extension FileDescriptor {
|
||||
/// Duplicates this file descriptor and return the newly created copy.
|
||||
/// Duplicates this file descriptor and returns the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
/// the copy is assigned to the file descriptor with the lowest raw value
|
||||
/// that is not currently in use by the process.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// - retryOnInterrupt: Whether to retry the duplicate 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.
|
||||
@@ -555,7 +403,6 @@ extension FileDescriptor {
|
||||
///
|
||||
/// However, each file descriptor maintains its own close-on-exec flag.
|
||||
///
|
||||
///
|
||||
/// The corresponding C functions are `dup` and `dup2`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(System 0.0.2, *)
|
||||
@@ -566,17 +413,77 @@ 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 is 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`.
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func duplicate(
|
||||
as target: FileDescriptor,
|
||||
options: DuplicateOptions,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> FileDescriptor {
|
||||
let result = _duplicate(
|
||||
as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor?,
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<FileDescriptor, Errno> {
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
if let target = target {
|
||||
return system_dup2(self.rawValue, target.rawValue)
|
||||
if let target {
|
||||
system_dup2(self.rawValue, target.rawValue)
|
||||
} else {
|
||||
system_dup(self.rawValue)
|
||||
}
|
||||
return system_dup(self.rawValue)
|
||||
}.map(FileDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor,
|
||||
options: Int32,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_dup3(self.rawValue, target.rawValue, options)
|
||||
}.map(FileDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
@@ -591,26 +498,57 @@ extension FileDescriptor {
|
||||
public func dup2() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "duplicate")
|
||||
public func dup3() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
#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, the
|
||||
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
|
||||
/// but this overload disables it when called with an empty option set.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - options: The behavior for creating the pipe.
|
||||
///
|
||||
/// - Returns: The pair of file descriptors.
|
||||
///
|
||||
/// The corresponding C function is `pipe2`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
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
|
||||
@@ -620,8 +558,29 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@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
|
||||
#endif // !os(WASI)
|
||||
|
||||
@available(System 1.2.0, *)
|
||||
extension FileDescriptor {
|
||||
@@ -710,4 +669,4 @@ extension FilePermissions {
|
||||
return system_umask(mode)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
@@ -461,7 +461,10 @@ extension String {
|
||||
public init(decoding path: FilePath) {
|
||||
self.init(_decoding: path)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string from a file path, validating its contents as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
///
|
||||
@@ -470,6 +473,7 @@ extension String {
|
||||
///
|
||||
/// If the contents of the file path isn't a well-formed Unicode string,
|
||||
/// this initializer returns `nil`.
|
||||
@available(System 0.0.2, *)
|
||||
public init?(validating path: FilePath) {
|
||||
self.init(_validating: path)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,21 @@
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
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 & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 {
|
||||
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 {
|
||||
let name = withUnsafeBytes(of: findData.cFileName) {
|
||||
return SystemString(platformString: $0.assumingMemoryBound(
|
||||
to: CInterop.PlatformChar.self).baseAddress!)
|
||||
@@ -94,7 +94,7 @@ internal func _recursiveRemove(
|
||||
let component = FilePath.Component(name)!
|
||||
let subpath = path.appending(component)
|
||||
|
||||
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 {
|
||||
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 {
|
||||
try subpath.withPlatformString { subpath in
|
||||
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
|
||||
@@ -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 DWORD(ERROR_SUCCESS) }
|
||||
if SUCCEEDED(hr) { return ERROR_SUCCESS }
|
||||
if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
|
||||
return HRESULT_CODE(hr)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 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
|
||||
@@ -45,7 +45,7 @@
|
||||
///
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -14,7 +14,7 @@
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C mode.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 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
|
||||
@@ -34,7 +34,7 @@
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw file-type bits from the C mode.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 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
|
||||
@@ -12,7 +12,7 @@
|
||||
#if !os(Windows)
|
||||
/// A Swift wrapper of the C `uid_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `uid_t`.
|
||||
@@ -30,7 +30,7 @@ public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// A Swift wrapper of the C `gid_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `gid_t`.
|
||||
@@ -48,7 +48,7 @@ public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// A Swift wrapper of the C `dev_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `dev_t`.
|
||||
@@ -66,7 +66,7 @@ public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// A Swift wrapper of the C `ino_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `ino_t`.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 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
|
||||
@@ -35,7 +35,7 @@ import Android
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C `stat` struct.
|
||||
@@ -521,42 +521,93 @@ public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number is used to distinguish between different files
|
||||
/// that have used the same inode over time.
|
||||
/// The file generation number may be used to distinguish between different
|
||||
/// files that have used the same inode over time.
|
||||
///
|
||||
/// The corresponding C property is `st_gen`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
|
||||
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var generationNumber: Int {
|
||||
get { Int(rawValue.st_gen) }
|
||||
set { rawValue.st_gen = numericCast(newValue)}
|
||||
public var generationNumber: UInt64 {
|
||||
get { UInt64(rawValue.st_gen) }
|
||||
set { rawValue.st_gen = numericCast(newValue) }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension Stat: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
/// Compares the raw bytes of two `Stat` structs for equality.
|
||||
/// Compares the meaningful file-metadata fields of two `Stat` values.
|
||||
///
|
||||
/// Alignment padding and platform reserved/"spare" fields are not compared.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
return withUnsafeBytes(of: lhs.rawValue) { lhsBytes in
|
||||
withUnsafeBytes(of: rhs.rawValue) { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
guard lhs.rawValue.st_dev == rhs.rawValue.st_dev,
|
||||
lhs.rawValue.st_ino == rhs.rawValue.st_ino,
|
||||
lhs.rawValue.st_mode == rhs.rawValue.st_mode,
|
||||
lhs.rawValue.st_nlink == rhs.rawValue.st_nlink,
|
||||
lhs.rawValue.st_uid == rhs.rawValue.st_uid,
|
||||
lhs.rawValue.st_gid == rhs.rawValue.st_gid,
|
||||
lhs.rawValue.st_rdev == rhs.rawValue.st_rdev,
|
||||
lhs.rawValue.st_size == rhs.rawValue.st_size,
|
||||
lhs.rawValue.st_blksize == rhs.rawValue.st_blksize,
|
||||
lhs.rawValue.st_blocks == rhs.rawValue.st_blocks,
|
||||
lhs.st_atim.tv_sec == rhs.st_atim.tv_sec,
|
||||
lhs.st_atim.tv_nsec == rhs.st_atim.tv_nsec,
|
||||
lhs.st_mtim.tv_sec == rhs.st_mtim.tv_sec,
|
||||
lhs.st_mtim.tv_nsec == rhs.st_mtim.tv_nsec,
|
||||
lhs.st_ctim.tv_sec == rhs.st_ctim.tv_sec,
|
||||
lhs.st_ctim.tv_nsec == rhs.st_ctim.tv_nsec else {
|
||||
return false
|
||||
}
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
guard lhs.st_birthtim.tv_sec == rhs.st_birthtim.tv_sec,
|
||||
lhs.st_birthtim.tv_nsec == rhs.st_birthtim.tv_nsec else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
guard lhs.rawValue.st_flags == rhs.rawValue.st_flags,
|
||||
lhs.rawValue.st_gen == rhs.rawValue.st_gen else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension Stat: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
/// Hashes the raw bytes of this `Stat` struct.
|
||||
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
|
||||
///
|
||||
/// These are the same fields compared by `==`, fed in the same order.
|
||||
/// Alignment padding and platform reserved/"spare" fields are not hashed.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
withUnsafeBytes(of: rawValue) { bytes in
|
||||
hasher.combine(bytes: bytes)
|
||||
}
|
||||
hasher.combine(rawValue.st_dev)
|
||||
hasher.combine(rawValue.st_ino)
|
||||
hasher.combine(rawValue.st_mode)
|
||||
hasher.combine(rawValue.st_nlink)
|
||||
hasher.combine(rawValue.st_uid)
|
||||
hasher.combine(rawValue.st_gid)
|
||||
hasher.combine(rawValue.st_rdev)
|
||||
hasher.combine(rawValue.st_size)
|
||||
hasher.combine(rawValue.st_blksize)
|
||||
hasher.combine(rawValue.st_blocks)
|
||||
hasher.combine(st_atim.tv_sec)
|
||||
hasher.combine(st_atim.tv_nsec)
|
||||
hasher.combine(st_mtim.tv_sec)
|
||||
hasher.combine(st_mtim.tv_nsec)
|
||||
hasher.combine(st_ctim.tv_sec)
|
||||
hasher.combine(st_ctim.tv_nsec)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
hasher.combine(st_birthtim.tv_sec)
|
||||
hasher.combine(st_birthtim.tv_nsec)
|
||||
#endif
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
hasher.combine(rawValue.st_flags)
|
||||
hasher.combine(rawValue.st_gen)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -564,7 +615,7 @@ extension Stat: Hashable {
|
||||
|
||||
// MARK: - FileDescriptor Extensions
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension FileDescriptor {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
|
||||
@@ -580,7 +631,7 @@ extension FileDescriptor {
|
||||
|
||||
// MARK: - FilePath Extensions
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension FilePath {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 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
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
@@ -45,12 +54,27 @@ public extension IORing.Completion {
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of the completed operation.
|
||||
///
|
||||
/// A non-negative value is the operation's success result: a byte count
|
||||
/// for a read or a write, an event mask for a poll, and so on.
|
||||
///
|
||||
/// A negative value is an `errno` code multiplied by -1. Recover the error
|
||||
/// by negating it again: `Errno(rawValue: -completion.result)`, or use
|
||||
/// ``error``.
|
||||
@inlinable var result: Int32 {
|
||||
get {
|
||||
rawValue.res
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of the completed operation, or `nil` if the operation succeeded.
|
||||
@inlinable var error: Errno? {
|
||||
get {
|
||||
rawValue.res < 0 ? Errno(rawValue: -rawValue.res) : nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var flags: IORing.Completion.Flags {
|
||||
get {
|
||||
Flags(rawValue: rawValue.flags & 0x0000FFFF)
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
@@ -23,6 +32,12 @@ internal enum IORequestCore {
|
||||
intoSlot: IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case pollAdd(
|
||||
file: FileDescriptor,
|
||||
events: IORing.Request.PollEvents,
|
||||
isMultiShot: Bool = false,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case read(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
@@ -99,6 +114,51 @@ internal enum IORequestCore {
|
||||
flags: UInt32,
|
||||
target: IORing.RegisteredFile
|
||||
)
|
||||
case socket(
|
||||
domain: CInt,
|
||||
type: CInt,
|
||||
protocol: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case connect(
|
||||
socket: FileDescriptor,
|
||||
address: PendingSocketAddress,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case bind(
|
||||
socket: FileDescriptor,
|
||||
address: PendingSocketAddress,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case listen(
|
||||
socket: FileDescriptor,
|
||||
backlog: UInt32,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case accept(
|
||||
socket: FileDescriptor,
|
||||
peerAddress: UnsafeMutablePointer<sockaddr>?,
|
||||
peerAddressLength: UnsafeMutablePointer<socklen_t>?,
|
||||
flags: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case send(
|
||||
socket: FileDescriptor,
|
||||
buffer: UnsafeRawBufferPointer,
|
||||
flags: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case receive(
|
||||
socket: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case shutdown(
|
||||
socket: FileDescriptor,
|
||||
how: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
@@ -187,6 +247,118 @@ extension IORing.Request {
|
||||
.init(core: .nop)
|
||||
}
|
||||
|
||||
// Poll
|
||||
|
||||
/// Multishot poll: the poll handler continues to report CQEs on behalf
|
||||
/// of the same SQE, each flagged with
|
||||
/// ``IORing/Completion/Flags/moreCompletions``.
|
||||
///
|
||||
/// Corresponds to `IORING_POLL_ADD_MULTI`. Note that since
|
||||
/// `sqe->poll_events` is the event space, the command flags for
|
||||
/// `POLL_ADD` are stored in `sqe->len`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_POLL_ADD_MULTI: UInt32 { 1 << 0 }
|
||||
|
||||
/// 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 occur 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.
|
||||
///
|
||||
/// Poll requests on a ring created with
|
||||
/// ``IORing/SetupFlags/pollCompletions`` fail with
|
||||
/// ``Errno/invalidArgument``.
|
||||
///
|
||||
/// ## 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 poll stays armed until it's canceled or the
|
||||
/// kernel ends it; its last completion is the one without
|
||||
/// ``IORing/Completion/Flags/moreCompletions``. Neither a hangup nor
|
||||
/// closing the descriptor ends the poll, and the request keeps the file
|
||||
/// open until the poll ends.
|
||||
///
|
||||
/// 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
|
||||
/// var ring = try IORing(queueDepth: 32)
|
||||
/// let pollRequest = IORing.Request.pollAdd(
|
||||
/// listenSocket,
|
||||
/// events: .readable,
|
||||
/// isMultiShot: true,
|
||||
/// context: 1
|
||||
/// )
|
||||
/// guard try ring.submit(linkedRequests: pollRequest) else {
|
||||
/// // The submission queue was full; retry or drain completions first.
|
||||
/// return
|
||||
/// }
|
||||
///
|
||||
/// // Process completions. A multishot poll stays armed while its
|
||||
/// // completions contain `.moreCompletions`.
|
||||
/// var armed = true
|
||||
/// while armed {
|
||||
/// let completion = try ring.blockingConsumeCompletion()
|
||||
/// guard completion.context == 1 else {
|
||||
/// // Handle completions for other requests.
|
||||
/// continue
|
||||
/// }
|
||||
/// armed = completion.flags.contains(.moreCompletions)
|
||||
/// if let error = completion.error {
|
||||
/// // The poll ended with an error, such as `.canceled`.
|
||||
/// throw error
|
||||
/// }
|
||||
/// // Handle incoming connection
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If the poll ends with an error, such as ``Errno/canceled``, its last
|
||||
/// completion carries that error in ``IORing/Completion/error`` and
|
||||
/// doesn't contain `.moreCompletions`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - file: The file descriptor to monitor for I/O events.
|
||||
/// - events: 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 `false`.
|
||||
/// - 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:)-(_,FileDescriptor)``:
|
||||
/// Canceling poll operations.
|
||||
@inlinable public static func pollAdd(
|
||||
_ file: FileDescriptor,
|
||||
events: PollEvents,
|
||||
isMultiShot: Bool = false,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .pollAdd(file: file, events: events, isMultiShot: isMultiShot, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: IORing.RegisteredFile,
|
||||
into buffer: IORing.RegisteredBuffer,
|
||||
@@ -316,24 +488,46 @@ extension IORing.Request {
|
||||
|
||||
// Cancel
|
||||
|
||||
/*
|
||||
* ASYNC_CANCEL flags.
|
||||
*
|
||||
* IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key
|
||||
* IORING_ASYNC_CANCEL_FD Key off 'fd' for cancellation rather than the
|
||||
* request 'user_data'
|
||||
* IORING_ASYNC_CANCEL_ANY Match any request
|
||||
* IORING_ASYNC_CANCEL_FD_FIXED 'fd' passed in is a fixed descriptor
|
||||
* IORING_ASYNC_CANCEL_USERDATA Match on user_data, default for no other key
|
||||
* IORING_ASYNC_CANCEL_OP Match request based on opcode
|
||||
*/
|
||||
/// Cancel every request matching the given key.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_ALL`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 }
|
||||
|
||||
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 }
|
||||
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 }
|
||||
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 }
|
||||
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 }
|
||||
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 }
|
||||
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 }
|
||||
/// Cancel any request matching the given file descriptor.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_FD`. Cannot be combined with
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_ANY``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 }
|
||||
|
||||
/// Cancel any matching request, disregarding every other key.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_ANY`. Cannot be combined with
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_FD`` or ``SWIFT_IORING_ASYNC_CANCEL_OP``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 }
|
||||
|
||||
/// Cancel any request matching a registered file.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_FD_FIXED`, and accompanies
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_FD``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 }
|
||||
|
||||
/// Cancel requests matching the `user_data`. This is the default when no other
|
||||
/// key is given.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_USERDATA`.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 }
|
||||
|
||||
/// Cancel requests matching the operation.
|
||||
///
|
||||
/// Corresponds to `IORING_ASYNC_CANCEL_OP`. Cannot be combined with
|
||||
/// ``SWIFT_IORING_ASYNC_CANCEL_ANY``.
|
||||
@_alwaysEmitIntoClient
|
||||
internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 }
|
||||
|
||||
public enum CancellationMatch {
|
||||
case all
|
||||
@@ -388,7 +582,9 @@ extension IORing.Request {
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal consuming func makeRawRequest() -> RawIORequest {
|
||||
internal consuming func makeRawRequest(
|
||||
pathBuffers: PendingPathBuffers
|
||||
) -> RawIORequest {
|
||||
var request = RawIORequest()
|
||||
switch extractCore() {
|
||||
case .nop:
|
||||
@@ -400,27 +596,19 @@ extension IORing.Request {
|
||||
request.operation = .openAt
|
||||
request.fileDescriptor = atDirectory
|
||||
request.rawValue.addr = UInt64(
|
||||
UInt(
|
||||
bitPattern: path.withPlatformString { ptr in
|
||||
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
|
||||
}))
|
||||
UInt(bitPattern: pathBuffers.pin(path)))
|
||||
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
|
||||
request.rawValue.len = permissions?.rawValue ?? 0
|
||||
request.rawValue.file_index = UInt32(fileSlot.index + 1)
|
||||
request.path = path
|
||||
request.rawValue.user_data = context
|
||||
case .openat(
|
||||
let atDirectory, let path, let mode, let options, let permissions, let context):
|
||||
request.operation = .openAt
|
||||
request.fileDescriptor = atDirectory
|
||||
request.rawValue.addr = UInt64(
|
||||
UInt(
|
||||
bitPattern: path.withPlatformString { ptr in
|
||||
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
|
||||
}))
|
||||
UInt(bitPattern: pathBuffers.pin(path)))
|
||||
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
|
||||
request.rawValue.len = permissions?.rawValue ?? 0
|
||||
request.path = path
|
||||
request.rawValue.user_data = context
|
||||
case .write(let file, let buffer, let offset, let context):
|
||||
request.operation = .writeFixed
|
||||
@@ -466,12 +654,7 @@ extension IORing.Request {
|
||||
request.operation = .unlinkAt
|
||||
request.fileDescriptor = atDirectory
|
||||
request.rawValue.addr = UInt64(
|
||||
UInt(
|
||||
bitPattern: path.withPlatformString { ptr in
|
||||
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
|
||||
})
|
||||
)
|
||||
request.path = path
|
||||
UInt(bitPattern: pathBuffers.pin(path)))
|
||||
request.rawValue.user_data = context
|
||||
case .cancelContext(let flags, let targetContext):
|
||||
request.operation = .asyncCancel
|
||||
@@ -488,10 +671,160 @@ extension IORing.Request {
|
||||
case .cancel(let flags):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
case .pollAdd(let file, let events, let isMultiShot, let context):
|
||||
request.operation = .pollAdd
|
||||
request.fileDescriptor = file
|
||||
request.rawValue.user_data = context
|
||||
if isMultiShot {
|
||||
request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI
|
||||
}
|
||||
request.pollEvents = events
|
||||
case .socket(let domain, let type, let `protocol`, let context):
|
||||
request.operation = .socket
|
||||
request.rawValue.fd = domain
|
||||
request.rawValue.off = UInt64(UInt32(bitPattern: type))
|
||||
request.rawValue.len = UInt32(bitPattern: `protocol`)
|
||||
request.rawValue.user_data = context
|
||||
case .connect(let socket, let address, let context):
|
||||
request.operation = .connect
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: pathBuffers.pin(address)))
|
||||
request.rawValue.addr2 = UInt64(address.length)
|
||||
request.rawValue.user_data = context
|
||||
case .bind(let socket, let address, let context):
|
||||
request.operation = .bind
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: pathBuffers.pin(address)))
|
||||
request.rawValue.addr2 = UInt64(address.length)
|
||||
request.rawValue.user_data = context
|
||||
case .listen(let socket, let backlog, let context):
|
||||
request.operation = .listen
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.len = backlog
|
||||
request.rawValue.user_data = context
|
||||
case .accept(let socket, let peerAddress, let peerAddressLength, let flags, let context):
|
||||
request.operation = .accept
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: peerAddress))
|
||||
request.rawValue.addr2 = UInt64(UInt(bitPattern: peerAddressLength))
|
||||
request.rawValue.accept_flags = UInt32(bitPattern: flags)
|
||||
request.rawValue.user_data = context
|
||||
case .send(let socket, let buffer, let flags, let context):
|
||||
request.operation = .send
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: buffer.baseAddress))
|
||||
request.rawValue.len = UInt32(exactly: buffer.count)!
|
||||
request.rawValue.msg_flags = UInt32(bitPattern: flags)
|
||||
request.rawValue.user_data = context
|
||||
case .receive(let socket, let buffer, let flags, let context):
|
||||
request.operation = .receive
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: buffer.baseAddress))
|
||||
request.rawValue.len = UInt32(exactly: buffer.count)!
|
||||
request.rawValue.msg_flags = UInt32(bitPattern: flags)
|
||||
request.rawValue.user_data = context
|
||||
case .shutdown(let socket, let how, let context):
|
||||
request.operation = .shutdown
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.len = UInt32(bitPattern: how)
|
||||
request.rawValue.user_data = context
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket requests
|
||||
|
||||
// These are the raw building blocks of the socket requests. The public,
|
||||
// typed API lives in `SystemSockets`, which owns the socket types.
|
||||
extension IORing.Request {
|
||||
package static func _socket(
|
||||
domain: CInt,
|
||||
type: CInt,
|
||||
protocol: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .socket(domain: domain, type: type, protocol: `protocol`, context: context))
|
||||
}
|
||||
|
||||
/// The address is copied, so `address` only has to be valid during this call.
|
||||
package static func _connect(
|
||||
_ socket: FileDescriptor,
|
||||
to address: UnsafePointer<sockaddr>,
|
||||
length: socklen_t,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .connect(
|
||||
socket: socket,
|
||||
address: PendingSocketAddress(copying: address, length: length),
|
||||
context: context
|
||||
))
|
||||
}
|
||||
|
||||
/// The address is copied, so `address` only has to be valid during this call.
|
||||
package static func _bind(
|
||||
_ socket: FileDescriptor,
|
||||
to address: UnsafePointer<sockaddr>,
|
||||
length: socklen_t,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .bind(
|
||||
socket: socket,
|
||||
address: PendingSocketAddress(copying: address, length: length),
|
||||
context: context
|
||||
))
|
||||
}
|
||||
|
||||
package static func _listen(
|
||||
_ socket: FileDescriptor,
|
||||
backlog: UInt32,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .listen(socket: socket, backlog: backlog, context: context))
|
||||
}
|
||||
|
||||
package static func _accept(
|
||||
_ socket: FileDescriptor,
|
||||
peerAddress: UnsafeMutablePointer<sockaddr>?,
|
||||
peerAddressLength: UnsafeMutablePointer<socklen_t>?,
|
||||
flags: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .accept(
|
||||
socket: socket,
|
||||
peerAddress: peerAddress,
|
||||
peerAddressLength: peerAddressLength,
|
||||
flags: flags,
|
||||
context: context
|
||||
))
|
||||
}
|
||||
|
||||
package static func _send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to socket: FileDescriptor,
|
||||
flags: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .send(socket: socket, buffer: buffer, flags: flags, context: context))
|
||||
}
|
||||
|
||||
package static func _receive(
|
||||
_ socket: FileDescriptor,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .receive(socket: socket, buffer: buffer, flags: flags, context: context))
|
||||
}
|
||||
|
||||
package static func _shutdown(
|
||||
_ socket: FileDescriptor,
|
||||
how: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .shutdown(socket: socket, how: how, context: context))
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// Throwing wrapper around the `io_uring_enter2` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result (the number of SQEs
|
||||
/// consumed by the kernel). On failure, reads `errno` and throws the matching
|
||||
/// `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringEnter2(
|
||||
ringDescriptor: Int32,
|
||||
toSubmit: UInt32,
|
||||
minComplete: UInt32,
|
||||
flags: UInt32,
|
||||
args: UnsafeMutablePointer<swift_io_uring_getevents_arg>?,
|
||||
argsSize: Int
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_enter2(
|
||||
ringDescriptor, toSubmit, minComplete, flags, args, argsSize
|
||||
)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `io_uring_enter` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result (the number of SQEs
|
||||
/// consumed by the kernel). On failure, reads `errno` and throws the matching
|
||||
/// `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringEnter(
|
||||
ringDescriptor: Int32,
|
||||
toSubmit: UInt32,
|
||||
minComplete: UInt32,
|
||||
flags: UInt32,
|
||||
sig: UnsafeMutablePointer<sigset_t>?
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `io_uring_register` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result. On failure, reads
|
||||
/// `errno` and throws the matching `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringRegister(
|
||||
ringDescriptor: Int32,
|
||||
opcode: UInt32,
|
||||
arg: UnsafeMutableRawPointer?,
|
||||
nrArgs: UInt32
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_register(ringDescriptor, opcode, arg, nrArgs)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
+217
-112
@@ -1,3 +1,12 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
@@ -41,6 +50,73 @@ 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] = []
|
||||
|
||||
/// The socket addresses of pending connect and bind requests. Like paths,
|
||||
/// the kernel copies them during `io_uring_enter`.
|
||||
@usableFromInline
|
||||
var socketAddresses: [PendingSocketAddress] = []
|
||||
|
||||
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 pin(_ address: PendingSocketAddress) -> UnsafePointer<sockaddr> {
|
||||
socketAddresses.append(address)
|
||||
// Safe to escape: `socketAddresses` keeps the allocation alive until
|
||||
// clear() or class deinit.
|
||||
return UnsafePointer(address.address)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func clear() {
|
||||
paths.removeAll(keepingCapacity: true)
|
||||
socketAddresses.removeAll(keepingCapacity: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of the socket address of a connect or bind request.
|
||||
///
|
||||
/// The copy has a stable address, so the request can point the kernel at it.
|
||||
@usableFromInline
|
||||
internal final class PendingSocketAddress {
|
||||
@usableFromInline
|
||||
let address: UnsafeMutablePointer<sockaddr>
|
||||
|
||||
@usableFromInline
|
||||
let length: socklen_t
|
||||
|
||||
init(copying address: UnsafePointer<sockaddr>, length: socklen_t) {
|
||||
let raw = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: Int(length),
|
||||
alignment: MemoryLayout<sockaddr_storage>.alignment
|
||||
)
|
||||
raw.copyMemory(from: address, byteCount: Int(length))
|
||||
self.address = raw.bindMemory(to: sockaddr.self, capacity: 1)
|
||||
self.length = length
|
||||
}
|
||||
|
||||
deinit {
|
||||
UnsafeMutableRawPointer(address).deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
// all pointers in this struct reference kernel-visible memory
|
||||
@usableFromInline struct SQRing: ~Copyable {
|
||||
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
|
||||
@@ -101,23 +177,30 @@ internal func _enter(
|
||||
// Ring always needs enter right now;
|
||||
// TODO: support SQPOLL here
|
||||
while true {
|
||||
let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil)
|
||||
do {
|
||||
let ret = try _ioUringEnter(
|
||||
ringDescriptor: ringDescriptor,
|
||||
toSubmit: numEvents,
|
||||
minComplete: minCompletions,
|
||||
flags: flags,
|
||||
sig: nil
|
||||
)
|
||||
if _getSubmissionQueueCount(ring: ring) > 0 {
|
||||
// See https://github.com/axboe/liburing/issues/309,
|
||||
// in some cases not all pending requests are submitted
|
||||
continue
|
||||
}
|
||||
return ret
|
||||
// error handling:
|
||||
// EAGAIN / EINTR (try again),
|
||||
// EAGAIN (try again),
|
||||
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
|
||||
// (failure in ring lifetime management, fatal),
|
||||
// EINVAL (bad constant flag?, fatal),
|
||||
// EFAULT (bad address for argument from library, fatal)
|
||||
if ret == -EAGAIN || ret == -EINTR {
|
||||
} catch Errno.resourceTemporarilyUnavailable {
|
||||
//TODO: should we wait a bit on AGAIN?
|
||||
//alternatively we could treat EAGAIN the same as EINTR in the wrapper
|
||||
continue
|
||||
} else if ret < 0 {
|
||||
throw(Errno(rawValue: -ret))
|
||||
} else if _getSubmissionQueueCount(ring: ring) > 0 {
|
||||
// See https://github.com/axboe/liburing/issues/309, in some cases not all pending requests are submitted
|
||||
continue
|
||||
} else {
|
||||
return ret
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -200,7 +283,14 @@ private func setUpRing(
|
||||
throw err
|
||||
}
|
||||
|
||||
if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0
|
||||
// We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced
|
||||
// pathnames (and other inline data) out of userspace before io_uring_enter
|
||||
// returns; the path-buffer side store on IORing relies on this to free
|
||||
// path buffers as soon as a submission completes.
|
||||
let requiredFeatures =
|
||||
IORing.Features.nonDroppingCompletions.rawValue
|
||||
| IORing.Features.stableSubmissions.rawValue
|
||||
if params.features & requiredFeatures != requiredFeatures
|
||||
{
|
||||
close(ringDescriptor)
|
||||
throw Errno.invalidArgument
|
||||
@@ -324,6 +414,8 @@ public struct IORing: ~Copyable {
|
||||
@usableFromInline var _registeredFiles: [UInt32]
|
||||
@usableFromInline var _registeredBuffers: [iovec]
|
||||
|
||||
@usableFromInline let _pendingPathBuffers: PendingPathBuffers
|
||||
|
||||
var features = Features(rawValue: 0)
|
||||
|
||||
/// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them.
|
||||
@@ -444,6 +536,7 @@ public struct IORing: ~Copyable {
|
||||
self.completionRingSize = tmpCQSize
|
||||
self._registeredFiles = []
|
||||
self._registeredBuffers = []
|
||||
self._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries))
|
||||
self.submissionRing = submissionRing
|
||||
self.completionRing = completionRing
|
||||
self.submissionQueueEntries = submissionQueueEntries
|
||||
@@ -466,11 +559,10 @@ public struct IORing: ~Copyable {
|
||||
var count = 0
|
||||
while let completion = _tryConsumeCompletion(ring: completionRing) {
|
||||
count += 1
|
||||
if completion.result < 0 {
|
||||
try consumer(nil, Errno(rawValue: -completion.result), false)
|
||||
} else {
|
||||
try consumer(completion, nil, false)
|
||||
}
|
||||
// We still return the completion for a failed operation so that the
|
||||
// caller can tell which request failed through its `context`.
|
||||
let error = completion.error
|
||||
try consumer(completion, error, false)
|
||||
if count == maximumCount {
|
||||
try consumer(nil, nil, true)
|
||||
return
|
||||
@@ -480,49 +572,56 @@ public struct IORing: ~Copyable {
|
||||
if count < minimumCount {
|
||||
while count < minimumCount {
|
||||
var sz = 0
|
||||
var flags = IORING_ENTER_GETEVENTS
|
||||
if extraArgs != nil {
|
||||
sz = MemoryLayout<swift_io_uring_getevents_arg>.size
|
||||
flags |= IORING_ENTER_EXT_ARG
|
||||
}
|
||||
let res = io_uring_enter2(
|
||||
ringDescriptor,
|
||||
0,
|
||||
minimumCount,
|
||||
IORING_ENTER_GETEVENTS,
|
||||
extraArgs,
|
||||
sz
|
||||
)
|
||||
do {
|
||||
_ = try _ioUringEnter2(
|
||||
ringDescriptor: ringDescriptor,
|
||||
toSubmit: 0,
|
||||
minComplete: minimumCount,
|
||||
flags: flags,
|
||||
args: extraArgs,
|
||||
argsSize: sz
|
||||
)
|
||||
break
|
||||
// error handling:
|
||||
// EAGAIN / EINTR (try again),
|
||||
// EAGAIN (try again),
|
||||
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
|
||||
// (failure in ring lifetime management, fatal),
|
||||
// EINVAL (bad constant flag?, fatal),
|
||||
// EFAULT (bad address for argument from library, fatal)
|
||||
// EBUSY (not enough space for events; implies events filled
|
||||
// by kernel between kernelTail load and now)
|
||||
if res >= 0 || res == -EBUSY {
|
||||
// ETIME (timeout from extraArgs.ts elapsed before
|
||||
// minimumCount completions arrived)
|
||||
} catch Errno.resourceBusy {
|
||||
break
|
||||
} else if res == -EAGAIN || res == -EINTR {
|
||||
} catch Errno.resourceTemporarilyUnavailable {
|
||||
continue
|
||||
} catch Errno.timeout {
|
||||
try consumer(nil, .timeout, true)
|
||||
return
|
||||
} catch {
|
||||
fatalError(
|
||||
"fatal error in receiving requests: "
|
||||
+ error.debugDescription
|
||||
)
|
||||
}
|
||||
fatalError(
|
||||
"fatal error in receiving requests: "
|
||||
+ Errno(rawValue: -res).debugDescription
|
||||
)
|
||||
}
|
||||
var count = 0
|
||||
while let completion = _tryConsumeCompletion(ring: completionRing) {
|
||||
count += 1
|
||||
if completion.result < 0 {
|
||||
try consumer(nil, Errno(rawValue: -completion.result), false)
|
||||
} else {
|
||||
try consumer(completion, nil, false)
|
||||
}
|
||||
let error = completion.error
|
||||
try consumer(completion, error, false)
|
||||
if count == maximumCount {
|
||||
break
|
||||
}
|
||||
}
|
||||
try consumer(nil, nil, true)
|
||||
}
|
||||
try consumer(nil, nil, true)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -532,17 +631,23 @@ public struct IORing: ~Copyable {
|
||||
var result: Completion? = nil
|
||||
try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) {
|
||||
(completion: consuming Completion?, error, done) throws(Errno) in
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
if let completion {
|
||||
result = consume completion
|
||||
} else if let error {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return result.take()!
|
||||
}
|
||||
|
||||
/// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified)
|
||||
///
|
||||
/// The completion is returned even if its operation failed. Check
|
||||
/// ``IORing/Completion/error`` to find out whether it did, and
|
||||
/// ``IORing/Completion/context`` to find out which request it belongs to.
|
||||
///
|
||||
/// - Throws: An error of the ring itself, such as ``Errno/timeout`` when
|
||||
/// no operation completed within `timeout`.
|
||||
@inlinable
|
||||
public func blockingConsumeCompletion(
|
||||
timeout: Duration? = nil
|
||||
@@ -566,7 +671,17 @@ public struct IORing: ~Copyable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout` (or forever if not specified). For each completed operation found, `consumer` is called to handle processing it
|
||||
/// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout`
|
||||
/// (or forever if not specified). For each completed operation found, `consumer` is called to handle
|
||||
/// processing it.
|
||||
///
|
||||
/// `consumer` receives a completion, an error, and whether consuming is done:
|
||||
/// - For each completed operation, it receives the completion. If the
|
||||
/// operation failed, it receives the operation's error alongside the
|
||||
/// completion.
|
||||
/// - If the ring itself fails, such as with ``Errno/timeout``, it receives
|
||||
/// the error without a completion.
|
||||
/// - Once consuming is done, it is called a final time with `done` set to `true`.
|
||||
@inlinable
|
||||
public func blockingConsumeCompletions<Err: Error>(
|
||||
minimumCount: UInt32 = 1,
|
||||
@@ -595,10 +710,6 @@ public struct IORing: ~Copyable {
|
||||
}
|
||||
}
|
||||
|
||||
// public func peekNextCompletion() -> IOCompletion {
|
||||
|
||||
// }
|
||||
|
||||
/// Takes a completed operation from the ring and returns it, if one is ready. Otherwise, returns nil.
|
||||
@inlinable
|
||||
public func tryConsumeCompletion() -> Completion? {
|
||||
@@ -623,31 +734,22 @@ public struct IORing: ~Copyable {
|
||||
/// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information.
|
||||
public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) {
|
||||
var rawfd = descriptor.rawValue
|
||||
let result = withUnsafePointer(to: &rawfd) { fdptr in
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.registerEventFD.rawValue,
|
||||
UnsafeMutableRawPointer(mutating: fdptr),
|
||||
1
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
if let result {
|
||||
throw result
|
||||
}
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.registerEventFD.rawValue,
|
||||
arg: &rawfd,
|
||||
nrArgs: 1
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes a registered event file descriptor from the ring
|
||||
public mutating func unregisterEventFD() throws(Errno) {
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.unregisterEventFD.rawValue,
|
||||
nil,
|
||||
0
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterEventFD.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
if result < 0 {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers `count` files with the ring for later use in IO operations
|
||||
@@ -656,18 +758,13 @@ public struct IORing: ~Copyable {
|
||||
precondition(count < UInt32.max)
|
||||
let files = [UInt32](repeating: UInt32.max, count: count)
|
||||
|
||||
let regResult = files.withUnsafeBufferPointer { bPtr in
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.registerFiles.rawValue,
|
||||
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
|
||||
UInt32(truncatingIfNeeded: count)
|
||||
try files.withUnsafeBufferPointer { bPtr throws(Errno) in
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.registerFiles.rawValue,
|
||||
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
|
||||
nrArgs: UInt32(truncatingIfNeeded: count)
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
|
||||
if let regResult {
|
||||
throw regResult
|
||||
}
|
||||
|
||||
_registeredFiles = files
|
||||
@@ -675,16 +772,13 @@ public struct IORing: ~Copyable {
|
||||
}
|
||||
|
||||
/// Removes registered files from the ring
|
||||
public func unregisterFiles() throws {
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.unregisterFiles.rawValue,
|
||||
nil,
|
||||
0
|
||||
public func unregisterFiles() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterFiles.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
if result < 0 {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Allows access to registered files by index
|
||||
@@ -700,18 +794,13 @@ public struct IORing: ~Copyable {
|
||||
precondition(buffers.count < UInt32.max)
|
||||
precondition(_registeredBuffers.isEmpty)
|
||||
let iovecs = buffers.map { $0.to_iovec() }
|
||||
let regResult = iovecs.withUnsafeBufferPointer { bPtr in
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.registerBuffers.rawValue,
|
||||
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
|
||||
UInt32(truncatingIfNeeded: buffers.count)
|
||||
try iovecs.withUnsafeBufferPointer { bPtr throws(Errno) in
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.registerBuffers.rawValue,
|
||||
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
|
||||
nrArgs: UInt32(truncatingIfNeeded: buffers.count)
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
|
||||
if let regResult {
|
||||
throw regResult
|
||||
}
|
||||
|
||||
_registeredBuffers = iovecs
|
||||
@@ -749,25 +838,34 @@ public struct IORing: ~Copyable {
|
||||
RegisteredResources(resources: _registeredBuffers)
|
||||
}
|
||||
|
||||
public func unregisterBuffers() throws {
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.unregisterBuffers.rawValue,
|
||||
nil,
|
||||
0
|
||||
public func unregisterBuffers() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterBuffers.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
guard result >= 0 else {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring.
|
||||
@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.
|
||||
///
|
||||
/// `consumer` receives a completion, an error, and whether consuming is done:
|
||||
/// - For each completed operation, it receives the completion. If the
|
||||
/// operation failed, it receives the operation's error alongside the
|
||||
/// completion.
|
||||
/// - If submitting the requests or waiting for completions fails, such as
|
||||
/// with ``Errno/timeout``, it receives the error without a completion.
|
||||
/// - Once consuming is done, it is called a final time with `done` set to `true`.
|
||||
@inlinable
|
||||
public func submitPreparedRequestsAndConsumeCompletions<Err: Error>(
|
||||
minimumCount: UInt32 = 1,
|
||||
@@ -790,9 +888,14 @@ public struct IORing: ~Copyable {
|
||||
/// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request
|
||||
@inlinable
|
||||
public mutating func prepare(request: __owned Request) -> Bool {
|
||||
var raw: RawIORequest? = request.makeRawRequest()
|
||||
return _tryWriteRequest(
|
||||
guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else {
|
||||
return false
|
||||
}
|
||||
var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers)
|
||||
let ok = _tryWriteRequest(
|
||||
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
|
||||
assert(ok)
|
||||
return ok
|
||||
}
|
||||
|
||||
/// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order.
|
||||
@@ -806,18 +909,20 @@ public struct IORing: ~Copyable {
|
||||
return false
|
||||
}
|
||||
let last = linkedRequests.last!
|
||||
var allAdded = true
|
||||
for req in linkedRequests.dropLast() {
|
||||
var raw = req.makeRawRequest()
|
||||
var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers)
|
||||
raw.linkToNextRequest()
|
||||
let successfullyAdded = _tryWriteRequest(
|
||||
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
|
||||
assert(successfullyAdded)
|
||||
allAdded = allAdded && successfullyAdded
|
||||
}
|
||||
let successfullyAdded = _tryWriteRequest(
|
||||
last.makeRawRequest(), ring: &submissionRing,
|
||||
last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing,
|
||||
submissionQueueEntries: submissionQueueEntries)
|
||||
assert(successfullyAdded)
|
||||
return true
|
||||
return allAdded && successfullyAdded
|
||||
}
|
||||
|
||||
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
|
||||
@@ -836,7 +941,7 @@ public struct IORing: ~Copyable {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Describes which io_uring features are supported by the kernel this program is running on
|
||||
/// Describes which `io_uring` features are supported by the kernel this program is running on
|
||||
public struct Features: OptionSet, RawRepresentable, Hashable {
|
||||
public let rawValue: UInt32
|
||||
|
||||
@@ -862,7 +967,7 @@ public struct IORing: ~Copyable {
|
||||
@inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE
|
||||
}
|
||||
|
||||
/// Describes which io_uring features are supported by the kernel this program is running on
|
||||
/// Describes which `io_uring` features are supported by the kernel this program is running on
|
||||
public var supportedFeatures: Features {
|
||||
return features
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
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(_:events: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,
|
||||
/// events: .readable,
|
||||
/// isMultiShot: true
|
||||
/// )
|
||||
/// ```
|
||||
public struct PollEvents: OptionSet, Hashable, Codable {
|
||||
public let rawValue: UInt32
|
||||
|
||||
@inlinable
|
||||
public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
init(_ event: Event) {
|
||||
self.rawValue = event.rawValue
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum Event: UInt32, RawRepresentable, Hashable, CaseIterable {
|
||||
case readable = 0x0001
|
||||
case priorityData = 0x0002
|
||||
case writable = 0x0004
|
||||
case error = 0x0008
|
||||
case hangUp = 0x0010
|
||||
case invalidDescriptor = 0x0020
|
||||
case peerClosed = 0x2000
|
||||
}
|
||||
|
||||
/// 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 readable: PollEvents { PollEvents(.readable) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "readable")
|
||||
public static var POLLIN: PollEvents { readable }
|
||||
|
||||
/// An event indicating out-of-band data is available for reading.
|
||||
///
|
||||
/// For sockets this signals urgent data; it is also used to report
|
||||
/// exceptional conditions on descriptors that have no other way to
|
||||
/// signal them, such as a `sysfs` attribute that has changed value.
|
||||
/// Corresponds to the POSIX `POLLPRI` event flag.
|
||||
@inlinable
|
||||
public static var priorityData: PollEvents { PollEvents(.priorityData) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "priorityData")
|
||||
public static var POLLPRI: PollEvents { priorityData }
|
||||
|
||||
/// 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 writable: PollEvents { PollEvents(.writable) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "writable")
|
||||
public static var POLLOUT: PollEvents { writable }
|
||||
|
||||
/// An event indicating an error condition on the file descriptor.
|
||||
///
|
||||
/// The kernel reports this event whether or not it was requested, so
|
||||
/// it can appear in a completion's result mask even when the poll
|
||||
/// asked only for ``readable`` or ``writable``. Requesting it
|
||||
/// explicitly has no effect. Corresponds to the POSIX `POLLERR` event
|
||||
/// flag.
|
||||
@inlinable
|
||||
public static var error: PollEvents { PollEvents(.error) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "error")
|
||||
public static var POLLERR: PollEvents { error }
|
||||
|
||||
/// An event indicating the peer closed its end of the channel.
|
||||
///
|
||||
/// For a pipe this means the writing end was closed; for a socket, that
|
||||
/// the connection was shut down.
|
||||
///
|
||||
/// The kernel reports this event whether or not it was requested, and
|
||||
/// requesting it explicitly has no effect. Corresponds to the POSIX
|
||||
/// `POLLHUP` event flag.
|
||||
@inlinable
|
||||
public static var hangUp: PollEvents { PollEvents(.hangUp) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "hangUp")
|
||||
public static var POLLHUP: PollEvents { hangUp }
|
||||
|
||||
/// An event indicating that the object a descriptor refers to is no
|
||||
/// longer valid.
|
||||
///
|
||||
/// This arises when the descriptor itself resolves, but the thing it
|
||||
/// refers to has since become invalid. For example, the disconnection
|
||||
/// of a sound device could cause this event.
|
||||
///
|
||||
/// A descriptor that doesn't resolve at all would make the request
|
||||
/// fail with ``Errno/badFileDescriptor`` instead.
|
||||
///
|
||||
/// The kernel reports this event whether or not it was requested, and
|
||||
/// requesting it explicitly has no effect. Corresponds to the POSIX
|
||||
/// `POLLNVAL` event flag.
|
||||
@inlinable
|
||||
public static var invalidDescriptor: PollEvents {
|
||||
PollEvents(.invalidDescriptor)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "invalidDescriptor")
|
||||
public static var POLLNVAL: PollEvents { invalidDescriptor }
|
||||
|
||||
/// An event indicating the peer closed its writing end of a stream
|
||||
/// socket, or shut it down for writing.
|
||||
///
|
||||
/// Unlike ``hangUp``, this event can arrive while the connection is
|
||||
/// still half-open: data already in flight can still be read, and the
|
||||
/// local end can still write. Once both directions are shut down,
|
||||
/// ``hangUp`` is reported alongside this event.
|
||||
///
|
||||
/// Unlike `poll(2)`, `io_uring` reports this event whether or not it
|
||||
/// was requested, and requesting it explicitly has no effect.
|
||||
/// Corresponds to the Linux `POLLRDHUP` event flag.
|
||||
@inlinable
|
||||
public static var peerClosed: PollEvents { PollEvents(.peerClosed) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "peerClosed")
|
||||
public static var POLLRDHUP: PollEvents { peerClosed }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,14 +1,27 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
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()
|
||||
@@ -30,8 +43,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
|
||||
@@ -40,9 +55,18 @@ extension RawIORequest {
|
||||
case read = 22
|
||||
case write = 23
|
||||
// ...
|
||||
case send = 26
|
||||
case receive = 27
|
||||
case openAt2 = 28
|
||||
// ...
|
||||
case shutdown = 34
|
||||
// ...
|
||||
case unlinkAt = 36
|
||||
// ...
|
||||
case socket = 45
|
||||
// ...
|
||||
case bind = 56
|
||||
case listen = 57
|
||||
}
|
||||
|
||||
public struct Flags: OptionSet, Hashable, Codable {
|
||||
@@ -76,6 +100,27 @@ extension RawIORequest {
|
||||
set { rawValue.addr = newValue }
|
||||
}
|
||||
|
||||
/// The poll event mask, stored in `sqe->poll32_events`.
|
||||
///
|
||||
/// Big-endian kernels swap the halfwords of this field before reading it.
|
||||
/// Equivalent to liburing's `__io_uring_prep_poll_mask`.
|
||||
@_alwaysEmitIntoClient var pollEvents: IORing.Request.PollEvents {
|
||||
get { .init(rawValue: Self._applyPollMask(rawValue.poll32_events)) }
|
||||
set { rawValue.poll32_events = Self._applyPollMask(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// Converts a poll event mask between its in-memory and `sqe` encodings.
|
||||
///
|
||||
/// This is a halfword rotate (`swahw32` from `<linux/swab.h>`), which keeps
|
||||
/// the byte order within each half.
|
||||
@_alwaysEmitIntoClient static func _applyPollMask(_ mask: UInt32) -> UInt32 {
|
||||
#if _endian(big)
|
||||
return (mask &<< 16) | (mask &>> 16)
|
||||
#else
|
||||
return mask
|
||||
#endif
|
||||
}
|
||||
|
||||
@inlinable public var flags: Flags {
|
||||
get { Flags(rawValue: rawValue.flags) }
|
||||
set { rawValue.flags = newValue.rawValue }
|
||||
@@ -177,20 +222,20 @@ extension RawIORequest {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func withTimeoutRequest<R>(
|
||||
static func withTimeoutRequest<R, E: Error>(
|
||||
linkedTo opEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
in timeoutEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
duration: Duration,
|
||||
flags: TimeOutFlags,
|
||||
work: () throws -> R) rethrows -> R {
|
||||
duration: Duration,
|
||||
flags: TimeOutFlags,
|
||||
work: () throws(E) -> R) throws(E) -> R {
|
||||
|
||||
opEntry.pointee.flags |= Flags.linkRequest.rawValue
|
||||
opEntry.pointee.off = 1
|
||||
var ts = timespec(
|
||||
tv_sec: Int(duration.components.seconds),
|
||||
tv_sec: Int(duration.components.seconds),
|
||||
tv_nsec: Int(duration.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
return try withUnsafePointer(to: &ts) { tsPtr in
|
||||
return try withUnsafePointer(to: &ts) { tsPtr throws(E) -> R in
|
||||
var req: RawIORequest = RawIORequest()
|
||||
req.operation = .link_timeout
|
||||
req.rawValue.timeout_flags = flags.rawValue
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -13,10 +13,10 @@ import Darwin
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
@@ -81,9 +81,33 @@ public enum CInterop {
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(System 99, *)
|
||||
@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 1.7.0, *)
|
||||
extension CInterop {
|
||||
public typealias DeviceID = dev_t
|
||||
public typealias Inode = ino_t
|
||||
public typealias UserID = uid_t
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -11,19 +11,16 @@
|
||||
// they can be used anywhere without imports and without confusion to
|
||||
// unavailable local decls.
|
||||
|
||||
import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import CSystem
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
@@ -619,9 +616,26 @@ internal var _O_DIRECTORY: CInt {
|
||||
internal var _O_SYMLINK: CInt { O_SYMLINK }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt {
|
||||
#if os(Windows)
|
||||
O_NOINHERIT
|
||||
#else
|
||||
O_CLOEXEC
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt { O_CLOEXEC }
|
||||
internal var _O_CLOFORK: CInt {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
COMPATIBILITY_O_CLOFORK
|
||||
#elseif !os(WASI) && !os(Linux) && !os(Android)
|
||||
O_CLOFORK
|
||||
#else
|
||||
0
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -693,8 +707,9 @@ 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 { S_IFWHT }
|
||||
internal var _S_IFWHT: mode_t { .init(S_IFWHT) }
|
||||
#endif
|
||||
|
||||
// MARK: - stat/chflags File Flags
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -18,15 +18,15 @@ import Darwin
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -91,19 +91,20 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(System 99, *)
|
||||
@available(System 0.0.2, *)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
stat(p, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_lstat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
lstat(p, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
|
||||
fstat(fd, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 {
|
||||
fstatat(fd, p, &s, flags)
|
||||
}
|
||||
@@ -183,9 +184,10 @@ extension String {
|
||||
// TLS
|
||||
#if os(Windows)
|
||||
internal typealias _PlatformTLSKey = DWORD
|
||||
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
|
||||
// Mock TLS storage for single-threaded WASI
|
||||
internal final class _PlatformTLSKey {
|
||||
#elseif os(WASI) && !_runtime(_multithreaded)
|
||||
// Mock TLS storage for single-threaded WASI.
|
||||
// Carries no state of its own, and only used to index `sharedTLSStorage`.
|
||||
internal final class _PlatformTLSKey: @unchecked Sendable {
|
||||
fileprivate init() {}
|
||||
}
|
||||
private final class TLSStorage: @unchecked Sendable {
|
||||
@@ -212,7 +214,7 @@ internal func makeTLSKey() -> _PlatformTLSKey {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
|
||||
#elseif os(WASI) && !_runtime(_multithreaded)
|
||||
return _PlatformTLSKey()
|
||||
#else
|
||||
var raw = pthread_key_t()
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@@ -14,7 +15,6 @@ import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import CSystem
|
||||
import WASILibc
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
@@ -139,7 +139,15 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
#endif
|
||||
return dup2(fd, fd2)
|
||||
}
|
||||
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
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 // !os(WASI)
|
||||
|
||||
#if !os(WASI)
|
||||
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
@@ -148,7 +156,15 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
#endif
|
||||
return pipe(fds)
|
||||
}
|
||||
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
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 // !os(WASI)
|
||||
|
||||
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
@@ -186,7 +202,7 @@ internal func system_confstr(
|
||||
) -> Int {
|
||||
return confstr(name, buf, len)
|
||||
}
|
||||
#endif
|
||||
#endif // SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
#if !os(Windows)
|
||||
internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR
|
||||
@@ -254,7 +270,7 @@ internal func system_openat(
|
||||
#endif
|
||||
return openat(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
#endif // !os(Windows)
|
||||
|
||||
#if !os(WASI) // WASI has no umask
|
||||
internal func system_umask(
|
||||
@@ -262,7 +278,7 @@ internal func system_umask(
|
||||
) -> CInterop.Mode {
|
||||
return umask(mode)
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
internal func system_getenv(
|
||||
_ name: UnsafePointer<CChar>
|
||||
|
||||
@@ -11,16 +11,15 @@
|
||||
|
||||
import ucrt
|
||||
import WinSDK
|
||||
import Synchronization
|
||||
|
||||
fileprivate var _umask: CInterop.Mode = 0o22
|
||||
private let _umask = Atomic<CInterop.Mode>(0o22)
|
||||
|
||||
@inline(__always)
|
||||
func umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
let oldMask = _umask
|
||||
_umask = mode
|
||||
return oldMask
|
||||
_umask.exchange(mode, ordering: .relaxed)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -38,9 +37,9 @@ internal func open(
|
||||
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
|
||||
CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
DWORD(FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE),
|
||||
FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE,
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
@@ -58,7 +57,7 @@ internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
let actualMode = mode & ~_umask
|
||||
let actualMode = mode & ~_umask.load(ordering: .relaxed)
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
@@ -80,9 +79,9 @@ internal func open(
|
||||
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
|
||||
CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
DWORD(FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE),
|
||||
FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE,
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
@@ -149,6 +148,12 @@ 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)!
|
||||
|
||||
@@ -171,6 +176,12 @@ 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)!
|
||||
|
||||
@@ -189,11 +200,18 @@ internal func pwrite(
|
||||
|
||||
@inline(__always)
|
||||
internal func pipe(
|
||||
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 4096
|
||||
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0
|
||||
) -> 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)
|
||||
@@ -206,16 +224,16 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
|
||||
// Save the current position and restore it when we're done
|
||||
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
|
||||
DWORD(FILE_CURRENT)) {
|
||||
FILE_CURRENT) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
defer {
|
||||
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN));
|
||||
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN);
|
||||
}
|
||||
|
||||
// Truncate (or extend) the file
|
||||
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN))
|
||||
if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN)
|
||||
|| !SetEndOfFile(hFile) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
@@ -229,7 +247,7 @@ internal func mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
let actualMode = mode & ~_umask
|
||||
let actualMode = mode & ~_umask.load(ordering: .relaxed)
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode,
|
||||
for: .directory) else {
|
||||
@@ -267,7 +285,7 @@ internal func rmdir(
|
||||
}
|
||||
|
||||
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
|
||||
switch Int32(errorCode) {
|
||||
switch errorCode {
|
||||
case ERROR_SUCCESS:
|
||||
return 0
|
||||
case ERROR_INVALID_FUNCTION,
|
||||
@@ -346,28 +364,28 @@ fileprivate func rightsFromModeBits(
|
||||
var rights: DWORD = 0
|
||||
|
||||
if (bits & 0o4) != 0 {
|
||||
rights |= DWORD(FILE_READ_ATTRIBUTES
|
||||
| FILE_READ_DATA
|
||||
| FILE_READ_EA
|
||||
| STANDARD_RIGHTS_READ
|
||||
| SYNCHRONIZE)
|
||||
rights |= (FILE_READ_ATTRIBUTES
|
||||
| FILE_READ_DATA
|
||||
| FILE_READ_EA
|
||||
| STANDARD_RIGHTS_READ
|
||||
| SYNCHRONIZE)
|
||||
}
|
||||
if (bits & 0o2) != 0 {
|
||||
rights |= DWORD(FILE_APPEND_DATA
|
||||
| FILE_WRITE_ATTRIBUTES
|
||||
| FILE_WRITE_DATA
|
||||
| FILE_WRITE_EA
|
||||
| STANDARD_RIGHTS_WRITE
|
||||
| SYNCHRONIZE)
|
||||
rights |= (FILE_APPEND_DATA
|
||||
| FILE_WRITE_ATTRIBUTES
|
||||
| FILE_WRITE_DATA
|
||||
| FILE_WRITE_EA
|
||||
| STANDARD_RIGHTS_WRITE
|
||||
| SYNCHRONIZE)
|
||||
if fileOrDirectory == .directory && !sticky {
|
||||
rights |= DWORD(FILE_DELETE_CHILD)
|
||||
rights |= FILE_DELETE_CHILD
|
||||
}
|
||||
}
|
||||
if (bits & 0o1) != 0 {
|
||||
rights |= DWORD(FILE_EXECUTE
|
||||
| FILE_READ_ATTRIBUTES
|
||||
| STANDARD_RIGHTS_EXECUTE
|
||||
| SYNCHRONIZE)
|
||||
rights |= (FILE_EXECUTE
|
||||
| FILE_READ_ATTRIBUTES
|
||||
| STANDARD_RIGHTS_EXECUTE
|
||||
| SYNCHRONIZE)
|
||||
}
|
||||
|
||||
return rights
|
||||
@@ -435,7 +453,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
var everyone: PSID? = nil
|
||||
|
||||
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
|
||||
DWORD(SECURITY_WORLD_RID),
|
||||
SECURITY_WORLD_RID,
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
&everyone) else {
|
||||
return nil
|
||||
@@ -476,7 +494,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: ownerRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
@@ -489,7 +507,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: groupRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
@@ -502,7 +520,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: otherRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
@@ -519,7 +537,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: ownerDenyRights,
|
||||
grfAccessMode: DENY_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
@@ -537,7 +555,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: groupDenyRights,
|
||||
grfAccessMode: DENY_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
grfInheritance: NO_INHERITANCE,
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
@@ -566,13 +584,13 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
var descriptor = SECURITY_DESCRIPTOR()
|
||||
|
||||
guard InitializeSecurityDescriptor(&descriptor,
|
||||
DWORD(SECURITY_DESCRIPTOR_REVISION)) else {
|
||||
SECURITY_DESCRIPTOR_REVISION) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard SetSecurityDescriptorControl(&descriptor,
|
||||
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED),
|
||||
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED))
|
||||
SE_DACL_PROTECTED,
|
||||
SE_DACL_PROTECTED)
|
||||
&& SetSecurityDescriptorOwner(&descriptor, user, false)
|
||||
&& SetSecurityDescriptorGroup(&descriptor, group, false)
|
||||
&& SetSecurityDescriptorDacl(&descriptor,
|
||||
@@ -612,15 +630,15 @@ fileprivate struct DecodedOpenFlags {
|
||||
init(_ oflag: Int32) {
|
||||
switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) {
|
||||
case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC:
|
||||
dwCreationDisposition = DWORD(CREATE_NEW)
|
||||
dwCreationDisposition = CREATE_NEW
|
||||
case _O_CREAT:
|
||||
dwCreationDisposition = DWORD(OPEN_ALWAYS)
|
||||
dwCreationDisposition = OPEN_ALWAYS
|
||||
case _O_CREAT | _O_TRUNC:
|
||||
dwCreationDisposition = DWORD(CREATE_ALWAYS)
|
||||
dwCreationDisposition = CREATE_ALWAYS
|
||||
case _O_TRUNC:
|
||||
dwCreationDisposition = DWORD(TRUNCATE_EXISTING)
|
||||
dwCreationDisposition = TRUNCATE_EXISTING
|
||||
default:
|
||||
dwCreationDisposition = DWORD(OPEN_EXISTING)
|
||||
dwCreationDisposition = OPEN_EXISTING
|
||||
}
|
||||
|
||||
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
|
||||
@@ -629,11 +647,11 @@ fileprivate struct DecodedOpenFlags {
|
||||
dwDesiredAccess = 0
|
||||
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
|
||||
case _O_RDONLY:
|
||||
dwDesiredAccess |= DWORD(GENERIC_READ)
|
||||
dwDesiredAccess |= GENERIC_READ
|
||||
case _O_WRONLY:
|
||||
dwDesiredAccess |= DWORD(GENERIC_WRITE)
|
||||
dwDesiredAccess |= GENERIC_WRITE
|
||||
case _O_RDWR:
|
||||
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE)
|
||||
dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -642,19 +660,19 @@ fileprivate struct DecodedOpenFlags {
|
||||
|
||||
dwFlagsAndAttributes = 0
|
||||
if (oflag & _O_SEQUENTIAL) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN)
|
||||
dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN
|
||||
}
|
||||
if (oflag & _O_RANDOM) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS)
|
||||
dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS
|
||||
}
|
||||
if (oflag & _O_TEMPORARY) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE)
|
||||
dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE
|
||||
}
|
||||
|
||||
if (oflag & _O_SHORT_LIVED) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY)
|
||||
dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY
|
||||
} else {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL)
|
||||
dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
#if canImport(Darwin, _version: 310)
|
||||
import Darwin.Mach
|
||||
#else
|
||||
@preconcurrency import Darwin.Mach
|
||||
#endif
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
public protocol MachPortRight {}
|
||||
@@ -145,6 +149,7 @@ 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")
|
||||
@@ -180,7 +185,6 @@ 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 +326,7 @@ extension Mach.Port where RightType == Mach.SendRight {
|
||||
///
|
||||
/// 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
|
||||
discard self
|
||||
@@ -365,7 +369,6 @@ 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
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
import WinSDK
|
||||
|
||||
@_transparent
|
||||
internal var CREATE_ALWAYS: DWORD {
|
||||
DWORD(WinSDK.CREATE_ALWAYS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var CREATE_NEW: DWORD {
|
||||
DWORD(WinSDK.CREATE_NEW)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_ACCESS_DENIED: DWORD {
|
||||
DWORD(WinSDK.ERROR_ACCESS_DENIED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_ALREADY_EXISTS: DWORD {
|
||||
DWORD(WinSDK.ERROR_ALREADY_EXISTS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_ARENA_TRASHED: DWORD {
|
||||
DWORD(WinSDK.ERROR_ARENA_TRASHED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_ENVIRONMENT: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_ENVIRONMENT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_FORMAT: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_FORMAT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_NET_NAME: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_NET_NAME)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_NETPATH: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_NETPATH)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BAD_PATHNAME: DWORD {
|
||||
DWORD(WinSDK.ERROR_BAD_PATHNAME)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_BROKEN_PIPE: DWORD {
|
||||
DWORD(WinSDK.ERROR_BROKEN_PIPE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_CANNOT_MAKE: DWORD {
|
||||
DWORD(WinSDK.ERROR_CANNOT_MAKE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_CHILD_NOT_COMPLETE: DWORD {
|
||||
DWORD(WinSDK.ERROR_CHILD_NOT_COMPLETE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_CURRENT_DIRECTORY: DWORD {
|
||||
DWORD(WinSDK.ERROR_CURRENT_DIRECTORY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DIR_NOT_EMPTY: DWORD {
|
||||
DWORD(WinSDK.ERROR_DIR_NOT_EMPTY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DISK_FULL: DWORD {
|
||||
DWORD(WinSDK.ERROR_DISK_FULL)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DRIVE_LOCKED: DWORD {
|
||||
DWORD(WinSDK.ERROR_DRIVE_LOCKED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_DIRECT_ACCESS_HANDLE: DWORD {
|
||||
DWORD(WinSDK.ERROR_DIRECT_ACCESS_HANDLE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FILE_EXISTS: DWORD {
|
||||
DWORD(WinSDK.ERROR_FILE_EXISTS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FILE_NOT_FOUND: DWORD {
|
||||
DWORD(WinSDK.ERROR_FILE_NOT_FOUND)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FAIL_I24: DWORD {
|
||||
DWORD(WinSDK.ERROR_FAIL_I24)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_FILENAME_EXCED_RANGE: DWORD {
|
||||
DWORD(WinSDK.ERROR_FILENAME_EXCED_RANGE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NEGATIVE_SEEK: DWORD {
|
||||
DWORD(WinSDK.ERROR_NEGATIVE_SEEK)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NO_MORE_FILES: DWORD {
|
||||
DWORD(WinSDK.ERROR_NO_MORE_FILES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NO_UNICODE_TRANSLATION: DWORD {
|
||||
DWORD(WinSDK.ERROR_NO_UNICODE_TRANSLATION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_ENOUGH_MEMORY: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_ENOUGH_MEMORY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_ACCESS: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_ACCESS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_BLOCK: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_BLOCK)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_DATA: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_DRIVE: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_DRIVE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_FUNCTION: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_FUNCTION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_HANDLE: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_HANDLE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD {
|
||||
DWORD(WinSDK.ERROR_INFLOOP_IN_RELOC_CHAIN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_PARAMETER: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_PARAMETER)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_STARTING_CODESEG: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_STARTING_CODESEG)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_INVALID_TARGET_HANDLE: DWORD {
|
||||
DWORD(WinSDK.ERROR_INVALID_TARGET_HANDLE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_LOCK_FAILED: DWORD {
|
||||
DWORD(WinSDK.ERROR_LOCK_FAILED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_LOCK_VIOLATION: DWORD {
|
||||
DWORD(WinSDK.ERROR_LOCK_VIOLATION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_MAX_THRDS_REACHED: DWORD {
|
||||
DWORD(WinSDK.ERROR_MAX_THRDS_REACHED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NESTING_NOT_ALLOWED: DWORD {
|
||||
DWORD(WinSDK.ERROR_NESTING_NOT_ALLOWED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NETWORK_ACCESS_DENIED: DWORD {
|
||||
DWORD(WinSDK.ERROR_NETWORK_ACCESS_DENIED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NO_PROC_SLOTS: DWORD {
|
||||
DWORD(WinSDK.ERROR_NO_PROC_SLOTS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_ENOUGH_QUOTA: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_ENOUGH_QUOTA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_LOCKED: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_LOCKED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_NOT_SAME_DEVICE: DWORD {
|
||||
DWORD(WinSDK.ERROR_NOT_SAME_DEVICE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_PATH_NOT_FOUND: DWORD {
|
||||
DWORD(WinSDK.ERROR_PATH_NOT_FOUND)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_SEEK_ON_DEVICE: DWORD {
|
||||
DWORD(WinSDK.ERROR_SEEK_ON_DEVICE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_SHARING_BUFFER_EXCEEDED: DWORD {
|
||||
DWORD(WinSDK.ERROR_SHARING_BUFFER_EXCEEDED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_SUCCESS: DWORD {
|
||||
DWORD(WinSDK.ERROR_SUCCESS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_WAIT_NO_CHILDREN: DWORD {
|
||||
DWORD(WinSDK.ERROR_WAIT_NO_CHILDREN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_WRITE_PROTECT: DWORD {
|
||||
DWORD(WinSDK.ERROR_WRITE_PROTECT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var ERROR_TOO_MANY_OPEN_FILES: DWORD {
|
||||
DWORD(WinSDK.ERROR_TOO_MANY_OPEN_FILES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_APPEND_DATA: DWORD {
|
||||
DWORD(WinSDK.FILE_APPEND_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_ATTRIBUTE_DIRECTORY: DWORD {
|
||||
DWORD(WinSDK.FILE_ATTRIBUTE_DIRECTORY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_ATTRIBUTE_NORMAL: DWORD {
|
||||
DWORD(WinSDK.FILE_ATTRIBUTE_NORMAL)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_ATTRIBUTE_TEMPORARY: DWORD {
|
||||
DWORD(WinSDK.FILE_ATTRIBUTE_TEMPORARY)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_BEGIN: DWORD {
|
||||
DWORD(WinSDK.FILE_BEGIN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_CURRENT: DWORD {
|
||||
DWORD(WinSDK.FILE_CURRENT)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_DELETE_CHILD: DWORD {
|
||||
DWORD(WinSDK.FILE_DELETE_CHILD)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
package var FILE_EXECUTE: DWORD {
|
||||
DWORD(WinSDK.FILE_EXECUTE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_FLAG_DELETE_ON_CLOSE: DWORD {
|
||||
DWORD(WinSDK.FILE_FLAG_DELETE_ON_CLOSE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_FLAG_RANDOM_ACCESS: DWORD {
|
||||
DWORD(WinSDK.FILE_FLAG_RANDOM_ACCESS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_FLAG_SEQUENTIAL_SCAN: DWORD {
|
||||
DWORD(WinSDK.FILE_FLAG_SEQUENTIAL_SCAN)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
package var FILE_READ_ATTRIBUTES: DWORD {
|
||||
DWORD(WinSDK.FILE_READ_ATTRIBUTES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_READ_DATA: DWORD {
|
||||
DWORD(WinSDK.FILE_READ_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_READ_EA: DWORD {
|
||||
DWORD(WinSDK.FILE_READ_EA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_SHARE_DELETE: DWORD {
|
||||
DWORD(WinSDK.FILE_SHARE_DELETE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_SHARE_READ: DWORD {
|
||||
DWORD(WinSDK.FILE_SHARE_READ)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_SHARE_WRITE: DWORD {
|
||||
DWORD(WinSDK.FILE_SHARE_WRITE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
package var FILE_WRITE_ATTRIBUTES: DWORD {
|
||||
DWORD(WinSDK.FILE_WRITE_ATTRIBUTES)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_WRITE_DATA: DWORD {
|
||||
DWORD(WinSDK.FILE_WRITE_DATA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var FILE_WRITE_EA: DWORD {
|
||||
DWORD(WinSDK.FILE_WRITE_EA)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var GENERIC_READ: DWORD {
|
||||
DWORD(WinSDK.GENERIC_READ)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var GENERIC_WRITE: DWORD {
|
||||
DWORD(WinSDK.GENERIC_WRITE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var NO_INHERITANCE: DWORD {
|
||||
DWORD(WinSDK.NO_INHERITANCE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var OPEN_ALWAYS: DWORD {
|
||||
DWORD(WinSDK.OPEN_ALWAYS)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var OPEN_EXISTING: DWORD {
|
||||
DWORD(WinSDK.OPEN_EXISTING)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SE_DACL_PROTECTED: SECURITY_DESCRIPTOR_CONTROL {
|
||||
SECURITY_DESCRIPTOR_CONTROL(WinSDK.SE_DACL_PROTECTED)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SECURITY_DESCRIPTOR_REVISION: DWORD {
|
||||
DWORD(WinSDK.SECURITY_DESCRIPTOR_REVISION)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SECURITY_WORLD_RID: DWORD {
|
||||
DWORD(WinSDK.SECURITY_WORLD_RID)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var STANDARD_RIGHTS_READ: DWORD {
|
||||
DWORD(WinSDK.STANDARD_RIGHTS_READ)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var STANDARD_RIGHTS_EXECUTE: DWORD {
|
||||
DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var STANDARD_RIGHTS_WRITE: DWORD {
|
||||
DWORD(WinSDK.STANDARD_RIGHTS_WRITE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var SYNCHRONIZE: DWORD {
|
||||
DWORD(WinSDK.SYNCHRONIZE)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
internal var TRUNCATE_EXISTING: DWORD {
|
||||
DWORD(WinSDK.TRUNCATE_EXISTING)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -12,13 +12,13 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -26,7 +26,7 @@ import Android
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension CInterop {
|
||||
/// Socket address structure.
|
||||
///
|
||||
|
||||
@@ -12,13 +12,13 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
|
||||
@@ -14,10 +14,13 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#endif
|
||||
|
||||
|
||||
@@ -12,13 +12,13 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
// MARK: - Socket requests
|
||||
|
||||
@available(System 199, *)
|
||||
extension IORing.Request {
|
||||
/// Creates a socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the file
|
||||
/// descriptor of the new socket. Wrap it with
|
||||
/// `SocketDescriptor(rawValue:)`. The caller owns the socket and has to
|
||||
/// close it.
|
||||
///
|
||||
/// The corresponding C function is `socket`, and the operation is
|
||||
/// `IORING_OP_SOCKET`. It requires Linux 5.19 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - domain: The communication domain of the socket.
|
||||
/// - type: The type of the socket.
|
||||
/// - protocol: The protocol of the socket.
|
||||
/// - flags: Flags for the new socket.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that creates the socket.
|
||||
public static func socket(
|
||||
_ domain: SocketDescriptor.Domain,
|
||||
_ type: SocketDescriptor.ConnectionType,
|
||||
protocol: SocketDescriptor.ProtocolID = .default,
|
||||
flags: SocketDescriptor.SocketFlags = [],
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._socket(
|
||||
domain: domain.rawValue,
|
||||
type: type.rawValue | flags.rawValue,
|
||||
protocol: `protocol`.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Connects a socket to an address.
|
||||
///
|
||||
/// The address is copied when the request is created. The kernel copies it
|
||||
/// again when the request is submitted, so `address` doesn't need to stay
|
||||
/// alive.
|
||||
///
|
||||
/// The corresponding C function is `connect`, and the operation is
|
||||
/// `IORING_OP_CONNECT`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to connect.
|
||||
/// - address: The address to connect to.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that connects the socket.
|
||||
public static func connect(
|
||||
_ socket: SocketDescriptor,
|
||||
to address: SocketAddress,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
address.withUnsafePointer { address, length in
|
||||
._connect(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
to: address,
|
||||
length: length,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Binds a socket to an address.
|
||||
///
|
||||
/// The address is copied when the request is created. The kernel copies it
|
||||
/// again when the request is submitted, so `address` doesn't need to stay
|
||||
/// alive.
|
||||
///
|
||||
/// The corresponding C function is `bind`, and the operation is
|
||||
/// `IORING_OP_BIND`. It requires Linux 6.11 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to bind.
|
||||
/// - address: The address to bind to.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that binds the socket.
|
||||
public static func bind(
|
||||
_ socket: SocketDescriptor,
|
||||
to address: SocketAddress,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
address.withUnsafePointer { address, length in
|
||||
._bind(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
to: address,
|
||||
length: length,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts listening for connections on a socket.
|
||||
///
|
||||
/// The corresponding C function is `listen`, and the operation is
|
||||
/// `IORING_OP_LISTEN`. It requires Linux 6.11 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to listen on.
|
||||
/// - backlog: The maximum number of pending connections.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that starts listening.
|
||||
public static func listen(
|
||||
_ socket: SocketDescriptor,
|
||||
backlog: Int,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._listen(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
backlog: UInt32(clamping: backlog),
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Accepts a connection on a listening socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the file
|
||||
/// descriptor of the accepted socket. Wrap it with
|
||||
/// `SocketDescriptor(rawValue:)`. The caller owns the socket and has to
|
||||
/// close it.
|
||||
///
|
||||
/// The corresponding C function is `accept4`, and the operation is
|
||||
/// `IORING_OP_ACCEPT`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The listening socket.
|
||||
/// - flags: Flags for the accepted socket.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that accepts a connection.
|
||||
public static func accept(
|
||||
_ socket: SocketDescriptor,
|
||||
flags: SocketDescriptor.SocketFlags = [],
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._accept(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
peerAddress: nil,
|
||||
peerAddressLength: nil,
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Accepts a connection on a listening socket and writes the peer's
|
||||
/// address into the given storage.
|
||||
///
|
||||
/// Before submitting the request, set the value that `peerAddressLength`
|
||||
/// points to to the size of the storage that `peerAddress` points to. When
|
||||
/// the request completes, the kernel has written the peer's address and its
|
||||
/// length there.
|
||||
///
|
||||
/// - Important: The kernel writes to `peerAddress` and `peerAddressLength`
|
||||
/// when the request completes, so both have to stay valid until the
|
||||
/// completion has been consumed.
|
||||
///
|
||||
/// The corresponding C function is `accept4`, and the operation is
|
||||
/// `IORING_OP_ACCEPT`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The listening socket.
|
||||
/// - peerAddress: The storage for the peer's address.
|
||||
/// - peerAddressLength: The size of the storage, replaced with the length
|
||||
/// of the peer's address.
|
||||
/// - flags: Flags for the accepted socket.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that accepts a connection.
|
||||
public static func accept(
|
||||
_ socket: SocketDescriptor,
|
||||
peerAddress: UnsafeMutablePointer<CInterop.SockAddr>,
|
||||
peerAddressLength: UnsafeMutablePointer<CInterop.SockLen>,
|
||||
flags: SocketDescriptor.SocketFlags = [],
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._accept(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
peerAddress: peerAddress,
|
||||
peerAddressLength: peerAddressLength,
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Sends bytes on a connected socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the number
|
||||
/// of bytes sent, which can be less than the size of `buffer`.
|
||||
///
|
||||
/// Unlike a write request, a send request doesn't raise `SIGPIPE` when the
|
||||
/// connection is closed for writing. io_uring sets `MSG_NOSIGNAL` for it,
|
||||
/// so the completion fails with ``Errno/brokenPipe`` instead.
|
||||
///
|
||||
/// - Important: The kernel reads from `buffer` until the request completes,
|
||||
/// so it has to stay valid until the completion has been consumed.
|
||||
///
|
||||
/// The corresponding C function is `send`, and the operation is
|
||||
/// `IORING_OP_SEND`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The bytes to send.
|
||||
/// - socket: The socket to send on.
|
||||
/// - flags: Flags for sending.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that sends the bytes.
|
||||
public static func send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to socket: SocketDescriptor,
|
||||
flags: SocketDescriptor.MessageFlags = .none,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._send(
|
||||
buffer,
|
||||
to: FileDescriptor(rawValue: socket.rawValue),
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Receives bytes from a connected socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the number
|
||||
/// of bytes received. Zero means that the peer closed its side of the
|
||||
/// connection.
|
||||
///
|
||||
/// - Important: The kernel writes into `buffer` until the request completes,
|
||||
/// so it has to stay valid until the completion has been consumed.
|
||||
///
|
||||
/// The corresponding C function is `recv`, and the operation is
|
||||
/// `IORING_OP_RECV`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to receive from.
|
||||
/// - buffer: The buffer to receive into.
|
||||
/// - flags: Flags for receiving.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that receives bytes.
|
||||
public static func receive(
|
||||
_ socket: SocketDescriptor,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: SocketDescriptor.MessageFlags = .none,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._receive(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
into: buffer,
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Shuts down one or both directions of a socket.
|
||||
///
|
||||
/// The corresponding C function is `shutdown`, and the operation is
|
||||
/// `IORING_OP_SHUTDOWN`. It requires Linux 5.11 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to shut down.
|
||||
/// - how: The directions to shut down.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that shuts down the socket.
|
||||
public static func shutdown(
|
||||
_ socket: SocketDescriptor,
|
||||
_ how: SocketDescriptor.ShutdownKind,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._shutdown(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
how: how.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -10,13 +10,13 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -24,7 +24,7 @@ import Android
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
@frozen
|
||||
/// The address family identifier
|
||||
@@ -90,7 +90,7 @@ extension SocketAddress {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress.Family: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self {
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -25,7 +28,7 @@ import Android
|
||||
///
|
||||
/// An IPv4 address consists of a 32-bit IP address and a 16-bit port number.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
public struct IPv4Address: Sendable, Equatable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
@@ -93,7 +96,7 @@ public struct IPv4Address: Sendable, Equatable, Hashable {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv4Address {
|
||||
/// The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -114,7 +117,7 @@ extension IPv4Address {
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv4Address {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -131,7 +134,7 @@ extension IPv4Address {
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv4Address: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"\(addressString):\(port)"
|
||||
@@ -140,7 +143,7 @@ extension IPv4Address: CustomStringConvertible {
|
||||
|
||||
// MARK: - ExpressibleByStringLiteral
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv4Address: ExpressibleByStringLiteral {
|
||||
/// Creates an IPv4 address from a string literal.
|
||||
///
|
||||
@@ -160,7 +163,7 @@ extension IPv4Address: ExpressibleByStringLiteral {
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv4Address {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: IPv4Address, rhs: IPv4Address) -> Bool {
|
||||
@@ -179,7 +182,7 @@ extension IPv4Address {
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from an IPv4 address.
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -26,7 +29,7 @@ import Android
|
||||
/// An IPv6 address consists of a 128-bit IP address, a 16-bit port number,
|
||||
/// a flow label, and a scope ID.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
public struct IPv6Address: Sendable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
@@ -94,7 +97,7 @@ public struct IPv6Address: Sendable, Hashable {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv6Address {
|
||||
/// The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -127,7 +130,7 @@ extension IPv6Address {
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv6Address {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -144,7 +147,7 @@ extension IPv6Address {
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv6Address: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"[\(addressString)]:\(port)"
|
||||
@@ -153,7 +156,7 @@ extension IPv6Address: CustomStringConvertible {
|
||||
|
||||
// MARK: - ExpressibleByStringLiteral
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv6Address: ExpressibleByStringLiteral {
|
||||
/// Creates an IPv6 address from a string literal.
|
||||
///
|
||||
@@ -186,7 +189,7 @@ extension IPv6Address: ExpressibleByStringLiteral {
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension IPv6Address {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: IPv6Address, rhs: IPv6Address) -> Bool {
|
||||
@@ -207,7 +210,7 @@ extension IPv6Address {
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from an IPv6 address.
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -25,7 +28,7 @@ import Android
|
||||
|
||||
/// An error returned by address resolution functions.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
public struct AddressResolutionError: Error, Hashable, Sendable {
|
||||
/// The error code returned by getaddrinfo or getnameinfo.
|
||||
public let code: CInt
|
||||
@@ -41,7 +44,7 @@ public struct AddressResolutionError: Error, Hashable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension AddressResolutionError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"AddressResolutionError(\(code)): \(message)"
|
||||
@@ -50,7 +53,7 @@ extension AddressResolutionError: CustomStringConvertible {
|
||||
|
||||
// MARK: - Resolution Hints
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Hints for address resolution.
|
||||
public struct ResolutionHints: Sendable {
|
||||
@@ -128,7 +131,7 @@ extension SocketAddress {
|
||||
|
||||
// MARK: - Resolution Result
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// A result from address resolution.
|
||||
public struct ResolvedAddress: Sendable {
|
||||
@@ -165,7 +168,7 @@ extension SocketAddress {
|
||||
|
||||
// MARK: - Address Resolution
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Resolves a hostname and service to a list of socket addresses.
|
||||
///
|
||||
@@ -250,7 +253,7 @@ extension SocketAddress {
|
||||
|
||||
// MARK: - Reverse Resolution
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Flags for reverse resolution.
|
||||
@frozen
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -25,7 +28,7 @@ import Android
|
||||
///
|
||||
/// Unix domain socket addresses use a filesystem path to identify the socket.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
public struct UnixAddress: Sendable, Equatable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
@@ -78,7 +81,7 @@ public struct UnixAddress: Sendable, Equatable, Hashable {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension UnixAddress {
|
||||
/// The path as a string.
|
||||
public var path: String {
|
||||
@@ -93,7 +96,7 @@ extension UnixAddress {
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension UnixAddress {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -117,7 +120,7 @@ extension UnixAddress {
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension UnixAddress: CustomStringConvertible {
|
||||
public var description: String {
|
||||
path
|
||||
@@ -126,7 +129,7 @@ extension UnixAddress: CustomStringConvertible {
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension UnixAddress {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: UnixAddress, rhs: UnixAddress) -> Bool {
|
||||
@@ -149,7 +152,7 @@ extension UnixAddress {
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from a Unix address.
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -44,7 +47,7 @@ import Android
|
||||
/// `SocketAddress` uses `sockaddr_storage` internally, which is large enough
|
||||
/// to hold any socket address type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
public struct SocketAddress: Sendable {
|
||||
/// The underlying storage using sockaddr_storage.
|
||||
@usableFromInline
|
||||
@@ -93,7 +96,7 @@ public struct SocketAddress: Sendable {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// The address family of this socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -119,7 +122,7 @@ extension SocketAddress {
|
||||
|
||||
// MARK: - Accessing Raw Bytes
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Calls the given closure with a pointer to the underlying socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -168,7 +171,7 @@ extension SocketAddress {
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: SocketAddress, rhs: SocketAddress) -> Bool {
|
||||
@@ -181,7 +184,7 @@ extension SocketAddress: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
@@ -194,7 +197,7 @@ extension SocketAddress: Hashable {
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketAddress: CustomStringConvertible {
|
||||
public var description: String {
|
||||
if isEmpty {
|
||||
|
||||
@@ -12,15 +12,28 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// Glibc imports the socket types as a C enum, every other platform imports
|
||||
// them as plain integers.
|
||||
#if canImport(Glibc)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _socketType(_ type: __socket_type) -> CInt { CInt(type.rawValue) }
|
||||
#else
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _socketType(_ type: CInt) -> CInt { type }
|
||||
#endif
|
||||
|
||||
/// A socket descriptor.
|
||||
///
|
||||
/// A `SocketDescriptor` is a type-safe wrapper around an operating system
|
||||
@@ -30,7 +43,7 @@ import Android
|
||||
/// socket rather than a general file descriptor, enabling socket-specific
|
||||
/// operations like `bind`, `listen`, `accept`, and `connect`.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
public struct SocketDescriptor: RawRepresentable, Hashable, Codable, Sendable {
|
||||
/// The raw C socket handle.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -41,7 +54,7 @@ public struct SocketDescriptor: RawRepresentable, Hashable, Codable, Sendable {
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// The file descriptor for this socket.
|
||||
///
|
||||
@@ -64,7 +77,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Domain (Protocol Family)
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Communications domain, identifying the protocol family.
|
||||
///
|
||||
@@ -156,7 +169,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Connection Type (Socket Type)
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// The socket type, specifying the semantics of communication.
|
||||
///
|
||||
@@ -178,26 +191,26 @@ extension SocketDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_STREAM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var stream: ConnectionType { ConnectionType(SOCK_STREAM) }
|
||||
public static var stream: ConnectionType { ConnectionType(_socketType(SOCK_STREAM)) }
|
||||
|
||||
/// Connectionless, unreliable datagrams of a fixed maximum length.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_DGRAM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var datagram: ConnectionType { ConnectionType(SOCK_DGRAM) }
|
||||
public static var datagram: ConnectionType { ConnectionType(_socketType(SOCK_DGRAM)) }
|
||||
|
||||
/// Raw network protocol access.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_RAW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var raw: ConnectionType { ConnectionType(SOCK_RAW) }
|
||||
public static var raw: ConnectionType { ConnectionType(_socketType(SOCK_RAW)) }
|
||||
|
||||
/// Reliably-delivered message.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_RDM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reliablyDeliveredMessage: ConnectionType {
|
||||
ConnectionType(SOCK_RDM)
|
||||
ConnectionType(_socketType(SOCK_RDM))
|
||||
}
|
||||
|
||||
/// Sequenced packet stream.
|
||||
@@ -205,7 +218,7 @@ extension SocketDescriptor {
|
||||
/// The corresponding C constant is `SOCK_SEQPACKET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sequencedPacketStream: ConnectionType {
|
||||
ConnectionType(SOCK_SEQPACKET)
|
||||
ConnectionType(_socketType(SOCK_SEQPACKET))
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
@@ -221,9 +234,56 @@ extension SocketDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket Flags
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Flags for a socket that is created or accepted.
|
||||
///
|
||||
/// The flags are combined with the socket type when a socket is created,
|
||||
/// and passed as `flags` to `accept4` when a connection is accepted. They
|
||||
/// apply atomically, so no other thread can observe the socket without them.
|
||||
///
|
||||
/// Darwin has no equivalent flags.
|
||||
@frozen
|
||||
public struct SocketFlags: OptionSet, Sendable, Hashable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Closes the socket when the process executes another program.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: SocketFlags {
|
||||
SocketFlags(rawValue: _socketType(SOCK_CLOEXEC))
|
||||
}
|
||||
|
||||
/// Opens the socket in non-blocking mode.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_NONBLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nonBlocking: SocketFlags {
|
||||
SocketFlags(rawValue: _socketType(SOCK_NONBLOCK))
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.closeOnExec, ".closeOnExec"),
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
]
|
||||
return _buildDescription(descriptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Protocol ID
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Identifies a particular protocol to use for communication.
|
||||
///
|
||||
@@ -248,37 +308,44 @@ extension SocketDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ip: ProtocolID { Self(IPPROTO_IP) }
|
||||
public static var ip: ProtocolID { Self(CInt(IPPROTO_IP)) }
|
||||
|
||||
/// Transmission Control Protocol (TCP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_TCP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tcp: ProtocolID { Self(IPPROTO_TCP) }
|
||||
public static var tcp: ProtocolID { Self(CInt(IPPROTO_TCP)) }
|
||||
|
||||
/// User Datagram Protocol (UDP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_UDP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var udp: ProtocolID { Self(IPPROTO_UDP) }
|
||||
public static var udp: ProtocolID { Self(CInt(IPPROTO_UDP)) }
|
||||
|
||||
/// IPv4 encapsulation.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV4`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: ProtocolID { Self(IPPROTO_IPV4) }
|
||||
public static var ipv4: ProtocolID {
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
// Linux names this protocol `IPPROTO_IPIP`.
|
||||
Self(CInt(IPPROTO_IPIP))
|
||||
#else
|
||||
Self(CInt(IPPROTO_IPV4))
|
||||
#endif
|
||||
}
|
||||
|
||||
/// IPv6 header.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: ProtocolID { Self(IPPROTO_IPV6) }
|
||||
public static var ipv6: ProtocolID { Self(CInt(IPPROTO_IPV6)) }
|
||||
|
||||
/// Raw IP packet.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_RAW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var raw: ProtocolID { Self(IPPROTO_RAW) }
|
||||
public static var raw: ProtocolID { Self(CInt(IPPROTO_RAW)) }
|
||||
|
||||
public var description: String {
|
||||
rawValue.description
|
||||
@@ -288,7 +355,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Message Flags
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Flags for send and receive operations.
|
||||
@frozen
|
||||
@@ -310,50 +377,50 @@ extension SocketDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `MSG_OOB`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var outOfBand: MessageFlags { MessageFlags(MSG_OOB) }
|
||||
public static var outOfBand: MessageFlags { MessageFlags(CInt(MSG_OOB)) }
|
||||
|
||||
/// Bypass routing, use direct interface.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_DONTROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var doNotRoute: MessageFlags { MessageFlags(MSG_DONTROUTE) }
|
||||
public static var doNotRoute: MessageFlags { MessageFlags(CInt(MSG_DONTROUTE)) }
|
||||
|
||||
/// Peek at incoming message without removing it.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_PEEK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var peek: MessageFlags { MessageFlags(MSG_PEEK) }
|
||||
public static var peek: MessageFlags { MessageFlags(CInt(MSG_PEEK)) }
|
||||
|
||||
/// Wait for full request or error.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_WAITALL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var waitForAll: MessageFlags { MessageFlags(MSG_WAITALL) }
|
||||
public static var waitForAll: MessageFlags { MessageFlags(CInt(MSG_WAITALL)) }
|
||||
|
||||
/// End-of-record marker.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_EOR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var endOfRecord: MessageFlags { MessageFlags(MSG_EOR) }
|
||||
public static var endOfRecord: MessageFlags { MessageFlags(CInt(MSG_EOR)) }
|
||||
|
||||
/// Data was truncated.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_TRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataTruncated: MessageFlags { MessageFlags(MSG_TRUNC) }
|
||||
public static var dataTruncated: MessageFlags { MessageFlags(CInt(MSG_TRUNC)) }
|
||||
|
||||
/// Control data was truncated.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_CTRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var controlTruncated: MessageFlags { MessageFlags(MSG_CTRUNC) }
|
||||
public static var controlTruncated: MessageFlags { MessageFlags(CInt(MSG_CTRUNC)) }
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
/// Do not generate SIGPIPE on broken pipe.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_NOSIGNAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSignal: MessageFlags { MessageFlags(MSG_NOSIGNAL) }
|
||||
public static var noSignal: MessageFlags { MessageFlags(CInt(MSG_NOSIGNAL)) }
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
@@ -376,7 +443,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Shutdown Kind
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Specifies which parts of a full-duplex connection to shut down.
|
||||
@frozen
|
||||
@@ -391,19 +458,19 @@ extension SocketDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_RD`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var read: ShutdownKind { ShutdownKind(rawValue: SHUT_RD) }
|
||||
public static var read: ShutdownKind { ShutdownKind(rawValue: CInt(SHUT_RD)) }
|
||||
|
||||
/// Disallow further sends.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_WR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var write: ShutdownKind { ShutdownKind(rawValue: SHUT_WR) }
|
||||
public static var write: ShutdownKind { ShutdownKind(rawValue: CInt(SHUT_WR)) }
|
||||
|
||||
/// Disallow further sends and receives.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_RDWR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var readWrite: ShutdownKind { ShutdownKind(rawValue: SHUT_RDWR) }
|
||||
public static var readWrite: ShutdownKind { ShutdownKind(rawValue: CInt(SHUT_RDWR)) }
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
@@ -418,7 +485,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Socket Option
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// A generic socket option identifier.
|
||||
///
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Writes a sequence of bytes to the socket
|
||||
///
|
||||
|
||||
@@ -9,7 +9,22 @@
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// A reusable collection of variable-sized ancillary messages
|
||||
/// sent or received over a socket. These represent protocol control
|
||||
@@ -119,7 +134,8 @@ extension SocketDescriptor {
|
||||
let length = try body(
|
||||
UnsafeMutableRawBufferPointer(start: p + headerSize, count: capacity))
|
||||
precondition(length >= 0 && length <= capacity)
|
||||
header.pointee.cmsg_len = CInterop.SockLen(headerSize + length)
|
||||
// `cmsg_len` is a `socklen_t` on Darwin and a `size_t` on Linux.
|
||||
header.pointee.cmsg_len = numericCast(headerSize + length)
|
||||
return headerSize + length
|
||||
}
|
||||
_endOffset += messageLength
|
||||
@@ -167,7 +183,7 @@ extension SocketDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor.AncillaryMessageBuffer: Collection {
|
||||
/// The index type in an ancillary message buffer.
|
||||
@frozen
|
||||
@@ -276,7 +292,7 @@ extension SocketDescriptor.AncillaryMessageBuffer: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor.AncillaryMessageBuffer.Message {
|
||||
internal var _header: CInterop.CMsgHdr {
|
||||
_base._withUnsafeBytes { buffer in
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -23,7 +26,7 @@ import Android
|
||||
|
||||
// MARK: - Socket Creation and Lifecycle
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Creates an endpoint for communication.
|
||||
///
|
||||
@@ -94,7 +97,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Connection Operations
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Binds a socket to an address.
|
||||
///
|
||||
@@ -202,7 +205,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Send and Receive
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Sends data on the socket.
|
||||
///
|
||||
@@ -347,7 +350,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Socket Information
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets the local address of the socket.
|
||||
///
|
||||
|
||||
@@ -12,10 +12,13 @@ import SystemPackage
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -23,7 +26,7 @@ import Android
|
||||
|
||||
// MARK: - Option Level
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Socket option levels.
|
||||
@frozen
|
||||
@@ -44,31 +47,31 @@ extension SocketDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ip: OptionLevel { OptionLevel(rawValue: IPPROTO_IP) }
|
||||
public static var ip: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_IP)) }
|
||||
|
||||
/// IPv6 protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: OptionLevel { OptionLevel(rawValue: IPPROTO_IPV6) }
|
||||
public static var ipv6: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_IPV6)) }
|
||||
|
||||
/// TCP protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_TCP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tcp: OptionLevel { OptionLevel(rawValue: IPPROTO_TCP) }
|
||||
public static var tcp: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_TCP)) }
|
||||
|
||||
/// UDP protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_UDP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var udp: OptionLevel { OptionLevel(rawValue: IPPROTO_UDP) }
|
||||
public static var udp: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_UDP)) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket-Level Options
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Socket-level options for use with `getOption` and `setOption`.
|
||||
@frozen
|
||||
@@ -171,7 +174,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - TCP Options
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// TCP-level options for use with `getOption` and `setOption`.
|
||||
@frozen
|
||||
@@ -227,7 +230,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Get and Set Options
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets a socket option value.
|
||||
///
|
||||
@@ -312,7 +315,7 @@ extension SocketDescriptor {
|
||||
|
||||
// MARK: - Convenience Methods
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets a socket-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
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/Android), 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) || canImport(Android)
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#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
|
||||
@@ -13,8 +13,6 @@ import SystemPackage
|
||||
|
||||
@Suite("Ancillary Message Buffer")
|
||||
struct AncillaryMessageBufferTests {
|
||||
|
||||
@available(System 99, *)
|
||||
@Test("Append and iterate messages")
|
||||
func testAppend() {
|
||||
// Create a buffer of 100 messages, with varying payload lengths.
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import Testing
|
||||
|
||||
#if canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
/// Whether the environment can create an `IORing` at all.
|
||||
private let ioRingAvailable: Bool = {
|
||||
do {
|
||||
_ = try IORing(queueDepth: 1)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}()
|
||||
|
||||
/// Whether the kernel knows the operation of the given request.
|
||||
///
|
||||
/// The request has to target an invalid descriptor or argument. A kernel that
|
||||
/// doesn't know the operation fails it with `EINVAL`, one that does fails it
|
||||
/// with another error.
|
||||
@available(System 199, *)
|
||||
private func kernelSupports(_ request: IORing.Request) -> Bool {
|
||||
guard ioRingAvailable else { return false }
|
||||
do {
|
||||
var ring = try IORing(queueDepth: 1)
|
||||
guard try ring.submit(linkedRequests: request) else { return false }
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
return completion.error != .invalidArgument
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
private let invalidSocket = SocketDescriptor(rawValue: -1)
|
||||
|
||||
@available(System 199, *)
|
||||
private let socketSupported = kernelSupports(
|
||||
.socket(SocketDescriptor.Domain(rawValue: -1), .stream)
|
||||
)
|
||||
|
||||
@available(System 199, *)
|
||||
private let shutdownSupported = kernelSupports(.shutdown(invalidSocket, .write))
|
||||
|
||||
@available(System 199, *)
|
||||
private let bindAndListenSupported = kernelSupports(.listen(invalidSocket, backlog: 1))
|
||||
|
||||
/// Whether the environment has an IPv6 loopback interface.
|
||||
@available(System 199, *)
|
||||
private let ipv6LoopbackAvailable: Bool = {
|
||||
do {
|
||||
let socket = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
try socket.bind(to: SocketAddress(ipv6: .loopback(port: 0)))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}()
|
||||
|
||||
/// Consumes the given number of completions and returns their results by context.
|
||||
private func consumeResults(
|
||||
_ count: Int,
|
||||
from ring: borrowing IORing
|
||||
) throws -> [UInt64: Int32] {
|
||||
var results: [UInt64: Int32] = [:]
|
||||
for _ in 0..<count {
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
results[completion.context] = completion.result
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@Suite("IORing socket requests", .enabled(if: ioRingAvailable))
|
||||
private struct IORingSocketTests {
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Creates a listening socket on the loopback interface.
|
||||
@available(System 199, *)
|
||||
private func makeListener() throws -> (SocketDescriptor, SocketAddress) {
|
||||
let listener = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
try listener.bind(to: SocketAddress(ipv4: .loopback(port: 0)))
|
||||
try listener.listen(backlog: 8)
|
||||
var address = SocketAddress()
|
||||
try listener.getLocalAddress(into: &address)
|
||||
return (listener, address)
|
||||
}
|
||||
|
||||
/// Creates a connected pair of sockets on the loopback interface.
|
||||
@available(System 199, *)
|
||||
private func makeConnectedPair() throws -> (client: SocketDescriptor, server: SocketDescriptor) {
|
||||
let (listener, address) = try makeListener()
|
||||
defer { try? listener.close() }
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
try client.connect(to: address)
|
||||
let server = try listener.accept()
|
||||
return (client, server)
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: socketSupported))
|
||||
func socketCreatesSocket() throws {
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests:
|
||||
.socket(.ipv4, .stream, protocol: .tcp, flags: .closeOnExec, context: 1)
|
||||
)
|
||||
#expect(submitted)
|
||||
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 1)
|
||||
#expect(completion.error == nil)
|
||||
|
||||
let socket = SocketDescriptor(rawValue: completion.result)
|
||||
defer { try? socket.close() }
|
||||
#expect(fcntl(socket.rawValue, F_GETFD) & FD_CLOEXEC != 0)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: bindAndListenSupported))
|
||||
func bindAndListen() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests:
|
||||
.bind(socket, to: SocketAddress(ipv4: .loopback(port: 0)), context: 1),
|
||||
.listen(socket, backlog: 8, context: 2)
|
||||
)
|
||||
#expect(submitted)
|
||||
let results = try consumeResults(2, from: ring)
|
||||
#expect(results[1] == 0)
|
||||
#expect(results[2] == 0)
|
||||
|
||||
// A client can connect, so the socket is listening.
|
||||
var address = SocketAddress()
|
||||
try socket.getLocalAddress(into: &address)
|
||||
#expect(address.ipv4?.port != 0)
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
try client.connect(to: address)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: shutdownSupported))
|
||||
func acceptConnectSendReceiveAndShutdown() throws {
|
||||
let (listener, address) = try makeListener()
|
||||
defer { try? listener.close() }
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
var ring = try IORing(queueDepth: 8)
|
||||
let acceptPrepared = ring.prepare(request: .accept(listener, flags: .closeOnExec, context: 1))
|
||||
#expect(acceptPrepared)
|
||||
let connectPrepared = ring.prepare(request: .connect(client, to: address, context: 2))
|
||||
#expect(connectPrepared)
|
||||
try ring.submitPreparedRequests()
|
||||
let connected = try consumeResults(2, from: ring)
|
||||
#expect(connected[2] == 0)
|
||||
let acceptedFD = try #require(connected[1])
|
||||
#expect(acceptedFD >= 0)
|
||||
let server = SocketDescriptor(rawValue: acceptedFD)
|
||||
defer { try? server.close() }
|
||||
|
||||
let message: [UInt8] = Array("Hello, io_uring!".utf8)
|
||||
var received = [UInt8](repeating: 0, count: 64)
|
||||
let exchanged = try message.withUnsafeBytes { sendBuffer in
|
||||
try received.withUnsafeMutableBytes { receiveBuffer in
|
||||
let sendPrepared = ring.prepare(request: .send(sendBuffer, to: client, context: 3))
|
||||
#expect(sendPrepared)
|
||||
let receivePrepared = ring.prepare(request: .receive(server, into: receiveBuffer, context: 4))
|
||||
#expect(receivePrepared)
|
||||
try ring.submitPreparedRequests()
|
||||
return try consumeResults(2, from: ring)
|
||||
}
|
||||
}
|
||||
#expect(exchanged[3] == Int32(message.count))
|
||||
#expect(exchanged[4] == Int32(message.count))
|
||||
#expect(Array(received.prefix(message.count)) == message)
|
||||
|
||||
// Once the client shuts down writing, the server reads the end of the stream.
|
||||
let endOfStream = try received.withUnsafeMutableBytes { receiveBuffer in
|
||||
let shutdownSubmitted = try ring.submit(linkedRequests: .shutdown(client, .write, context: 5))
|
||||
#expect(shutdownSubmitted)
|
||||
let receiveSubmitted = try ring.submit(linkedRequests: .receive(server, into: receiveBuffer, context: 6))
|
||||
#expect(receiveSubmitted)
|
||||
return try consumeResults(2, from: ring)
|
||||
}
|
||||
#expect(endOfStream[5] == 0)
|
||||
#expect(endOfStream[6] == 0)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func acceptWritesPeerAddress() throws {
|
||||
let (listener, address) = try makeListener()
|
||||
defer { try? listener.close() }
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
// The kernel writes the peer's address when the accept completes, so both
|
||||
// pointers have to stay valid until the completion is consumed.
|
||||
var peerStorage = sockaddr_storage()
|
||||
var peerLength = CInterop.SockLen(MemoryLayout<sockaddr_storage>.size)
|
||||
let acceptedFD = try withUnsafeMutablePointer(to: &peerLength) { peerAddressLength in
|
||||
try withUnsafeMutablePointer(to: &peerStorage) { storage in
|
||||
try storage.withMemoryRebound(to: CInterop.SockAddr.self, capacity: 1) { peerAddress in
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests: .accept(
|
||||
listener, peerAddress: peerAddress, peerAddressLength: peerAddressLength, context: 1
|
||||
))
|
||||
#expect(submitted)
|
||||
try client.connect(to: address)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 1)
|
||||
return completion.result
|
||||
}
|
||||
}
|
||||
}
|
||||
#expect(acceptedFD >= 0)
|
||||
try? SocketDescriptor(rawValue: acceptedFD).close()
|
||||
|
||||
var clientAddress = SocketAddress()
|
||||
try client.getLocalAddress(into: &clientAddress)
|
||||
let peer = withUnsafePointer(to: &peerStorage) { storage in
|
||||
storage.withMemoryRebound(to: CInterop.SockAddr.self, capacity: 1) {
|
||||
SocketAddress(address: $0, length: peerLength)
|
||||
}
|
||||
}
|
||||
#expect(peer.ipv4?.port == clientAddress.ipv4?.port)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func sendDoesNotRaiseSigpipe() throws {
|
||||
let (client, server) = try makeConnectedPair()
|
||||
defer {
|
||||
try? client.close()
|
||||
try? server.close()
|
||||
}
|
||||
// Writing to a socket that is shut down for writing raises `SIGPIPE`. A
|
||||
// send request doesn't, since io_uring sets `MSG_NOSIGNAL` for it, even
|
||||
// without passing `.noSignal`.
|
||||
try client.shutdown(.write)
|
||||
|
||||
// The test process might ignore `SIGPIPE`, which would hide it. Blocking
|
||||
// it on this thread keeps a raised `SIGPIPE` pending, so we can check
|
||||
// for it. The send fails right away, so it runs on this thread.
|
||||
var sigpipe = sigset_t()
|
||||
sigemptyset(&sigpipe)
|
||||
sigaddset(&sigpipe, SIGPIPE)
|
||||
var previousMask = sigset_t()
|
||||
pthread_sigmask(SIG_BLOCK, &sigpipe, &previousMask)
|
||||
defer {
|
||||
// Consume a pending `SIGPIPE` so that it isn't delivered once unblocked.
|
||||
var noWait = timespec()
|
||||
while sigtimedwait(&sigpipe, nil, &noWait) == SIGPIPE {}
|
||||
pthread_sigmask(SIG_SETMASK, &previousMask, nil)
|
||||
}
|
||||
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let message: [UInt8] = [1, 2, 3]
|
||||
let results = try message.withUnsafeBytes { buffer in
|
||||
let submitted = try ring.submit(linkedRequests: .send(buffer, to: client, context: 1))
|
||||
#expect(submitted)
|
||||
return try consumeResults(1, from: ring)
|
||||
}
|
||||
#expect(results[1] == -Errno.brokenPipe.rawValue)
|
||||
|
||||
var pending = sigset_t()
|
||||
sigpending(&pending)
|
||||
#expect(sigismember(&pending, SIGPIPE) == 0, "the send raised SIGPIPE")
|
||||
}
|
||||
|
||||
// An IPv6 address is longer than an IPv4 one, so this checks that connect
|
||||
// passes the length of the given address.
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: ipv6LoopbackAvailable))
|
||||
func connectOverIPv6() throws {
|
||||
let listener = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
defer { try? listener.close() }
|
||||
try listener.bind(to: SocketAddress(ipv6: .loopback(port: 0)))
|
||||
try listener.listen(backlog: 8)
|
||||
var address = SocketAddress()
|
||||
try listener.getLocalAddress(into: &address)
|
||||
|
||||
let client = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests: .connect(client, to: address, context: 1))
|
||||
#expect(submitted)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 1)
|
||||
// Accepting blocks, so it only runs once the client is connected.
|
||||
try #require(completion.error == nil)
|
||||
|
||||
let server = try listener.accept()
|
||||
try server.close()
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func connectToClosedPortFails() throws {
|
||||
// Bind a socket to get a free port, then close it so nothing listens there.
|
||||
let (listener, address) = try makeListener()
|
||||
try listener.close()
|
||||
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests: .connect(client, to: address, context: 7))
|
||||
#expect(submitted)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 7)
|
||||
#expect(completion.error == .connectionRefused)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -14,10 +14,13 @@ import Testing
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -31,7 +34,7 @@ private struct SocketAddressTests {
|
||||
|
||||
// MARK: - IPv4 Address Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4BasicCreation() {
|
||||
let addr = IPv4Address("127.0.0.1", port: 8080)
|
||||
#expect(addr != nil)
|
||||
@@ -39,34 +42,34 @@ private struct SocketAddressTests {
|
||||
#expect(addr?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4InvalidAddress() {
|
||||
let addr = IPv4Address("not.an.ip.address", port: 8080)
|
||||
#expect(addr == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Any() {
|
||||
let addr = IPv4Address.any(port: 0)
|
||||
#expect(addr.port == 0)
|
||||
#expect(addr.addressString == "0.0.0.0")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Loopback() {
|
||||
let addr = IPv4Address.loopback(port: 80)
|
||||
#expect(addr.port == 80)
|
||||
#expect(addr.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4StringLiteral() {
|
||||
let addr: IPv4Address = "192.168.1.1:443"
|
||||
#expect(addr.port == 443)
|
||||
#expect(addr.addressString == "192.168.1.1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Equality() {
|
||||
let addr1 = IPv4Address("10.0.0.1", port: 8080)!
|
||||
let addr2 = IPv4Address("10.0.0.1", port: 8080)!
|
||||
@@ -78,7 +81,7 @@ private struct SocketAddressTests {
|
||||
#expect(addr1 != addr4)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Description() {
|
||||
let addr = IPv4Address("8.8.8.8", port: 53)!
|
||||
#expect(addr.description == "8.8.8.8:53")
|
||||
@@ -86,7 +89,7 @@ private struct SocketAddressTests {
|
||||
|
||||
// MARK: - IPv6 Address Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv6BasicCreation() {
|
||||
let addr = IPv6Address("::1", port: 8080)
|
||||
#expect(addr != nil)
|
||||
@@ -94,33 +97,33 @@ private struct SocketAddressTests {
|
||||
#expect(addr?.addressString == "::1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv6InvalidAddress() {
|
||||
let addr = IPv6Address("not:an:ipv6:address", port: 8080)
|
||||
#expect(addr == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv6Any() {
|
||||
let addr = IPv6Address.any(port: 0)
|
||||
#expect(addr.port == 0)
|
||||
#expect(addr.addressString == "::")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv6Loopback() {
|
||||
let addr = IPv6Address.loopback(port: 80)
|
||||
#expect(addr.port == 80)
|
||||
#expect(addr.addressString == "::1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv6Description() {
|
||||
let addr = IPv6Address("2001:db8::1", port: 443)!
|
||||
#expect(addr.description == "[2001:db8::1]:443")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func ipv6StringLiteral() {
|
||||
let addr: IPv6Address = "[::1]:8080"
|
||||
#expect(addr.port == 8080)
|
||||
@@ -129,20 +132,20 @@ private struct SocketAddressTests {
|
||||
|
||||
// MARK: - Unix Address Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func unixBasicCreation() {
|
||||
let addr = UnixAddress("/tmp/test.sock")
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.path == "/tmp/test.sock")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func unixDescription() {
|
||||
let addr = UnixAddress("/var/run/daemon.sock")!
|
||||
#expect(addr.description == "/var/run/daemon.sock")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func unixEquality() {
|
||||
let addr1 = UnixAddress("/tmp/a.sock")!
|
||||
let addr2 = UnixAddress("/tmp/a.sock")!
|
||||
@@ -154,7 +157,7 @@ private struct SocketAddressTests {
|
||||
|
||||
// MARK: - SocketAddress Container Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func socketAddressFromIPv4() {
|
||||
let ipv4 = IPv4Address.loopback(port: 8080)
|
||||
let sockAddr = SocketAddress(ipv4: ipv4)
|
||||
@@ -166,7 +169,7 @@ private struct SocketAddressTests {
|
||||
#expect(sockAddr.unix == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func socketAddressFromIPv6() {
|
||||
let ipv6 = IPv6Address.loopback(port: 443)
|
||||
let sockAddr = SocketAddress(ipv6: ipv6)
|
||||
@@ -178,7 +181,7 @@ private struct SocketAddressTests {
|
||||
#expect(sockAddr.unix == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func socketAddressFromUnix() {
|
||||
let unix = UnixAddress("/tmp/test.sock")!
|
||||
let sockAddr = SocketAddress(unix: unix)
|
||||
|
||||
@@ -14,10 +14,13 @@ import Testing
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -31,20 +34,38 @@ private struct SocketDescriptorTests {
|
||||
|
||||
// MARK: - Type Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func domainValues() {
|
||||
#expect(SocketDescriptor.Domain.ipv4.rawValue == AF_INET)
|
||||
#expect(SocketDescriptor.Domain.ipv6.rawValue == AF_INET6)
|
||||
#expect(SocketDescriptor.Domain.local.rawValue == AF_UNIX)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func connectionTypeValues() {
|
||||
// Glibc imports the socket types as a C enum.
|
||||
#if canImport(Glibc)
|
||||
#expect(SocketDescriptor.ConnectionType.stream.rawValue == CInt(SOCK_STREAM.rawValue))
|
||||
#expect(SocketDescriptor.ConnectionType.datagram.rawValue == CInt(SOCK_DGRAM.rawValue))
|
||||
#else
|
||||
#expect(SocketDescriptor.ConnectionType.stream.rawValue == SOCK_STREAM)
|
||||
#expect(SocketDescriptor.ConnectionType.datagram.rawValue == SOCK_DGRAM)
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
@Test func socketFlagsValues() {
|
||||
#if canImport(Glibc)
|
||||
#expect(SocketDescriptor.SocketFlags.closeOnExec.rawValue == CInt(SOCK_CLOEXEC.rawValue))
|
||||
#expect(SocketDescriptor.SocketFlags.nonBlocking.rawValue == CInt(SOCK_NONBLOCK.rawValue))
|
||||
#else
|
||||
#expect(SocketDescriptor.SocketFlags.closeOnExec.rawValue == SOCK_CLOEXEC)
|
||||
#expect(SocketDescriptor.SocketFlags.nonBlocking.rawValue == SOCK_NONBLOCK)
|
||||
#endif
|
||||
#expect(
|
||||
"\(SocketDescriptor.SocketFlags([.closeOnExec, .nonBlocking]))" == "[.closeOnExec, .nonBlocking]"
|
||||
)
|
||||
}
|
||||
#endif
|
||||
|
||||
@Test func protocolValues() {
|
||||
#expect(SocketDescriptor.ProtocolID.tcp.rawValue == CInt(IPPROTO_TCP))
|
||||
#expect(SocketDescriptor.ProtocolID.udp.rawValue == CInt(IPPROTO_UDP))
|
||||
@@ -52,28 +73,28 @@ private struct SocketDescriptorTests {
|
||||
|
||||
// MARK: - Socket Creation Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func createTCPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func createUDPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func createIPv6TCPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func createUnixSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.local, .stream)
|
||||
#expect(socket.rawValue >= 0)
|
||||
@@ -82,7 +103,6 @@ private struct SocketDescriptorTests {
|
||||
|
||||
// MARK: - Shutdown Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func shutdownKindValues() {
|
||||
#expect(SocketDescriptor.ShutdownKind.read.rawValue == SHUT_RD)
|
||||
#expect(SocketDescriptor.ShutdownKind.write.rawValue == SHUT_WR)
|
||||
|
||||
@@ -14,10 +14,13 @@ import Testing
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -31,7 +34,7 @@ private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Bind Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func bindToAnyPort() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
@@ -46,7 +49,7 @@ private struct SocketOperationsTests {
|
||||
#expect(localAddr.ipv4?.port != 0) // Port should be assigned
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func bindToLoopback() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
@@ -61,7 +64,7 @@ private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Listen Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func listenWithDefaultBacklog() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
@@ -73,7 +76,7 @@ private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Connect and Accept Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func tcpConnectAndAccept() throws {
|
||||
// Create server socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
@@ -106,7 +109,7 @@ private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Send and Receive Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func tcpSendReceive() throws {
|
||||
// Create server socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
@@ -152,7 +155,7 @@ private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - UDP Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func udpSendReceive() throws {
|
||||
// Create receiver socket
|
||||
let receiver = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
@@ -193,7 +196,7 @@ private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Socket Options Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func setReuseAddress() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
@@ -203,7 +206,7 @@ private struct SocketOperationsTests {
|
||||
#expect(value != 0)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func getSendBufferSize() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
@@ -212,7 +215,7 @@ private struct SocketOperationsTests {
|
||||
#expect(size > 0)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 199, *)
|
||||
@Test func getReceiveBufferSize() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 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
|
||||
@@ -36,7 +36,7 @@ import Android
|
||||
@Suite("FileMode")
|
||||
private struct FileModeTests {
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func basics() async throws {
|
||||
var mode = FileMode(rawValue: S_IFREG | 0o644) // Regular file, rw-r--r--
|
||||
#expect(mode.type == .regular)
|
||||
@@ -67,7 +67,7 @@ private struct FileModeTests {
|
||||
#expect(mode.type == mode2.type)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func invalidInput() async throws {
|
||||
// No permissions, all other bits set
|
||||
var invalidMode = FileMode(rawValue: ~0o7777)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -157,7 +157,8 @@ final class FileOperationsTest: XCTestCase {
|
||||
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
|
||||
}
|
||||
|
||||
#if !os(WASI) // WASI has no pipe
|
||||
#if !os(WASI) // WASI has no pipe
|
||||
@available(System 1.1.0, *)
|
||||
func testAdHocPipe() 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`.
|
||||
@@ -176,7 +177,107 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testAdHocPipeWithOptions() throws {
|
||||
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
|
||||
throw XCTSkip("pipe2 and PipeOptions require Darwin 27 or newer")
|
||||
}
|
||||
// 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 // !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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAdHocDuplicate3() throws {
|
||||
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
|
||||
throw XCTSkip("dup3 and DuplicateOptions require Darwin 27 or newer")
|
||||
}
|
||||
|
||||
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 // !os(Windows)
|
||||
|
||||
func testAdHocOpen() {
|
||||
// Ad-hoc test touching a file system.
|
||||
@@ -236,6 +337,7 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
@available(System 1.2.0, *)
|
||||
func testResizeFile() throws {
|
||||
try withTemporaryFilePath(basename: "testResizeFile") { path in
|
||||
let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
|
||||
@@ -18,6 +18,11 @@ import XCTest
|
||||
#endif
|
||||
|
||||
import WinSDK
|
||||
import ucrt
|
||||
|
||||
private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA)
|
||||
private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE)
|
||||
private let FILE_READ_ATTRIBUTES = DWORD(WinSDK.FILE_READ_ATTRIBUTES)
|
||||
|
||||
@available(iOS 8, *)
|
||||
final class FileOperationsTestWindows: XCTestCase {
|
||||
@@ -43,6 +48,8 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
| SYNCHRONIZE
|
||||
)
|
||||
|
||||
private let none = ACCESS_MASK(0)
|
||||
|
||||
private struct Test {
|
||||
var permissions: CModeT
|
||||
var ownerAccess: ACCESS_MASK
|
||||
@@ -72,7 +79,7 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
var psidEveryone: PSID? = nil
|
||||
|
||||
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
|
||||
DWORD(SECURITY_WORLD_RID),
|
||||
SECURITY_WORLD_RID,
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
&psidEveryone))
|
||||
defer {
|
||||
@@ -106,7 +113,7 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
&psidGroup,
|
||||
&pDacl,
|
||||
nil,
|
||||
&pSD), DWORD(ERROR_SUCCESS))
|
||||
&pSD), ERROR_SUCCESS)
|
||||
defer {
|
||||
LocalFree(pSD)
|
||||
}
|
||||
@@ -135,15 +142,15 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
XCTAssertEqual(GetEffectiveRightsFromAclW(
|
||||
pDacl,
|
||||
&owner,
|
||||
&ownerAccess), DWORD(ERROR_SUCCESS))
|
||||
&ownerAccess), ERROR_SUCCESS)
|
||||
XCTAssertEqual(GetEffectiveRightsFromAclW(
|
||||
pDacl,
|
||||
&group,
|
||||
&groupAccess), DWORD(ERROR_SUCCESS))
|
||||
&groupAccess), ERROR_SUCCESS)
|
||||
XCTAssertEqual(GetEffectiveRightsFromAclW(
|
||||
pDacl,
|
||||
&everyone,
|
||||
&otherAccess), DWORD(ERROR_SUCCESS))
|
||||
&otherAccess), ERROR_SUCCESS)
|
||||
|
||||
return (ownerAccess, groupAccess, otherAccess)
|
||||
}
|
||||
@@ -182,9 +189,9 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
|
||||
try withTemporaryFilePath(basename: "testUmask") { path in
|
||||
let tests = [
|
||||
Test(0o000, 0, 0, 0),
|
||||
Test(0o700, r|w|x, 0, 0),
|
||||
Test(0o770, r|w|x, r|x, 0),
|
||||
Test(0o000, none, none, none),
|
||||
Test(0o700, r|w|x, none, none),
|
||||
Test(0o770, r|w|x, r|x, none),
|
||||
Test(0o777, r|w|x, r|x, r|x)
|
||||
]
|
||||
|
||||
@@ -195,9 +202,9 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
.otherWrite, .otherExecute]) {
|
||||
try withTemporaryFilePath(basename: "testUmask") { path in
|
||||
let tests = [
|
||||
Test(0o000, 0, 0, 0),
|
||||
Test(0o700, r|w|x, 0, 0),
|
||||
Test(0o770, r|w|x, r, 0),
|
||||
Test(0o000, none, none, none),
|
||||
Test(0o700, r|w|x, none, none),
|
||||
Test(0o770, r|w|x, r, none),
|
||||
Test(0o777, r|w|x, r, r)
|
||||
]
|
||||
|
||||
@@ -214,34 +221,113 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
try FilePermissions.withCreationMask([]) {
|
||||
try withTemporaryFilePath(basename: "testPermissions") { path in
|
||||
let tests = [
|
||||
Test(0o000, 0, 0, 0),
|
||||
Test(0o000, none, none, none),
|
||||
|
||||
Test(0o400, r, 0, 0),
|
||||
Test(0o200, w, 0, 0),
|
||||
Test(0o100, x, 0, 0),
|
||||
Test(0o040, 0, r, 0),
|
||||
Test(0o020, 0, w, 0),
|
||||
Test(0o010, 0, x, 0),
|
||||
Test(0o004, 0, 0, r),
|
||||
Test(0o002, 0, 0, w),
|
||||
Test(0o001, 0, 0, x),
|
||||
Test(0o400, r, none, none),
|
||||
Test(0o200, w, none, none),
|
||||
Test(0o100, x, none, none),
|
||||
Test(0o040, none, r, none),
|
||||
Test(0o020, none, w, none),
|
||||
Test(0o010, none, x, none),
|
||||
Test(0o004, none, none, r),
|
||||
Test(0o002, none, none, w),
|
||||
Test(0o001, none, none, x),
|
||||
|
||||
Test(0o700, r|w|x, 0, 0),
|
||||
Test(0o770, r|w|x, r|w|x, 0),
|
||||
Test(0o700, r|w|x, none, none),
|
||||
Test(0o770, r|w|x, r|w|x, none),
|
||||
Test(0o777, r|w|x, r|w|x, r|w|x),
|
||||
|
||||
Test(0o755, r|w|x, r|x, r|x),
|
||||
Test(0o644, r|w, r, r),
|
||||
|
||||
Test(0o007, 0, 0, r|w|x),
|
||||
Test(0o070, 0, r|w|x, 0),
|
||||
Test(0o077, 0, r|w|x, r|w|x),
|
||||
Test(0o007, none, none, r|w|x),
|
||||
Test(0o070, none, r|w|x, none),
|
||||
Test(0o077, none, r|w|x, r|w|x),
|
||||
]
|
||||
|
||||
try runTests(tests, at: path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
func testCloseOnExecOpenOption() throws {
|
||||
try withTemporaryFilePath(basename: "testCloseOnExec") { path in
|
||||
|
||||
func hasInheritFlag(of fd: FileDescriptor) throws -> Bool {
|
||||
let osfHandle = _get_osfhandle(fd.rawValue)
|
||||
let handle = try XCTUnwrap(HANDLE(bitPattern: osfHandle))
|
||||
var flags: DWORD = 0
|
||||
XCTAssertTrue(GetHandleInformation(handle, &flags))
|
||||
return flags & DWORD(HANDLE_FLAG_INHERIT) == DWORD(HANDLE_FLAG_INHERIT)
|
||||
}
|
||||
|
||||
var fd: FileDescriptor
|
||||
fd = try FileDescriptor.open(
|
||||
path.appending("wontinherit.txt"), .readWrite,
|
||||
options: [.create, .truncate, .closeOnExec],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
XCTAssertEqual(try hasInheritFlag(of: fd), false)
|
||||
}
|
||||
|
||||
fd = try FileDescriptor.open(
|
||||
path.appending("inheritable.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
XCTAssertEqual(try hasInheritFlag(of: fd), true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // os(Windows)
|
||||
@@ -22,7 +22,8 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
|
||||
// which are known to work correctly.
|
||||
final class IORequestTests: XCTestCase {
|
||||
func testNop() {
|
||||
let req = IORing.Request.nop().makeRawRequest()
|
||||
let req = IORing.Request.nop().makeRawRequest(
|
||||
pathBuffers: PendingPathBuffers(reservedCapacity: 0))
|
||||
let sourceBytes = requestBytes(req)
|
||||
// convenient property of nop: it's all zeros!
|
||||
// for some unknown reason, liburing sets the fd field to -1.
|
||||
|
||||
@@ -3,36 +3,94 @@
|
||||
|
||||
import XCTest
|
||||
import CSystem //for eventfd
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#if canImport(Glibc)
|
||||
import Glibc // for errno
|
||||
#elseif canImport(Musl)
|
||||
import Musl // for errno
|
||||
#endif
|
||||
|
||||
func uringEnabled() throws -> Bool {
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
// Cache `isUringEnabled()`. The probe is complex and the answer doesn't change
|
||||
// during a test run.
|
||||
let uringEnabled: Bool = {
|
||||
do {
|
||||
let procPath = FilePath("/proc/sys/kernel/io_uring_disabled")
|
||||
let fd = try FileDescriptor.open(procPath, .readOnly)
|
||||
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0)
|
||||
_ = try fd.read(into: buffer)
|
||||
if buffer.load(fromByteOffset: 0, as: Int.self) == 0 {
|
||||
return true
|
||||
}
|
||||
} catch (_) {
|
||||
return try isUringEnabled()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}()
|
||||
|
||||
let failureMessage = "Runtime environment does not support IORing."
|
||||
|
||||
func isUringEnabled() throws -> Bool {
|
||||
// Even if the kernel supports io_uring, the SystemPackage build may have
|
||||
// been compiled against older kernel headers that lack features it needs
|
||||
// (gated on IORING_TIMEOUT_BOOTTIME in CSystem); in that configuration
|
||||
// IORing.init throws ENOTSUP. Treat that as disabled so tests skip cleanly
|
||||
// instead of failing.
|
||||
do throws(Errno) {
|
||||
_ = try IORing(queueDepth: 1, flags: [])
|
||||
} catch {
|
||||
switch error {
|
||||
case .notSupported, .noFunction, .invalidArgument,
|
||||
.notPermitted, .permissionDenied:
|
||||
return false
|
||||
default:
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// The ideal test uses /proc/sys/kernel/io_uring_disabled (Linux >= 6.6).
|
||||
if let fd = try? FileDescriptor.open(
|
||||
"/proc/sys/kernel/io_uring_disabled", .readOnly)
|
||||
{
|
||||
defer { try? fd.close() }
|
||||
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1, alignment: 1)
|
||||
defer { buffer.deallocate() }
|
||||
let n = try fd.read(into: buffer)
|
||||
return n == 1 && (buffer.load(as: UInt8.self) == UInt8(ascii: "0"))
|
||||
}
|
||||
|
||||
// Fallback for older kernels: simply attempt io_uring_setup.
|
||||
// - ENOSYS -> syscall doesn't exist (Linux < 5.1) -> disabled.
|
||||
// - EPERM or EACCES -> treat as disabled
|
||||
// - propagate any other error.
|
||||
var params = io_uring_params()
|
||||
let raw = io_uring_setup(1, ¶ms)
|
||||
if raw < 0 {
|
||||
let err = Errno(rawValue: errno)
|
||||
switch err {
|
||||
case .noFunction, .notPermitted, .permissionDenied:
|
||||
return false
|
||||
default:
|
||||
throw err
|
||||
}
|
||||
}
|
||||
try? FileDescriptor(rawValue: raw).close()
|
||||
return true
|
||||
}
|
||||
|
||||
final class IORingTests: XCTestCase {
|
||||
func testIsUringEnabled() throws {
|
||||
// If `isUringEnabled()` throws, it is incomplete in some way.
|
||||
let enabled = try isUringEnabled()
|
||||
if !enabled {
|
||||
print("IORing tests will be skipped.")
|
||||
}
|
||||
}
|
||||
|
||||
func testInit() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
_ = try IORing(queueDepth: 32, flags: [])
|
||||
}
|
||||
|
||||
func testNop() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 32, flags: [])
|
||||
_ = try ring.submit(linkedRequests: .nop())
|
||||
let completion = try ring.blockingConsumeCompletion()
|
||||
@@ -68,7 +126,7 @@ final class IORingTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testUndersizedSubmissionQueue() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring: IORing = try IORing(queueDepth: 1)
|
||||
let enqueued = ring.prepare(linkedRequests: .nop(), .nop())
|
||||
XCTAssertFalse(enqueued)
|
||||
@@ -76,7 +134,7 @@ final class IORingTests: XCTestCase {
|
||||
|
||||
// Exercises opening, reading, closing, registered files, registered buffers, and eventfd
|
||||
func testOpenReadAndWriteFixedFile() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
let (parent, path) = try makeHelloWorldFile()
|
||||
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
|
||||
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
|
||||
@@ -117,16 +175,525 @@ final class IORingTests: XCTestCase {
|
||||
_ = try ring.blockingConsumeCompletion() //close
|
||||
memset(rawBuffer.baseAddress!, 0, rawBuffer.count)
|
||||
//Verify using a non-ring IO method that what we wrote matches our expectations
|
||||
print("about to open")
|
||||
let nonRingFD = try FileDescriptor.open(path, .readOnly)
|
||||
let bytesRead = try nonRingFD.read(into: rawBuffer)
|
||||
XCTAssert(bytesRead == 13)
|
||||
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 {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
let (parent, _) = try makeHelloWorldFile()
|
||||
var ring = try IORing(queueDepth: 6)
|
||||
|
||||
func enqueueOpen() {
|
||||
let path: FilePath = "/tmp/IORingTests/test.txt"
|
||||
let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly))
|
||||
XCTAssertTrue(ok)
|
||||
}
|
||||
enqueueOpen()
|
||||
|
||||
var churn: [UnsafeMutableRawBufferPointer] = []
|
||||
for _ in 0..<256 {
|
||||
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
|
||||
memset(buf.baseAddress!, 0x41, 64)
|
||||
churn.append(buf)
|
||||
}
|
||||
for buf in churn { buf.deallocate() }
|
||||
churn.removeAll()
|
||||
|
||||
try ring.submitPreparedRequests()
|
||||
let completion = try ring.blockingConsumeCompletion()
|
||||
XCTAssertGreaterThanOrEqual(
|
||||
completion.result, 0,
|
||||
"open should succeed; got \(completion.result)")
|
||||
|
||||
if completion.result >= 0 {
|
||||
let fd = FileDescriptor(rawValue: Int32(completion.result))
|
||||
try fd.close()
|
||||
}
|
||||
try cleanUpHelloWorldFile(parent)
|
||||
}
|
||||
|
||||
func testPathBufferLifetimeAcrossLinkedRequests() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
let (parent, _) = try makeHelloWorldFile()
|
||||
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
|
||||
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
|
||||
|
||||
func enqueueLinkedReadback() {
|
||||
let path: FilePath = "/tmp/IORingTests/test.txt"
|
||||
let ok = ring.prepare(linkedRequests:
|
||||
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly),
|
||||
.read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]),
|
||||
.close(ring.registeredFileSlots[0]))
|
||||
XCTAssertTrue(ok)
|
||||
}
|
||||
enqueueLinkedReadback()
|
||||
|
||||
var churn: [UnsafeMutableRawBufferPointer] = []
|
||||
for _ in 0..<256 {
|
||||
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
|
||||
memset(buf.baseAddress!, 0x41, 64)
|
||||
churn.append(buf)
|
||||
}
|
||||
for buf in churn { buf.deallocate() }
|
||||
|
||||
try ring.submitPreparedRequests()
|
||||
_ = try ring.blockingConsumeCompletion() // open
|
||||
_ = try ring.blockingConsumeCompletion() // read
|
||||
_ = try ring.blockingConsumeCompletion() // close
|
||||
|
||||
let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
|
||||
XCTAssertEqual(result, "Hello, World!")
|
||||
|
||||
try cleanUpHelloWorldFile(parent)
|
||||
rawBuffer.deallocate()
|
||||
}
|
||||
|
||||
// Timeout test for `blockingConsumeCompletion(timeout:)`:
|
||||
func testBlockingConsumeCompletionWithTimeoutOnIdleRing() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
let ring = try IORing(queueDepth: 4, flags: [])
|
||||
try XCTSkipIf(
|
||||
!ring.supportedFeatures.contains(.extendedArguments),
|
||||
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
|
||||
)
|
||||
|
||||
let clock = ContinuousClock()
|
||||
let start = clock.now
|
||||
|
||||
var thrown: Errno? = nil
|
||||
do throws(Errno) {
|
||||
_ = try ring.blockingConsumeCompletion(timeout: .milliseconds(100))
|
||||
XCTFail("expected timeout, got a completion on an idle ring")
|
||||
} catch {
|
||||
thrown = error
|
||||
}
|
||||
|
||||
let elapsed = start.duration(to: clock.now)
|
||||
|
||||
XCTAssertEqual(thrown, .timeout)
|
||||
XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(50))
|
||||
}
|
||||
|
||||
func testBlockingConsumeCompletionsSendsDone() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
XCTAssertTrue(try ring.submit(linkedRequests: .nop()))
|
||||
var dones: [Bool] = []
|
||||
ring.blockingConsumeCompletions { (completion: consuming IORing.Completion?, error, done) in
|
||||
dones.append(done)
|
||||
}
|
||||
XCTAssertEqual(dones, [false, true])
|
||||
}
|
||||
|
||||
func testBlockingConsumeCompletionsKeepsContextOfFailedCompletion() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
XCTAssertTrue(try ring.submit(
|
||||
linkedRequests: .close(FileDescriptor(rawValue: -1), context: 42)
|
||||
))
|
||||
|
||||
var received: [(context: UInt64?, error: Errno?, done: Bool)] = []
|
||||
ring.blockingConsumeCompletions { (completion: consuming IORing.Completion?, error, done) in
|
||||
received.append((completion?.context, error, done))
|
||||
}
|
||||
|
||||
XCTAssertEqual(received.count, 2)
|
||||
XCTAssertEqual(received.first?.context, 42)
|
||||
XCTAssertEqual(received.first?.error, .badFileDescriptor)
|
||||
XCTAssertEqual(received.first?.done, false)
|
||||
XCTAssertEqual(received.last?.context, nil)
|
||||
XCTAssertEqual(received.last?.error, nil)
|
||||
XCTAssertEqual(received.last?.done, true)
|
||||
}
|
||||
|
||||
func testBlockingConsumeCompletionReturnsFailedCompletion() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
XCTAssertTrue(try ring.submit(
|
||||
linkedRequests: .close(FileDescriptor(rawValue: -1), context: 43)
|
||||
))
|
||||
|
||||
let completion = try ring.blockingConsumeCompletion()
|
||||
XCTAssertEqual(completion.context, 43)
|
||||
XCTAssertEqual(completion.error, .badFileDescriptor)
|
||||
XCTAssertEqual(completion.result, -Errno.badFileDescriptor.rawValue)
|
||||
}
|
||||
|
||||
func testSubmitAndConsumeCompletionsKeepsContextOfFailedCompletion() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
XCTAssertTrue(ring.prepare(request: .close(FileDescriptor(rawValue: -1), context: 44)))
|
||||
|
||||
var received: [(context: UInt64?, error: Errno?, done: Bool)] = []
|
||||
ring.submitPreparedRequestsAndConsumeCompletions {
|
||||
(completion: consuming IORing.Completion?, error, done) in
|
||||
received.append((completion?.context, error, done))
|
||||
}
|
||||
|
||||
XCTAssertEqual(received.count, 2)
|
||||
XCTAssertEqual(received.first?.context, 44)
|
||||
XCTAssertEqual(received.first?.error, .badFileDescriptor)
|
||||
XCTAssertEqual(received.first?.done, false)
|
||||
XCTAssertEqual(received.last?.context, nil)
|
||||
XCTAssertEqual(received.last?.error, nil)
|
||||
XCTAssertEqual(received.last?.done, true)
|
||||
}
|
||||
|
||||
func testCompletionOfSuccessfulOperationHasNoError() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
XCTAssertTrue(try ring.submit(linkedRequests: .nop()))
|
||||
|
||||
let completion = try ring.blockingConsumeCompletion()
|
||||
XCTAssertEqual(completion.result, 0)
|
||||
XCTAssertNil(completion.error)
|
||||
}
|
||||
|
||||
func testRegisterEventFDTwiceThrows() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let efd = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE)))
|
||||
defer { try? efd.close() }
|
||||
|
||||
try ring.registerEventFD(efd)
|
||||
do throws(Errno) {
|
||||
try ring.registerEventFD(efd) // second registration -> EBUSY
|
||||
XCTFail("expected second registerEventFD to throw")
|
||||
} catch {
|
||||
XCTAssertEqual(error, .resourceBusy)
|
||||
}
|
||||
}
|
||||
|
||||
func testSubmitOnDisabledRingThrows() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 4, flags: [.startDisabled])
|
||||
|
||||
do throws(Errno) {
|
||||
_ = try ring.submit(linkedRequests: .nop())
|
||||
XCTFail("expected submit on a disabled ring to throw")
|
||||
} catch {
|
||||
XCTAssertEqual(error, Errno(rawValue: EBADFD))
|
||||
}
|
||||
}
|
||||
|
||||
func testPollAddPollIn() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 32, flags: [])
|
||||
|
||||
// This test case requires timeout support
|
||||
try XCTSkipIf(
|
||||
!ring.supportedFeatures.contains(.extendedArguments),
|
||||
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
|
||||
)
|
||||
|
||||
// Test POLLIN: Create an eventfd to monitor for read readiness
|
||||
let testEventFD = FileDescriptor(rawValue: eventfd(0, 0))
|
||||
defer {
|
||||
try? testEventFD.close()
|
||||
}
|
||||
let pollInContext: UInt64 = 42
|
||||
|
||||
// Submit a pollAdd request to monitor for POLLIN events (data available for reading)
|
||||
let enqueued = try ring.submit(linkedRequests:
|
||||
.pollAdd(testEventFD, events: .readable, 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)
|
||||
}
|
||||
|
||||
// Consume the completion from the poll operation
|
||||
let completion = try ring.blockingConsumeCompletion(
|
||||
timeout: .seconds(1)
|
||||
)
|
||||
XCTAssertEqual(completion.context, pollInContext)
|
||||
let readable = Int32(IORing.Request.PollEvents.readable.rawValue)
|
||||
XCTAssertNotEqual(
|
||||
completion.result & readable, 0, "expected POLLIN in the result mask"
|
||||
)
|
||||
}
|
||||
|
||||
func testPollAddPollOut() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 32, flags: [])
|
||||
|
||||
// This test case requires timeout support
|
||||
try XCTSkipIf(
|
||||
!ring.supportedFeatures.contains(.extendedArguments),
|
||||
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
|
||||
)
|
||||
|
||||
// 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 {
|
||||
try? writeFD.close()
|
||||
try? readFD.close()
|
||||
}
|
||||
let pollOutContext: UInt64 = 43
|
||||
|
||||
// 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, events: .writable, isMultiShot: false, context: pollOutContext))
|
||||
XCTAssert(enqueuedOut)
|
||||
|
||||
// Consume the completion from the poll operation
|
||||
let completionOut = try ring.blockingConsumeCompletion(
|
||||
timeout: .seconds(1)
|
||||
)
|
||||
XCTAssertEqual(completionOut.context, pollOutContext)
|
||||
let writable = Int32(IORing.Request.PollEvents.writable.rawValue)
|
||||
XCTAssertNotEqual(
|
||||
completionOut.result & writable, 0,
|
||||
"expected POLLOUT in the result mask"
|
||||
)
|
||||
}
|
||||
|
||||
// Similar to the multishot example in the documentation for
|
||||
// `pollAdd(_:events:isMultiShot:context:)`: arm a multishot poll,
|
||||
// then consume completions for as long as they carry `.moreCompletions`.
|
||||
func testPollAddMultiShotRearmsAcrossEvents() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 32, flags: [])
|
||||
|
||||
// This test case requires timeout support
|
||||
try XCTSkipIf(
|
||||
!ring.supportedFeatures.contains(.extendedArguments),
|
||||
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
|
||||
)
|
||||
|
||||
var pipeFDs: [Int32] = [0, 0]
|
||||
XCTAssertEqual(pipe(&pipeFDs), 0)
|
||||
let readFD = FileDescriptor(rawValue: pipeFDs[0])
|
||||
let writeFD = FileDescriptor(rawValue: pipeFDs[1])
|
||||
defer {
|
||||
try? readFD.close()
|
||||
try? writeFD.close()
|
||||
}
|
||||
|
||||
func writeByte() throws {
|
||||
var byte: UInt8 = 1
|
||||
try withUnsafeBytes(of: &byte) {
|
||||
try XCTAssertEqual(writeFD.write($0), 1)
|
||||
}
|
||||
}
|
||||
|
||||
func readByte() throws {
|
||||
var scratch: UInt8 = 0
|
||||
try withUnsafeMutableBytes(of: &scratch) {
|
||||
try XCTAssertEqual(readFD.read(into: $0), 1)
|
||||
}
|
||||
}
|
||||
|
||||
let context: UInt64 = 44
|
||||
let readable = Int32(IORing.Request.PollEvents.readable.rawValue)
|
||||
|
||||
let pollRequest = IORing.Request.pollAdd(
|
||||
readFD, events: .readable, isMultiShot: true, context: context
|
||||
)
|
||||
let enqueued = try ring.submit(linkedRequests: pollRequest)
|
||||
XCTAssert(enqueued)
|
||||
|
||||
try writeByte()
|
||||
let first = try ring.blockingConsumeCompletion(timeout: .seconds(1))
|
||||
// Kernels before 5.13 reject IORING_POLL_ADD_MULTI
|
||||
try XCTSkipIf(
|
||||
first.result == -EINVAL,
|
||||
"Kernel < 5.13: multishot poll is unsupported."
|
||||
)
|
||||
XCTAssertEqual(first.context, context)
|
||||
XCTAssertNotEqual(
|
||||
first.result & readable, 0, "expected POLLIN in the result mask"
|
||||
)
|
||||
XCTAssert(first.flags.contains(.moreCompletions))
|
||||
|
||||
// Drain the pipe, then any extra completions.
|
||||
try readByte()
|
||||
while ring.tryConsumeCompletion() != nil {}
|
||||
|
||||
try writeByte()
|
||||
// This written byte will only be reported by a re-armed poll.
|
||||
let second = try ring.blockingConsumeCompletion(timeout: .seconds(1))
|
||||
XCTAssertEqual(second.context, context)
|
||||
XCTAssertNotEqual(
|
||||
second.result & readable, 0, "expected POLLIN in the result mask"
|
||||
)
|
||||
|
||||
// Drain again
|
||||
try readByte()
|
||||
while ring.tryConsumeCompletion() != nil {}
|
||||
|
||||
// Cancel to end the multishot poll.
|
||||
try XCTAssert(
|
||||
ring.submit(linkedRequests: .cancel(.all, matchingContext: context))
|
||||
)
|
||||
var terminal: (result: Int32, flags: IORing.Completion.Flags)? = nil
|
||||
var observed: [(context: UInt64, result: Int32, flags: UInt32)] = []
|
||||
// The cancel posts a completion of its own under a different context,
|
||||
// and the two may land a moment apart, so retry briefly rather than
|
||||
// draining exactly once.
|
||||
for _ in 0..<100 where terminal == nil {
|
||||
while let completion = ring.tryConsumeCompletion() {
|
||||
observed.append(
|
||||
(
|
||||
completion.context,
|
||||
completion.result,
|
||||
completion.flags.rawValue
|
||||
)
|
||||
)
|
||||
if completion.context == context {
|
||||
terminal = (completion.result, completion.flags)
|
||||
}
|
||||
}
|
||||
if terminal == nil { usleep(1000) }
|
||||
}
|
||||
XCTAssertNotNil(
|
||||
terminal,
|
||||
"no terminal completion for the cancelled poll; "
|
||||
+ "completions seen: \(observed)"
|
||||
)
|
||||
if let terminal {
|
||||
XCTAssertEqual(terminal.result, -ECANCELED)
|
||||
XCTAssertFalse(
|
||||
terminal.flags.contains(.moreCompletions),
|
||||
"poll kept its armed state after being cancelled"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func testPollHangup() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 8)
|
||||
let (readFD, writeFD) = try FileDescriptor.pipe()
|
||||
// The hangup is produced by closing the write end mid-test, so the
|
||||
// cleanup below must not close it a second time: the descriptor number
|
||||
// may already have been reused elsewhere in the test process.
|
||||
var writeEndClosed = false
|
||||
defer {
|
||||
try? readFD.close()
|
||||
if !writeEndClosed { try? writeFD.close() }
|
||||
}
|
||||
|
||||
// This test case requires timeout support
|
||||
try XCTSkipIf(
|
||||
!ring.supportedFeatures.contains(.extendedArguments),
|
||||
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
|
||||
)
|
||||
|
||||
let request = IORing.Request.pollAdd(
|
||||
readFD, events: .readable, isMultiShot: false, context: 97
|
||||
)
|
||||
let success = try ring.submit(linkedRequests: request)
|
||||
XCTAssertEqual(success, true)
|
||||
try writeFD.close()
|
||||
writeEndClosed = true
|
||||
|
||||
let dt = Duration.seconds(1)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: dt)
|
||||
|
||||
for event in IORing.Request.PollEvents.Event.allCases {
|
||||
if completion.result & Int32(event.rawValue) != 0 {
|
||||
XCTAssertEqual(event, .hangUp)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let unexpected = completion.result
|
||||
XCTFail("Unexpected poll event: 0x\(String(unexpected, radix: 16))")
|
||||
}
|
||||
|
||||
func testPollError() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 8)
|
||||
let (readFD, writeFD) = try FileDescriptor.pipe(options: .nonBlocking)
|
||||
// POLLERR is produced by closing the read end mid-test; see the note in
|
||||
// `testPollHangup` for why cleanup must not close it twice.
|
||||
var readEndClosed = false
|
||||
defer {
|
||||
if !readEndClosed { try? readFD.close() }
|
||||
try? writeFD.close()
|
||||
}
|
||||
|
||||
// This test case requires timeout support
|
||||
try XCTSkipIf(
|
||||
!ring.supportedFeatures.contains(.extendedArguments),
|
||||
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
|
||||
)
|
||||
|
||||
let chunk = [UInt8](repeating: 0, count: 4096)
|
||||
chunk.withUnsafeBytes {
|
||||
// Fill the pipe by writing until an operation fails
|
||||
while let written = try? writeFD.write($0), written > 0 {}
|
||||
}
|
||||
|
||||
let request = IORing.Request.pollAdd(
|
||||
writeFD, events: .writable, isMultiShot: false, context: 98
|
||||
)
|
||||
let success = try ring.submit(linkedRequests: request)
|
||||
XCTAssertEqual(success, true)
|
||||
try readFD.close()
|
||||
readEndClosed = true
|
||||
|
||||
let dt = Duration.seconds(1)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: dt)
|
||||
XCTAssertEqual(completion.context, 98)
|
||||
|
||||
let pollError = IORing.Request.PollEvents.error.rawValue
|
||||
let result = completion.result & Int32(pollError)
|
||||
if result != pollError {
|
||||
XCTFail("expected POLLERR, got 0x\(String(result, radix: 16))")
|
||||
}
|
||||
}
|
||||
|
||||
// A completion's `result` is two things in one field: a non-negative
|
||||
// value is an event mask, and a negative value is a negated errno. The
|
||||
// sign is the only thing distinguishing them, so it has to be checked
|
||||
// before the value is treated as anything else.
|
||||
func testPollAddOnInvalidDescriptor() throws {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring = try IORing(queueDepth: 8)
|
||||
|
||||
let request = IORing.Request.pollAdd(
|
||||
FileDescriptor(rawValue: -1), events: .readable,
|
||||
isMultiShot: false, context: 99
|
||||
)
|
||||
let success = try ring.submit(linkedRequests: request)
|
||||
XCTAssertEqual(success, true)
|
||||
|
||||
guard let completion = ring.tryConsumeCompletion() else {
|
||||
XCTFail("expected a completion for the failed poll")
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(completion.context, 99)
|
||||
|
||||
// A negative value for `result` marks the completion a a failure.
|
||||
XCTAssertLessThan(completion.result, 0, "expected a failure")
|
||||
// The negative value is the error code multiplied by -1.
|
||||
XCTAssertEqual(Errno(rawValue: -completion.result), .badFileDescriptor)
|
||||
|
||||
// A negative result may look like another result code.
|
||||
// Checking for the error must happen first.
|
||||
let invalidDescriptor = Int32(IORing.Request.PollEvents.invalidDescriptor.rawValue)
|
||||
XCTAssertNotEqual(completion.result & invalidDescriptor, 0)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -1,467 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if compiler(>=6.2)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
@Suite("Span-based File I/O")
|
||||
private struct SpanFileIOTests {
|
||||
|
||||
// MARK: - Basic Functionality
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func basicReadWriteOperations() async throws {
|
||||
try withTemporaryFilePath(basename: "basicReadWriteOperations") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
// Test write(_:)
|
||||
let data1: [UInt8] = [0x61, 0x62, 0x63] // "abc"
|
||||
let written1 = try data1.withUnsafeBytes { bytes in
|
||||
try fd.write(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
#expect(written1 == 3)
|
||||
|
||||
// Test write(toAbsoluteOffset:_:)
|
||||
let data2: [UInt8] = [0x64, 0x65, 0x66] // "def"
|
||||
let written2 = try data2.withUnsafeBytes { bytes in
|
||||
try fd.write(toAbsoluteOffset: 3, RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
#expect(written2 == 3)
|
||||
|
||||
// Test writeAll(_:)
|
||||
try fd.seek(offset: 6, from: .start)
|
||||
let data3: [UInt8] = [0x67, 0x68, 0x69] // "ghi"
|
||||
let written3 = try data3.withUnsafeBytes { bytes in
|
||||
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
#expect(written3 == 3)
|
||||
|
||||
// Test writeAll(toAbsoluteOffset:_:)
|
||||
let data4: [UInt8] = [0x6A, 0x6B, 0x6C] // "jkl"
|
||||
let written4 = try data4.withUnsafeBytes { bytes in
|
||||
try fd.writeAll(toAbsoluteOffset: 9, RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
#expect(written4 == 3)
|
||||
|
||||
// Test read(into:)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
let result1 = try [UInt8](unsafeUninitializedCapacity: 12) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
_ = try fd.read(into: &output)
|
||||
count = output.byteCount
|
||||
}
|
||||
#expect(result1.count <= 12) // May be partial
|
||||
|
||||
// Test read(filling:)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
let result2 = try [UInt8](unsafeUninitializedCapacity: 12) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(filling: &output)
|
||||
}
|
||||
#expect(result2 == data1 + data2 + data3 + data4)
|
||||
|
||||
// Test read(fromAbsoluteOffset:into:)
|
||||
let result3 = try [UInt8](unsafeUninitializedCapacity: 3) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
_ = try fd.read(fromAbsoluteOffset: 3, into: &output)
|
||||
count = output.byteCount
|
||||
}
|
||||
#expect(result3.count <= 3) // May be partial
|
||||
|
||||
// Test read(fromAbsoluteOffset:filling:)
|
||||
let result4 = try [UInt8](unsafeUninitializedCapacity: 3) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(fromAbsoluteOffset: 6, filling: &output)
|
||||
}
|
||||
#expect(result4 == data3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func writeOperations() async throws {
|
||||
try withTemporaryFilePath(basename: "writeOperations") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
// Small write
|
||||
let small: [UInt8] = [0x61, 0x62, 0x63]
|
||||
_ = try small.withUnsafeBytes { bytes in
|
||||
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
|
||||
// Large write
|
||||
let large: [UInt8] = Array((0..<1024).map { UInt8($0 % 256) })
|
||||
_ = try large.withUnsafeBytes { bytes in
|
||||
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
|
||||
// Verify size
|
||||
let size = try fd.seek(offset: 0, from: .end)
|
||||
#expect(size == 3 + 1024)
|
||||
|
||||
// Verify content
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
let readBack = try [UInt8](unsafeUninitializedCapacity: 3 + 1024) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(filling: &output)
|
||||
}
|
||||
#expect(readBack == small + large)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1, *)
|
||||
@Test func readOperations() async throws {
|
||||
try withTemporaryFilePath(basename: "readOperations") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
let data: [UInt8] = Array((0..<1024).map { UInt8($0 % 256) })
|
||||
try fd.writeAll(data)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
// Small read
|
||||
let small = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(filling: &output)
|
||||
}
|
||||
#expect(small == Array(0..<10))
|
||||
|
||||
// Large read
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
let large = try [UInt8](unsafeUninitializedCapacity: 1024) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(filling: &output)
|
||||
}
|
||||
#expect(large == data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func absoluteOffsetOperations() async throws {
|
||||
try withTemporaryFilePath(basename: "absoluteOffsetOperations") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
let data: [UInt8] = Array(0..<100)
|
||||
try fd.writeAll(data)
|
||||
|
||||
// Write at absolute offset should not change file position
|
||||
let initialOffset = try fd.seek(offset: 0, from: .current)
|
||||
let patchData: [UInt8] = [0xFF, 0xFE]
|
||||
_ = try patchData.withUnsafeBytes { bytes in
|
||||
try fd.writeAll(toAbsoluteOffset: 50, RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
let afterWriteOffset = try fd.seek(offset: 0, from: .current)
|
||||
#expect(initialOffset == afterWriteOffset)
|
||||
|
||||
// Read at absolute offset should not change file position
|
||||
try fd.seek(offset: 10, from: .start)
|
||||
let readAtOffset = try [UInt8](unsafeUninitializedCapacity: 2) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(fromAbsoluteOffset: 50, filling: &output)
|
||||
}
|
||||
#expect(readAtOffset == patchData)
|
||||
let afterReadOffset = try fd.seek(offset: 0, from: .current)
|
||||
#expect(afterReadOffset == 10) // Should still be at 10
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Semantic Behavior
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func partialReadBehavior() async throws {
|
||||
try withTemporaryFilePath(basename: "partialReadBehavior") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
let data: [UInt8] = Array(0..<100)
|
||||
try fd.writeAll(data)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
// read(into:) may return partial data - this is valid behavior
|
||||
let output = UnsafeMutableRawBufferPointer.allocate(byteCount: 100, alignment: 1)
|
||||
defer { output.deallocate() }
|
||||
var span = OutputRawSpan(buffer: output, initializedCount: 0)
|
||||
|
||||
var totalRead = 0
|
||||
while span.freeCapacity > 0 {
|
||||
let bytesRead = try fd.read(into: &span)
|
||||
if bytesRead == 0 { break } // EOF
|
||||
totalRead += bytesRead
|
||||
#expect(bytesRead > 0)
|
||||
#expect(bytesRead <= span.freeCapacity + bytesRead) // Can't read more than capacity
|
||||
}
|
||||
|
||||
// Should eventually get all data with multiple reads
|
||||
#expect(totalRead == 100)
|
||||
#expect(span.byteCount == 100)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func readFillingBehavior() async throws {
|
||||
try withTemporaryFilePath(basename: "readFillingBehavior") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
// Test 1: read(filling:) fills buffer completely when data available
|
||||
let fullData: [UInt8] = Array(0..<100)
|
||||
try fd.writeAll(fullData)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
let result1 = try [UInt8](unsafeUninitializedCapacity: 100) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
let bytesRead = try fd.read(filling: &output)
|
||||
#expect(bytesRead == 100)
|
||||
#expect(output.freeCapacity == 0) // Should be completely full
|
||||
count = output.byteCount
|
||||
}
|
||||
#expect(result1 == fullData)
|
||||
|
||||
// Test 2: read(filling:) stops at EOF even if buffer not full
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
let result2 = try [UInt8](unsafeUninitializedCapacity: 200) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
let bytesRead = try fd.read(filling: &output)
|
||||
#expect(bytesRead == 100) // Only 100 bytes available
|
||||
#expect(output.freeCapacity == 100) // 100 bytes unfilled
|
||||
count = output.byteCount
|
||||
}
|
||||
#expect(result2 == fullData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Edge Cases
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func emptyIO() async throws {
|
||||
try withTemporaryFilePath(basename: "emptyIO") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
// Empty write
|
||||
let empty: [UInt8] = []
|
||||
let written = try empty.withUnsafeBytes { bytes in
|
||||
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
#expect(written == 0)
|
||||
|
||||
// Empty read (from empty file)
|
||||
let result1 = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(into: &output)
|
||||
}
|
||||
#expect(result1.isEmpty)
|
||||
|
||||
// Zero-capacity buffer
|
||||
let data: [UInt8] = [0x61, 0x62, 0x63]
|
||||
try fd.writeAll(data)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
let result2 = try [UInt8](unsafeUninitializedCapacity: 0) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(into: &output)
|
||||
}
|
||||
#expect(result2.isEmpty)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func eofBehavior() async throws {
|
||||
try withTemporaryFilePath(basename: "eofBehavior") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
let data: [UInt8] = [0x61, 0x62, 0x63]
|
||||
try fd.writeAll(data)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
// Read all data
|
||||
let result1 = try [UInt8](unsafeUninitializedCapacity: 3) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(filling: &output)
|
||||
}
|
||||
#expect(result1 == data)
|
||||
|
||||
// Read at EOF returns 0
|
||||
let result2 = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(into: &output)
|
||||
}
|
||||
#expect(result2.isEmpty)
|
||||
|
||||
// read(filling:) with buffer larger than file stops at EOF
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
let result3 = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
let bytesRead = try fd.read(filling: &output)
|
||||
#expect(bytesRead == 3) // Only 3 bytes available
|
||||
count = bytesRead
|
||||
}
|
||||
#expect(result3 == data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func preInitializedSpan() async throws {
|
||||
try withTemporaryFilePath(basename: "preInitializedSpan") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
let fileData: [UInt8] = [0x61, 0x62, 0x63] // "abc"
|
||||
try fd.writeAll(fileData)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
// Create buffer with pre-existing initialized data
|
||||
let result = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
|
||||
// Pre-initialize first 2 bytes
|
||||
buffer[0] = 0xFF
|
||||
buffer[1] = 0xFE
|
||||
|
||||
// Create OutputRawSpan that knows about pre-initialized portion
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 2)
|
||||
|
||||
// Read more data - should append after pre-initialized data
|
||||
let bytesRead = try fd.read(filling: &output)
|
||||
#expect(bytesRead == 3) // Read "abc"
|
||||
#expect(output.byteCount == 5) // 2 pre-initialized + 3 read = 5 total
|
||||
|
||||
count = output.byteCount
|
||||
}
|
||||
|
||||
// Verify: first 2 bytes are pre-initialized, next 3 are from file
|
||||
#expect(result == [0xFF, 0xFE, 0x61, 0x62, 0x63])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func errorHandling() throws {
|
||||
// Test 1: Reading from closed FD
|
||||
let fd1 = try FileDescriptor.open(FilePath("/dev/null"), .readOnly)
|
||||
try fd1.close()
|
||||
|
||||
#expect(throws: Errno.badFileDescriptor) {
|
||||
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 10, alignment: 1)
|
||||
defer { buffer.deallocate() }
|
||||
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
|
||||
_ = try fd1.read(into: &output)
|
||||
}
|
||||
|
||||
// Test 2: Writing to closed FD
|
||||
let fd2 = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly)
|
||||
try fd2.close()
|
||||
|
||||
let data: [UInt8] = [0x61, 0x62, 0x63]
|
||||
#expect(throws: Errno.badFileDescriptor) {
|
||||
try data.withUnsafeBytes { bytes in
|
||||
try fd2.write(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
}
|
||||
|
||||
// Test 3: Writing to read-only FD
|
||||
try withTemporaryFilePath(basename: "errorHandling") { path in
|
||||
// Create file first
|
||||
let fdWrite = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .writeOnly,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
_ = try fdWrite.closeAfter {
|
||||
try fdWrite.writeAll(data)
|
||||
}
|
||||
|
||||
// Open read-only and try to write
|
||||
let fdRead = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readOnly
|
||||
)
|
||||
_ = try fdRead.closeAfter {
|
||||
#expect(throws: Errno.badFileDescriptor) {
|
||||
try data.withUnsafeBytes { bytes in
|
||||
try fdRead.write(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Regression/Examples
|
||||
|
||||
@available(SystemWithSpan 0.0.1, *)
|
||||
@Test func proposalExample() async throws {
|
||||
// Example from the proposal
|
||||
try withTemporaryFilePath(basename: "proposalExample") { path in
|
||||
let fd = try FileDescriptor.open(
|
||||
path.appending("test.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
let writeData: [UInt8] = Array(repeating: 42, count: 4096)
|
||||
try fd.writeAll(writeData)
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
|
||||
let chunk = try [UInt8](unsafeUninitializedCapacity: 4096) { buffer, count in
|
||||
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
|
||||
count = try fd.read(filling: &output, retryOnInterrupt: true)
|
||||
}
|
||||
|
||||
#expect(chunk.count == 4096)
|
||||
#expect(chunk == writeData)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // compiler(>=6.2)
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 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
|
||||
@@ -39,7 +39,7 @@ import Android
|
||||
@Suite("Stat")
|
||||
private struct StatTests {
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func basics() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_basics") { tempDir in
|
||||
let dirStatFromFilePath = try tempDir.stat()
|
||||
@@ -81,7 +81,7 @@ private struct StatTests {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func followSymlinkInits() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_followSymlinkInits") { tempDir in
|
||||
let targetFilePath = tempDir.appending("target.txt")
|
||||
@@ -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
|
||||
|
||||
@@ -190,7 +190,7 @@ private struct StatTests {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func permissions() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_permissions") { tempDir in
|
||||
let testFile = tempDir.appending("test.txt")
|
||||
@@ -220,8 +220,13 @@ private struct StatTests {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func times() async throws {
|
||||
// This test pauses with `usleep` between some measurements to ensure that
|
||||
// the timestamp used by the filesystem will advance. On Linux and Android
|
||||
// the granularity of that clock may be as much as 10ms. We use 50ms
|
||||
// in order to have a comfortable margin.
|
||||
let timestampSleep: useconds_t = 50_000
|
||||
var start = timespec()
|
||||
try #require(clock_gettime(CLOCK_REALTIME, &start) == 0, "\(Errno.current)")
|
||||
start.tv_sec -= 1 // A little wiggle room
|
||||
@@ -247,8 +252,7 @@ private struct StatTests {
|
||||
#expect(dirCreationTime0 < startUpperBound)
|
||||
#endif
|
||||
|
||||
// Fails intermittently if less than 5ms
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
let file1 = tempDir.appending("test1.txt")
|
||||
let fd1 = try FileDescriptor.open(file1, .writeOnly, options: .create, permissions: .ownerReadWrite)
|
||||
@@ -274,7 +278,7 @@ private struct StatTests {
|
||||
#expect(dirCreationTime1 == dirCreationTime0)
|
||||
#endif
|
||||
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
// Changing permissions only updates directory change time
|
||||
|
||||
@@ -302,7 +306,7 @@ private struct StatTests {
|
||||
let file1CreationTime1 = stat1.st_birthtim
|
||||
#endif
|
||||
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
try fd1.writeAll("Hello, world!".utf8)
|
||||
stat1 = try file1.stat()
|
||||
@@ -330,7 +334,7 @@ private struct StatTests {
|
||||
#expect(dirStat.st_birthtim == dirCreationTime1)
|
||||
#endif
|
||||
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
let file2 = tempDir.appending("test2.txt")
|
||||
let fd2 = try FileDescriptor.open(file2, .writeOnly, options: .create, permissions: .ownerReadWrite)
|
||||
@@ -339,9 +343,9 @@ private struct StatTests {
|
||||
}
|
||||
|
||||
let stat2 = try file2.stat()
|
||||
#expect(stat2.st_atim > file1AccessTime2)
|
||||
#expect(stat2.st_mtim > file1ModificationTime2)
|
||||
#expect(stat2.st_ctim > file1ChangeTime2)
|
||||
#expect(stat2.st_atim >= file1AccessTime2)
|
||||
#expect(stat2.st_mtim >= file1ModificationTime2)
|
||||
#expect(stat2.st_ctim >= file1ChangeTime2)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
#expect(stat2.st_birthtim > file1CreationTime2)
|
||||
#endif
|
||||
@@ -349,7 +353,7 @@ private struct StatTests {
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func flags() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_flags") { tempDir in
|
||||
let filePath = tempDir.appending("test.txt")
|
||||
@@ -368,14 +372,11 @@ private struct StatTests {
|
||||
]
|
||||
#elseif os(FreeBSD)
|
||||
let userSettableFlags: FileFlags = [
|
||||
.noDump, .userImmutable, .userAppend,
|
||||
.opaque, .tracked, .hidden,
|
||||
.userNoUnlink,
|
||||
.offline,
|
||||
.readOnly,
|
||||
.reparse,
|
||||
.sparse,
|
||||
.system
|
||||
.noDump, .hidden, .offline,
|
||||
.readOnly, .sparse, .system
|
||||
// The following flags throw EPERM on ZFS.
|
||||
// .userImmutable, .userAppend, .opaque,
|
||||
// .userNoUnlink, .reparse,
|
||||
]
|
||||
#else // os(OpenBSD)
|
||||
let userSettableFlags: FileFlags = [
|
||||
@@ -384,13 +385,15 @@ private struct StatTests {
|
||||
#endif
|
||||
|
||||
flags.insert(userSettableFlags)
|
||||
try #require(fchflags(fd.rawValue, flags.rawValue) == 0, "\(Errno.current)")
|
||||
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
|
||||
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
|
||||
|
||||
stat = try fd.stat()
|
||||
#expect(stat.flags == flags)
|
||||
|
||||
flags.remove(userSettableFlags)
|
||||
try #require(fchflags(fd.rawValue, flags.rawValue) == 0, "\(Errno.current)")
|
||||
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
|
||||
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
|
||||
|
||||
stat = try fd.stat()
|
||||
#expect(stat.flags == flags)
|
||||
@@ -398,6 +401,38 @@ private struct StatTests {
|
||||
}
|
||||
#endif
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
@Test func equalityAndHashing() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_equality") { tempDir in
|
||||
let file = tempDir.appending("test.txt")
|
||||
let fd = try FileDescriptor.open(
|
||||
file, .writeOnly, options: .create, permissions: .ownerReadWrite)
|
||||
defer { try? fd.close() }
|
||||
|
||||
// Two stats of the same, unchanged file compare equal and hash equal,
|
||||
// so they coalesce in a Set.
|
||||
let stat1 = try file.stat()
|
||||
var stat2 = try file.stat()
|
||||
stat2.st_atim = stat1.st_atim // stat() can bump access time
|
||||
#expect(stat1 == stat2)
|
||||
#expect(stat1.hashValue == stat2.hashValue)
|
||||
#expect(Set([stat1, stat2]).count == 1)
|
||||
|
||||
// Reserved/"spare" and padding bytes must not affect equality.
|
||||
// Poke a reserved field and confirm equality/hashing are stable.
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
var stat3 = stat1
|
||||
stat3.rawValue.st_lspare = stat1.rawValue.st_lspare &+ 1
|
||||
#expect(stat1 == stat3)
|
||||
#expect(stat1.hashValue == stat3.hashValue)
|
||||
#endif
|
||||
|
||||
// A stat of a different file (the containing directory) is not equal.
|
||||
let dirStat = try tempDir.stat()
|
||||
#expect(stat1 != dirStat)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Comparison operators for timespec until UTCClock.Instant properties are available
|
||||
|
||||
Reference in new issue
Block a user