mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
461
Commits
release/1.3.0
...
staging
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81fded4dd9 | ||
|
|
774c7eb5a0 | ||
|
|
2e372aa16c | ||
|
|
4956c2c512 | ||
|
|
b083113aef | ||
|
|
f9a2b9443b | ||
|
|
b252c123a7 | ||
|
|
e133abb3e0 | ||
|
|
b11b33ab57 | ||
|
|
55350cd06d | ||
|
|
87f8e49ba7 | ||
|
|
d5f59fe404 | ||
|
|
c2e385e849 | ||
|
|
4911642226 | ||
|
|
40e1deb663 | ||
|
|
eee0145671 | ||
|
|
90dba1dc68 | ||
|
|
501bb7d052 | ||
|
|
67a2fd2ca1 | ||
|
|
bc16a3c120 | ||
|
|
98712f67f2 | ||
|
|
2f5b12b854 | ||
|
|
905f9f842d | ||
|
|
a07696ace3 | ||
|
|
57d515e1d0 | ||
|
|
2f4c8c216c | ||
|
|
70f197f036 | ||
|
|
f477389569 | ||
|
|
bc4e6e3bea | ||
|
|
d8dd95176b | ||
|
|
2ae0c650be | ||
|
|
478da393fa | ||
|
|
80587df07f | ||
|
|
4bbe3f3eeb | ||
|
|
9ddc89964b | ||
|
|
18a52c4729 | ||
|
|
1c1ad1d3f4 | ||
|
|
2fdd948a28 | ||
|
|
227ebbbe2d | ||
|
|
b6bd66889b | ||
|
|
395a77f0aa | ||
|
|
b1618475cc | ||
|
|
b2711a872a | ||
|
|
b6a7776360 | ||
|
|
0b3b691d0b | ||
|
|
0610d8f893 | ||
|
|
0ea6743c17 | ||
|
|
890830fff1 | ||
|
|
a5f13c77b8 | ||
|
|
086219bf62 | ||
|
|
11d9d4a78e | ||
|
|
0c11feadd4 | ||
|
|
2410aed341 | ||
|
|
9ec41a667c | ||
|
|
9226c72b3a | ||
|
|
d9d138a88e | ||
|
|
13ad3fe4ac | ||
|
|
2610d66a52 | ||
|
|
e0d9cb0638 | ||
|
|
c4fef8b59a | ||
|
|
f97a80426c | ||
|
|
e5198c2b2d | ||
|
|
9a1530813e | ||
|
|
b63d24d465 | ||
|
|
a717516d69 | ||
|
|
d89ca1d511 | ||
|
|
d32abd8c6e | ||
|
|
d75acaac3a | ||
|
|
5fedb102b5 | ||
|
|
960067d31a | ||
|
|
0bb855ac35 | ||
|
|
3f68d42246 | ||
|
|
c72c758953 | ||
|
|
a067a0751a | ||
|
|
e1191b2ba5 | ||
|
|
c7eaf63462 | ||
|
|
4f5b5fb40d | ||
|
|
5059730d24 | ||
|
|
8de80270cb | ||
|
|
41daa93a5d | ||
|
|
2adb6b41cc | ||
|
|
6ee9a58c36 | ||
|
|
7f9dba80cf | ||
|
|
08ed962064 | ||
|
|
08ea3343a5 | ||
|
|
a66176f518 | ||
|
|
33b58a8110 | ||
|
|
52d9c99a94 | ||
|
|
b93169b8e2 | ||
|
|
9a046498d0 | ||
|
|
a56bcda3c1 | ||
|
|
f7c05e1fb8 | ||
|
|
7fc787e6ba | ||
|
|
779c9ac628 | ||
|
|
2f6c4e0f03 | ||
|
|
d121081c01 | ||
|
|
a6675d7e5c | ||
|
|
329c5f59a2 | ||
|
|
6dd0eba8e3 | ||
|
|
4b70ffe375 | ||
|
|
8757fae97c | ||
|
|
d2b78f801b | ||
|
|
d6687d2bbb | ||
|
|
528e7485ba | ||
|
|
a6c5a39ca5 | ||
|
|
55e55c1978 | ||
|
|
bc097e91dc | ||
|
|
227a38f230 | ||
|
|
bbe2f1c192 | ||
|
|
e580c13ca8 | ||
|
|
a6149c215e | ||
|
|
de2d6e2d39 | ||
|
|
0d4c6fc971 | ||
|
|
27ccce55db | ||
|
|
321a71c2e9 | ||
|
|
131326c8ae | ||
|
|
c0273af7e5 | ||
|
|
f91cb6b8de | ||
|
|
f9c2a2b8e7 | ||
|
|
61e4ca4b81 | ||
|
|
f3154e33ec | ||
|
|
99feed67fe | ||
|
|
40d22dace6 | ||
|
|
595c862c19 | ||
|
|
3d6cba22b6 | ||
|
|
f5b8e02ba7 | ||
|
|
7e2f797fb4 | ||
|
|
3a649e32a6 | ||
|
|
5695a8831b | ||
|
|
f38d72f310 | ||
|
|
a49ba8a8b3 | ||
|
|
c47779fac0 | ||
|
|
344b3b85f8 | ||
|
|
a98cd3f2da | ||
|
|
3760dc265a | ||
|
|
baa3d62569 | ||
|
|
ea77ef8a21 | ||
|
|
9d325b29ce | ||
|
|
7798f0c957 | ||
|
|
5691e92a4b | ||
|
|
28ce835363 | ||
|
|
05eac87c08 | ||
|
|
c029c1bfbd | ||
|
|
261ca250fe | ||
|
|
014f8b78eb | ||
|
|
41f9676907 | ||
|
|
d4ca203c09 | ||
|
|
2f91217c90 | ||
|
|
27275f843a | ||
|
|
b40b09440c | ||
|
|
0e652c4d25 | ||
|
|
009b07e140 | ||
|
|
1b8167d354 | ||
|
|
2ac80d6f4e | ||
|
|
7fff872441 | ||
|
|
d6b40a7284 | ||
|
|
72c316ba86 | ||
|
|
48455a9135 | ||
|
|
880ec9086e | ||
|
|
9ad16c0aae | ||
|
|
91155fd527 | ||
|
|
49dd7977ca | ||
|
|
5e24673259 | ||
|
|
d338de1478 | ||
|
|
f3b8cc473d | ||
|
|
a34201439c | ||
|
|
12573bfb88 | ||
|
|
3a1b4a8e05 | ||
|
|
d9b03016dc | ||
|
|
f18ed75481 | ||
|
|
d895f2a828 | ||
|
|
283e8d6b7b | ||
|
|
901f4c80c4 | ||
|
|
0064649631 | ||
|
|
5ba137703c | ||
|
|
6983196ad6 | ||
|
|
a22e5f6858 | ||
|
|
0c6ef16ca9 | ||
|
|
7f6e673750 | ||
|
|
74366c3341 | ||
|
|
5bfed03c97 | ||
|
|
d4ca4129a0 | ||
|
|
a396967e3a | ||
|
|
bb03f0fba3 | ||
|
|
02481e0daa | ||
|
|
7107a570b4 | ||
|
|
b1b7b60a55 | ||
|
|
2228d64644 | ||
|
|
fdbcecab0b | ||
|
|
e5fdf9ea96 | ||
|
|
3b053e055b | ||
|
|
90702d6d15 | ||
|
|
849d005b2b | ||
|
|
8790e47013 | ||
|
|
f27874d762 | ||
|
|
df7341ee2b | ||
|
|
4d735a6631 | ||
|
|
bebd7c146e | ||
|
|
4fa2a719c5 | ||
|
|
0d824eee86 | ||
|
|
eb566de2d3 | ||
|
|
a4fb6cb206 | ||
|
|
7e73a336fb | ||
|
|
85b83fddb1 | ||
|
|
55fd6e7150 | ||
|
|
7ea32aefce | ||
|
|
ef94a37193 | ||
|
|
61a2af5e8b | ||
|
|
eb3b1fa54b | ||
|
|
f1393b76f3 | ||
|
|
f369347b73 | ||
|
|
1a3e37d791 | ||
|
|
a9f92a6e31 | ||
|
|
6f793cfe60 | ||
|
|
fcb0b69df6 | ||
|
|
822e4814d1 | ||
|
|
32966f975d | ||
|
|
10c070abd6 | ||
|
|
60299362ed | ||
|
|
baab9b26b7 | ||
|
|
fbd61a676d | ||
|
|
f21f6a8866 | ||
|
|
c8a44d836f | ||
|
|
b80d743dab | ||
|
|
eeeb81d0cd | ||
|
|
234e15320e | ||
|
|
154cbf7c95 | ||
|
|
3f4e7cb45c | ||
|
|
11d481252d | ||
|
|
2e8f58ac41 | ||
|
|
5cd7eade6d | ||
|
|
b2d4917ebe | ||
|
|
d96435c72b | ||
|
|
95784d018f | ||
|
|
448bef7c38 | ||
|
|
69e737de3d | ||
|
|
afeecb6c28 | ||
|
|
69eee996ac | ||
|
|
209dfeacb8 | ||
|
|
b2b60a6b94 | ||
|
|
e11703d915 | ||
|
|
8df901cb24 | ||
|
|
938fda53e2 | ||
|
|
e7ffa45882 | ||
|
|
607542a559 | ||
|
|
b9e4d2b2ba | ||
|
|
473b493ab0 | ||
|
|
9eb1f34cbf | ||
|
|
7a18b4bf34 | ||
|
|
6c64372b85 | ||
|
|
3a4e2f8071 | ||
|
|
53471ce33b | ||
|
|
f1d7eb52c6 | ||
|
|
cf7530848e | ||
|
|
5ae5d5a3af | ||
|
|
bcc7f6d569 | ||
|
|
e293300430 | ||
|
|
4cafcc96f6 | ||
|
|
85de4e51e2 | ||
|
|
d4e2b09c37 | ||
|
|
5ea5b2e89a | ||
|
|
8564f96d1f | ||
|
|
b85a788897 | ||
|
|
88a60e08b3 | ||
|
|
4c612a1e29 | ||
|
|
603c451818 | ||
|
|
2662793bd6 | ||
|
|
d581098eeb | ||
|
|
edbc9e4fdc | ||
|
|
9c42c54644 | ||
|
|
3841a7531f | ||
|
|
3b43b391b5 | ||
|
|
c64775ef71 | ||
|
|
4c96faa6d8 | ||
|
|
19e7f0fdd4 | ||
|
|
02811ea6b4 | ||
|
|
2ce971a831 | ||
|
|
80788529b5 | ||
|
|
05fb1f1142 | ||
|
|
8d2dda76fa | ||
|
|
c1789e0525 | ||
|
|
848a927122 | ||
|
|
318d2159d1 | ||
|
|
1a8d472f35 | ||
|
|
d82bccbb17 | ||
|
|
9c17c8562d | ||
|
|
0d6be7ac22 | ||
|
|
b642f54526 | ||
|
|
36987d6d37 | ||
|
|
082adfe732 | ||
|
|
abc0a6d26f | ||
|
|
c3559ecd61 | ||
|
|
8e09ede76d | ||
|
|
25c4b1ad75 | ||
|
|
aac7f54e89 | ||
|
|
62e62b3a7c | ||
|
|
a6fd8ba9ba | ||
|
|
3433699e6e | ||
|
|
d18980c960 | ||
|
|
08800445eb | ||
|
|
d8c0e24651 | ||
|
|
63b05e24e8 | ||
|
|
b0e2a510ed | ||
|
|
73baf1113d | ||
|
|
cf5e688e70 | ||
|
|
93d600b5c9 | ||
|
|
7fe8e6cfc2 | ||
|
|
84077b3b4b | ||
|
|
027c936a26 | ||
|
|
f5ad5e57fb | ||
|
|
2357d6932c | ||
|
|
33773a8eb9 | ||
|
|
21638a06b1 | ||
|
|
ec7d406cd4 | ||
|
|
c6456a9c03 | ||
|
|
cfd3f9da90 | ||
|
|
40b6b0ef8c | ||
|
|
dae787c199 | ||
|
|
5ca37e7d39 | ||
|
|
14597334dc | ||
|
|
403776dc2a | ||
|
|
6609a401b9 | ||
|
|
17e9790792 | ||
|
|
def7b1a70c | ||
|
|
c86758849a | ||
|
|
afb7fa4eef | ||
|
|
f59a0b73ce | ||
|
|
8441d4a310 | ||
|
|
adca1f70b1 | ||
|
|
cc1962b882 | ||
|
|
6b15689813 | ||
|
|
51f6be041f | ||
|
|
e49d2b9bd2 | ||
|
|
c6b2119c81 | ||
|
|
c2e8f24c7c | ||
|
|
5c3617b9e9 | ||
|
|
9a812b5fef | ||
|
|
882466a730 | ||
|
|
11f1c6da5a | ||
|
|
b92be8a02a | ||
|
|
c81d5f35e1 | ||
|
|
fb0efe832c | ||
|
|
495f729347 | ||
|
|
7654f14f8c | ||
|
|
0e060b7a7a | ||
|
|
1ccaee141c | ||
|
|
8a8552f617 | ||
|
|
ad407249fe | ||
|
|
faffb9a15a | ||
|
|
547b2a5828 | ||
|
|
87e68fca36 | ||
|
|
f32faad415 | ||
|
|
a3aff2f913 | ||
|
|
8730f2cf25 | ||
|
|
65693b8b80 | ||
|
|
f5edd720bd | ||
|
|
6189c1f553 | ||
|
|
6b4084c69f | ||
|
|
b596783bd9 | ||
|
|
b58450413e | ||
|
|
d099546787 | ||
|
|
0762f57d80 | ||
|
|
e4d06ae3ea | ||
|
|
d259ef476e | ||
|
|
5e03246e4e | ||
|
|
40b5b3068b | ||
|
|
e8bb779909 | ||
|
|
6ee96ffdb5 | ||
|
|
0539daa364 | ||
|
|
669dcf2c25 | ||
|
|
9123120c08 | ||
|
|
bf16d3da30 | ||
|
|
2df5b0b031 | ||
|
|
af4544c869 | ||
|
|
1f821a8539 | ||
|
|
996e940942 | ||
|
|
6338029b74 | ||
|
|
15794f5cad | ||
|
|
164fe8ce93 | ||
|
|
e1ab868059 | ||
|
|
022a7fe638 | ||
|
|
32026456ba | ||
|
|
0062c82c90 | ||
|
|
4116b8cbfb | ||
|
|
adbf8d2856 | ||
|
|
a87eaf71f6 | ||
|
|
1d1bef36c9 | ||
|
|
a74751c99c | ||
|
|
1cbb2cbcc6 | ||
|
|
7bcc01f0bf | ||
|
|
6bbed6b199 | ||
|
|
2d6c6a82b3 | ||
|
|
5b1b4cab56 | ||
|
|
7c6609eaca | ||
|
|
aabb8d0019 | ||
|
|
f059b4bfb3 | ||
|
|
64486e7d26 | ||
|
|
9674a9fee8 | ||
|
|
bb6ab43e44 | ||
|
|
e86702b34a | ||
|
|
cee9335aeb | ||
|
|
f572e4becb | ||
|
|
e708e4adda | ||
|
|
cc96d40bee | ||
|
|
9cdaaa356e | ||
|
|
16c7885387 | ||
|
|
08e9abe4e6 | ||
|
|
0fb71dd6ad | ||
|
|
16a2775645 | ||
|
|
7c11f19259 | ||
|
|
13bf719c29 | ||
|
|
3750b96b2e | ||
|
|
12baba9706 | ||
|
|
2c2a831f66 | ||
|
|
deb56e1ad2 | ||
|
|
a2bf0d5708 | ||
|
|
b5e330163a | ||
|
|
3f66dfbaf8 | ||
|
|
ccea4eed1a | ||
|
|
700b8f867e | ||
|
|
d129f62ce9 | ||
|
|
ae6b1f24a9 | ||
|
|
47feb93a38 | ||
|
|
6a9ebce259 | ||
|
|
7f4560f022 | ||
|
|
6dd57fe3a9 | ||
|
|
551d7b897f | ||
|
|
296374ecef | ||
|
|
213165ab72 | ||
|
|
bd036acda6 | ||
|
|
4536c47763 | ||
|
|
bdc776bd3e | ||
|
|
c2d940ecf3 | ||
|
|
304ccc3abb | ||
|
|
77d9ca18c1 | ||
|
|
18cceda484 | ||
|
|
252c0f0905 | ||
|
|
e1f6974ba6 | ||
|
|
015e9baf40 | ||
|
|
036f567f23 | ||
|
|
348b4de820 | ||
|
|
e378fb2f0d | ||
|
|
e9886bf251 | ||
|
|
63cdebeff6 | ||
|
|
97a03f97c8 | ||
|
|
0a7e8e121b | ||
|
|
a102156af3 | ||
|
|
dc5a3107c0 | ||
|
|
bcba321273 | ||
|
|
a5c43b17a9 | ||
|
|
429f64259f | ||
|
|
18c5f7a54b | ||
|
|
f9a514897e | ||
|
|
8e247d927e | ||
|
|
59ddf00c8e | ||
|
|
6d8abddbc8 | ||
|
|
ca700460b1 | ||
|
|
81d78be499 | ||
|
|
915070e006 | ||
|
|
6469433909 | ||
|
|
c0e8ef346b |
No files matched your search
@@ -0,0 +1,83 @@
|
||||
name: Pull request
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
with:
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
|
||||
enable_linux_checks: true
|
||||
linux_os_versions: '["noble", "jammy", "focal"]'
|
||||
linux_exclude_swift_versions: |
|
||||
[
|
||||
{"swift_version": "5.9"},
|
||||
{"swift_version": "5.10"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.2"},
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_macos_checks: true
|
||||
macos_exclude_xcode_versions: '[]'
|
||||
enable_windows_checks: true
|
||||
windows_exclude_swift_versions: |
|
||||
[
|
||||
{"swift_version": "5.9"},
|
||||
{"swift_version": "5.10"}
|
||||
]
|
||||
enable_linux_static_sdk_build: true
|
||||
linux_static_sdk_exclude_swift_versions: |
|
||||
[
|
||||
{"os_version": "focal", "swift_version": "nightly-6.2"},
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_wasm_sdk_build: true
|
||||
wasm_exclude_swift_versions: |
|
||||
[
|
||||
{"os_version": "focal", "swift_version": "nightly-6.2"},
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_android_sdk_build: true
|
||||
android_exclude_swift_versions: |
|
||||
[
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
|
||||
build-abi-stable:
|
||||
name: Build ABI Stable
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
|
||||
with:
|
||||
enable_linux_checks: false
|
||||
enable_macos_checks: true
|
||||
enable_windows_checks: false
|
||||
# Only build
|
||||
macos_build_command: "xcrun swift build --build-tests"
|
||||
macos_exclude_xcode_versions: '[]'
|
||||
# Enable availability to match ABI stable verion of system.
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE"
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
with:
|
||||
license_header_check_project_name: "Swift.org"
|
||||
# https://github.com/apple/swift-system/issues/224
|
||||
docs_check_enabled: false
|
||||
unacceptable_language_check_enabled: false
|
||||
license_header_check_enabled: false
|
||||
format_check_enabled: false
|
||||
python_lint_check_enabled: false
|
||||
@@ -1,7 +1,10 @@
|
||||
.DS_Store
|
||||
/.swiftpm
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
.*.sw?
|
||||
/.swiftpm
|
||||
.docc-build
|
||||
Package.resolved
|
||||
@@ -0,0 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [SystemPackage]
|
||||
@@ -1,5 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.10-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.8-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.9-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
macOSSwiftPackageJob {
|
||||
swift_version = "6.0"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
nightly_docker_tag = "nightly-6.0-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
macOSSwiftPackageJob {
|
||||
swift_version = "main"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
nightly_docker_tag = "nightly-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
WindowsSwiftPackageWithDockerImageJob {
|
||||
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.3.0"
|
||||
branch = "main"
|
||||
sub_dir = "swift-system"
|
||||
label = "windows-server-2019"
|
||||
}
|
||||
@@ -11,6 +11,8 @@ cmake_minimum_required(VERSION 3.16.0)
|
||||
project(SwiftSystem
|
||||
LANGUAGES C Swift)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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/).
|
||||
+162
-45
@@ -1,53 +1,170 @@
|
||||
// swift-tools-version:5.8
|
||||
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
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
|
||||
*/
|
||||
// swift-tools-version:6.0
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let DarwinPlatforms: [Platform]
|
||||
#if swift(<5.9)
|
||||
DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS]
|
||||
struct Available {
|
||||
var name: String
|
||||
var version: String
|
||||
var osAvailability: String
|
||||
var sourceAvailability: String
|
||||
|
||||
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 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 availability: [Available] = [
|
||||
Available("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
|
||||
|
||||
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.4.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.4.2", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.5.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.6.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.6.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
|
||||
Available("99", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
]
|
||||
|
||||
let swiftSettingsAvailability = availability.map(\.swiftSetting)
|
||||
|
||||
#if SYSTEM_CI
|
||||
let swiftSettingsCI: [SwiftSetting] = [
|
||||
.unsafeFlags(["-require-explicit-availability=error"]),
|
||||
]
|
||||
#else
|
||||
DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS, .visionOS]
|
||||
let swiftSettingsCI: [SwiftSetting] = []
|
||||
#endif
|
||||
|
||||
let swiftSettings = swiftSettingsAvailability + swiftSettingsCI + [
|
||||
.define(
|
||||
"SYSTEM_PACKAGE_DARWIN",
|
||||
.when(platforms: [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS])),
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug)),
|
||||
.enableExperimentalFeature("Lifetimes"),
|
||||
]
|
||||
|
||||
let cSettings: [CSetting] = [
|
||||
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])),
|
||||
]
|
||||
|
||||
#if SYSTEM_ABI_STABLE
|
||||
let platforms: [SupportedPlatform] = [
|
||||
.macOS("26"),
|
||||
.iOS("26"),
|
||||
.watchOS("26"),
|
||||
.tvOS("26"),
|
||||
.visionOS("26"),
|
||||
]
|
||||
#else
|
||||
let platforms: [SupportedPlatform]? = nil
|
||||
#endif
|
||||
|
||||
#if os(Linux)
|
||||
let filesToExclude = ["CMakeLists.txt"]
|
||||
#else
|
||||
let filesToExclude = ["CMakeLists.txt", "IORing"]
|
||||
#endif
|
||||
|
||||
#if os(Linux)
|
||||
let testsToExclude:[String] = []
|
||||
#else
|
||||
let testsToExclude = ["IORequestTests.swift", "IORingTests.swift"]
|
||||
#endif
|
||||
|
||||
let package = Package(
|
||||
name: "swift-system",
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: [],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: ["CSystem"],
|
||||
path: "Sources/System",
|
||||
exclude: ["CMakeLists.txt"],
|
||||
cSettings: [
|
||||
.define("_CRT_SECURE_NO_WARNINGS")
|
||||
],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug))
|
||||
]),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)),
|
||||
]),
|
||||
]
|
||||
name: "swift-system",
|
||||
platforms: platforms,
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
.library(name: "SystemSockets", targets: ["SystemSockets"]),
|
||||
.executable(name: "system-samples", targets: ["Samples"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: [],
|
||||
exclude: ["CMakeLists.txt"],
|
||||
cSettings: cSettings),
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: ["CSystem"],
|
||||
path: "Sources/System",
|
||||
exclude: filesToExclude,
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
exclude: testsToExclude,
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.target(
|
||||
name: "SystemSockets",
|
||||
dependencies: ["SystemPackage", "CSystem"],
|
||||
path: "Sources/SystemSockets",
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
name: "SystemSocketsTests",
|
||||
dependencies: ["SystemSockets"],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.executableTarget(
|
||||
name: "Samples",
|
||||
dependencies: [
|
||||
"SystemPackage",
|
||||
"SystemSockets",
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
path: "Sources/Samples",
|
||||
swiftSettings: swiftSettings),
|
||||
],
|
||||
swiftLanguageVersions: [.v5]
|
||||
)
|
||||
@@ -0,0 +1,982 @@
|
||||
# Stat for Swift System
|
||||
|
||||
* Proposal: [SYS-0006](0006-system-stat.md)
|
||||
* Authors: [Jonathan Flat](https://github.com/jrflat), [Michael Ilseman](https://github.com/milseman), [Rauhul Varma](https://github.com/rauhul)
|
||||
* Review Manager: TBD
|
||||
* Status: **Awaiting review**
|
||||
* Implementation: [apple/swift-system#256](https://github.com/apple/swift-system/pull/256)
|
||||
* Review: ([pitch](https://forums.swift.org/t/pitch-stat-types-for-swift-system/81616))
|
||||
|
||||
#### Revision history
|
||||
|
||||
* **v1** Initial version
|
||||
* **v2** Moved `UTCClock.Instant` properties to **Future Directions** and exposed C `timespec` properties. Expanded **Alternatives Considered** for `Stat` name and time properties.
|
||||
* **v3** Add `init(_:)` to wrapper types, clarify `FileType(rawValue:)` behavior with `S_IFMT`, rename `.pipe` to `.fifo`, mention `ALLPERMS` instead of `0o7777`, explain "is"-less flag names in **Alternatives Considered**, fix conditionals for FreeBSD flags, clarify that `.type` and `.permissions` depend on `.mode`, clarify that size property behaviors are file system-dependent.
|
||||
|
||||
## Introduction
|
||||
|
||||
This proposal introduces a Swift-native `Stat` type to the System library, providing comprehensive access to file metadata on Unix-like platforms through type-safe, platform-aware APIs that wrap the C `stat` types and system calls.
|
||||
|
||||
## Motivation
|
||||
|
||||
Currently, Swift developers who want to work with the file system's lowest level API can only do so through bridged C interfaces. These interfaces lack type safety and require writing non-idiomatic Swift, leading to errors and confusion.
|
||||
|
||||
The goal of the `Stat` type is to provide a faithful and performant Swift wrapper around the underlying C system calls while adding type safety, platform abstraction, and improved discoverability/usability with clear naming. For more on the motivation behind System, see [https://www.swift.org/blog/swift-system](https://www.swift.org/blog/swift-system)
|
||||
|
||||
## Proposed solution
|
||||
|
||||
This proposal adds a `struct Stat` that is available on Unix-like platforms. See discussion on Windows-specific API in **Future Directions**.
|
||||
|
||||
### `Stat` - File Metadata
|
||||
A Swift wrapper around the C `stat` struct that provides type-safe access to file metadata:
|
||||
|
||||
```swift
|
||||
// Get file status from path String
|
||||
let stat = try Stat("/path/to/file")
|
||||
|
||||
// From FileDescriptor
|
||||
let stat = try fd.stat()
|
||||
|
||||
// From FilePath
|
||||
let stat = try filePath.stat()
|
||||
|
||||
// `followTargetSymlink: true` (default) behaves like `stat()`
|
||||
// `followTargetSymlink: false` behaves like `lstat()`
|
||||
let stat = try symlinkPath.stat(followTargetSymlink: false)
|
||||
|
||||
// Supply flags and optional file descriptor to use the `fstatat()` variant
|
||||
let stat = try Stat("path/to/file", relativeTo: fd, flags: .symlinkNoFollow)
|
||||
|
||||
print("Size: \(stat.size) bytes")
|
||||
print("Size allocated: \(stat.sizeAllocated) bytes")
|
||||
print("Type: \(stat.type)") // .regular, .directory, .symbolicLink, etc.
|
||||
print("Permissions: \(stat.permissions)")
|
||||
print("Modified: \(stat.modificationTime)")
|
||||
|
||||
// Platform-specific information when available
|
||||
#if canImport(Darwin) || os(FreeBSD)
|
||||
print("Creation time: \(stat.creationTime)")
|
||||
#endif
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
All initializers throw the existing `Errno` type:
|
||||
|
||||
```swift
|
||||
do {
|
||||
let stat = try Stat("/nonexistent/file")
|
||||
} catch Errno.noSuchFileOrDirectory {
|
||||
print("File not found")
|
||||
} catch {
|
||||
print("Other error: \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
These initializers use a typed `throws(Errno)` and require Swift 6.0 or later.
|
||||
|
||||
## Detailed design
|
||||
|
||||
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.
|
||||
|
||||
### FileType
|
||||
|
||||
This proposal introduces `FileType` and `FileMode` types to represent `mode_t` values from the C `stat` struct. The type and permissions of a `FileMode` can be modified for convenience, and `FileMode` handles the respective bit masking.
|
||||
|
||||
```swift
|
||||
/// A file type matching those contained in a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw file-type bits from the C mode.
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed file type from the raw C `mode_t`.
|
||||
///
|
||||
/// - Note: This initializer stores the `rawValue` directly and **does not**
|
||||
/// mask the value with `S_IFMT`. If the supplied `rawValue` contains bits
|
||||
/// outside of the `S_IFMT` mask, the resulting `FileType` will not compare
|
||||
/// equal to constants like `.directory` and `.symbolicLink`, which may
|
||||
/// be unexpected.
|
||||
///
|
||||
/// If you're unsure whether the `mode_t` contains bits outside of `S_IFMT`,
|
||||
/// you can use `FileMode(rawValue:)` instead to get a strongly-typed
|
||||
/// `FileMode`, then call `.type` to get the properly masked `FileType`.
|
||||
public init(rawValue: CInterop.Mode)
|
||||
|
||||
/// Directory
|
||||
///
|
||||
/// The corresponding C constant is `S_IFDIR`.
|
||||
public static var directory: FileType { get }
|
||||
|
||||
/// Character special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFCHR`.
|
||||
public static var characterSpecial: FileType { get }
|
||||
|
||||
/// Block special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFBLK`.
|
||||
public static var blockSpecial: FileType { get }
|
||||
|
||||
/// Regular file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFREG`.
|
||||
public static var regular: FileType { get }
|
||||
|
||||
/// FIFO (or named pipe)
|
||||
///
|
||||
/// The corresponding C constant is `S_IFIFO`.
|
||||
public static var fifo: FileType { get }
|
||||
|
||||
/// Symbolic link
|
||||
///
|
||||
/// The corresponding C constant is `S_IFLNK`.
|
||||
public static var symbolicLink: FileType { get }
|
||||
|
||||
/// Socket
|
||||
///
|
||||
/// The corresponding C constant is `S_IFSOCK`.
|
||||
public static var socket: FileType { get }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Whiteout file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFWHT`.
|
||||
public static var whiteout: FileType { get }
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
### FileMode
|
||||
```swift
|
||||
/// A strongly-typed file mode representing a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C mode.
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed `FileMode` from the raw C value.
|
||||
public init(rawValue: CInterop.Mode)
|
||||
|
||||
/// Creates a strongly-typed `FileMode` from the raw C value.
|
||||
public init(_ rawValue: CInterop.Mode)
|
||||
|
||||
/// Creates a `FileMode` from the given file type and permissions.
|
||||
///
|
||||
/// - Note: This initializer masks the inputs with their respective bit masks.
|
||||
public init(type: FileType, permissions: FilePermissions)
|
||||
|
||||
/// The file's type, from the mode's file-type bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the file-type bit mask `S_IFMT`.
|
||||
public var type: FileType { get set }
|
||||
|
||||
/// The file's permissions, from the mode's permission bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the permissions bit mask `ALLPERMS`.
|
||||
public var permissions: FilePermissions { get set }
|
||||
}
|
||||
```
|
||||
|
||||
### Supporting ID Types
|
||||
|
||||
This proposal also uses new `DeviceID`, `UserID`, `GroupID`, and `Inode` types to represent the respective C data types found in `stat`. These are strongly-typed structs instead of `CInterop` typealiases to prevent ambiguity in future System implementations and to allow for added functionality.
|
||||
|
||||
For example, with an implementation of `chown`, a developer might accidentally misplace user and group parameters with no warning if both were a typealias of the underlying `unsigned int`. Furthermore, a strongly-typed `DeviceID` would allow us to add functionality such as a `makedev` function, or `major` and `minor` getters.
|
||||
|
||||
For now, we define the following for use in `Stat`.
|
||||
|
||||
```swift
|
||||
@frozen
|
||||
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.UserID
|
||||
public init(rawValue: CInterop.UserID)
|
||||
public init(_ rawValue: CInterop.UserID)
|
||||
}
|
||||
|
||||
@frozen
|
||||
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.GroupID
|
||||
public init(rawValue: CInterop.GroupID)
|
||||
public init(_ rawValue: CInterop.GroupID)
|
||||
}
|
||||
|
||||
@frozen
|
||||
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.DeviceID
|
||||
public init(rawValue: CInterop.DeviceID)
|
||||
public init(_ rawValue: CInterop.DeviceID)
|
||||
}
|
||||
|
||||
@frozen
|
||||
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
public var rawValue: CInterop.Inode
|
||||
public init(rawValue: CInterop.Inode)
|
||||
public init(_ rawValue: CInterop.Inode)
|
||||
}
|
||||
```
|
||||
|
||||
Each type stores a `CInterop` typealias to ensure an appropriate `rawValue` for the current platform. Added functionality is outside the scope of this proposal and will be included in a future proposal.
|
||||
|
||||
### FileFlags
|
||||
|
||||
A new `FileFlags` type represents file-specific flags found in a `stat` struct on Darwin, FreeBSD, and OpenBSD. This type would also be useful for an implementation of `chflags()`.
|
||||
|
||||
```swift
|
||||
/// File-specific flags found in the `st_flags` property of a `stat` struct
|
||||
/// or used as input to `chflags()`.
|
||||
///
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@frozen
|
||||
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
public let rawValue: CInterop.FileFlags
|
||||
|
||||
/// Creates a strongly-typed `FileFlags` from the raw C value.
|
||||
public init(rawValue: CInterop.FileFlags)
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
/// Do not dump the file during backups.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NODUMP`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var noDump: FileFlags { get }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_IMMUTABLE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var userImmutable: FileFlags { get }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `UF_APPEND`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var userAppend: FileFlags { get }
|
||||
|
||||
/// File has been archived.
|
||||
///
|
||||
/// The corresponding C constant is `SF_ARCHIVED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var archived: FileFlags { get }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_IMMUTABLE`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var systemImmutable: FileFlags { get }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `SF_APPEND`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var systemAppend: FileFlags { get }
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Directory is opaque when viewed through a union mount.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OPAQUE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var opaque: FileFlags { get }
|
||||
|
||||
/// File should not be displayed in a GUI.
|
||||
///
|
||||
/// The corresponding C constant is `UF_HIDDEN`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var hidden: FileFlags { get }
|
||||
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_NOUNLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var systemNoUnlink: FileFlags { get }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// File is compressed at the file system level.
|
||||
///
|
||||
/// The corresponding C constant is `UF_COMPRESSED`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
public static var compressed: FileFlags { get }
|
||||
|
||||
/// File is tracked for the purpose of document IDs.
|
||||
///
|
||||
/// The corresponding C constant is `UF_TRACKED`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var tracked: FileFlags { get }
|
||||
|
||||
/// File requires an entitlement for reading and writing.
|
||||
///
|
||||
/// The corresponding C constant is `UF_DATAVAULT`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var dataVault: FileFlags { get }
|
||||
|
||||
/// File requires an entitlement for writing.
|
||||
///
|
||||
/// The corresponding C constant is `SF_RESTRICTED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var restricted: FileFlags { get }
|
||||
|
||||
/// File is a firmlink.
|
||||
///
|
||||
/// Firmlinks are used by macOS to create transparent links between
|
||||
/// the read-only system volume and writable data volume. For example,
|
||||
/// the `/Applications` folder on the system volume is a firmlink to
|
||||
/// the `/Applications` folder on the data volume, allowing the user
|
||||
/// to see both system- and user-installed applications in a single folder.
|
||||
///
|
||||
/// The corresponding C constant is `SF_FIRMLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var firmlink: FileFlags { get }
|
||||
|
||||
/// File is a dataless placeholder (content is stored remotely).
|
||||
///
|
||||
/// The system will attempt to materialize the file when accessed according to
|
||||
/// the dataless file materialization policy of the accessing thread or process.
|
||||
/// See `getiopolicy_np(3)`.
|
||||
///
|
||||
/// The corresponding C constant is `SF_DATALESS`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
public static var dataless: FileFlags { get }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NOUNLINK`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var userNoUnlink: FileFlags { get }
|
||||
|
||||
/// File has the Windows offline attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_OFFLINE` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OFFLINE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var offline: FileFlags { get }
|
||||
|
||||
/// File is read-only.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_READONLY` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_READONLY`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var readOnly: FileFlags { get }
|
||||
|
||||
/// File contains a Windows reparse point.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_REPARSE_POINT` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_REPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var reparse: FileFlags { get }
|
||||
|
||||
/// File is sparse.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SPARSE_FILE` attribute,
|
||||
/// or to indicate a sparse file.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var sparse: FileFlags { get }
|
||||
|
||||
/// File has the Windows system attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SYSTEM` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SYSTEM`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
public static var system: FileFlags { get }
|
||||
|
||||
/// File is a snapshot.
|
||||
///
|
||||
/// The corresponding C constant is `SF_SNAPSHOT`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
public static var snapshot: FileFlags { get }
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
The initializer accepting a `FileDescriptor` corresponds to `fstat()`. If the file descriptor points to a symlink, this will return information about the symlink itself.
|
||||
|
||||
In the non-`FileDescriptor` case, one form of the initializer takes a `followTargetSymlink: Bool = true` parameter. The default `true` corresponds to `stat()` and will follow a symlink at the end of the path. Setting `followTargetSymlink: false` corresponds to `lstat()` and will return information about the symlink itself.
|
||||
|
||||
The other form of the initializer receives a path, which can be optionally resolved against a given file descriptor, and a set of `Stat.Flags`. These APIs correspond to the `fstatat()` system call and use a default file descriptor of `AT_FDCWD` if one isn't supplied.
|
||||
|
||||
```swift
|
||||
/// A Swift wrapper of the C `stat` struct.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C `stat` struct.
|
||||
public var rawValue: CInterop.Stat
|
||||
|
||||
/// Creates a Swift `Stat` from the raw C struct.
|
||||
public init(rawValue: CInterop.Stat)
|
||||
|
||||
// MARK: Stat.Flags
|
||||
|
||||
/// Flags representing those passed to `fstatat()`.
|
||||
@frozen
|
||||
public struct Flags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a strongly-typed `Stat.Flags` from raw C flags.
|
||||
public init(rawValue: CInt)
|
||||
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW`.
|
||||
public static var symlinkNoFollow: Flags { get }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
/// If _any_ symbolic link is encountered during path resolution, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW_ANY`.
|
||||
/// - Note: Only available on Darwin.
|
||||
public static var symlinkNoFollowAny: Flags { get }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// If the path does not reside in the hierarchy beneath the starting directory, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_RESOLVE_BENEATH`.
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
@available(macOS 26.0, iOS 26.0, tvOS 26.0, watchOS 26.0, visionOS 26.0, *)
|
||||
public static var resolveBeneath: Flags { get }
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD) || os(Linux) || os(Android)
|
||||
/// If the path is an empty string (or `NULL` since Linux 6.11),
|
||||
/// return information about the given file descriptor.
|
||||
///
|
||||
/// The corresponding C constant is `AT_EMPTY_PATH`.
|
||||
/// - Note: Only available on FreeBSD, Linux, and Android.
|
||||
public static var emptyPath: Flags { get }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from a `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno)
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// ID of device containing file
|
||||
///
|
||||
/// The corresponding C property is `st_dev`.
|
||||
public var deviceID: DeviceID { get set }
|
||||
|
||||
/// Inode number
|
||||
///
|
||||
/// The corresponding C property is `st_ino`.
|
||||
public var inode: Inode { get set }
|
||||
|
||||
/// File mode
|
||||
///
|
||||
/// The corresponding C property is `st_mode`.
|
||||
public var mode: FileMode { get set }
|
||||
|
||||
/// File type for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.type`. Modifying this
|
||||
/// property will update the underlying `st_mode` accordingly.
|
||||
public var type: FileType { get set }
|
||||
|
||||
/// File permissions for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.permissions`. Modifying
|
||||
/// this property will update the underlying `st_mode` accordingly.
|
||||
public var permissions: FilePermissions { get set }
|
||||
|
||||
/// Number of hard links
|
||||
///
|
||||
/// The corresponding C property is `st_nlink`.
|
||||
public var linkCount: Int { get set }
|
||||
|
||||
/// User ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_uid`.
|
||||
public var userID: UserID { get set }
|
||||
|
||||
/// Group ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_gid`.
|
||||
public var groupID: GroupID { get set }
|
||||
|
||||
/// Device ID (if special file)
|
||||
///
|
||||
/// For character or block special files, the returned `DeviceID` may have
|
||||
/// meaningful `.major` and `.minor` values. For non-special files, this
|
||||
/// property is usually meaningless and often set to 0.
|
||||
///
|
||||
/// The corresponding C property is `st_rdev`.
|
||||
public var specialDeviceID: DeviceID { get set }
|
||||
|
||||
/// Total size, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_size` field,
|
||||
/// which can have file system-dependent behavior. For example, this property
|
||||
/// can return different values for a file's data fork and resource fork, and some
|
||||
/// file systems report logical size rather than actual disk usage for compressed
|
||||
/// or cloned files.
|
||||
///
|
||||
/// The corresponding C property is `st_size`.
|
||||
public var size: Int64 { get set }
|
||||
|
||||
/// Block size for filesystem I/O, in bytes
|
||||
///
|
||||
/// The corresponding C property is `st_blksize`.
|
||||
public var preferredIOBlockSize: Int { get set }
|
||||
|
||||
/// Number of 512-byte blocks allocated
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file system-dependent behavior.
|
||||
///
|
||||
/// The corresponding C property is `st_blocks`.
|
||||
public var blocksAllocated: Int64 { get set }
|
||||
|
||||
/// Total size allocated, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file system-dependent behavior.
|
||||
///
|
||||
/// - Note: Calculated as `512 * blocksAllocated`.
|
||||
public var sizeAllocated: Int64 { get }
|
||||
|
||||
// NOTE: "st_" property names are used for the `timespec` properties so
|
||||
// we can reserve `accessTime`, `modificationTime`, etc. for potential
|
||||
// `UTCClock.Instant` properties in the future.
|
||||
// See Future Directions for more info.
|
||||
|
||||
/// Time of last access, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin).
|
||||
public var st_atim: timespec { get set }
|
||||
|
||||
/// Time of last modification, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin).
|
||||
public var st_mtim: timespec { get set }
|
||||
|
||||
/// Time of last status (inode) change, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin).
|
||||
public var st_ctim: timespec { get set }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Time of file creation, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin).
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
public var st_birthtim: timespec { get set }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// File flags
|
||||
///
|
||||
/// The corresponding C property is `st_flags`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
public var flags: FileFlags { get set }
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number is 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 }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
extension Stat: Equatable {
|
||||
/// Compares the raw bytes of two `Stat` structs for equality.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool
|
||||
}
|
||||
|
||||
extension Stat: Hashable {
|
||||
/// Hashes the raw bytes of this `Stat` struct.
|
||||
public func hash(into hasher: inout Hasher)
|
||||
}
|
||||
```
|
||||
|
||||
### FileDescriptor and FilePath Extensions
|
||||
|
||||
```swift
|
||||
extension FileDescriptor {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
public func stat(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
public func stat(
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public func stat(
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
public func stat(
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat
|
||||
}
|
||||
```
|
||||
|
||||
### CInterop Extensions
|
||||
|
||||
This proposal extends the existing `CInterop` namespace with platform-appropriate typealiases for the underlying C types. These typealiases are used as the `rawValue` for their strongly-typed representations.
|
||||
|
||||
```swift
|
||||
extension CInterop {
|
||||
public typealias Stat
|
||||
public typealias Inode
|
||||
public typealias UserID
|
||||
public typealias GroupID
|
||||
public typealias DeviceID
|
||||
public typealias FileFlags
|
||||
}
|
||||
```
|
||||
|
||||
## Source compatibility
|
||||
|
||||
This proposal is additive and source-compatible with existing code.
|
||||
|
||||
## ABI compatibility
|
||||
|
||||
This proposal is additive and ABI-compatible with existing code.
|
||||
|
||||
## Implications on adoption
|
||||
|
||||
This feature can be freely adopted and un-adopted in source code with no deployment constraints and without affecting source or ABI compatibility.
|
||||
|
||||
## Future directions
|
||||
|
||||
To remain faithful to the underlying system calls, we don't anticipate extending `Stat`. However, the types introduced in this proposal could serve as the foundation of broader file system APIs in Swift.
|
||||
|
||||
While this proposal does not include `Stat` on Windows, a separate proposal should provide Swift-native wrappers of idiomatic `GetFileInformation` functions with their associated types.
|
||||
|
||||
A more general `FileInfo` API could then build on these OS-specific types to provide an ergonomic, cross-platform abstraction for file metadata. These future cross-platform APIs might be better implemented outside of System, such as in Foundation, the standard library, or somewhere in between. They could provide additional information or convenience features, such as reading and modifying extended attributes or setting file timestamps.
|
||||
|
||||
In the future, more functionality could be added to types such as `DeviceID`.
|
||||
|
||||
### Using `UTCClock.Instant` for time properties
|
||||
|
||||
When the `UTCClock` proposal and code destination is finalized, we could use the `UTCClock.Instant` type for `Stat` time properties:
|
||||
|
||||
```swift
|
||||
extension Stat {
|
||||
/// Time of last access, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin).
|
||||
public var accessTime: UTCClock.Instant { get set }
|
||||
|
||||
/// Time of last modification, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin).
|
||||
public var modificationTime: UTCClock.Instant { get set }
|
||||
|
||||
/// Time of last status (inode) change, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin).
|
||||
public var changeTime: UTCClock.Instant { get set }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Time of file creation, given as a `UTCClock.Instant`
|
||||
///
|
||||
/// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin).
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
public var creationTime: UTCClock.Instant { get set }
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
We would reserve the more ergonomic `accessTime`, `modificationTime`, etc. names for these future extensions.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### `FileInfo` as the lowest-level type
|
||||
An alternative approach could be to have a more general `FileInfo` type be the lowest level of abstraction provided by the System library. This type would then handle all the `stat` or Windows-specific struct storage and accessors. However, this alternative:
|
||||
|
||||
- Is inconsistent with System's philosophy of providing low-level system abstractions.
|
||||
- Introduces an even larger number of system-specific APIs on each type.
|
||||
- Misses out on the familiarity of the `stat` name. Developers know what to look for and what to expect from this type.
|
||||
|
||||
### Single combined type for both file and file system metadata
|
||||
Combining `Stat` and `StatFS` (separate proposal) into a single type was considered but rejected because file and file system information serve different purposes and are typically needed in different contexts. Storing and/or initializing both `stat` and `statfs` structs unnecessarily reduces performance when one isn't needed.
|
||||
|
||||
### Making `Stat` available on Windows
|
||||
It's possible to make `Stat` available on Windows and use either the non-native `_stat` functions from CRT or populate the information via a separate `GetFileInformation` call. However, many of the `stat` fields are not- or less-applicable on Windows and are treated as such by `_stat`. For instance, `st_uid` is always zero on Windows, `st_ino` has no meaning in FAT, HPFS, or NTFS file systems, and `st_mode` can only specify a regular file, directory, or character special, with the executable bit depending entirely on the file's path extension.
|
||||
|
||||
Rather than forcing Windows file metadata semantics into a cross-platform `Stat` type, we should instead create Windows-specific types that give developers full access to platform-native file metadata. Combined with a higher-level `FileInfo` type that _is_ cross-platform, this gives the best of both low-level and platform-agnostic APIs.
|
||||
|
||||
### Only have `FilePath` and `FileDescriptor` extensions rather than initializers that accept these types
|
||||
While having `.stat()` functions on `FilePath` and `FileDescriptor` is preferred for ergonomics and function chaining, this technique might lack the discoverability of having an initializer on `Stat` directly. This proposal therefore includes both the initializers and extensions.
|
||||
|
||||
### Types for time properties
|
||||
|
||||
`UTCClock.Instant` would ideally be chosen over alternatives such as `Duration` or a new `Timespec` type to provide a comparable instant in time rather than a duration since the Epoch. However, this would depend on lowering `UTCClock` to System or the standard library and depends on that separate proposal.
|
||||
|
||||
Exposing a `timespec` property directly also has benefits; it's faithful to the underlying system's type and already has conversion support to/from `Duration` in the standard library.
|
||||
|
||||
Given that `timespec` is not particularly crufty and already has public API supporting its conversions, we decided to expose the raw `timespec` for now under the original C property names (`st_atim`, `st_mtim`, etc.) and reserve more ergonomic names for future extensions.
|
||||
|
||||
### Type names
|
||||
|
||||
`Stat` was chosen over alternatives like `FileStat` or `FileStatus` for its brevity and likeness to the "stat" system call. Unlike generic names such as `FileInfo` or `FileMetadata`, `Stat` emphasizes the platform-specific nature of this type.
|
||||
|
||||
`Stat` and (possible future) `StatFS` names were chosen over `FileStat` and `FileSystemStat`, or a namespaced `File.Stat` and `FileSystem.Stat`, because `Stat` is recognized more as its own concept rather than shorthand for "status." Thus, using `FileSystem.Stat` or `FileSystemStat` for `statfs` in the future might lead to confusion. Also, precedence from other languages' `stat` APIs that use a "file system" namespace might add to this confusion:
|
||||
|
||||
```
|
||||
Rust: fs::metadata() -> fs::Metadata
|
||||
Python: os.stat() -> os.stat_result
|
||||
Go: os.Stat() -> fs.FileInfo
|
||||
```
|
||||
|
||||
`Inode` was chosen over alternatives like `FileIndex` or `FileID` to emphasize the platform-specific nature. `IndexNode` is a bit verbose, and despite its etymology, "inode" is now ubiquitous and understood as a single word, making the capitalization `Inode` preferable to `INode`.
|
||||
|
||||
### `FileFlags` naming conventions
|
||||
|
||||
`FileFlags` property names such as `hidden` and `compressed` could alternatively use an "is" prefix commonly seen in boolean properties to form `.isHidden` and `.isCompressed`. However, we chose to omit the "is" prefix for the following reasons:
|
||||
|
||||
- The "is"-less flag names are succinct and closely aligned with the underlying C constants they represent.
|
||||
- `OptionSet` property names often use an adjective ("hidden") rather than a predicate ("is hidden") when describing a single subject, such as a file. This is likely because "is" does not add to the flow of `flags.contains(.isHidden)` like it does for a direct boolean property, such as `file.isHidden`.
|
||||
- For both `OptionSet` APIs that describe a single subject and those that describe a collection of elements, there's precedence to omit the "is". Examples of single-subject `OptionSet` APIs include `UIControl.State`, which uses `.highlighted` and `.disabled` rather than `.isHighlighted` and `.isDisabled`, and `FilePermissions`, which uses `.ownerRead` rather than `.isOwnerReadable`. Examples of multi-subject `OptionSet` APIs include `Edge.Set`, which uses `.top` and `.bottom`, and `ShippingOptions` from the `OptionSet` documentation, which uses `.nextDay`, `.priority`, etc.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
These new APIs build on excellent types currently available in the System library.
|
||||
|
||||
## Appendix
|
||||
|
||||
### Swift API to C Mappings
|
||||
|
||||
The following tables show the mapping between Swift APIs and their underlying C system calls across different operating systems:
|
||||
|
||||
#### `Stat` Initializer Mappings
|
||||
|
||||
The `retryOnInterrupt: Bool = true` parameter is omitted for clarity.
|
||||
|
||||
| Swift API | Unix-like Platforms |
|
||||
|-----------|---------------------|
|
||||
| `Stat(_ path: FilePath, followTargetSymlink: true)` | `stat()` |
|
||||
| `Stat(_ path: UnsafePointer<CChar>, followTargetSymlink: true)` | `stat()` |
|
||||
||
|
||||
| `Stat(_ path: FilePath, followTargetSymlink: false)` | `lstat()` |
|
||||
| `Stat(_ path: UnsafePointer<CChar>, followTargetSymlink: false)` | `lstat()` |
|
||||
||
|
||||
| `Stat(_ path: FilePath, relativeTo: FileDescriptor, flags: Stat.Flags)` | `fstatat()` |
|
||||
| `Stat(_ path: UnsafePointer<CChar>, relativeTo: FileDescriptor, flags: Stat.Flags)` | `fstatat()` |
|
||||
||
|
||||
| `Stat(_ fd: FileDescriptor)` | `fstat()` |
|
||||
| `FileDescriptor.stat()` | `fstat()` |
|
||||
||
|
||||
| `FilePath.stat(followTargetSymlink: true)` | `stat()` |
|
||||
| `FilePath.stat(followTargetSymlink: false)` | `lstat()` |
|
||||
| `FilePath.stat(relativeTo: FileDescriptor, flags: Stat.Flags)` | `fstatat()` |
|
||||
|
||||
#### `Stat` Property Mappings
|
||||
|
||||
`"` denotes the same property name across all operating systems.
|
||||
|
||||
| Swift Property | Darwin | FreeBSD | OpenBSD | Linux | Android | WASI |
|
||||
|----------------|--------|---------|---------|-------|---------|------|
|
||||
| `deviceID` | `st_dev` | " | " | " | " | " |
|
||||
| `inode` | `st_ino` | " | " | " | " | " |
|
||||
| `mode` | `st_mode` | " | " | " | " | " |
|
||||
| `linkCount` | `st_nlink` | " | " | " | " | " |
|
||||
| `userID` | `st_uid` | " | " | " | " | " |
|
||||
| `groupID` | `st_gid` | " | " | " | " | " |
|
||||
| `specialDeviceID` | `st_rdev` | " | " | " | " | " |
|
||||
| `size` | `st_size` | " | " | " | " | " |
|
||||
| `preferredIOBlockSize` | `st_blksize` | " | " | " | " | " |
|
||||
| `blocksAllocated` | `st_blocks` | " | " | " | " | " |
|
||||
| `st_atim` | `st_atimespec` | `st_atim` | `st_atim` | `st_atim` | `st_atim` | `st_atim` |
|
||||
| `st_mtim` | `st_mtimespec` | `st_mtim` | `st_mtim` | `st_mtim` | `st_mtim` | `st_mtim` |
|
||||
| `st_ctim` | `st_ctimespec` | `st_ctim` | `st_ctim` | `st_ctim` | `st_ctim` | `st_ctim` |
|
||||
| `st_birthtim` | `st_birthtimespec` | `st_birthtim` | N/A | N/A | N/A | N/A |
|
||||
| `flags` | `st_flags` | `st_flags` | `st_flags` | N/A | N/A | N/A |
|
||||
| `generationNumber` | `st_gen` | `st_gen` | `st_gen` | N/A | N/A | N/A |
|
||||
|
||||
#### `Stat.Flags` Mappings
|
||||
|
||||
| Swift Flag | Darwin | FreeBSD | OpenBSD | Linux | Android | WASI |
|
||||
|------------|--------|---------|---------|-------|---------|------|
|
||||
| `symlinkNoFollow` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` | `AT_SYMLINK_NOFOLLOW` |
|
||||
| `symlinkNoFollowAny` | `AT_SYMLINK_NOFOLLOW_ANY` | N/A | N/A | N/A | N/A | N/A |
|
||||
| `resolveBeneath` | `AT_RESOLVE_BENEATH` | `AT_RESOLVE_BENEATH` | N/A | N/A | N/A | N/A |
|
||||
| `emptyPath` | N/A | `AT_EMPTY_PATH` | N/A | `AT_EMPTY_PATH` | `AT_EMPTY_PATH` | N/A |
|
||||
|
||||
#### `FileFlags` Mappings
|
||||
|
||||
**Note:** `FileFlags` is only available on Darwin, FreeBSD, and OpenBSD.
|
||||
|
||||
| Swift Flag | Darwin | FreeBSD | OpenBSD |
|
||||
|------------|--------|---------|---------|
|
||||
| `noDump` | `UF_NODUMP` | `UF_NODUMP` | `UF_NODUMP` |
|
||||
| `userImmutable` | `UF_IMMUTABLE` | `UF_IMMUTABLE` | `UF_IMMUTABLE` |
|
||||
| `userAppend` | `UF_APPEND` | `UF_APPEND` | `UF_APPEND` |
|
||||
| `archived` | `SF_ARCHIVED` | `SF_ARCHIVED` | `SF_ARCHIVED` |
|
||||
| `systemImmutable` | `SF_IMMUTABLE` | `SF_IMMUTABLE` | `SF_IMMUTABLE` |
|
||||
| `systemAppend` | `SF_APPEND` | `SF_APPEND` | `SF_APPEND` |
|
||||
| `opaque` | `UF_OPAQUE` | `UF_OPAQUE` | N/A |
|
||||
| `hidden` | `UF_HIDDEN` | `UF_HIDDEN` | N/A |
|
||||
| `systemNoUnlink` | `SF_NOUNLINK` | `SF_NOUNLINK` | N/A |
|
||||
| `compressed` | `UF_COMPRESSED` | N/A | N/A |
|
||||
| `tracked` | `UF_TRACKED` | N/A | N/A |
|
||||
| `dataVault` | `UF_DATAVAULT` | N/A | N/A |
|
||||
| `restricted` | `SF_RESTRICTED` | N/A | N/A |
|
||||
| `firmlink` | `SF_FIRMLINK` | N/A | N/A |
|
||||
| `dataless` | `SF_DATALESS` | N/A | N/A |
|
||||
| `userNoUnlink` | N/A | `UF_NOUNLINK` | N/A |
|
||||
| `offline` | N/A | `UF_OFFLINE` | N/A |
|
||||
| `readOnly` | N/A | `UF_READONLY` | N/A |
|
||||
| `reparse` | N/A | `UF_REPARSE` | N/A |
|
||||
| `sparse` | N/A | `UF_SPARSE` | N/A |
|
||||
| `system` | N/A | `UF_SYSTEM` | N/A |
|
||||
| `snapshot` | N/A | `SF_SNAPSHOT` | N/A |
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
Swift System provides idiomatic interfaces to system calls and low-level currency types. Our vision is for System to act as the single home for low-level system interfaces for all supported Swift platforms.
|
||||
|
||||
## Multi-platform not Cross-platform
|
||||
## No Cross-platform Abstractions
|
||||
|
||||
System is a multi-platform library, not a cross-platform one. It provides a separate set of APIs and behaviors on every supported platform, closely reflecting the underlying OS interfaces. A single import will pull in the native platform interfaces specific for the targeted OS.
|
||||
Swift System is not a cross-platform library. It provides a separate set of APIs and behaviors on every supported platform, closely reflecting the underlying OS interfaces. A single import will pull in the native platform interfaces specific for the targeted OS.
|
||||
|
||||
Our immediate goal is to simplify building cross-platform libraries and applications such as SwiftNIO and SwiftPM. System does not eliminate the need for `#if os()` conditionals to implement cross-platform abstractions, but it does make it safer and more expressive to fill out the platform-specific parts.
|
||||
Our immediate goal is to simplify building cross-platform libraries and applications such as SwiftNIO and SwiftPM. It is not a design goal for System to eliminate the need for `#if os()` conditionals to implement cross-platform abstractions; rather, our goal is to make it safer and more expressive to fill out the platform-specific parts.
|
||||
|
||||
(That said, it is desirable to avoid unnecessary differences -- for example, when two operating systems share the same C name for a system call, ideally Swift System would expose them using the same Swift name. This is a particularly obvious expectation for system interfaces that implement an industry standard, such as POSIX.)
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -22,13 +24,15 @@ try fd.closeAfter {
|
||||
}
|
||||
```
|
||||
|
||||
[API documentation](https://swiftpackageindex.com/apple/swift-system/documentation/SystemPackage)
|
||||
|
||||
## Adding `SystemPackage` as a Dependency
|
||||
|
||||
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.3.0"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
|
||||
```
|
||||
|
||||
Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
@@ -37,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.3.0"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
@@ -51,14 +55,72 @@ let package = Package(
|
||||
|
||||
## Source Stability
|
||||
|
||||
The Swift System package is source stable. The version numbers follow [Semantic Versioning][semver] -- source breaking changes to public API can only land in a new major version.
|
||||
At this time, the Swift System package supports three types of operating systems: Darwin-based, POSIX-like, and Windows. The source-stability status of the package differs according to the platform:
|
||||
|
||||
| Platform type | Source Stability |
|
||||
| ----------------- | --------------- |
|
||||
| Darwin (macOS, iOS, etc.) | Stable |
|
||||
| POSIX (Linux, WASI, etc.) | Stable |
|
||||
| Windows | Unstable |
|
||||
|
||||
The package version numbers follow [Semantic Versioning][semver] -- source breaking changes to source-stable public API can only land in a new major version. However, platforms for which support has not reached source stability may see source-breaking changes in a new minor version.
|
||||
|
||||
[semver]: https://semver.org
|
||||
|
||||
## Contributing
|
||||
The public API of the swift-system package consists of non-underscored declarations that are marked `public` in the `SystemPackage` module.
|
||||
|
||||
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
By "underscored declarations" we mean declarations that have a leading underscore anywhere in their fully qualified name. For instance, here are some names that wouldn't be considered part of the public API, even if they were technically marked public:
|
||||
|
||||
## LICENSE
|
||||
- `FooModule.Bar._someMember(value:)` (underscored member)
|
||||
- `FooModule._Bar.someMember` (underscored type)
|
||||
- `_FooModule.Bar` (underscored module)
|
||||
- `FooModule.Bar.init(_value:)` (underscored initializer)
|
||||
|
||||
Interfaces that aren't part of the public API may continue to change in any release, including patch releases. If you have a use case that requires using non-public APIs, please submit a Feature Request describing it! We'd like the public interface to be as useful as possible -- although preferably without compromising safety or limiting future evolution.
|
||||
|
||||
Future minor versions of the package may update these rules as needed.
|
||||
|
||||
## Toolchain Requirements
|
||||
|
||||
The following table maps existing package releases to their minimum required Swift toolchain release:
|
||||
|
||||
| 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 |
|
||||
|
||||
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.
|
||||
|
||||
(Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.)
|
||||
|
||||
## Licensing
|
||||
|
||||
See [LICENSE](LICENSE.txt) for license information.
|
||||
|
||||
## Contributing
|
||||
|
||||
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
### Branching Strategy
|
||||
|
||||
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 |
|
||||
|
||||
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`
|
||||
|
||||
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.)
|
||||
|
||||
### 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
|
||||
@@ -9,8 +9,8 @@ See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
add_library(CSystem INTERFACE)
|
||||
target_include_directories(CSystem INTERFACE
|
||||
include)
|
||||
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
||||
$<INSTALL_INTERFACE:include/CSystem>)
|
||||
|
||||
install(FILES
|
||||
include/CSystemLinux.h
|
||||
|
||||
@@ -21,5 +21,6 @@
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
#include "io_uring.h"
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2024 - 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
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#if __wasi__
|
||||
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h> // For NAME_MAX
|
||||
|
||||
// wasi-libc defines the following constants in a way that Clang Importer can't
|
||||
// understand, so we need to expose them manually.
|
||||
static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; }
|
||||
static inline int32_t _getConst_O_APPEND(void) { return O_APPEND; }
|
||||
static inline int32_t _getConst_O_CREAT(void) { return O_CREAT; }
|
||||
static inline int32_t _getConst_O_DIRECTORY(void) { return O_DIRECTORY; }
|
||||
static inline int32_t _getConst_O_EXCL(void) { return O_EXCL; }
|
||||
static inline int32_t _getConst_O_NONBLOCK(void) { return O_NONBLOCK; }
|
||||
static inline int32_t _getConst_O_TRUNC(void) { return O_TRUNC; }
|
||||
static inline int32_t _getConst_O_WRONLY(void) { return O_WRONLY; }
|
||||
|
||||
static inline int32_t _getConst_EWOULDBLOCK(void) { return EWOULDBLOCK; }
|
||||
static inline int32_t _getConst_EOPNOTSUPP(void) { return EOPNOTSUPP; }
|
||||
|
||||
static inline uint8_t _getConst_DT_DIR(void) { return DT_DIR; }
|
||||
|
||||
// Modified dirent struct that can be imported to Swift
|
||||
struct _system_dirent {
|
||||
ino_t d_ino;
|
||||
unsigned char d_type;
|
||||
// char d_name[] cannot be imported to Swift
|
||||
char d_name[NAME_MAX + 1];
|
||||
};
|
||||
|
||||
// Convert WASI dirent with d_name[] to _system_dirent
|
||||
static inline
|
||||
struct _system_dirent *
|
||||
_system_dirent_from_wasi_dirent(const struct dirent *wasi_dirent) {
|
||||
|
||||
// Match readdir behavior and use thread-local storage for the converted dirent
|
||||
static __thread struct _system_dirent _converted_dirent;
|
||||
|
||||
if (wasi_dirent == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
memset(&_converted_dirent, 0, sizeof(struct _system_dirent));
|
||||
|
||||
_converted_dirent.d_ino = wasi_dirent->d_ino;
|
||||
_converted_dirent.d_type = wasi_dirent->d_type;
|
||||
|
||||
strncpy(_converted_dirent.d_name, wasi_dirent->d_name, NAME_MAX);
|
||||
_converted_dirent.d_name[NAME_MAX] = '\0';
|
||||
|
||||
return &_converted_dirent;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,247 @@
|
||||
#include <unistd.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <signal.h>
|
||||
|
||||
#define __SWIFT_IORING_SQE_FALLBACK_STRUCT { \
|
||||
__u8 opcode; \
|
||||
__u8 flags; \
|
||||
__u16 ioprio; \
|
||||
__s32 fd; \
|
||||
union { \
|
||||
__u64 off; \
|
||||
__u64 addr2; \
|
||||
struct { \
|
||||
__u32 cmd_op; \
|
||||
__u32 __pad1; \
|
||||
}; \
|
||||
}; \
|
||||
union { \
|
||||
__u64 addr; \
|
||||
__u64 splice_off_in; \
|
||||
struct { \
|
||||
__u32 level; \
|
||||
__u32 optname; \
|
||||
}; \
|
||||
}; \
|
||||
__u32 len; \
|
||||
union { \
|
||||
__kernel_rwf_t rw_flags; \
|
||||
__u32 fsync_flags; \
|
||||
__u16 poll_events; \
|
||||
__u32 poll32_events; \
|
||||
__u32 sync_range_flags; \
|
||||
__u32 msg_flags; \
|
||||
__u32 timeout_flags; \
|
||||
__u32 accept_flags; \
|
||||
__u32 cancel_flags; \
|
||||
__u32 open_flags; \
|
||||
__u32 statx_flags; \
|
||||
__u32 fadvise_advice; \
|
||||
__u32 splice_flags; \
|
||||
__u32 rename_flags; \
|
||||
__u32 unlink_flags; \
|
||||
__u32 hardlink_flags; \
|
||||
__u32 xattr_flags; \
|
||||
__u32 msg_ring_flags; \
|
||||
__u32 uring_cmd_flags; \
|
||||
__u32 waitid_flags; \
|
||||
__u32 futex_flags; \
|
||||
__u32 install_fd_flags; \
|
||||
__u32 nop_flags; \
|
||||
}; \
|
||||
__u64 user_data; \
|
||||
union { \
|
||||
__u16 buf_index; \
|
||||
__u16 buf_group; \
|
||||
} __attribute__((packed)); \
|
||||
__u16 personality; \
|
||||
union { \
|
||||
__s32 splice_fd_in; \
|
||||
__u32 file_index; \
|
||||
__u32 optlen; \
|
||||
struct { \
|
||||
__u16 addr_len; \
|
||||
__u16 __pad3[1]; \
|
||||
}; \
|
||||
}; \
|
||||
union { \
|
||||
struct { \
|
||||
__u64 addr3; \
|
||||
__u64 __pad2[1]; \
|
||||
}; \
|
||||
__u64 optval; \
|
||||
__u8 cmd[0]; \
|
||||
}; \
|
||||
}
|
||||
|
||||
#if __has_include(<linux/io_uring.h>)
|
||||
#include <linux/io_uring.h>
|
||||
|
||||
#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
|
||||
typedef struct io_uring_sqe swift_io_uring_sqe;
|
||||
#else
|
||||
// io_uring_sqe is missing properties that IORequest expects.
|
||||
// This configuration is not supported for now.
|
||||
//
|
||||
// Define a fallback struct to avoid build errors, but IORing
|
||||
// will throw ENOTSUP on initialization.
|
||||
#define __SWIFT_IORING_SUPPORTED false
|
||||
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
#endif
|
||||
|
||||
// We can define more specific availability later
|
||||
|
||||
#ifdef IORING_FEAT_RW_CUR_POS
|
||||
// Kernel version >= 5.6, io_uring_sqe has open_flags
|
||||
#endif
|
||||
|
||||
#ifdef IORING_FEAT_NODROP
|
||||
// Kernel version >= 5.5, io_uring_sqe has cancel_flags
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK)
|
||||
#include <stdint.h>
|
||||
|
||||
#define __SWIFT_IORING_SUPPORTED false
|
||||
|
||||
#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_FEAT_SINGLE_MMAP (1U << 0)
|
||||
#define IORING_FEAT_NODROP (1U << 1)
|
||||
#define IORING_FEAT_SUBMIT_STABLE (1U << 2)
|
||||
#define IORING_FEAT_RW_CUR_POS (1U << 3)
|
||||
#define IORING_FEAT_CUR_PERSONALITY (1U << 4)
|
||||
#define IORING_FEAT_FAST_POLL (1U << 5)
|
||||
#define IORING_FEAT_POLL_32BITS (1U << 6)
|
||||
#define IORING_FEAT_SQPOLL_NONFIXED (1U << 7)
|
||||
#define IORING_FEAT_EXT_ARG (1U << 8)
|
||||
#define IORING_FEAT_NATIVE_WORKERS (1U << 9)
|
||||
#define IORING_FEAT_RSRC_TAGS (1U << 10)
|
||||
#define IORING_FEAT_CQE_SKIP (1U << 11)
|
||||
#define IORING_FEAT_LINKED_FILE (1U << 12)
|
||||
#define IORING_FEAT_REG_REG_RING (1U << 13)
|
||||
#define IORING_FEAT_RECVSEND_BUNDLE (1U << 14)
|
||||
#define IORING_FEAT_MIN_TIMEOUT (1U << 15)
|
||||
#define IORING_FEAT_RW_ATTR (1U << 16)
|
||||
#define IORING_FEAT_NO_IOWAIT (1U << 17)
|
||||
|
||||
#if !defined(_ASM_GENERIC_INT_LL64_H) && !defined(_ASM_GENERIC_INT_L64_H) && !defined(_UAPI_ASM_GENERIC_INT_LL64_H) && !defined(_UAPI_ASM_GENERIC_INT_L64_H)
|
||||
typedef uint8_t __u8;
|
||||
typedef uint16_t __u16;
|
||||
typedef uint32_t __u32;
|
||||
typedef uint64_t __u64;
|
||||
typedef int32_t __s32;
|
||||
#endif
|
||||
|
||||
#ifndef __kernel_rwf_t
|
||||
typedef int __kernel_rwf_t;
|
||||
#endif
|
||||
|
||||
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
|
||||
struct io_uring_cqe {
|
||||
__u64 user_data;
|
||||
__s32 res;
|
||||
__u32 flags;
|
||||
};
|
||||
|
||||
struct io_sqring_offsets {
|
||||
__u32 head;
|
||||
__u32 tail;
|
||||
__u32 ring_mask;
|
||||
__u32 ring_entries;
|
||||
__u32 flags;
|
||||
__u32 dropped;
|
||||
__u32 array;
|
||||
__u32 resv1;
|
||||
__u64 user_addr;
|
||||
};
|
||||
|
||||
struct io_cqring_offsets {
|
||||
__u32 head;
|
||||
__u32 tail;
|
||||
__u32 ring_mask;
|
||||
__u32 ring_entries;
|
||||
__u32 overflow;
|
||||
__u32 cqes;
|
||||
__u32 flags;
|
||||
__u32 resv1;
|
||||
__u64 user_addr;
|
||||
};
|
||||
|
||||
struct io_uring_params {
|
||||
__u32 sq_entries;
|
||||
__u32 cq_entries;
|
||||
__u32 flags;
|
||||
__u32 sq_thread_cpu;
|
||||
__u32 sq_thread_idle;
|
||||
__u32 features;
|
||||
__u32 wq_fd;
|
||||
__u32 resv[3];
|
||||
struct io_sqring_offsets sq_off;
|
||||
struct io_cqring_offsets cq_off;
|
||||
};
|
||||
#endif // __has_include(<linux/io_uring.h>)
|
||||
|
||||
#ifndef SWIFT_IORING_C_WRAPPER
|
||||
#define SWIFT_IORING_C_WRAPPER
|
||||
|
||||
# ifndef __NR_io_uring_setup
|
||||
# define __NR_io_uring_setup 425
|
||||
# endif
|
||||
# ifndef __NR_io_uring_enter
|
||||
# define __NR_io_uring_enter 426
|
||||
# endif
|
||||
# ifndef __NR_io_uring_register
|
||||
# define __NR_io_uring_register 427
|
||||
# endif
|
||||
|
||||
/*
|
||||
struct io_uring_getevents_arg {
|
||||
__u64 sigmask;
|
||||
__u32 sigmask_sz;
|
||||
__u32 min_wait_usec; //used to be called `pad`. This compatibility wrapper avoids dealing with that.
|
||||
__u64 ts;
|
||||
};
|
||||
*/
|
||||
struct swift_io_uring_getevents_arg {
|
||||
__u64 sigmask;
|
||||
__u32 sigmask_sz;
|
||||
__u32 min_wait_usec;
|
||||
__u64 ts;
|
||||
};
|
||||
|
||||
static inline int io_uring_register(int fd, unsigned int opcode, void *arg,
|
||||
unsigned int nr_args)
|
||||
{
|
||||
return syscall(__NR_io_uring_register, fd, opcode, arg, nr_args);
|
||||
}
|
||||
|
||||
static inline int io_uring_setup(unsigned int entries, struct io_uring_params *p)
|
||||
{
|
||||
return syscall(__NR_io_uring_setup, entries, p);
|
||||
}
|
||||
|
||||
static inline int io_uring_enter2(int fd, unsigned int to_submit, unsigned int min_complete,
|
||||
unsigned int flags, void *args, size_t sz)
|
||||
{
|
||||
return syscall(__NR_io_uring_enter, fd, to_submit, min_complete,
|
||||
flags, args, _NSIG / 8);
|
||||
}
|
||||
|
||||
static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete,
|
||||
unsigned int flags, sigset_t *sig)
|
||||
{
|
||||
return io_uring_enter2(fd, to_submit, min_complete, flags, sig, _NSIG / 8);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,5 +1,6 @@
|
||||
module CSystem {
|
||||
header "CSystemLinux.h"
|
||||
header "CSystemWASI.h"
|
||||
header "CSystemWindows.h"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct Connect: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Connect to a TCP server and send/receive messages"
|
||||
)
|
||||
|
||||
@Argument(help: "The host to connect to")
|
||||
var host: String
|
||||
|
||||
@Argument(help: "The port to connect to")
|
||||
var port: UInt16
|
||||
|
||||
@Option(name: .shortAndLong, help: "Message to send")
|
||||
var message: String = "Hello from swift-system sockets!"
|
||||
|
||||
func run() throws {
|
||||
print("Resolving \(host)...")
|
||||
|
||||
// Resolve the hostname
|
||||
let hints = SocketAddress.ResolutionHints(family: .ipv4, socketType: .stream, protocol: .tcp)
|
||||
let addresses = try SocketAddress.resolve(hostname: host, service: "\(port)", hints: hints)
|
||||
|
||||
guard let first = addresses.first else {
|
||||
print("No addresses found for \(host)")
|
||||
return
|
||||
}
|
||||
|
||||
print("Connecting to \(first.address.ipv4?.description ?? "unknown")...")
|
||||
|
||||
// Create socket
|
||||
let socket = try SocketDescriptor.open(first.family, first.socketType, protocol: first.protocol)
|
||||
defer { try? socket.close() }
|
||||
|
||||
// Connect
|
||||
try socket.connect(to: first.address)
|
||||
print("Connected!")
|
||||
|
||||
// Send message
|
||||
let messageBytes = Array(message.utf8)
|
||||
let sent = try messageBytes.withUnsafeBytes { buffer in
|
||||
try socket.send(UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
print("Sent \(sent) bytes: \(message)")
|
||||
|
||||
// Receive response
|
||||
var buffer = [UInt8](repeating: 0, count: 4096)
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try socket.receive(into: buffer)
|
||||
}
|
||||
|
||||
if received > 0 {
|
||||
let response = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
print("Received \(received) bytes: \(response)")
|
||||
} else {
|
||||
print("Connection closed by server")
|
||||
}
|
||||
|
||||
print("Done!")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct Listen: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Run a simple TCP echo server"
|
||||
)
|
||||
|
||||
@Option(name: .shortAndLong, help: "The port to listen on")
|
||||
var port: UInt16 = 8080
|
||||
|
||||
@Option(name: .shortAndLong, help: "Maximum number of connections to accept (0 for unlimited)")
|
||||
var maxConnections: Int = 0
|
||||
|
||||
func run() throws {
|
||||
// Create socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? server.close() }
|
||||
|
||||
// Set reuse address
|
||||
try server.setReuseAddress(true)
|
||||
|
||||
// Bind
|
||||
let address = SocketAddress(ipv4: IPv4Address.any(port: port))
|
||||
try server.bind(to: address)
|
||||
|
||||
// Listen
|
||||
try server.listen(backlog: 5)
|
||||
|
||||
var localAddr = SocketAddress()
|
||||
try server.getLocalAddress(into: &localAddr)
|
||||
print("Listening on \(localAddr.ipv4?.description ?? "unknown")...")
|
||||
|
||||
var connectionCount = 0
|
||||
while maxConnections == 0 || connectionCount < maxConnections {
|
||||
print("Waiting for connection...")
|
||||
|
||||
var peerAddr = SocketAddress()
|
||||
let client = try server.accept(client: &peerAddr)
|
||||
connectionCount += 1
|
||||
|
||||
print("[\(connectionCount)] Connection from \(peerAddr.ipv4?.description ?? "unknown")")
|
||||
|
||||
// Handle client in a simple blocking manner
|
||||
defer { try? client.close() }
|
||||
|
||||
var buffer = [UInt8](repeating: 0, count: 4096)
|
||||
|
||||
while true {
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try client.receive(into: buffer)
|
||||
}
|
||||
if received == 0 {
|
||||
print("[\(connectionCount)] Client disconnected")
|
||||
break
|
||||
}
|
||||
|
||||
let message = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
print("[\(connectionCount)] Received \(received) bytes: \(message)")
|
||||
|
||||
// Echo back
|
||||
let sent = try buffer.prefix(received).withUnsafeBytes { buffer in
|
||||
try client.send(UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
print("[\(connectionCount)] Echoed \(sent) bytes")
|
||||
}
|
||||
}
|
||||
|
||||
print("Server shutting down after \(connectionCount) connections")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct Resolve: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Resolve a hostname to IP addresses using getaddrinfo"
|
||||
)
|
||||
|
||||
@Argument(help: "The hostname to resolve")
|
||||
var hostname: String
|
||||
|
||||
@Option(name: .shortAndLong, help: "Service name or port number")
|
||||
var service: String?
|
||||
|
||||
@Flag(name: .long, help: "Show only IPv4 addresses")
|
||||
var ipv4Only: Bool = false
|
||||
|
||||
@Flag(name: .long, help: "Show only IPv6 addresses")
|
||||
var ipv6Only: Bool = false
|
||||
|
||||
func run() throws {
|
||||
let family: SocketDescriptor.Domain?
|
||||
if ipv4Only {
|
||||
family = .ipv4
|
||||
} else if ipv6Only {
|
||||
family = .ipv6
|
||||
} else {
|
||||
family = nil
|
||||
}
|
||||
|
||||
let hints = SocketAddress.ResolutionHints(family: family)
|
||||
|
||||
print("Resolving \(hostname)...")
|
||||
|
||||
let addresses = try SocketAddress.resolve(
|
||||
hostname: hostname,
|
||||
service: service,
|
||||
hints: hints
|
||||
)
|
||||
|
||||
if addresses.isEmpty {
|
||||
print("No addresses found")
|
||||
return
|
||||
}
|
||||
|
||||
print("Found \(addresses.count) address(es):\n")
|
||||
|
||||
for (index, info) in addresses.enumerated() {
|
||||
print("[\(index + 1)] Family: \(familyName(info.family))")
|
||||
print(" Type: \(typeName(info.socketType))")
|
||||
print(" Protocol: \(protocolName(info.protocol))")
|
||||
|
||||
if let ipv4 = info.address.ipv4 {
|
||||
print(" Address: \(ipv4.addressString):\(ipv4.port)")
|
||||
} else if let ipv6 = info.address.ipv6 {
|
||||
print(" Address: [\(ipv6.addressString)]:\(ipv6.port)")
|
||||
}
|
||||
|
||||
if let canonName = info.canonicalName {
|
||||
print(" Canonical: \(canonName)")
|
||||
}
|
||||
|
||||
print()
|
||||
}
|
||||
}
|
||||
|
||||
private func familyName(_ domain: SocketDescriptor.Domain) -> String {
|
||||
switch domain {
|
||||
case .ipv4: return "IPv4"
|
||||
case .ipv6: return "IPv6"
|
||||
case .local: return "Unix"
|
||||
default: return "Unknown (\(domain.rawValue))"
|
||||
}
|
||||
}
|
||||
|
||||
private func typeName(_ type: SocketDescriptor.ConnectionType) -> String {
|
||||
switch type {
|
||||
case .stream: return "Stream (TCP)"
|
||||
case .datagram: return "Datagram (UDP)"
|
||||
case .raw: return "Raw"
|
||||
default: return "Unknown (\(type.rawValue))"
|
||||
}
|
||||
}
|
||||
|
||||
private func protocolName(_ proto: SocketDescriptor.ProtocolID) -> String {
|
||||
switch proto {
|
||||
case .tcp: return "TCP"
|
||||
case .udp: return "UDP"
|
||||
case .ip: return "IP"
|
||||
default: return "Unknown (\(proto.rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct ReverseResolve: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Reverse resolve an IP address to a hostname using getnameinfo"
|
||||
)
|
||||
|
||||
@Argument(help: "The IP address to resolve (IPv4 or IPv6)")
|
||||
var address: String
|
||||
|
||||
@Option(name: .shortAndLong, help: "Port number")
|
||||
var port: UInt16 = 0
|
||||
|
||||
@Flag(name: .long, help: "Request numeric host (don't resolve)")
|
||||
var numericHost: Bool = false
|
||||
|
||||
@Flag(name: .long, help: "Request numeric service (don't resolve)")
|
||||
var numericService: Bool = false
|
||||
|
||||
func run() throws {
|
||||
// Try to parse as IPv4
|
||||
if let ipv4 = IPv4Address(address, port: port) {
|
||||
let sockAddr = SocketAddress(ipv4: ipv4)
|
||||
try resolve(sockAddr)
|
||||
return
|
||||
}
|
||||
|
||||
// Try to parse as IPv6
|
||||
if let ipv6 = IPv6Address(address, port: port) {
|
||||
let sockAddr = SocketAddress(ipv6: ipv6)
|
||||
try resolve(sockAddr)
|
||||
return
|
||||
}
|
||||
|
||||
print("Error: '\(address)' is not a valid IPv4 or IPv6 address")
|
||||
}
|
||||
|
||||
private func resolve(_ address: SocketAddress) throws {
|
||||
var flags: SocketAddress.ReverseResolutionFlags = []
|
||||
if numericHost {
|
||||
flags.insert(.numericHost)
|
||||
}
|
||||
if numericService {
|
||||
flags.insert(.numericService)
|
||||
}
|
||||
|
||||
print("Resolving \(addressDescription(address))...")
|
||||
|
||||
let info = try address.reverseLookup(flags: flags)
|
||||
|
||||
print()
|
||||
if let host = info.hostname {
|
||||
print("Host: \(host)")
|
||||
} else {
|
||||
print("Host: (not resolved)")
|
||||
}
|
||||
|
||||
if let service = info.service {
|
||||
print("Service: \(service)")
|
||||
} else {
|
||||
print("Service: (not resolved)")
|
||||
}
|
||||
}
|
||||
|
||||
private func addressDescription(_ address: SocketAddress) -> String {
|
||||
if let ipv4 = address.ipv4 {
|
||||
return "\(ipv4.addressString):\(ipv4.port)"
|
||||
} else if let ipv6 = address.ipv6 {
|
||||
return "[\(ipv6.addressString)]:\(ipv6.port)"
|
||||
} else {
|
||||
return "(unknown address)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
import SystemSockets
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// Turn off libc's input/output buffering.
|
||||
internal func disableBuffering() {
|
||||
setbuf(stdin, nil)
|
||||
setbuf(stdout, nil)
|
||||
setbuf(stderr, nil)
|
||||
}
|
||||
|
||||
internal func complain(_ message: String) {
|
||||
var message = message + "\n"
|
||||
message.withUTF8 { buffer in
|
||||
_ = try? FileDescriptor.standardError.writeAll(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketAddress.ResolvedAddress {
|
||||
var niceDescription: String {
|
||||
var proto = ""
|
||||
switch self.protocol {
|
||||
case .udp: proto = "udp"
|
||||
case .tcp: proto = "tcp"
|
||||
default: proto = "\(self.protocol)"
|
||||
}
|
||||
return "\(address.niceDescription) (\(proto))"
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketAddress {
|
||||
var niceDescription: String {
|
||||
if let ipv4 = self.ipv4 { return ipv4.description }
|
||||
if let ipv6 = self.ipv6 { return ipv6.description }
|
||||
if let unix = self.unix { return unix.description }
|
||||
return self.description
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketDescriptor.ConnectionType {
|
||||
var isConnectionless: Bool {
|
||||
self == .datagram || self == .reliablyDeliveredMessage
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
struct SystemSamples: ParsableCommand {
|
||||
static var configuration = CommandConfiguration(
|
||||
commandName: "system-samples",
|
||||
abstract: "A collection of little programs exercising some System features.",
|
||||
subcommands: [
|
||||
Resolve.self,
|
||||
ReverseResolve.self,
|
||||
Connect.self,
|
||||
Listen.self,
|
||||
])
|
||||
}
|
||||
|
||||
disableBuffering()
|
||||
SystemSamples.main()
|
||||
@@ -13,9 +13,11 @@ add_library(SystemPackage
|
||||
FileHelpers.swift
|
||||
FileOperations.swift
|
||||
FilePermissions.swift
|
||||
MachPort.swift
|
||||
PlatformString.swift
|
||||
SystemString.swift
|
||||
Util.swift
|
||||
Util+StringArray.swift
|
||||
UtilConsumers.swift)
|
||||
set_target_properties(SystemPackage PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
@@ -28,10 +30,12 @@ target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePathSyntax.swift
|
||||
FilePath/FilePathWindows.swift)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
Internals/Backcompat.swift
|
||||
Internals/CInterop.swift
|
||||
Internals/Constants.swift
|
||||
Internals/Exports.swift
|
||||
Internals/Mocking.swift
|
||||
Internals/RawBuffer.swift
|
||||
Internals/Syscalls.swift
|
||||
Internals/WindowsSyscallAdapters.swift)
|
||||
target_link_libraries(SystemPackage PUBLIC
|
||||
|
||||
+177
-127
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
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
|
||||
|
||||
extension Errno {
|
||||
internal init(windowsError: DWORD) {
|
||||
self.init(rawValue: _mapWindowsErrorToErrno(windowsError))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -14,7 +14,7 @@
|
||||
/// of `FileDescriptor` values,
|
||||
/// in the same way as you manage a raw C file handle.
|
||||
@frozen
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
/// The raw C file handle.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -25,7 +25,8 @@ public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
// Standard file descriptors
|
||||
// Standard file descriptors.
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// The standard input file descriptor, with a numeric value of 0.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -40,11 +41,12 @@ extension FileDescriptor {
|
||||
public static var standardError: FileDescriptor { .init(rawValue: 2) }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// The desired read and write access for a newly opened file.
|
||||
@frozen
|
||||
public struct AccessMode: RawRepresentable, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct AccessMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C access mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -86,7 +88,8 @@ extension FileDescriptor {
|
||||
|
||||
/// Options that specify behavior for a newly-opened file.
|
||||
@frozen
|
||||
public struct OpenOptions: OptionSet, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct OpenOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -95,9 +98,6 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInt) { self.init(rawValue: raw) }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that opening the file doesn't
|
||||
/// wait for the file or device to become available.
|
||||
@@ -114,7 +114,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_NONBLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nonBlocking: OpenOptions { OpenOptions(_O_NONBLOCK) }
|
||||
public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "nonBlocking")
|
||||
@@ -130,7 +130,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_APPEND`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var append: OpenOptions { OpenOptions(_O_APPEND) }
|
||||
public static var append: OpenOptions { .init(rawValue: _O_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "append")
|
||||
@@ -140,7 +140,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_CREAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var create: OpenOptions { OpenOptions(_O_CREAT) }
|
||||
public static var create: OpenOptions { .init(rawValue: _O_CREAT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "create")
|
||||
@@ -154,7 +154,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_TRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var truncate: OpenOptions { OpenOptions(_O_TRUNC) }
|
||||
public static var truncate: OpenOptions { .init(rawValue: _O_TRUNC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "truncate")
|
||||
@@ -176,13 +176,13 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EXCL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exclusiveCreate: OpenOptions { OpenOptions(_O_EXCL) }
|
||||
public static var exclusiveCreate: OpenOptions { .init(rawValue: _O_EXCL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exclusiveCreate")
|
||||
public static var O_EXCL: OpenOptions { exclusiveCreate }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Indicates that opening the file
|
||||
/// atomically obtains a shared lock on the file.
|
||||
///
|
||||
@@ -194,7 +194,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_SHLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sharedLock: OpenOptions { OpenOptions(_O_SHLOCK) }
|
||||
public static var sharedLock: OpenOptions { .init(rawValue: _O_SHLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "sharedLock")
|
||||
@@ -211,7 +211,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EXLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exclusiveLock: OpenOptions { OpenOptions(_O_EXLOCK) }
|
||||
public static var exclusiveLock: OpenOptions { .init(rawValue: _O_EXLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exclusiveLock")
|
||||
@@ -229,7 +229,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_NOFOLLOW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noFollow: OpenOptions { OpenOptions(_O_NOFOLLOW) }
|
||||
public static var noFollow: OpenOptions { .init(rawValue: _O_NOFOLLOW) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "noFollow")
|
||||
@@ -243,13 +243,29 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_DIRECTORY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: OpenOptions { OpenOptions(_O_DIRECTORY) }
|
||||
public static var directory: OpenOptions { .init(rawValue: _O_DIRECTORY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "directory")
|
||||
public static var O_DIRECTORY: OpenOptions { directory }
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD)
|
||||
/// Indicates that each write operation is synchronous.
|
||||
///
|
||||
/// If this option is specified,
|
||||
/// each time you write to the file,
|
||||
/// the new data is written immediately and synchronously to the disk.
|
||||
///
|
||||
/// The corresponding C constant is `O_SYNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sync: OpenOptions { .init(rawValue: _O_SYNC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "sync")
|
||||
public static var O_SYNC: OpenOptions { sync }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Indicates that opening the file
|
||||
/// opens symbolic links instead of following them.
|
||||
@@ -262,7 +278,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_SYMLINK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlink: OpenOptions { OpenOptions(_O_SYMLINK) }
|
||||
public static var symlink: OpenOptions { .init(rawValue: _O_SYMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "symlink")
|
||||
@@ -278,7 +294,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EVTONLY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var eventOnly: OpenOptions { OpenOptions(_O_EVTONLY) }
|
||||
public static var eventOnly: OpenOptions { .init(rawValue: _O_EVTONLY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "eventOnly")
|
||||
@@ -300,7 +316,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: OpenOptions { OpenOptions(_O_CLOEXEC) }
|
||||
public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
@@ -310,7 +326,8 @@ extension FileDescriptor {
|
||||
|
||||
/// Options for specifying what a file descriptor's offset is relative to.
|
||||
@frozen
|
||||
public struct SeekOrigin: RawRepresentable, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct SeekOrigin: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -353,7 +370,7 @@ extension FileDescriptor {
|
||||
|
||||
// TODO: These are available on some versions of Linux with appropriate
|
||||
// macro defines.
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Indicates that the offset should be set
|
||||
/// to the next hole after the specified number of bytes.
|
||||
///
|
||||
@@ -385,7 +402,7 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor.AccessMode
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -404,7 +421,7 @@ extension FileDescriptor.AccessMode
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor.SeekOrigin
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -427,7 +444,7 @@ extension FileDescriptor.SeekOrigin
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor.OpenOptions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -455,6 +472,19 @@ extension FileDescriptor.OpenOptions
|
||||
(.truncate, ".truncate"),
|
||||
(.exclusiveCreate, ".exclusiveCreate"),
|
||||
]
|
||||
#elseif os(FreeBSD)
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
(.append, ".append"),
|
||||
(.create, ".create"),
|
||||
(.truncate, ".truncate"),
|
||||
(.exclusiveCreate, ".exclusiveCreate"),
|
||||
(.sharedLock, ".sharedLock"),
|
||||
(.exclusiveLock, ".exclusiveLock"),
|
||||
(.sync, ".sync"),
|
||||
(.noFollow, ".noFollow"),
|
||||
(.closeOnExec, ".closeOnExec")
|
||||
]
|
||||
#else
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
@@ -473,3 +503,8 @@ extension FileDescriptor.OpenOptions
|
||||
/// A textual representation of the open options, suitable for debugging.
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// The decision on whether to make FileDescriptor Sendable or not
|
||||
// is currently being discussed in https://github.com/apple/swift-system/pull/112
|
||||
//@available(*, unavailable, message: "File descriptors are not completely thread-safe.")
|
||||
//extension FileDescriptor: Sendable {}
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// Runs a closure and then closes the file descriptor, even if an error occurs.
|
||||
///
|
||||
@@ -62,20 +62,27 @@ extension FileDescriptor {
|
||||
_ sequence: S
|
||||
) -> Result<Int, Errno> where S.Element == UInt8 {
|
||||
sequence._withRawBufferPointer { buffer in
|
||||
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)
|
||||
_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)
|
||||
}
|
||||
}
|
||||
assert(idx == buffer.count)
|
||||
return .success(buffer.count)
|
||||
}
|
||||
|
||||
/// Writes a sequence of bytes to the given offset.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -104,19 +111,150 @@ extension FileDescriptor {
|
||||
toAbsoluteOffset offset: Int64, _ sequence: S
|
||||
) -> Result<Int, Errno> where S.Element == UInt8 {
|
||||
sequence._withRawBufferPointer { buffer in
|
||||
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)
|
||||
_writeAllBuffer(toAbsoluteOffset: offset, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@_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)
|
||||
}
|
||||
}
|
||||
assert(idx == buffer.count)
|
||||
return .success(buffer.count)
|
||||
}
|
||||
|
||||
/// 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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func writeAll(
|
||||
_ data: RawSpan,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Int {
|
||||
try data.withUnsafeBytes { buffer throws(Errno) -> Int in
|
||||
try _writeAllBuffer(buffer).get()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
/*
|
||||
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 - 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
|
||||
*/
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FileDescriptor {
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
@@ -31,12 +31,70 @@ extension FileDescriptor {
|
||||
permissions: FilePermissions? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileDescriptor {
|
||||
try path.withPlatformString {
|
||||
#if !os(Windows)
|
||||
return try path.withCString {
|
||||
try FileDescriptor.open(
|
||||
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
#else
|
||||
return try path.withPlatformString {
|
||||
try FileDescriptor.open(
|
||||
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
// On Darwin, `CInterop.PlatformChar` is less available than
|
||||
// `FileDescriptor.open`, so we need to use `CChar` instead.
|
||||
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The location of the file to open.
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: A file descriptor for the open file
|
||||
///
|
||||
/// The corresponding C function is `open`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileDescriptor {
|
||||
try FileDescriptor._open(
|
||||
path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
let oFlag = mode.rawValue | options.rawValue
|
||||
let descOrError: Result<CInt, Errno> = valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
if let permissions = permissions {
|
||||
return system_open(path, oFlag, permissions.rawValue)
|
||||
}
|
||||
precondition(!options.contains(.create),
|
||||
"Create must be given permissions")
|
||||
return system_open(path, oFlag)
|
||||
}
|
||||
return descOrError.map { FileDescriptor(rawValue: $0) }
|
||||
}
|
||||
#else
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -77,12 +135,11 @@ extension FileDescriptor {
|
||||
if let permissions = permissions {
|
||||
return system_open(path, oFlag, permissions.rawValue)
|
||||
}
|
||||
precondition(!options.contains(.create),
|
||||
"Create must be given permissions")
|
||||
return system_open(path, oFlag)
|
||||
}
|
||||
return descOrError.map { FileDescriptor(rawValue: $0) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Deletes a file descriptor.
|
||||
///
|
||||
@@ -99,7 +156,7 @@ extension FileDescriptor {
|
||||
nothingOrErrno(retryOnInterrupt: false) { system_close(self.rawValue) }
|
||||
}
|
||||
|
||||
/// Reposition the offset for the given file descriptor.
|
||||
/// Repositions the offset for the given file descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The new offset for the file descriptor.
|
||||
@@ -144,7 +201,7 @@ extension FileDescriptor {
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/3019191-count> property of `buffer`
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/count-95usp> property of `buffer`
|
||||
/// determines the maximum number of bytes that are read into that buffer.
|
||||
///
|
||||
/// After reading,
|
||||
@@ -182,7 +239,7 @@ extension FileDescriptor {
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/3019191-count> property of `buffer`
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/count-95usp> property of `buffer`
|
||||
/// determines the maximum number of bytes that are read into that buffer.
|
||||
///
|
||||
/// Unlike <doc:FileDescriptor/read(into:retryOnInterrupt:)>,
|
||||
@@ -309,7 +366,155 @@ extension FileDescriptor {
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
/// Duplicate this file descriptor and return the newly created copy.
|
||||
/// 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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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(macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2, *)
|
||||
@_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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@available(System 0.0.2, *)
|
||||
extension FileDescriptor {
|
||||
/// Duplicates this file descriptor and return the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
@@ -337,7 +542,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C functions are `dup` and `dup2`.
|
||||
@_alwaysEmitIntoClient
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
public func duplicate(
|
||||
as target: FileDescriptor? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
@@ -345,7 +550,7 @@ extension FileDescriptor {
|
||||
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor?,
|
||||
@@ -371,22 +576,23 @@ extension FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
#if !os(WASI)
|
||||
@available(System 1.1.0, *)
|
||||
extension FileDescriptor {
|
||||
/// Create a pipe, 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
|
||||
/*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@available(System 1.1.0, *)
|
||||
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
try _pipe().get()
|
||||
}
|
||||
|
||||
/*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
|
||||
@available(System 1.1.0, *)
|
||||
@usableFromInline
|
||||
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
|
||||
var fds: (Int32, Int32) = (-1, -1)
|
||||
@@ -401,10 +607,9 @@ extension FileDescriptor {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/*System 1.2.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@available(System 1.2.0, *)
|
||||
extension FileDescriptor {
|
||||
/// Truncate or extend the file referenced by this file descriptor.
|
||||
/// Truncates or extends the file referenced by this file descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newSize: The length in bytes to resize the file to.
|
||||
@@ -424,7 +629,7 @@ extension FileDescriptor {
|
||||
/// associated with the file.
|
||||
///
|
||||
/// The corresponding C function is `ftruncate`.
|
||||
/*System 1.2.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@available(System 1.2.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func resize(
|
||||
to newSize: Int64,
|
||||
@@ -436,7 +641,7 @@ extension FileDescriptor {
|
||||
).get()
|
||||
}
|
||||
|
||||
/*System 1.2.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@available(System 1.2.0, *)
|
||||
@usableFromInline
|
||||
internal func _resize(
|
||||
to newSize: Int64,
|
||||
@@ -447,4 +652,46 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(WASI) // WASI has no umask
|
||||
extension FilePermissions {
|
||||
/// The file creation permission mask (aka "umask").
|
||||
///
|
||||
/// Permissions set in this mask will be cleared by functions that create
|
||||
/// files or directories. Note that this mask is process-wide, and that
|
||||
/// *getting* it is not thread safe.
|
||||
internal static var creationMask: FilePermissions {
|
||||
get {
|
||||
let oldMask = _umask(0o22)
|
||||
_ = _umask(oldMask)
|
||||
return FilePermissions(rawValue: oldMask)
|
||||
}
|
||||
set {
|
||||
_ = _umask(newValue.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Change the file creation permission mask, run some code, then
|
||||
/// restore it to its original value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - permissions: The new permission mask.
|
||||
///
|
||||
/// This is more efficient than reading `creationMask` and restoring it
|
||||
/// afterwards, because of the way reading the creation mask works.
|
||||
internal static func withCreationMask<R>(
|
||||
_ permissions: FilePermissions,
|
||||
body: () throws -> R
|
||||
) rethrows -> R {
|
||||
let oldMask = _umask(permissions.rawValue)
|
||||
defer {
|
||||
_ = _umask(oldMask)
|
||||
}
|
||||
return try body()
|
||||
}
|
||||
|
||||
internal static func _umask(_ mode: CModeT) -> CModeT {
|
||||
return system_umask(mode)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -37,11 +37,10 @@
|
||||
/// However, the rules for path equivalence
|
||||
/// are file-system–specific and have additional considerations
|
||||
/// like case insensitivity, Unicode normalization, and symbolic links.
|
||||
///
|
||||
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
|
||||
// components, etc.
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
public struct FilePath {
|
||||
@available(System 0.0.1, *)
|
||||
public struct FilePath: Sendable {
|
||||
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
|
||||
// components, etc.
|
||||
internal var _storage: SystemString
|
||||
|
||||
/// Creates an empty, null-terminated path.
|
||||
@@ -60,17 +59,20 @@ public struct FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
/// The length of the file path, excluding the null terminator.
|
||||
public var length: Int { _storage.length }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePath: Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: Hashable {}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: Codable {
|
||||
// Encoder is synthesized; it probably should have been explicit and used
|
||||
// a single-value container, but making that change now is somewhat risky.
|
||||
|
||||
|
||||
// Decoder is written explicitly to ensure that we validate invariants on
|
||||
// untrusted input.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - API
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// A bidirectional, range replaceable collection of the non-root components
|
||||
/// that make up a file path.
|
||||
@@ -28,8 +28,8 @@ extension FilePath {
|
||||
///
|
||||
/// path.components.removeAll { $0.kind == .currentDirectory }
|
||||
/// // path is "/home/username/bin/scripts/tree"
|
||||
///
|
||||
public struct ComponentView {
|
||||
@available(System 0.0.2, *)
|
||||
public struct ComponentView: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _start: SystemString.Index
|
||||
|
||||
@@ -40,30 +40,6 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
/// View the non-root components that make up this path.
|
||||
public var components: ComponentView {
|
||||
get { ComponentView(self) }
|
||||
_modify {
|
||||
// RRC's empty init means that we can't guarantee that the yielded
|
||||
// view will restore our root. So copy it out first.
|
||||
//
|
||||
// TODO(perf): Small-form root (especially on Unix). Have Root
|
||||
// always copy out (not worth ref counting). Make sure that we're
|
||||
// not needlessly sliding values around or triggering a COW
|
||||
let rootStr = self.root?._systemString ?? SystemString()
|
||||
var comp = ComponentView(self)
|
||||
self = FilePath()
|
||||
defer {
|
||||
self = comp._path
|
||||
if root?._slice.elementsEqual(rootStr) != true {
|
||||
self.root = Root(rootStr)
|
||||
}
|
||||
}
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#else
|
||||
/// View the non-root components that make up this path.
|
||||
public var components: ComponentView {
|
||||
__consuming get { ComponentView(self) }
|
||||
@@ -86,13 +62,14 @@ extension FilePath {
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView: BidirectionalCollection {
|
||||
public typealias Element = FilePath.Component
|
||||
public struct Index: Comparable, Hashable {
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
public struct Index: Sendable, Comparable, Hashable {
|
||||
internal typealias Storage = SystemString.Index
|
||||
|
||||
internal var _storage: Storage
|
||||
@@ -123,7 +100,7 @@ extension FilePath.ComponentView: BidirectionalCollection {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView: RangeReplaceableCollection {
|
||||
public init() {
|
||||
self.init(FilePath())
|
||||
@@ -173,7 +150,7 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Create a file path from a root and a collection of components.
|
||||
public init<C: Collection>(
|
||||
@@ -202,6 +179,7 @@ extension FilePath {
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
_start ..< _path._storage.endIndex
|
||||
@@ -214,6 +192,7 @@ extension FilePath.ComponentView: _PathSlice {
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - API
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Represents a root of a file path.
|
||||
///
|
||||
@@ -28,7 +28,8 @@ extension FilePath {
|
||||
/// * `\\server\share\`
|
||||
/// * `\\?\UNC\server\share\`
|
||||
/// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\`
|
||||
public struct Root {
|
||||
@available(System 0.0.2, *)
|
||||
public struct Root: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _rootEnd: SystemString.Index
|
||||
|
||||
@@ -54,8 +55,8 @@ extension FilePath {
|
||||
/// file.kind == .regular // true
|
||||
/// file.extension // "txt"
|
||||
/// path.append(file) // path is "/tmp/foo.txt"
|
||||
///
|
||||
public struct Component {
|
||||
@available(System 0.0.2, *)
|
||||
public struct Component: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _range: Range<SystemString.Index>
|
||||
|
||||
@@ -73,13 +74,14 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
|
||||
/// Whether a component is a regular file or directory name, or a special
|
||||
/// directory `.` or `..`
|
||||
@frozen
|
||||
public enum Kind {
|
||||
@available(System 0.0.2, *)
|
||||
public enum Kind: Sendable {
|
||||
/// The special directory `.`, representing the current directory.
|
||||
case currentDirectory
|
||||
|
||||
@@ -98,6 +100,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
// TODO: Windows analysis APIs
|
||||
}
|
||||
@@ -143,7 +146,7 @@ extension _StrSlice {
|
||||
internal func _withSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try _storage.withSystemChars {
|
||||
try _storage.withNullTerminatedSystemChars {
|
||||
try f(UnsafeBufferPointer(rebasing: $0[_range]))
|
||||
}
|
||||
}
|
||||
@@ -183,15 +186,18 @@ extension _PathSlice {
|
||||
internal var _storage: SystemString { _path._storage }
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component: _PathSlice {
|
||||
}
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
(..<_rootEnd).relative(to: _path._storage)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: _PlatformStringable {
|
||||
@usableFromInline
|
||||
func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
|
||||
try _storage.withPlatformString(body)
|
||||
}
|
||||
@@ -202,6 +208,7 @@ extension FilePath: _PlatformStringable {
|
||||
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
// The index of the `.` denoting an extension
|
||||
internal func _extensionIndex() -> SystemString.Index? {
|
||||
@@ -230,6 +237,7 @@ internal func _makeExtension(_ ext: String) -> SystemString {
|
||||
return result
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
internal init?(_ str: SystemString) {
|
||||
// FIXME: explicit null root? Or something else?
|
||||
@@ -242,6 +250,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
internal init?(_ str: SystemString) {
|
||||
// FIXME: explicit null root? Or something else?
|
||||
@@ -256,6 +265,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
// TODO: ensure this all gets easily optimized away in release...
|
||||
internal func _invariantCheck() {
|
||||
@@ -267,6 +277,8 @@ extension FilePath.Component {
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
|
||||
@@ -89,6 +89,11 @@ extension SystemString {
|
||||
// `_prenormalizeWindowsRoots` and resume.
|
||||
readIdx = _prenormalizeWindowsRoots()
|
||||
writeIdx = readIdx
|
||||
|
||||
// Skip redundant separators
|
||||
while readIdx < endIndex && isSeparator(self[readIdx]) {
|
||||
self.formIndex(after: &readIdx)
|
||||
}
|
||||
} else {
|
||||
assert(genericSeparator == platformSeparator)
|
||||
}
|
||||
@@ -111,6 +116,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal mutating func _removeTrailingSeparator() {
|
||||
_storage._removeTrailingSeparator()
|
||||
@@ -191,6 +197,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal var _relativeStart: SystemString.Index {
|
||||
_storage._relativePathStart
|
||||
@@ -202,6 +209,7 @@ extension FilePath {
|
||||
|
||||
// Parse separators
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal typealias _Index = SystemString.Index
|
||||
|
||||
@@ -265,6 +273,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.ComponentView {
|
||||
// TODO: Store this...
|
||||
internal var _relativeStart: SystemString.Index {
|
||||
@@ -289,6 +298,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
// Asserting self is a root, returns whether this is an
|
||||
// absolute root.
|
||||
@@ -313,6 +323,7 @@ extension FilePath.Root {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal var _portableDescription: String {
|
||||
guard _windowsPaths else { return description }
|
||||
@@ -324,13 +335,17 @@ extension FilePath {
|
||||
// Whether we are providing Windows paths
|
||||
@inline(__always)
|
||||
internal var _windowsPaths: Bool {
|
||||
if let forceWindowsPaths = forceWindowsPaths {
|
||||
return forceWindowsPaths
|
||||
}
|
||||
#if os(Windows)
|
||||
return true
|
||||
#else
|
||||
return forceWindowsPaths
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
// Whether we should add a separator when doing an append
|
||||
internal var _needsSeparatorForAppend: Bool {
|
||||
@@ -358,6 +373,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK: - Invariants
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
internal func _invariantsSatisfied() -> Bool {
|
||||
var normal = self
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - Platform string
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Creates a file path by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
@@ -63,6 +63,13 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
// Note: This function should have been opaque, but it shipped as
|
||||
// `@_alwaysEmitIntoClient` in macOS 12/iOS 15, and now it is stuck
|
||||
// this way forever. (Or until the language provides a way for us
|
||||
// to declare separate availability for a function's exported symbol
|
||||
// and its inlinable body.)
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
@@ -79,16 +86,30 @@ extension FilePath {
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
// For backwards deployment, call withCString if available.
|
||||
#if !os(Windows)
|
||||
return try withCString(body)
|
||||
#else
|
||||
return try _withPlatformString(body)
|
||||
#endif
|
||||
}
|
||||
#else
|
||||
/// Calls the given closure with a pointer to the contents of the file path,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
return try _withPlatformString(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
/// Creates a file path component by copying bytes from a null-terminated
|
||||
/// platform string.
|
||||
@@ -98,7 +119,6 @@ extension FilePath.Component {
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
public init?(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
@@ -178,7 +198,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
/// Creates a file path root by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
@@ -187,7 +207,6 @@ extension FilePath.Root {
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
public init?(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
@@ -268,7 +287,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - String literals
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: ExpressibleByStringLiteral {
|
||||
/// Creates a file path from a string literal.
|
||||
///
|
||||
@@ -287,7 +306,7 @@ extension FilePath: ExpressibleByStringLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
/// Create a file path component from a string literal.
|
||||
///
|
||||
@@ -312,7 +331,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
/// Create a file path root from a string literal.
|
||||
///
|
||||
@@ -337,7 +356,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
|
||||
// MARK: - Printing and dumping
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the file path.
|
||||
///
|
||||
@@ -353,7 +372,7 @@ extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
|
||||
/// A textual representation of the path component.
|
||||
@@ -370,7 +389,7 @@ extension FilePath.Component: CustomStringConvertible, CustomDebugStringConverti
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
|
||||
/// A textual representation of the path root.
|
||||
@@ -390,7 +409,7 @@ extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
// MARK: - Convenience helpers
|
||||
|
||||
// Convenience helpers
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Creates a string by interpreting the path’s content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
@@ -401,7 +420,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
/// Creates a string by interpreting the component’s content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
@@ -412,7 +431,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Root {
|
||||
/// On Unix, this returns `"/"`.
|
||||
///
|
||||
@@ -426,7 +445,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - Decoding and validating
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the file path's content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
@@ -456,7 +475,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the path component's content as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
@@ -486,7 +505,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// On Unix, creates the string `"/"`
|
||||
///
|
||||
@@ -539,7 +558,7 @@ extension String {
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension String {
|
||||
@available(*, deprecated, renamed: "init(decoding:)")
|
||||
public init(_ path: FilePath) { self.init(decoding: path) }
|
||||
@@ -549,7 +568,7 @@ extension String {
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePath {
|
||||
/// For backwards compatibility only. This initializer is equivalent to
|
||||
/// the preferred `FilePath(platformString:)`.
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - Query API
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns true if this path uniquely identifies the location of
|
||||
/// a file without reference to an additional starting location.
|
||||
@@ -52,6 +52,8 @@ extension FilePath {
|
||||
/// * `\Users`
|
||||
public var isRelative: Bool { !isAbsolute }
|
||||
|
||||
// TODO(Windows docs): examples with roots, such as whether `\foo\bar`
|
||||
// starts with `C:\foo`
|
||||
/// Returns whether `other` is a prefix of `self`, only considering
|
||||
/// whole path components.
|
||||
///
|
||||
@@ -63,15 +65,14 @@ extension FilePath {
|
||||
/// path.starts(with: "/usr/bin/ls") // true
|
||||
/// path.starts(with: "/usr/bin/ls///") // true
|
||||
/// path.starts(with: "/us") // false
|
||||
///
|
||||
// TODO(Windows docs): examples with roots, such as whether `\foo\bar`
|
||||
// starts with `C:\foo`
|
||||
public func starts(with other: FilePath) -> Bool {
|
||||
guard !other.isEmpty else { return true }
|
||||
return self.root == other.root && components.starts(
|
||||
with: other.components)
|
||||
}
|
||||
|
||||
// TODO(Windows docs): examples with roots, such as whether `C:\foo\bar`
|
||||
// ends with `C:bar`
|
||||
/// Returns whether `other` is a suffix of `self`, only considering
|
||||
/// whole path components.
|
||||
///
|
||||
@@ -83,9 +84,6 @@ extension FilePath {
|
||||
/// path.ends(with: "usr/bin/ls") // true
|
||||
/// path.ends(with: "/usr/bin/ls///") // true
|
||||
/// path.ends(with: "/ls") // false
|
||||
///
|
||||
// TODO(Windows docs): examples with roots, such as whether `C:\foo\bar`
|
||||
// ends with `C:bar`
|
||||
public func ends(with other: FilePath) -> Bool {
|
||||
if other.root != nil {
|
||||
// TODO: anything tricky here for Windows?
|
||||
@@ -101,7 +99,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK: - Decompose a path
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns the root of a path if there is one, otherwise `nil`.
|
||||
///
|
||||
@@ -145,7 +143,6 @@ extension FilePath {
|
||||
/// path.root = nil // path is #"foo\bar"#
|
||||
/// path.root = "C:" // path is #"C:foo\bar"#
|
||||
/// path.root = #"C:\"# // path is #"C:\foo\bar"#
|
||||
///
|
||||
public var root: FilePath.Root? {
|
||||
get {
|
||||
guard _hasRoot else { return nil }
|
||||
@@ -178,7 +175,6 @@ extension FilePath {
|
||||
/// * `\\?\device\folder\file.exe => folder\file.exe`
|
||||
/// * `\\server\share\file => file`
|
||||
/// * `\ => ""`
|
||||
///
|
||||
public __consuming func removingRoot() -> FilePath {
|
||||
var copy = self
|
||||
copy.root = nil
|
||||
@@ -186,7 +182,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns the final component of the path.
|
||||
/// Returns `nil` if the path is empty or only contains a root.
|
||||
@@ -209,7 +205,6 @@ extension FilePath {
|
||||
/// * `\\?\UNC\server\share\bar.exe => bar.exe`
|
||||
/// * `\\server\share => nil`
|
||||
/// * `\\?\UNC\server\share\ => nil`
|
||||
///
|
||||
public var lastComponent: Component? { components.last }
|
||||
|
||||
/// Creates a new path with everything up to but not including
|
||||
@@ -247,7 +242,6 @@ extension FilePath {
|
||||
/// path.removeLastComponent() == true // path is "/usr"
|
||||
/// path.removeLastComponent() == true // path is "/"
|
||||
/// path.removeLastComponent() == false // path is "/"
|
||||
///
|
||||
@discardableResult
|
||||
public mutating func removeLastComponent() -> Bool {
|
||||
defer { _invariantCheck() }
|
||||
@@ -258,7 +252,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath.Component {
|
||||
/// The extension of this file or directory component.
|
||||
///
|
||||
@@ -271,7 +265,6 @@ extension FilePath.Component {
|
||||
/// * `Foo.app => app`
|
||||
/// * `.hidden => nil`
|
||||
/// * `.. => nil`
|
||||
///
|
||||
public var `extension`: String? {
|
||||
guard let range = _extensionRange() else { return nil }
|
||||
return _slice[range].string
|
||||
@@ -285,13 +278,12 @@ extension FilePath.Component {
|
||||
/// * `Foo.app => Foo`
|
||||
/// * `.hidden => .hidden`
|
||||
/// * `.. => ..`
|
||||
///
|
||||
public var stem: String {
|
||||
_slice[_stemRange()].string
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
|
||||
/// The extension of the file or directory last component.
|
||||
@@ -322,7 +314,6 @@ extension FilePath {
|
||||
/// path.extension = "o" // path is "/tmp/file.o"
|
||||
/// path.extension = nil // path is "/tmp/file"
|
||||
/// path.extension = "" // path is "/tmp/file."
|
||||
///
|
||||
public var `extension`: String? {
|
||||
get { lastComponent?.extension }
|
||||
set {
|
||||
@@ -349,8 +340,8 @@ extension FilePath {
|
||||
/// Returns `nil` if `lastComponent` is `nil`
|
||||
///
|
||||
/// * `/tmp/foo.txt => foo`
|
||||
/// * `/Appliations/Foo.app/ => Foo`
|
||||
/// * `/Appliations/Foo.app/bar.txt => bar`
|
||||
/// * `/Applications/Foo.app/ => Foo`
|
||||
/// * `/Applications/Foo.app/bar.txt => bar`
|
||||
/// * `/tmp/.hidden => .hidden`
|
||||
/// * `/tmp/.. => ..`
|
||||
/// * `/ => nil`
|
||||
@@ -358,7 +349,7 @@ extension FilePath {
|
||||
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Whether the path is in lexical-normal form, that is `.` and `..`
|
||||
/// components have been collapsed lexically (i.e. without following
|
||||
@@ -439,8 +430,9 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// Modification and concatenation API
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
// TODO(Windows docs): example with roots
|
||||
/// If `prefix` is a prefix of `self`, removes it and returns `true`.
|
||||
/// Otherwise returns `false`.
|
||||
///
|
||||
@@ -450,8 +442,6 @@ extension FilePath {
|
||||
/// path.removePrefix("/usr/bin") // false
|
||||
/// path.removePrefix("/us") // false
|
||||
/// path.removePrefix("/usr/local") // true, path is "bin"
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public mutating func removePrefix(_ prefix: FilePath) -> Bool {
|
||||
defer { _invariantCheck() }
|
||||
// FIXME: Should Windows have more nuanced semantics?
|
||||
@@ -462,6 +452,7 @@ extension FilePath {
|
||||
return true
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Append a `component` on to the end of this path.
|
||||
///
|
||||
/// Example:
|
||||
@@ -472,13 +463,12 @@ extension FilePath {
|
||||
/// path.append(comp)
|
||||
/// }
|
||||
/// // path is "/tmp/foo/bar/../baz"
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public mutating func append(_ component: __owned FilePath.Component) {
|
||||
defer { _invariantCheck() }
|
||||
_append(unchecked: component._slice)
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Append `components` on to the end of this path.
|
||||
///
|
||||
/// Example:
|
||||
@@ -487,8 +477,6 @@ extension FilePath {
|
||||
/// path.append(["usr", "local"]) // path is "/usr/local"
|
||||
/// let otherPath: FilePath = "/bin/ls"
|
||||
/// path.append(otherPath.components) // path is "/usr/local/bin/ls"
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public mutating func append<C: Collection>(
|
||||
_ components: __owned C
|
||||
) where C.Element == FilePath.Component {
|
||||
@@ -498,6 +486,8 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots, should we rephrase this "spurious
|
||||
// roots"?
|
||||
/// Append the contents of `other`, ignoring any spurious leading separators.
|
||||
///
|
||||
/// A leading separator is spurious if `self` is non-empty.
|
||||
@@ -508,9 +498,6 @@ extension FilePath {
|
||||
/// path.append("/var/www/website") // "/var/www/website"
|
||||
/// path.append("static/assets") // "/var/www/website/static/assets"
|
||||
/// path.append("/main.css") // "/var/www/website/static/assets/main.css"
|
||||
///
|
||||
// TODO(Windows docs): example with roots, should we rephrase this "spurious
|
||||
// roots"?
|
||||
public mutating func append(_ other: __owned String) {
|
||||
defer { _invariantCheck() }
|
||||
guard !other.utf8.isEmpty else { return }
|
||||
@@ -522,18 +509,16 @@ extension FilePath {
|
||||
_append(unchecked: otherPath._storage[otherPath._relativeStart...])
|
||||
}
|
||||
|
||||
/// Non-mutating version of `append(_:Component)`.
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Non-mutating version of `append(_:Component)`.
|
||||
public __consuming func appending(_ other: __owned Component) -> FilePath {
|
||||
var copy = self
|
||||
copy.append(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Non-mutating version of `append(_:C)`.
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Non-mutating version of `append(_:C)`.
|
||||
public __consuming func appending<C: Collection>(
|
||||
_ components: __owned C
|
||||
) -> FilePath where C.Element == FilePath.Component {
|
||||
@@ -542,15 +527,16 @@ extension FilePath {
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Non-mutating version of `append(_:String)`.
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Non-mutating version of `append(_:String)`.
|
||||
public __consuming func appending(_ other: __owned String) -> FilePath {
|
||||
var copy = self
|
||||
copy.append(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
// TODO(Windows docs): examples and docs with roots, update/generalize doc
|
||||
// comment
|
||||
/// If `other` does not have a root, append each component of `other`. If
|
||||
/// `other` has a root, replaces `self` with other.
|
||||
///
|
||||
@@ -564,9 +550,6 @@ extension FilePath {
|
||||
/// var path: FilePath = "/tmp"
|
||||
/// path.push("dir/file.txt") // path is "/tmp/dir/file.txt"
|
||||
/// path.push("/bin") // path is "/bin"
|
||||
///
|
||||
// TODO(Windows docs): examples and docs with roots, update/generalize doc
|
||||
// comment
|
||||
public mutating func push(_ other: __owned FilePath) {
|
||||
defer { _invariantCheck() }
|
||||
guard other.root == nil else {
|
||||
@@ -577,9 +560,8 @@ extension FilePath {
|
||||
_append(unchecked: other._storage[...])
|
||||
}
|
||||
|
||||
/// Non-mutating version of `push()`.
|
||||
///
|
||||
// TODO(Windows docs): examples and docs with roots
|
||||
/// Non-mutating version of `push()`.
|
||||
public __consuming func pushing(_ other: __owned FilePath) -> FilePath {
|
||||
var copy = self
|
||||
copy.push(other)
|
||||
@@ -601,7 +583,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK - Renamed
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
@available(*, unavailable, renamed: "removingLastComponent()")
|
||||
public var dirname: FilePath { removingLastComponent() }
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// MARK: - API
|
||||
|
||||
/// Create a temporary path for the duration of the closure.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - basename: The base name for the temporary path.
|
||||
/// - body: The closure to execute.
|
||||
///
|
||||
/// Creates a temporary directory with a name based on the given `basename`,
|
||||
/// executes `body`, passing in the path of the created directory, then
|
||||
/// deletes the directory and all of its contents before returning.
|
||||
internal func withTemporaryFilePath<R>(
|
||||
basename: FilePath.Component,
|
||||
_ body: (FilePath) throws -> R
|
||||
) throws -> R {
|
||||
let temporaryDir = try createUniqueTemporaryDirectory(basename: basename)
|
||||
defer {
|
||||
try? _recursiveRemove(at: temporaryDir)
|
||||
}
|
||||
|
||||
return try body(temporaryDir)
|
||||
}
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
fileprivate let base64 = Array<UInt8>(
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8
|
||||
)
|
||||
|
||||
/// Create a directory that is only accessible to the current user.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the directory to create.
|
||||
/// - Returns: `true` if a new directory was created.
|
||||
///
|
||||
/// This function will throw if there is an error, except if the error
|
||||
/// is that the directory exists, in which case it returns `false`.
|
||||
fileprivate func makeLockedDownDirectory(at path: FilePath) throws -> Bool {
|
||||
return try path.withPlatformString {
|
||||
if system_mkdir($0, 0o700) == 0 {
|
||||
return true
|
||||
}
|
||||
let err = system_errno
|
||||
if err == Errno.fileExists.rawValue {
|
||||
return false
|
||||
} else {
|
||||
throw Errno(rawValue: err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a random string of base64 filename safe characters.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - length: The number of characters in the returned string.
|
||||
/// - Returns: A random string of length `length`.
|
||||
fileprivate func createRandomString(length: Int) -> String {
|
||||
return String(
|
||||
decoding: (0..<length).map{
|
||||
_ in base64[Int.random(in: 0..<64)]
|
||||
},
|
||||
as: UTF8.self
|
||||
)
|
||||
}
|
||||
|
||||
/// Given a base name, create a uniquely named temporary directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - basename: The base name for the new directory.
|
||||
/// - Returns: The path to the new directory.
|
||||
///
|
||||
/// Creates a directory in the system temporary directory whose name
|
||||
/// starts with `basename`, followed by a `.` and then a random
|
||||
/// string of characters.
|
||||
fileprivate func createUniqueTemporaryDirectory(
|
||||
basename: FilePath.Component
|
||||
) throws -> FilePath {
|
||||
var tempDir = try _getTemporaryDirectory()
|
||||
tempDir.append(basename)
|
||||
|
||||
while true {
|
||||
tempDir.extension = createRandomString(length: 16)
|
||||
|
||||
if try makeLockedDownDirectory(at: tempDir) {
|
||||
return tempDir
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
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)
|
||||
|
||||
/// Get the path to the system temporary directory.
|
||||
internal func _getTemporaryDirectory() throws -> FilePath {
|
||||
guard let tmp = system_getenv("TMPDIR") else {
|
||||
return "/tmp"
|
||||
}
|
||||
|
||||
return FilePath(SystemString(platformString: tmp))
|
||||
}
|
||||
|
||||
/// Delete the entire contents of a directory, including its subdirectories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The directory to be deleted.
|
||||
///
|
||||
/// Removes a directory completely, including all of its contents.
|
||||
internal func _recursiveRemove(
|
||||
at path: FilePath
|
||||
) throws {
|
||||
let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory)
|
||||
defer {
|
||||
try? dirfd.close()
|
||||
}
|
||||
|
||||
let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0)
|
||||
try withUnsafeBytes(of: dot) {
|
||||
try recursiveRemove(
|
||||
in: dirfd.rawValue,
|
||||
name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress!
|
||||
)
|
||||
}
|
||||
|
||||
try path.withPlatformString {
|
||||
if system_rmdir($0) != 0 {
|
||||
throw Errno.current
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a directory by reference to its parent and name.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dirfd: An open file descriptor for the parent directory.
|
||||
/// - name: The name of the directory to open.
|
||||
/// - Returns: A pointer to a `DIR` structure.
|
||||
///
|
||||
/// This is like `opendir()`, but instead of taking a path, it uses a
|
||||
/// file descriptor pointing at the parent, thus avoiding path length
|
||||
/// limits.
|
||||
fileprivate func impl_opendirat(
|
||||
_ dirfd: CInt,
|
||||
_ name: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> system_DIRPtr? {
|
||||
let fd = system_openat(dirfd, name,
|
||||
FileDescriptor.AccessMode.readOnly.rawValue
|
||||
| FileDescriptor.OpenOptions.directory.rawValue)
|
||||
if fd < 0 {
|
||||
return nil
|
||||
}
|
||||
return system_fdopendir(fd)
|
||||
}
|
||||
|
||||
/// Invoke a closure for each file within a particular directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dirfd: The parent of the directory to be enumerated.
|
||||
/// - subdir: The subdirectory to be enumerated.
|
||||
/// - body: The closure that will be invoked.
|
||||
///
|
||||
/// We skip the `.` and `..` pseudo-entries.
|
||||
fileprivate func forEachFile(
|
||||
in dirfd: CInt,
|
||||
subdir: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ body: (system_dirent) throws -> ()
|
||||
) throws {
|
||||
guard let dir = impl_opendirat(dirfd, subdir) else {
|
||||
throw Errno.current
|
||||
}
|
||||
defer {
|
||||
_ = system_closedir(dir)
|
||||
}
|
||||
|
||||
while let dirent = system_readdir(dir) {
|
||||
// Skip . and ..
|
||||
if dirent.pointee.d_name.0 == 46
|
||||
&& (dirent.pointee.d_name.1 == 0
|
||||
|| (dirent.pointee.d_name.1 == 46
|
||||
&& dirent.pointee.d_name.2 == 0)) {
|
||||
continue
|
||||
}
|
||||
|
||||
try body(dirent.pointee)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the entire contents of a directory, including its subdirectories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dirfd: The parent of the directory to be removed.
|
||||
/// - name: The name of the directory to be removed.
|
||||
///
|
||||
/// Removes a directory completely, including all of its contents.
|
||||
fileprivate func recursiveRemove(
|
||||
in dirfd: CInt,
|
||||
name: UnsafePointer<CInterop.PlatformChar>
|
||||
) throws {
|
||||
// First, deal with subdirectories
|
||||
try forEachFile(in: dirfd, subdir: name) { dirent in
|
||||
if dirent.d_type == SYSTEM_DT_DIR {
|
||||
try withUnsafeBytes(of: dirent.d_name) {
|
||||
try recursiveRemove(
|
||||
in: dirfd,
|
||||
name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
.baseAddress!
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now delete the contents of this directory
|
||||
try forEachFile(in: dirfd, subdir: name) { dirent in
|
||||
let flag: CInt
|
||||
|
||||
if dirent.d_type == SYSTEM_DT_DIR {
|
||||
flag = SYSTEM_AT_REMOVE_DIR
|
||||
} else {
|
||||
flag = 0
|
||||
}
|
||||
|
||||
let result = withUnsafeBytes(of: dirent.d_name) {
|
||||
system_unlinkat(dirfd,
|
||||
$0.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
.baseAddress!,
|
||||
flag)
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
throw Errno.current
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !os(Windows)
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
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
|
||||
|
||||
/// Get the path to the system temporary directory.
|
||||
internal func _getTemporaryDirectory() throws -> FilePath {
|
||||
return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self,
|
||||
capacity: Int(MAX_PATH) + 1) {
|
||||
buffer in
|
||||
|
||||
guard GetTempPathW(DWORD(buffer.count), buffer.baseAddress) != 0 else {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
|
||||
return FilePath(SystemString(platformString: buffer.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
/// Invoke a closure for each file within a particular directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path at which we should enumerate items.
|
||||
/// - body: The closure that will be invoked.
|
||||
///
|
||||
/// We skip the `.` and `..` pseudo-entries.
|
||||
fileprivate func forEachFile(
|
||||
at path: FilePath,
|
||||
_ body: (WIN32_FIND_DATAW) throws -> ()
|
||||
) rethrows {
|
||||
let searchPath = path.appending("\\*")
|
||||
|
||||
try searchPath.withPlatformString { szPath in
|
||||
var findData = WIN32_FIND_DATAW()
|
||||
let hFind = try szPath.withCanonicalPathRepresentation({ szPath in FindFirstFileW(szPath, &findData) })
|
||||
if hFind == INVALID_HANDLE_VALUE {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
defer {
|
||||
FindClose(hFind)
|
||||
}
|
||||
|
||||
repeat {
|
||||
// Skip . and ..
|
||||
if findData.cFileName.0 == 46
|
||||
&& (findData.cFileName.1 == 0
|
||||
|| (findData.cFileName.1 == 46
|
||||
&& findData.cFileName.2 == 0)) {
|
||||
continue
|
||||
}
|
||||
|
||||
try body(findData)
|
||||
} while FindNextFileW(hFind, &findData)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the entire contents of a directory, including its subdirectories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The directory to be deleted.
|
||||
///
|
||||
/// Removes a directory completely, including all of its contents.
|
||||
internal func _recursiveRemove(
|
||||
at path: FilePath
|
||||
) throws {
|
||||
// First, deal with subdirectories
|
||||
try forEachFile(at: path) { findData in
|
||||
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 {
|
||||
let name = withUnsafeBytes(of: findData.cFileName) {
|
||||
return SystemString(platformString: $0.assumingMemoryBound(
|
||||
to: CInterop.PlatformChar.self).baseAddress!)
|
||||
}
|
||||
let component = FilePath.Component(name)!
|
||||
let subpath = path.appending(component)
|
||||
|
||||
try _recursiveRemove(at: subpath)
|
||||
}
|
||||
}
|
||||
|
||||
// Now delete everything else
|
||||
try forEachFile(at: path) { findData in
|
||||
let name = withUnsafeBytes(of: findData.cFileName) {
|
||||
return SystemString(platformString: $0.assumingMemoryBound(
|
||||
to: CInterop.PlatformChar.self).baseAddress!)
|
||||
}
|
||||
let component = FilePath.Component(name)!
|
||||
let subpath = path.appending(component)
|
||||
|
||||
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 {
|
||||
try subpath.withPlatformString { subpath in
|
||||
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, delete the parent
|
||||
try path.withPlatformString {
|
||||
if try !$0.withCanonicalPathRepresentation({ RemoveDirectoryW($0) }) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // os(Windows)
|
||||
@@ -150,21 +150,19 @@ internal struct WindowsRootInfo {
|
||||
/// * Omitted volume from other forms: `\\.\`, `\\.\UNC\server\\`, `\\server\\`
|
||||
case empty
|
||||
|
||||
// TODO: NT paths? Admin paths using `$`?
|
||||
/// A specified drive.
|
||||
///
|
||||
/// * Traditional disk: `C:\`, `C:`
|
||||
/// * Device disk: `\\.\C:\`, `\\?\C:\`
|
||||
/// * UNC: `\\server\e:\`, `\\?\UNC\server\e:\`
|
||||
///
|
||||
// TODO: NT paths? Admin paths using `$`?
|
||||
case drive(Character)
|
||||
|
||||
// TODO: GUID type?
|
||||
/// A volume with a GUID in a non-traditional path
|
||||
///
|
||||
/// * UNC: `\\host\Volume{0000-...}\`, `\\.\UNC\host\Volume{0000-...}\`
|
||||
/// * Device roots: `\\.\Volume{0000-...}\`, `\\?\Volume{000-...}\`
|
||||
///
|
||||
// TODO: GUID type?
|
||||
case guid(String)
|
||||
|
||||
// TODO: Legacy DOS devices, such as COM1?
|
||||
@@ -463,3 +461,78 @@ extension SystemString {
|
||||
return lexer.current
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Windows)
|
||||
import WinSDK
|
||||
|
||||
// FIXME: Rather than canonicalizing the path at every call site to a Win32 API,
|
||||
// we should consider always storing absolute paths with the \\?\ prefix applied,
|
||||
// for better performance.
|
||||
extension UnsafePointer where Pointee == CInterop.PlatformChar {
|
||||
/// Invokes `body` with a resolved and potentially `\\?\`-prefixed version of the pointee,
|
||||
/// to ensure long paths greater than MAX_PATH (260) characters are handled correctly.
|
||||
///
|
||||
/// - seealso: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
|
||||
internal func withCanonicalPathRepresentation<Result>(_ body: (Self) throws -> Result) throws -> Result {
|
||||
// 1. Normalize the path first.
|
||||
// Contrary to the documentation, this works on long paths independently
|
||||
// of the registry or process setting to enable long paths (but it will also
|
||||
// not add the \\?\ prefix required by other functions under these conditions).
|
||||
let dwLength: DWORD = GetFullPathNameW(self, 0, nil, nil)
|
||||
return try withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) { pwszFullPath in
|
||||
guard (1..<dwLength).contains(GetFullPathNameW(self, DWORD(pwszFullPath.count), pwszFullPath.baseAddress, nil)) else {
|
||||
throw Errno(rawValue: _mapWindowsErrorToErrno(GetLastError()))
|
||||
}
|
||||
|
||||
// 1.5 Leave \\.\ prefixed paths alone since device paths are already an exact representation and PathCchCanonicalizeEx will mangle these.
|
||||
if let base = pwszFullPath.baseAddress,
|
||||
base[0] == UInt8(ascii: "\\"),
|
||||
base[1] == UInt8(ascii: "\\"),
|
||||
base[2] == UInt8(ascii: "."),
|
||||
base[3] == UInt8(ascii: "\\") {
|
||||
return try body(base)
|
||||
}
|
||||
|
||||
// 2. Canonicalize the path.
|
||||
// This will add the \\?\ prefix if needed based on the path's length.
|
||||
var pwszCanonicalPath: LPWSTR?
|
||||
let flags: ULONG = numericCast(PATHCCH_ALLOW_LONG_PATHS.rawValue)
|
||||
let result = PathAllocCanonicalize(pwszFullPath.baseAddress, flags, &pwszCanonicalPath)
|
||||
if let pwszCanonicalPath {
|
||||
defer { LocalFree(pwszCanonicalPath) }
|
||||
if result == S_OK {
|
||||
// 3. Perform the operation on the normalized path.
|
||||
return try body(pwszCanonicalPath)
|
||||
}
|
||||
}
|
||||
throw Errno(rawValue: _mapWindowsErrorToErrno(WIN32_FROM_HRESULT(result)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func HRESULT_CODE(_ hr: HRESULT) -> DWORD {
|
||||
DWORD(hr) & 0xffff
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD {
|
||||
DWORD(hr << 16) & 0x1fff
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func SUCCEEDED(_ hr: HRESULT) -> Bool {
|
||||
hr >= 0
|
||||
}
|
||||
|
||||
// This is a non-standard extension to the Windows SDK that allows us to convert
|
||||
// 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 HRESULT_FACILITY(hr) == FACILITY_WIN32 {
|
||||
return HRESULT_CODE(hr)
|
||||
}
|
||||
return DWORD(hr)
|
||||
}
|
||||
#endif
|
||||
@@ -17,114 +17,111 @@
|
||||
/// let perms = FilePermissions(rawValue: 0o644)
|
||||
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
|
||||
@frozen
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
@available(System 0.0.1, *)
|
||||
public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C file permissions.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.Mode
|
||||
public let rawValue: CModeT
|
||||
|
||||
/// Create a strongly-typed file permission from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
|
||||
public init(rawValue: CModeT) { self.rawValue = rawValue }
|
||||
|
||||
/// Indicates that other users have read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherRead: FilePermissions { FilePermissions(0o4) }
|
||||
public static var otherRead: FilePermissions { .init(rawValue: 0o4) }
|
||||
|
||||
/// Indicates that other users have write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherWrite: FilePermissions { FilePermissions(0o2) }
|
||||
public static var otherWrite: FilePermissions { .init(rawValue: 0o2) }
|
||||
|
||||
/// Indicates that other users have execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherExecute: FilePermissions { FilePermissions(0o1) }
|
||||
public static var otherExecute: FilePermissions { .init(rawValue: 0o1) }
|
||||
|
||||
/// Indicates that other users have read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadWrite: FilePermissions { FilePermissions(0o6) }
|
||||
public static var otherReadWrite: FilePermissions { .init(rawValue: 0o6) }
|
||||
|
||||
/// Indicates that other users have read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadExecute: FilePermissions { FilePermissions(0o5) }
|
||||
public static var otherReadExecute: FilePermissions { .init(rawValue: 0o5) }
|
||||
|
||||
/// Indicates that other users have write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) }
|
||||
public static var otherWriteExecute: FilePermissions { .init(rawValue: 0o3) }
|
||||
|
||||
/// Indicates that other users have read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) }
|
||||
public static var otherReadWriteExecute: FilePermissions { .init(rawValue: 0o7) }
|
||||
|
||||
/// Indicates that the group has read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupRead: FilePermissions { FilePermissions(0o40) }
|
||||
public static var groupRead: FilePermissions { .init(rawValue: 0o40) }
|
||||
|
||||
/// Indicates that the group has write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupWrite: FilePermissions { FilePermissions(0o20) }
|
||||
public static var groupWrite: FilePermissions { .init(rawValue: 0o20) }
|
||||
|
||||
/// Indicates that the group has execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupExecute: FilePermissions { FilePermissions(0o10) }
|
||||
public static var groupExecute: FilePermissions { .init(rawValue: 0o10) }
|
||||
|
||||
/// Indicates that the group has read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadWrite: FilePermissions { FilePermissions(0o60) }
|
||||
public static var groupReadWrite: FilePermissions { .init(rawValue: 0o60) }
|
||||
|
||||
/// Indicates that the group has read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadExecute: FilePermissions { FilePermissions(0o50) }
|
||||
public static var groupReadExecute: FilePermissions { .init(rawValue: 0o50) }
|
||||
|
||||
/// Indicates that the group has write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) }
|
||||
public static var groupWriteExecute: FilePermissions { .init(rawValue: 0o30) }
|
||||
|
||||
/// Indicates that the group has read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) }
|
||||
public static var groupReadWriteExecute: FilePermissions { .init(rawValue: 0o70) }
|
||||
|
||||
/// Indicates that the owner has read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerRead: FilePermissions { FilePermissions(0o400) }
|
||||
public static var ownerRead: FilePermissions { .init(rawValue: 0o400) }
|
||||
|
||||
/// Indicates that the owner has write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerWrite: FilePermissions { FilePermissions(0o200) }
|
||||
public static var ownerWrite: FilePermissions { .init(rawValue: 0o200) }
|
||||
|
||||
/// Indicates that the owner has execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerExecute: FilePermissions { FilePermissions(0o100) }
|
||||
public static var ownerExecute: FilePermissions { .init(rawValue: 0o100) }
|
||||
|
||||
/// Indicates that the owner has read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) }
|
||||
public static var ownerReadWrite: FilePermissions { .init(rawValue: 0o600) }
|
||||
|
||||
/// Indicates that the owner has read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) }
|
||||
public static var ownerReadExecute: FilePermissions { .init(rawValue: 0o500) }
|
||||
|
||||
/// Indicates that the owner has write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) }
|
||||
public static var ownerWriteExecute: FilePermissions { .init(rawValue: 0o300) }
|
||||
|
||||
/// Indicates that the owner has read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) }
|
||||
public static var ownerReadWriteExecute: FilePermissions { .init(rawValue: 0o700) }
|
||||
|
||||
/// Indicates that the file is executed as the owner.
|
||||
///
|
||||
/// For more information, see the `setuid(2)` man page.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setUserID: FilePermissions { FilePermissions(0o4000) }
|
||||
public static var setUserID: FilePermissions { .init(rawValue: 0o4000) }
|
||||
|
||||
/// Indicates that the file is executed as the group.
|
||||
///
|
||||
/// For more information, see the `setgid(2)` man page.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setGroupID: FilePermissions { FilePermissions(0o2000) }
|
||||
public static var setGroupID: FilePermissions { .init(rawValue: 0o2000) }
|
||||
|
||||
/// Indicates that executable's text segment
|
||||
/// should be kept in swap space even after it exits.
|
||||
@@ -132,10 +129,10 @@ public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISVTX` (the sticky bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var saveText: FilePermissions { FilePermissions(0o1000) }
|
||||
public static var saveText: FilePermissions { .init(rawValue: 0o1000) }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
extension FilePermissions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// |------------------------|
|
||||
// | Swift API to C Mapping |
|
||||
// |------------------------------------------------------------------|
|
||||
// | FileFlags | Darwin | FreeBSD | OpenBSD |
|
||||
// |------------------|---------------|---------------|---------------|
|
||||
// | noDump | UF_NODUMP | UF_NODUMP | UF_NODUMP |
|
||||
// | userImmutable | UF_IMMUTABLE | UF_IMMUTABLE | UF_IMMUTABLE |
|
||||
// | userAppend | UF_APPEND | UF_APPEND | UF_APPEND |
|
||||
// | archived | SF_ARCHIVED | SF_ARCHIVED | SF_ARCHIVED |
|
||||
// | systemImmutable | SF_IMMUTABLE | SF_IMMUTABLE | SF_IMMUTABLE |
|
||||
// | systemAppend | SF_APPEND | SF_APPEND | SF_APPEND |
|
||||
// | opaque | UF_OPAQUE | UF_OPAQUE | N/A |
|
||||
// | hidden | UF_HIDDEN | UF_HIDDEN | N/A |
|
||||
// | systemNoUnlink | SF_NOUNLINK | SF_NOUNLINK | N/A |
|
||||
// | compressed | UF_COMPRESSED | N/A | N/A |
|
||||
// | tracked | UF_TRACKED | N/A | N/A |
|
||||
// | dataVault | UF_DATAVAULT | N/A | N/A |
|
||||
// | restricted | SF_RESTRICTED | N/A | N/A |
|
||||
// | firmlink | SF_FIRMLINK | N/A | N/A |
|
||||
// | dataless | SF_DATALESS | N/A | N/A |
|
||||
// | userNoUnlink | N/A | UF_NOUNLINK | N/A |
|
||||
// | offline | N/A | UF_OFFLINE | N/A |
|
||||
// | readOnly | N/A | UF_READONLY | N/A |
|
||||
// | reparse | N/A | UF_REPARSE | N/A |
|
||||
// | sparse | N/A | UF_SPARSE | N/A |
|
||||
// | system | N/A | UF_SYSTEM | N/A |
|
||||
// | snapshot | N/A | SF_SNAPSHOT | N/A |
|
||||
// |------------------|---------------|---------------|---------------|
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
|
||||
/// File-specific flags found in the `st_flags` property of a `stat` struct
|
||||
/// or used as input to `chflags()`.
|
||||
///
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.FileFlags
|
||||
|
||||
/// Creates a strongly-typed `FileFlags` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.FileFlags) { self.rawValue = rawValue }
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
/// Do not dump the file during backups.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NODUMP`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDump: FileFlags { FileFlags(rawValue: _UF_NODUMP) }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_IMMUTABLE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userImmutable: FileFlags { FileFlags(rawValue: _UF_IMMUTABLE) }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `UF_APPEND`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userAppend: FileFlags { FileFlags(rawValue: _UF_APPEND) }
|
||||
|
||||
/// File has been archived.
|
||||
///
|
||||
/// The corresponding C constant is `SF_ARCHIVED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var archived: FileFlags { FileFlags(rawValue: _SF_ARCHIVED) }
|
||||
|
||||
/// File may not be changed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_IMMUTABLE`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var systemImmutable: FileFlags { FileFlags(rawValue: _SF_IMMUTABLE) }
|
||||
|
||||
/// Writes to the file may only append.
|
||||
///
|
||||
/// The corresponding C constant is `SF_APPEND`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var systemAppend: FileFlags { FileFlags(rawValue: _SF_APPEND) }
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Directory is opaque when viewed through a union mount.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OPAQUE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var opaque: FileFlags { FileFlags(rawValue: _UF_OPAQUE) }
|
||||
|
||||
/// File should not be displayed in a GUI.
|
||||
///
|
||||
/// The corresponding C constant is `UF_HIDDEN`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var hidden: FileFlags { FileFlags(rawValue: _UF_HIDDEN) }
|
||||
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `SF_NOUNLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var systemNoUnlink: FileFlags { FileFlags(rawValue: _SF_NOUNLINK) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// File is compressed at the file system level.
|
||||
///
|
||||
/// The corresponding C constant is `UF_COMPRESSED`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var compressed: FileFlags { FileFlags(rawValue: _UF_COMPRESSED) }
|
||||
|
||||
/// File is tracked for the purpose of document IDs.
|
||||
///
|
||||
/// The corresponding C constant is `UF_TRACKED`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tracked: FileFlags { FileFlags(rawValue: _UF_TRACKED) }
|
||||
|
||||
/// File requires an entitlement for reading and writing.
|
||||
///
|
||||
/// The corresponding C constant is `UF_DATAVAULT`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataVault: FileFlags { FileFlags(rawValue: _UF_DATAVAULT) }
|
||||
|
||||
/// File requires an entitlement for writing.
|
||||
///
|
||||
/// The corresponding C constant is `SF_RESTRICTED`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var restricted: FileFlags { FileFlags(rawValue: _SF_RESTRICTED) }
|
||||
|
||||
/// File is a firmlink.
|
||||
///
|
||||
/// Firmlinks are used by macOS to create transparent links between
|
||||
/// the read-only system volume and writable data volume. For example,
|
||||
/// the `/Applications` folder on the system volume is a firmlink to
|
||||
/// the `/Applications` folder on the data volume, allowing the user
|
||||
/// to see both system- and user-installed applications in a single folder.
|
||||
///
|
||||
/// The corresponding C constant is `SF_FIRMLINK`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var firmlink: FileFlags { FileFlags(rawValue: _SF_FIRMLINK) }
|
||||
|
||||
/// File is a dataless placeholder (content is stored remotely).
|
||||
///
|
||||
/// The system will attempt to materialize the file when accessed according to
|
||||
/// the dataless file materialization policy of the accessing thread or process.
|
||||
/// See `getiopolicy_np(3)`.
|
||||
///
|
||||
/// The corresponding C constant is `SF_DATALESS`.
|
||||
/// - Note: This flag is read-only. Attempting to change it will result in undefined behavior.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataless: FileFlags { FileFlags(rawValue: _SF_DATALESS) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
/// File may not be removed or renamed.
|
||||
///
|
||||
/// The corresponding C constant is `UF_NOUNLINK`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var userNoUnlink: FileFlags { FileFlags(rawValue: _UF_NOUNLINK) }
|
||||
|
||||
/// File has the Windows offline attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_OFFLINE` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_OFFLINE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var offline: FileFlags { FileFlags(rawValue: _UF_OFFLINE) }
|
||||
|
||||
/// File is read-only.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_READONLY` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_READONLY`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var readOnly: FileFlags { FileFlags(rawValue: _UF_READONLY) }
|
||||
|
||||
/// File contains a Windows reparse point.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_REPARSE_POINT` attribute.
|
||||
///
|
||||
/// The corresponding C constant is `UF_REPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reparse: FileFlags { FileFlags(rawValue: _UF_REPARSE) }
|
||||
|
||||
/// File is sparse.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SPARSE_FILE` attribute,
|
||||
/// or to indicate a sparse file.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SPARSE`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sparse: FileFlags { FileFlags(rawValue: _UF_SPARSE) }
|
||||
|
||||
/// File has the Windows system attribute.
|
||||
///
|
||||
/// File systems may use this flag for compatibility with the Windows `FILE_ATTRIBUTE_SYSTEM` attribute,
|
||||
/// but otherwise provide no special handling when it's set.
|
||||
///
|
||||
/// The corresponding C constant is `UF_SYSTEM`.
|
||||
/// - Note: This flag may be changed by the file owner or superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var system: FileFlags { FileFlags(rawValue: _UF_SYSTEM) }
|
||||
|
||||
/// File is a snapshot.
|
||||
///
|
||||
/// The corresponding C constant is `SF_SNAPSHOT`.
|
||||
/// - Note: This flag may only be changed by the superuser.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var snapshot: FileFlags { FileFlags(rawValue: _SF_SNAPSHOT) }
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 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 !os(Windows)
|
||||
/// A strongly-typed file mode representing a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed `FileMode` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a `FileMode` from the given file type and permissions.
|
||||
///
|
||||
/// - Note: This initializer masks the inputs with their respective bit masks.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(type: FileType, permissions: FilePermissions) {
|
||||
self.rawValue = (type.rawValue & _MODE_FILETYPE_MASK) | (permissions.rawValue & _MODE_PERMISSIONS_MASK)
|
||||
}
|
||||
|
||||
/// The file's type, from the mode's file-type bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the file-type bit mask `S_IFMT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var type: FileType {
|
||||
get { FileType(rawValue: rawValue & _MODE_FILETYPE_MASK) }
|
||||
set { rawValue = (rawValue & ~_MODE_FILETYPE_MASK) | (newValue.rawValue & _MODE_FILETYPE_MASK) }
|
||||
}
|
||||
|
||||
/// The file's permissions, from the mode's permission bits.
|
||||
///
|
||||
/// Setting this property will mask the `newValue` with the permissions bit mask `ALLPERMS`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var permissions: FilePermissions {
|
||||
get { FilePermissions(rawValue: rawValue & _MODE_PERMISSIONS_MASK) }
|
||||
set { rawValue = (rawValue & ~_MODE_PERMISSIONS_MASK) | (newValue.rawValue & _MODE_PERMISSIONS_MASK) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,108 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// |------------------------|
|
||||
// | Swift API to C Mapping |
|
||||
// |----------------------------------------|
|
||||
// | FileType | Unix-like Platforms |
|
||||
// |------------------|---------------------|
|
||||
// | directory | S_IFDIR |
|
||||
// | characterSpecial | S_IFCHR |
|
||||
// | blockSpecial | S_IFBLK |
|
||||
// | regular | S_IFREG |
|
||||
// | fifo | S_IFIFO |
|
||||
// | symbolicLink | S_IFLNK |
|
||||
// | socket | S_IFSOCK |
|
||||
// |------------------|---------------------|
|
||||
//
|
||||
// |------------------------------------------------------------------|
|
||||
// | FileType | Darwin | FreeBSD | Other Unix-like Platforms |
|
||||
// |------------------|---------|---------|---------------------------|
|
||||
// | whiteout | S_IFWHT | S_IFWHT | N/A |
|
||||
// |------------------|---------|---------|---------------------------|
|
||||
|
||||
#if !os(Windows)
|
||||
/// A file type matching those contained in a C `mode_t`.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw file-type bits from the C mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Mode
|
||||
|
||||
/// Creates a strongly-typed file type from the raw C `mode_t`.
|
||||
///
|
||||
/// - Note: This initializer stores the `rawValue` directly and **does not**
|
||||
/// mask the value with `S_IFMT`. If the supplied `rawValue` contains bits
|
||||
/// outside of the `S_IFMT` mask, the resulting `FileType` will not compare
|
||||
/// equal to constants like `.directory` and `.symbolicLink`, which may
|
||||
/// be unexpected.
|
||||
///
|
||||
/// If you're unsure whether the `mode_t` contains bits outside of `S_IFMT`,
|
||||
/// you can use `FileMode(rawValue:)` instead to get a strongly-typed
|
||||
/// `FileMode`, then call `.type` to get the properly masked `FileType`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
/// Directory
|
||||
///
|
||||
/// The corresponding C constant is `S_IFDIR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: FileType { FileType(rawValue: _S_IFDIR) }
|
||||
|
||||
/// Character special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFCHR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var characterSpecial: FileType { FileType(rawValue: _S_IFCHR) }
|
||||
|
||||
/// Block special device
|
||||
///
|
||||
/// The corresponding C constant is `S_IFBLK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var blockSpecial: FileType { FileType(rawValue: _S_IFBLK) }
|
||||
|
||||
/// Regular file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFREG`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var regular: FileType { FileType(rawValue: _S_IFREG) }
|
||||
|
||||
/// FIFO (or named pipe)
|
||||
///
|
||||
/// The corresponding C constant is `S_IFIFO`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var fifo: FileType { FileType(rawValue: _S_IFIFO) }
|
||||
|
||||
/// Symbolic link
|
||||
///
|
||||
/// The corresponding C constant is `S_IFLNK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symbolicLink: FileType { FileType(rawValue: _S_IFLNK) }
|
||||
|
||||
/// Socket
|
||||
///
|
||||
/// The corresponding C constant is `S_IFSOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var socket: FileType { FileType(rawValue: _S_IFSOCK) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Whiteout file
|
||||
///
|
||||
/// The corresponding C constant is `S_IFWHT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var whiteout: FileType { FileType(rawValue: _S_IFWHT) }
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,84 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 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 !os(Windows)
|
||||
/// A Swift wrapper of the C `uid_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `uid_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.UserID
|
||||
|
||||
/// Creates a strongly-typed `UserID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.UserID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `UserID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.UserID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
/// A Swift wrapper of the C `gid_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `gid_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.GroupID
|
||||
|
||||
/// Creates a strongly-typed `GroupID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.GroupID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `GroupID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.GroupID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
/// A Swift wrapper of the C `dev_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `dev_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.DeviceID
|
||||
|
||||
/// Creates a strongly-typed `DeviceID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.DeviceID) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `DeviceID` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.DeviceID) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
/// A Swift wrapper of the C `ino_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `ino_t`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Inode
|
||||
|
||||
/// Creates a strongly-typed `Inode` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Inode) { self.rawValue = rawValue }
|
||||
|
||||
/// Creates a strongly-typed `Inode` from the raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ rawValue: CInterop.Inode) { self.rawValue = rawValue }
|
||||
}
|
||||
#endif // !os(Windows)
|
||||
@@ -0,0 +1,632 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 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 !os(Windows)
|
||||
|
||||
// Must import here to use C stat properties in @_alwaysEmitIntoClient APIs.
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Stat
|
||||
|
||||
/// A Swift wrapper of the C `stat` struct.
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C `stat` struct.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInterop.Stat
|
||||
|
||||
/// Creates a Swift `Stat` from the raw C struct.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Stat) { self.rawValue = rawValue }
|
||||
|
||||
// MARK: Stat.Flags
|
||||
|
||||
/// Flags representing those passed to `fstatat()`.
|
||||
@frozen
|
||||
public struct Flags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a strongly-typed `Stat.Flags` from raw C flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlinkNoFollow: Flags { Flags(rawValue: _AT_SYMLINK_NOFOLLOW) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// If the path ends with a symbolic link, return information about the link itself.
|
||||
/// If _any_ symbolic link is encountered during path resolution, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_SYMLINK_NOFOLLOW_ANY`.
|
||||
/// - Note: Only available on Darwin.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlinkNoFollowAny: Flags { Flags(rawValue: _AT_SYMLINK_NOFOLLOW_ANY) }
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin, _version: 346) || os(FreeBSD)
|
||||
/// If the path does not reside in the hierarchy beneath the starting directory, return an error.
|
||||
///
|
||||
/// The corresponding C constant is `AT_RESOLVE_BENEATH`.
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var resolveBeneath: Flags { Flags(rawValue: _AT_RESOLVE_BENEATH) }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._stat(
|
||||
$0,
|
||||
followTargetSymlink: followTargetSymlink,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._stat(
|
||||
path,
|
||||
followTargetSymlink: followTargetSymlink,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _stat(
|
||||
_ ptr: UnsafePointer<CChar>,
|
||||
followTargetSymlink: Bool,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.Stat, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
if followTargetSymlink {
|
||||
system_stat(ptr, &result)
|
||||
} else {
|
||||
system_lstat(ptr, &result)
|
||||
}
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from a `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstat(
|
||||
fd,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _fstat(
|
||||
_ fd: FileDescriptor,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.Stat, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstat(fd.rawValue, &result)
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._fstatat(
|
||||
$0,
|
||||
relativeTo: _AT_FDCWD,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from a `FilePath` and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: FilePath,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try path.withPlatformString {
|
||||
Self._fstatat(
|
||||
$0,
|
||||
relativeTo: fd.rawValue,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
}.get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstatat(
|
||||
path,
|
||||
relativeTo: _AT_FDCWD,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct from an `UnsafePointer<CChar>` path and `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) {
|
||||
self.rawValue = try Self._fstatat(
|
||||
path,
|
||||
relativeTo: fd.rawValue,
|
||||
flags: flags,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _fstatat(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
relativeTo fd: FileDescriptor.RawValue,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<CInterop.Stat, Errno> {
|
||||
var result = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fstatat(fd, path, &result, flags.rawValue)
|
||||
}.map { result }
|
||||
}
|
||||
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// ID of device containing file
|
||||
///
|
||||
/// The corresponding C property is `st_dev`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var deviceID: DeviceID {
|
||||
get { DeviceID(rawValue: numericCast(rawValue.st_dev)) }
|
||||
set { rawValue.st_dev = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// Inode number
|
||||
///
|
||||
/// The corresponding C property is `st_ino`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var inode: Inode {
|
||||
get { Inode(rawValue: numericCast(rawValue.st_ino)) }
|
||||
set { rawValue.st_ino = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// File mode
|
||||
///
|
||||
/// The corresponding C property is `st_mode`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var mode: FileMode {
|
||||
get { FileMode(rawValue: numericCast(rawValue.st_mode)) }
|
||||
set { rawValue.st_mode = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// File type for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.type`. Modifying this
|
||||
/// property will update the underlying `st_mode` accordingly.
|
||||
@_alwaysEmitIntoClient
|
||||
public var type: FileType {
|
||||
get { mode.type }
|
||||
set {
|
||||
var newMode = mode
|
||||
newMode.type = newValue
|
||||
mode = newMode
|
||||
}
|
||||
}
|
||||
|
||||
/// File permissions for the given mode
|
||||
///
|
||||
/// - Note: This property is equivalent to `mode.permissions`. Modifying
|
||||
/// this property will update the underlying `st_mode` accordingly.
|
||||
@_alwaysEmitIntoClient
|
||||
public var permissions: FilePermissions {
|
||||
get { mode.permissions }
|
||||
set {
|
||||
var newMode = mode
|
||||
newMode.permissions = newValue
|
||||
mode = newMode
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of hard links
|
||||
///
|
||||
/// The corresponding C property is `st_nlink`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var linkCount: Int {
|
||||
get { Int(rawValue.st_nlink) }
|
||||
set { rawValue.st_nlink = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// User ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_uid`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var userID: UserID {
|
||||
get { UserID(rawValue: rawValue.st_uid) }
|
||||
set { rawValue.st_uid = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// Group ID of owner
|
||||
///
|
||||
/// The corresponding C property is `st_gid`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var groupID: GroupID {
|
||||
get { GroupID(rawValue: rawValue.st_gid) }
|
||||
set { rawValue.st_gid = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// Device ID (if special file)
|
||||
///
|
||||
/// For character or block special files, the returned `DeviceID` may have
|
||||
/// meaningful major and minor values. For non-special files, this
|
||||
/// property is usually meaningless and often set to 0.
|
||||
///
|
||||
/// The corresponding C property is `st_rdev`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var specialDeviceID: DeviceID {
|
||||
get { DeviceID(rawValue: numericCast(rawValue.st_rdev)) }
|
||||
set { rawValue.st_rdev = numericCast(newValue.rawValue) }
|
||||
}
|
||||
|
||||
/// Total size, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_size` field,
|
||||
/// which can have file-system–dependent behavior. For example, this property
|
||||
/// can return different values for a file's data fork and resource fork, and some
|
||||
/// file systems report logical size rather than actual disk usage for compressed
|
||||
/// or cloned files.
|
||||
///
|
||||
/// The corresponding C property is `st_size`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var size: Int64 {
|
||||
get { Int64(rawValue.st_size) }
|
||||
set { rawValue.st_size = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// Block size for file system I/O, in bytes
|
||||
///
|
||||
/// The corresponding C property is `st_blksize`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var preferredIOBlockSize: Int {
|
||||
get { Int(rawValue.st_blksize) }
|
||||
set { rawValue.st_blksize = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// Number of 512-byte blocks allocated
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file-system–dependent behavior.
|
||||
///
|
||||
/// The corresponding C property is `st_blocks`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var blocksAllocated: Int64 {
|
||||
get { Int64(rawValue.st_blocks) }
|
||||
set { rawValue.st_blocks = numericCast(newValue) }
|
||||
}
|
||||
|
||||
/// Total size allocated, in bytes
|
||||
///
|
||||
/// The semantics of this property are tied to the underlying C `st_blocks` field,
|
||||
/// which can have file-system–dependent behavior.
|
||||
///
|
||||
/// - Note: Calculated as `512 * blocksAllocated`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var sizeAllocated: Int64 {
|
||||
512 * blocksAllocated
|
||||
}
|
||||
|
||||
// NOTE: "st_" property names are used for the `timespec` properties so
|
||||
// we can reserve `accessTime`, `modificationTime`, etc. for potential
|
||||
// `UTCClock.Instant` properties in the future.
|
||||
|
||||
/// Time of last access, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin).
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_atim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_atimespec
|
||||
#else
|
||||
rawValue.st_atim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_atimespec = newValue
|
||||
#else
|
||||
rawValue.st_atim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Time of last modification, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin).
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_mtim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_mtimespec
|
||||
#else
|
||||
rawValue.st_mtim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_mtimespec = newValue
|
||||
#else
|
||||
rawValue.st_mtim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Time of last status (inode) change, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin).
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_ctim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_ctimespec
|
||||
#else
|
||||
rawValue.st_ctim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_ctimespec = newValue
|
||||
#else
|
||||
rawValue.st_ctim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
/// Time of file creation, given as a C `timespec` since the Epoch.
|
||||
///
|
||||
/// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin).
|
||||
/// - Note: Only available on Darwin and FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var st_birthtim: timespec {
|
||||
get {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_birthtimespec
|
||||
#else
|
||||
rawValue.st_birthtim
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
rawValue.st_birthtimespec = newValue
|
||||
#else
|
||||
rawValue.st_birthtim = newValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
/// File flags
|
||||
///
|
||||
/// The corresponding C property is `st_flags`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var flags: FileFlags {
|
||||
get { FileFlags(rawValue: rawValue.st_flags) }
|
||||
set { rawValue.st_flags = newValue.rawValue }
|
||||
}
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number is 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.
|
||||
@_alwaysEmitIntoClient
|
||||
public var generationNumber: Int {
|
||||
get { Int(rawValue.st_gen) }
|
||||
set { rawValue.st_gen = numericCast(newValue)}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
extension Stat: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
/// Compares the raw bytes of two `Stat` structs for equality.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
return withUnsafeBytes(of: lhs.rawValue) { lhsBytes in
|
||||
withUnsafeBytes(of: rhs.rawValue) { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension Stat: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
/// Hashes the raw bytes of this `Stat` struct.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
withUnsafeBytes(of: rawValue) { bytes in
|
||||
hasher.combine(bytes: bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible and CustomDebugStringConvertible
|
||||
|
||||
// MARK: - FileDescriptor Extensions
|
||||
|
||||
@available(System 99, *)
|
||||
extension FileDescriptor {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
|
||||
///
|
||||
/// The corresponding C function is `fstat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FilePath Extensions
|
||||
|
||||
@available(System 99, *)
|
||||
extension FilePath {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
|
||||
///
|
||||
/// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link.
|
||||
/// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`.
|
||||
/// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and
|
||||
/// returns information about the symlink itself.
|
||||
///
|
||||
/// The corresponding C function is `stat()` or `lstat()` as described above.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
followTargetSymlink: Bool = true,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, followTargetSymlink: followTargetSymlink, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`.
|
||||
///
|
||||
/// If `path` is relative, it is resolved against the current working directory.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, flags: flags, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`,
|
||||
/// including a `FileDescriptor` to resolve a relative path.
|
||||
///
|
||||
/// If `path` is absolute (starts with a forward slash), then `fd` is ignored.
|
||||
/// If `path` is relative, it is resolved against the directory given by `fd`.
|
||||
///
|
||||
/// The corresponding C function is `fstatat()`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func stat(
|
||||
relativeTo fd: FileDescriptor,
|
||||
flags: Stat.Flags,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> Stat {
|
||||
try Stat(self, relativeTo: fd, flags: flags, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !os(Windows)
|
||||
@@ -0,0 +1,71 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
|
||||
public extension IORing {
|
||||
struct Completion: ~Copyable {
|
||||
@inlinable init(rawValue inRawValue: io_uring_cqe) {
|
||||
rawValue = inRawValue
|
||||
}
|
||||
@usableFromInline let rawValue: io_uring_cqe
|
||||
}
|
||||
}
|
||||
|
||||
public extension IORing.Completion {
|
||||
struct Flags: OptionSet, Hashable, Codable {
|
||||
public let rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
///`IORING_CQE_F_BUFFER` Indicates the buffer ID is stored in the upper 16 bits
|
||||
@inlinable public static var allocatedBuffer: Flags { Flags(rawValue: 1 << 0) }
|
||||
///`IORING_CQE_F_MORE` Indicates more completions will be generated from the request that generated this
|
||||
@inlinable public static var moreCompletions: Flags { Flags(rawValue: 1 << 1) }
|
||||
//`IORING_CQE_F_SOCK_NONEMPTY`, but currently unused
|
||||
//@inlinable public static var socketNotEmpty: Flags { Flags(rawValue: 1 << 2) }
|
||||
//`IORING_CQE_F_NOTIF`, but currently unused
|
||||
//@inlinable public static var isNotificationEvent: Flags { Flags(rawValue: 1 << 3) }
|
||||
//IORING_CQE_F_BUF_MORE will eventually be (1U << 4) if we add IOU_PBUF_RING_INC support
|
||||
}
|
||||
}
|
||||
|
||||
public extension IORing.Completion {
|
||||
@inlinable var context: UInt64 {
|
||||
get {
|
||||
rawValue.user_data
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var userPointer: UnsafeRawPointer? {
|
||||
get {
|
||||
UnsafeRawPointer(bitPattern: UInt(rawValue.user_data))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var result: Int32 {
|
||||
get {
|
||||
rawValue.res
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var flags: IORing.Completion.Flags {
|
||||
get {
|
||||
Flags(rawValue: rawValue.flags & 0x0000FFFF)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable var bufferIndex: UInt16? {
|
||||
get {
|
||||
if self.flags.contains(.allocatedBuffer) {
|
||||
return UInt16(rawValue.flags >> 16)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,497 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
|
||||
@usableFromInline
|
||||
internal enum IORequestCore {
|
||||
case nop // nothing here
|
||||
case openat(
|
||||
atDirectory: FileDescriptor,
|
||||
path: FilePath,
|
||||
FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case openatSlot(
|
||||
atDirectory: FileDescriptor,
|
||||
path: FilePath,
|
||||
FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
intoSlot: IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case read(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case readUnregistered(
|
||||
file: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case readSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case readUnregisteredSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case write(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case writeUnregistered(
|
||||
file: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case writeSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case writeUnregisteredSlot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case close(
|
||||
FileDescriptor,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case closeSlot(
|
||||
IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case unlinkAt(
|
||||
atDirectory: FileDescriptor,
|
||||
path: FilePath,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case cancel(
|
||||
flags:UInt32
|
||||
)
|
||||
case cancelContext(
|
||||
flags: UInt32,
|
||||
targetContext: UInt64
|
||||
)
|
||||
case cancelFD(
|
||||
flags: UInt32,
|
||||
targetFD: FileDescriptor
|
||||
)
|
||||
case cancelFDSlot(
|
||||
flags: UInt32,
|
||||
target: IORing.RegisteredFile
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_registered(
|
||||
file: FileDescriptor,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.fileDescriptor = file
|
||||
request.buffer = buffer.unsafeBuffer
|
||||
request.rawValue.buf_index = UInt16(exactly: buffer.index)!
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_registered_slot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: IORing.RegisteredBuffer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.rawValue.fd = Int32(exactly: file.index)!
|
||||
request.flags = .fixedFile
|
||||
request.buffer = buffer.unsafeBuffer
|
||||
request.rawValue.buf_index = UInt16(exactly: buffer.index)!
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_unregistered(
|
||||
file: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.fileDescriptor = file
|
||||
request.buffer = buffer
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func makeRawRequest_readWrite_unregistered_slot(
|
||||
file: IORing.RegisteredFile,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
offset: UInt64,
|
||||
context: UInt64 = 0,
|
||||
request: consuming RawIORequest
|
||||
) -> RawIORequest {
|
||||
request.rawValue.fd = Int32(exactly: file.index)!
|
||||
request.flags = .fixedFile
|
||||
request.buffer = buffer
|
||||
request.offset = offset
|
||||
request.rawValue.user_data = context
|
||||
return request
|
||||
}
|
||||
|
||||
extension IORing {
|
||||
public struct Request {
|
||||
@usableFromInline var core: IORequestCore
|
||||
|
||||
@inlinable internal init(core inCore: IORequestCore) {
|
||||
core = inCore
|
||||
}
|
||||
|
||||
@inlinable internal consuming func extractCore() -> IORequestCore {
|
||||
return core
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
extension IORing.Request {
|
||||
@inlinable public static func nop(context: UInt64 = 0) -> IORing.Request {
|
||||
.init(core: .nop)
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: IORing.RegisteredFile,
|
||||
into buffer: IORing.RegisteredBuffer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: FileDescriptor,
|
||||
into buffer: IORing.RegisteredBuffer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .read(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: IORing.RegisteredFile,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func read(
|
||||
_ file: FileDescriptor,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func write(
|
||||
_ buffer: IORing.RegisteredBuffer,
|
||||
into file: IORing.RegisteredFile,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func write(
|
||||
_ buffer: IORing.RegisteredBuffer,
|
||||
into file: FileDescriptor,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .write(file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func write(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
into file: IORing.RegisteredFile,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .writeUnregisteredSlot(
|
||||
file: file, buffer: buffer, offset: offset, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func write(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
into file: FileDescriptor,
|
||||
at offset: UInt64 = 0,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(
|
||||
core: .writeUnregistered(file: file, buffer: buffer, offset: offset, context: context)
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable public static func close(
|
||||
_ file: FileDescriptor,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .close(file, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func close(
|
||||
_ file: IORing.RegisteredFile,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .closeSlot(file, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func open(
|
||||
_ path: FilePath,
|
||||
in directory: FileDescriptor,
|
||||
into slot: IORing.RegisteredFile,
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(
|
||||
core: .openatSlot(
|
||||
atDirectory: directory, path: path, mode, options: options,
|
||||
permissions: permissions, intoSlot: slot, context: context))
|
||||
}
|
||||
|
||||
@inlinable public static func open(
|
||||
_ path: FilePath,
|
||||
in directory: FileDescriptor,
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(
|
||||
core: .openat(
|
||||
atDirectory: directory, path: path, mode, options: options,
|
||||
permissions: permissions, context: context
|
||||
))
|
||||
}
|
||||
|
||||
@inlinable public static func unlink(
|
||||
_ path: FilePath,
|
||||
in directory: FileDescriptor,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
.init(core: .unlinkAt(atDirectory: directory, path: path, context: context))
|
||||
}
|
||||
|
||||
// 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
|
||||
*/
|
||||
|
||||
@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 }
|
||||
|
||||
public enum CancellationMatch {
|
||||
case all
|
||||
case first
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
matchingContext: UInt64
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext))
|
||||
case .first:
|
||||
.init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
matching: FileDescriptor
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching))
|
||||
case .first:
|
||||
.init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
matching: IORing.RegisteredFile
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching))
|
||||
case .first:
|
||||
.init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching))
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public static func cancel(
|
||||
_ matchAll: CancellationMatch,
|
||||
) -> IORing.Request {
|
||||
switch matchAll {
|
||||
case .all:
|
||||
.init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ALL))
|
||||
case .first:
|
||||
.init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ANY))
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal consuming func makeRawRequest() -> RawIORequest {
|
||||
var request = RawIORequest()
|
||||
switch extractCore() {
|
||||
case .nop:
|
||||
request.operation = .nop
|
||||
case .openatSlot(
|
||||
let atDirectory, let path, let mode, let options, let permissions, let fileSlot,
|
||||
let context):
|
||||
// TODO: use rawValue less
|
||||
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
|
||||
}))
|
||||
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
|
||||
}))
|
||||
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
|
||||
return makeRawRequest_readWrite_registered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .writeSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .writeFixed
|
||||
return makeRawRequest_readWrite_registered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .writeUnregistered(let file, let buffer, let offset, let context):
|
||||
request.operation = .write
|
||||
return makeRawRequest_readWrite_unregistered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .writeUnregisteredSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .write
|
||||
return makeRawRequest_readWrite_unregistered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .read(let file, let buffer, let offset, let context):
|
||||
request.operation = .readFixed
|
||||
return makeRawRequest_readWrite_registered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .readSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .readFixed
|
||||
return makeRawRequest_readWrite_registered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .readUnregistered(let file, let buffer, let offset, let context):
|
||||
request.operation = .read
|
||||
return makeRawRequest_readWrite_unregistered(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .readUnregisteredSlot(let file, let buffer, let offset, let context):
|
||||
request.operation = .read
|
||||
return makeRawRequest_readWrite_unregistered_slot(
|
||||
file: file, buffer: buffer, offset: offset, context: context, request: request)
|
||||
case .close(let file, let context):
|
||||
request.operation = .close
|
||||
request.fileDescriptor = file
|
||||
request.rawValue.user_data = context
|
||||
case .closeSlot(let file, let context):
|
||||
request.operation = .close
|
||||
request.rawValue.file_index = UInt32(file.index + 1)
|
||||
request.rawValue.user_data = context
|
||||
case .unlinkAt(let atDirectory, let path, let context):
|
||||
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
|
||||
request.rawValue.user_data = context
|
||||
case .cancelContext(let flags, let targetContext):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
request.addr = targetContext
|
||||
case .cancelFD(let flags, let targetFD):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
request.fileDescriptor = targetFD
|
||||
case .cancelFDSlot(let flags, let target):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
request.rawValue.fd = Int32(target.index)
|
||||
case .cancel(let flags):
|
||||
request.operation = .asyncCancel
|
||||
request.cancel_flags = flags
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,904 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
// needed for mmap
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
import Synchronization
|
||||
|
||||
private var ioringSupported: Bool {
|
||||
__SWIFT_IORING_SUPPORTED != 0
|
||||
}
|
||||
|
||||
//This was #defines in older headers, so we redeclare it to get a consistent import
|
||||
internal enum RegistrationOps: UInt32 {
|
||||
case registerBuffers = 0
|
||||
case unregisterBuffers = 1
|
||||
case registerFiles = 2
|
||||
case unregisterFiles = 3
|
||||
case registerEventFD = 4
|
||||
case unregisterEventFD = 5
|
||||
case registerFilesUpdate = 6
|
||||
case registerEventFDAsync = 7
|
||||
case registerProbe = 8
|
||||
case registerPersonality = 9
|
||||
case unregisterPersonality = 10
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawPointer {
|
||||
func advanced(by offset: UInt32) -> UnsafeMutableRawPointer {
|
||||
return advanced(by: Int(offset))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer {
|
||||
func to_iovec() -> iovec {
|
||||
iovec(iov_base: baseAddress, iov_len: count)
|
||||
}
|
||||
}
|
||||
|
||||
// all pointers in this struct reference kernel-visible memory
|
||||
@usableFromInline struct SQRing: ~Copyable {
|
||||
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
|
||||
@usableFromInline let kernelTail: UnsafePointer<Atomic<UInt32>>
|
||||
@usableFromInline var userTail: UInt32
|
||||
|
||||
// from liburing: the kernel should never change these
|
||||
// might change in the future with resizable rings?
|
||||
@usableFromInline let ringMask: UInt32
|
||||
// let ringEntries: UInt32 - absorbed into array.count
|
||||
|
||||
// ring flags bitfield
|
||||
// currently used by the kernel only in SQPOLL mode to indicate
|
||||
// when the polling thread needs to be woken up
|
||||
@usableFromInline let flags: UnsafePointer<Atomic<UInt32>>
|
||||
|
||||
// ring array
|
||||
// maps indexes between the actual ring and the submissionQueueEntries list,
|
||||
// allowing the latter to be used as a kind of freelist with enough work?
|
||||
// currently, just 1:1 mapping (0..<n)
|
||||
@usableFromInline let array: UnsafeMutableBufferPointer<UInt32>
|
||||
}
|
||||
|
||||
@usableFromInline struct CQRing: ~Copyable {
|
||||
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
|
||||
@usableFromInline let kernelTail: UnsafePointer<Atomic<UInt32>>
|
||||
|
||||
@usableFromInline let ringMask: UInt32
|
||||
|
||||
@usableFromInline let cqes: UnsafeBufferPointer<io_uring_cqe>
|
||||
}
|
||||
|
||||
@inline(__always) @inlinable
|
||||
internal func _tryWriteRequest(
|
||||
_ request: __owned RawIORequest, ring: inout SQRing,
|
||||
submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
if let entry = _getSubmissionEntry(
|
||||
ring: &ring, submissionQueueEntries: submissionQueueEntries) {
|
||||
entry.pointee = request.rawValue
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//TODO: omitting signal mask for now
|
||||
//Tell the kernel that we've submitted requests and/or are waiting for completions
|
||||
@inlinable
|
||||
internal func _enter(
|
||||
ring: borrowing SQRing,
|
||||
ringDescriptor: Int32,
|
||||
numEvents: UInt32,
|
||||
minCompletions: UInt32,
|
||||
flags: UInt32
|
||||
) throws(Errno) -> Int32 {
|
||||
// Ring always needs enter right now;
|
||||
// TODO: support SQPOLL here
|
||||
while true {
|
||||
let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil)
|
||||
// error handling:
|
||||
// EAGAIN / EINTR (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 {
|
||||
//TODO: should we wait a bit on AGAIN?
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(Errno) {
|
||||
let flushedEvents = _flushQueue(ring: ring)
|
||||
_ = try _enter(
|
||||
ring: ring, ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getSubmissionQueueCount(ring: borrowing SQRing) -> UInt32 {
|
||||
return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getRemainingSubmissionQueueCapacity(ring: borrowing SQRing) -> UInt32 {
|
||||
return UInt32(truncatingIfNeeded: ring.array.count) - _getSubmissionQueueCount(ring: ring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getUnconsumedCompletionCount(ring: borrowing CQRing) -> UInt32 {
|
||||
return ring.kernelTail.pointee.load(ordering: .acquiring)
|
||||
- ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _flushQueue(ring: borrowing SQRing) -> UInt32 {
|
||||
ring.kernelTail.pointee.store(
|
||||
ring.userTail, ordering: .releasing
|
||||
)
|
||||
return _getSubmissionQueueCount(ring: ring)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _getSubmissionEntry(
|
||||
ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
|
||||
) -> UnsafeMutablePointer<
|
||||
swift_io_uring_sqe
|
||||
>? {
|
||||
let next = ring.userTail &+ 1 //this is expected to wrap
|
||||
|
||||
let kernelHead: UInt32 = ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
|
||||
// FEAT: 128-bit event support (not in MVP)
|
||||
if next - kernelHead <= ring.array.count {
|
||||
// let sqe = &sq->sqes[(sq->sqe_tail & sq->ring_mask) << shift];
|
||||
let sqeIndex = Int(
|
||||
ring.userTail & ring.ringMask
|
||||
)
|
||||
|
||||
let sqe = submissionQueueEntries
|
||||
.baseAddress.unsafelyUnwrapped
|
||||
.advanced(by: sqeIndex)
|
||||
|
||||
ring.userTail = next
|
||||
return sqe
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func setUpRing(
|
||||
queueDepth: UInt32, flags: IORing.SetupFlags
|
||||
) throws(Errno) ->
|
||||
(params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer?, ringSize: Int, submissionRingPtr: UnsafeMutableRawPointer?, submissionRingSize: Int, completionRingPtr: UnsafeMutableRawPointer?, completionRingSize: Int, sqes: UnsafeMutableRawPointer) {
|
||||
var params = io_uring_params()
|
||||
params.flags = flags.rawValue
|
||||
|
||||
var err: Errno? = nil
|
||||
let ringDescriptor = withUnsafeMutablePointer(to: ¶ms) {
|
||||
let result = io_uring_setup(queueDepth, $0)
|
||||
if result < 0 {
|
||||
err = Errno.current
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
if let err {
|
||||
throw err
|
||||
}
|
||||
|
||||
if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0
|
||||
{
|
||||
close(ringDescriptor)
|
||||
throw Errno.invalidArgument
|
||||
}
|
||||
|
||||
let submitRingSize =
|
||||
params.sq_off.array
|
||||
+ params.sq_entries * UInt32(MemoryLayout<UInt32>.size)
|
||||
|
||||
let completionRingSize =
|
||||
params.cq_off.cqes
|
||||
+ params.cq_entries * UInt32(MemoryLayout<io_uring_cqe>.size)
|
||||
|
||||
let ringSize = Int(max(submitRingSize, completionRingSize))
|
||||
|
||||
var ringPtr: UnsafeMutableRawPointer!
|
||||
var sqPtr: UnsafeMutableRawPointer!
|
||||
var cqPtr: UnsafeMutableRawPointer!
|
||||
|
||||
if params.features & IORING_FEAT_SINGLE_MMAP != 0{
|
||||
ringPtr = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ ringSize,
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_SQ_RING)
|
||||
)
|
||||
|
||||
if ringPtr == MAP_FAILED {
|
||||
let errno = Errno.current
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
} else {
|
||||
sqPtr = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ Int(submitRingSize),
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_SQ_RING)
|
||||
)
|
||||
|
||||
if sqPtr == MAP_FAILED {
|
||||
let errno = Errno.current
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
|
||||
cqPtr = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ Int(completionRingSize),
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_CQ_RING)
|
||||
)
|
||||
|
||||
if cqPtr == MAP_FAILED {
|
||||
let errno: Errno = Errno.current
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
}
|
||||
|
||||
// map the submission queue
|
||||
let sqes = mmap(
|
||||
/* addr: */ nil,
|
||||
/* len: */ Int(params.sq_entries) * MemoryLayout<swift_io_uring_sqe>.size,
|
||||
/* prot: */ PROT_READ | PROT_WRITE,
|
||||
/* flags: */ MAP_SHARED | MAP_POPULATE,
|
||||
/* fd: */ ringDescriptor,
|
||||
/* offset: */ off_t(IORING_OFF_SQES)
|
||||
)
|
||||
|
||||
if sqes == MAP_FAILED {
|
||||
let errno = Errno.current
|
||||
if ringPtr != nil {
|
||||
munmap(ringPtr, ringSize)
|
||||
} else {
|
||||
if sqPtr != nil {
|
||||
munmap(sqPtr, Int(submitRingSize))
|
||||
}
|
||||
if cqPtr != nil {
|
||||
munmap(cqPtr, Int(completionRingSize))
|
||||
}
|
||||
}
|
||||
close(ringDescriptor)
|
||||
throw errno
|
||||
}
|
||||
|
||||
return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr, ringSize: ringSize, submissionRingPtr: sqPtr, submissionRingSize: Int(submitRingSize), completionRingPtr: cqPtr, completionRingSize: Int(completionRingSize), sqes: sqes!)
|
||||
}
|
||||
|
||||
///IORing provides facilities for
|
||||
/// * Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file IOdescriptors that improves their efficiency
|
||||
/// * Registering and unregistering eventfds, which allow asynchronous waiting for completions
|
||||
/// * Enqueueing IO requests
|
||||
/// * Dequeueing IO completions
|
||||
public struct IORing: ~Copyable {
|
||||
let ringFlags: UInt32
|
||||
@usableFromInline let ringDescriptor: Int32
|
||||
|
||||
@usableFromInline var submissionRing: SQRing
|
||||
// FEAT: set this eventually
|
||||
let submissionPolling: Bool = false
|
||||
|
||||
@usableFromInline let completionRing: CQRing
|
||||
|
||||
@usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
|
||||
|
||||
// kept around for unmap / cleanup. TODO: we can save a few words of memory by figuring out how to handle cleanup for non-IORING_FEAT_SINGLE_MMAP better
|
||||
let ringSize: Int
|
||||
let ringPtr: UnsafeMutableRawPointer?
|
||||
let submissionRingSize: Int
|
||||
let submissionRingPtr: UnsafeMutableRawPointer?
|
||||
let completionRingSize: Int
|
||||
let completionRingPtr: UnsafeMutableRawPointer?
|
||||
|
||||
@usableFromInline var _registeredFiles: [UInt32]
|
||||
@usableFromInline var _registeredBuffers: [iovec]
|
||||
|
||||
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.
|
||||
public struct RegisteredResource<T> {
|
||||
public typealias Resource = T
|
||||
@usableFromInline let resource: T
|
||||
public let index: Int
|
||||
|
||||
@inlinable internal init(
|
||||
resource: T,
|
||||
index: Int
|
||||
) {
|
||||
self.resource = resource
|
||||
self.index = index
|
||||
}
|
||||
}
|
||||
|
||||
public typealias RegisteredFile = RegisteredResource<UInt32>
|
||||
public typealias RegisteredBuffer = RegisteredResource<iovec>
|
||||
|
||||
/// SetupFlags represents configuration options to an IORing as it's being created
|
||||
public struct SetupFlags: OptionSet, RawRepresentable, Hashable {
|
||||
public var rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
@inlinable public static var pollCompletions: SetupFlags { .init(rawValue: UInt32(1) << 0) } //IORING_SETUP_IOPOLL
|
||||
@inlinable public static var pollSubmissions: SetupFlags { .init(rawValue: UInt32(1) << 1) } //IORING_SETUP_SQPOLL
|
||||
//TODO: figure out how to expose IORING_SETUP_SQ_AFF, IORING_SETUP_CQSIZE, IORING_SETUP_ATTACH_WQ
|
||||
@inlinable public static var clampMaxEntries: SetupFlags { .init(rawValue: UInt32(1) << 4) } //IORING_SETUP_CLAMP
|
||||
@inlinable public static var startDisabled: SetupFlags { .init(rawValue: UInt32(1) << 6) } //IORING_SETUP_R_DISABLED
|
||||
@inlinable public static var continueSubmittingOnError: SetupFlags { .init(rawValue: UInt32(1) << 7) } //IORING_SETUP_SUBMIT_ALL
|
||||
//TODO: do we want to expose IORING_SETUP_COOP_TASKRUN and IORING_SETUP_TASKRUN_FLAG?
|
||||
//public static var runTasksCooperatively: SetupFlags { .init(rawValue: UInt32(1) << 8) } //IORING_SETUP_COOP_TASKRUN
|
||||
//TODO: can we even do different size sqe/cqe? It requires a kernel feature, but how do we convince swift to let the types be different sizes?
|
||||
//internal static var use128ByteSQEs: SetupFlags { .init(rawValue: UInt32(1) << 10) } //IORING_SETUP_SQE128
|
||||
//internal static var use32ByteCQEs: SetupFlags { .init(rawValue: UInt32(1) << 11) } //IORING_SETUP_CQE32
|
||||
@inlinable public static var singleSubmissionThread: SetupFlags { .init(rawValue: UInt32(1) << 12) } //IORING_SETUP_SINGLE_ISSUER
|
||||
@inlinable public static var deferRunningTasks: SetupFlags { .init(rawValue: UInt32(1) << 13) } //IORING_SETUP_DEFER_TASKRUN
|
||||
//pretty sure we don't want to expose IORING_SETUP_NO_MMAP or IORING_SETUP_REGISTERED_FD_ONLY currently
|
||||
//TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it?
|
||||
}
|
||||
|
||||
/// Initializes an IORing with enough space for `queueDepth` prepared requests and completed operations
|
||||
public init(queueDepth: UInt32, flags: SetupFlags = []) throws(Errno) {
|
||||
guard ioringSupported else {
|
||||
throw Errno.notSupported
|
||||
}
|
||||
|
||||
let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, tmpSQPtr, tmpSQSize, tmpCQPtr, tmpCQSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags)
|
||||
// All throws need to be before initializing ivars here to avoid
|
||||
// "error: conditional initialization or destruction of noncopyable types is not supported;
|
||||
// this variable must be consistently in an initialized or uninitialized state through every code path"
|
||||
|
||||
// Pre-compute values to avoid accessing partially initialized state
|
||||
let ringBasePtr = tmpRingPtr ?? tmpSQPtr!
|
||||
let completionBasePtr = tmpRingPtr ?? tmpCQPtr!
|
||||
|
||||
let submissionRing = SQRing(
|
||||
kernelHead: UnsafePointer<Atomic<UInt32>>(
|
||||
ringBasePtr.advanced(by: params.sq_off.head)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
kernelTail: UnsafePointer<Atomic<UInt32>>(
|
||||
ringBasePtr.advanced(by: params.sq_off.tail)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
userTail: 0, // no requests yet
|
||||
ringMask: ringBasePtr.advanced(by: params.sq_off.ring_mask)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee,
|
||||
flags: UnsafePointer<Atomic<UInt32>>(
|
||||
ringBasePtr.advanced(by: params.sq_off.flags)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
array: UnsafeMutableBufferPointer(
|
||||
start: ringBasePtr.advanced(by: params.sq_off.array)
|
||||
.assumingMemoryBound(to: UInt32.self),
|
||||
count: Int(
|
||||
ringBasePtr.advanced(by: params.sq_off.ring_entries)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee)
|
||||
)
|
||||
)
|
||||
|
||||
let completionRing = CQRing(
|
||||
kernelHead: UnsafePointer<Atomic<UInt32>>(
|
||||
completionBasePtr.advanced(by: params.cq_off.head)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
kernelTail: UnsafePointer<Atomic<UInt32>>(
|
||||
completionBasePtr.advanced(by: params.cq_off.tail)
|
||||
.assumingMemoryBound(to: Atomic<UInt32>.self)
|
||||
),
|
||||
ringMask: completionBasePtr.advanced(by: params.cq_off.ring_mask)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee,
|
||||
cqes: UnsafeBufferPointer(
|
||||
start: completionBasePtr.advanced(by: params.cq_off.cqes)
|
||||
.assumingMemoryBound(to: io_uring_cqe.self),
|
||||
count: Int(
|
||||
completionBasePtr.advanced(by: params.cq_off.ring_entries)
|
||||
.assumingMemoryBound(to: UInt32.self).pointee)
|
||||
)
|
||||
)
|
||||
|
||||
let submissionQueueEntries = UnsafeMutableBufferPointer(
|
||||
start: sqes.assumingMemoryBound(to: swift_io_uring_sqe.self),
|
||||
count: Int(params.sq_entries)
|
||||
)
|
||||
|
||||
// Now initialize all stored properties
|
||||
self.features = Features(rawValue: params.features)
|
||||
self.ringDescriptor = tmpRingDescriptor
|
||||
self.ringPtr = tmpRingPtr
|
||||
self.ringSize = tmpRingSize
|
||||
self.submissionRingPtr = tmpSQPtr
|
||||
self.submissionRingSize = tmpSQSize
|
||||
self.completionRingPtr = tmpCQPtr
|
||||
self.completionRingSize = tmpCQSize
|
||||
self._registeredFiles = []
|
||||
self._registeredBuffers = []
|
||||
self.submissionRing = submissionRing
|
||||
self.completionRing = completionRing
|
||||
self.submissionQueueEntries = submissionQueueEntries
|
||||
self.ringFlags = params.flags
|
||||
|
||||
// fill submission ring array with 1:1 map to underlying SQEs
|
||||
// (happens after all properties are initialized)
|
||||
for i in 0 ..< self.submissionRing.array.count {
|
||||
self.submissionRing.array[i] = UInt32(i)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _blockingConsumeCompletionGuts<Err: Error>(
|
||||
minimumCount: UInt32,
|
||||
maximumCount: UInt32,
|
||||
extraArgs: UnsafeMutablePointer<swift_io_uring_getevents_arg>? = nil,
|
||||
consumer: (consuming IORing.Completion?, Errno?, Bool) throws(Err) -> Void
|
||||
) throws(Err) {
|
||||
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)
|
||||
}
|
||||
if count == maximumCount {
|
||||
try consumer(nil, nil, true)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if count < minimumCount {
|
||||
while count < minimumCount {
|
||||
var sz = 0
|
||||
if extraArgs != nil {
|
||||
sz = MemoryLayout<swift_io_uring_getevents_arg>.size
|
||||
}
|
||||
let res = io_uring_enter2(
|
||||
ringDescriptor,
|
||||
0,
|
||||
minimumCount,
|
||||
IORING_ENTER_GETEVENTS,
|
||||
extraArgs,
|
||||
sz
|
||||
)
|
||||
// error handling:
|
||||
// EAGAIN / EINTR (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 {
|
||||
break
|
||||
} else if res == -EAGAIN || res == -EINTR {
|
||||
continue
|
||||
}
|
||||
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)
|
||||
}
|
||||
if count == maximumCount {
|
||||
break
|
||||
}
|
||||
}
|
||||
try consumer(nil, nil, true)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _blockingConsumeOneCompletion(
|
||||
extraArgs: UnsafeMutablePointer<swift_io_uring_getevents_arg>? = nil
|
||||
) throws(Errno) -> Completion {
|
||||
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
|
||||
}
|
||||
}
|
||||
return result.take()!
|
||||
}
|
||||
|
||||
/// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified)
|
||||
@inlinable
|
||||
public func blockingConsumeCompletion(
|
||||
timeout: Duration? = nil
|
||||
) throws(Errno) -> Completion {
|
||||
if let timeout {
|
||||
var ts = timespec(
|
||||
tv_sec: Int(timeout.components.seconds),
|
||||
tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> Completion in
|
||||
var args = swift_io_uring_getevents_arg(
|
||||
sigmask: 0,
|
||||
sigmask_sz: 0,
|
||||
min_wait_usec: 0,
|
||||
ts: UInt64(UInt(bitPattern: tsPtr))
|
||||
)
|
||||
return try _blockingConsumeOneCompletion(extraArgs: &args)
|
||||
}
|
||||
} else {
|
||||
return try _blockingConsumeOneCompletion()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@inlinable
|
||||
public func blockingConsumeCompletions<Err: Error>(
|
||||
minimumCount: UInt32 = 1,
|
||||
timeout: Duration? = nil,
|
||||
consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void
|
||||
) throws(Err) {
|
||||
if let timeout {
|
||||
var ts = timespec(
|
||||
tv_sec: Int(timeout.components.seconds),
|
||||
tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
try withUnsafePointer(to: &ts) { (tsPtr) throws(Err) in
|
||||
var args = swift_io_uring_getevents_arg(
|
||||
sigmask: 0,
|
||||
sigmask_sz: 0,
|
||||
min_wait_usec: 0,
|
||||
ts: UInt64(UInt(bitPattern: tsPtr))
|
||||
)
|
||||
try _blockingConsumeCompletionGuts(
|
||||
minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args,
|
||||
consumer: consumer)
|
||||
}
|
||||
} else {
|
||||
try _blockingConsumeCompletionGuts(
|
||||
minimumCount: minimumCount, maximumCount: UInt32.max, consumer: consumer)
|
||||
}
|
||||
}
|
||||
|
||||
// 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? {
|
||||
return _tryConsumeCompletion(ring: completionRing)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func _tryConsumeCompletion(ring: borrowing CQRing) -> Completion? {
|
||||
let tail = ring.kernelTail.pointee.load(ordering: .acquiring)
|
||||
let head = ring.kernelHead.pointee.load(ordering: .acquiring)
|
||||
|
||||
if tail != head {
|
||||
// 32 byte copy - oh well
|
||||
let res = ring.cqes[Int(head & ring.ringMask)]
|
||||
ring.kernelHead.pointee.store(head &+ 1, ordering: .releasing)
|
||||
return Completion(rawValue: res)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
)
|
||||
if result < 0 {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers `count` files with the ring for later use in IO operations
|
||||
public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources<RegisteredFile.Resource> {
|
||||
precondition(_registeredFiles.isEmpty)
|
||||
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)
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
|
||||
if let regResult {
|
||||
throw regResult
|
||||
}
|
||||
|
||||
_registeredFiles = files
|
||||
return registeredFileSlots
|
||||
}
|
||||
|
||||
/// Removes registered files from the ring
|
||||
public func unregisterFiles() throws {
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.unregisterFiles.rawValue,
|
||||
nil,
|
||||
0
|
||||
)
|
||||
if result < 0 {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Allows access to registered files by index
|
||||
@inlinable
|
||||
public var registeredFileSlots: RegisteredResources<RegisteredFile.Resource> {
|
||||
RegisteredResources(resources: _registeredFiles)
|
||||
}
|
||||
|
||||
/// Registers buffers with the ring for later use in IO operations
|
||||
public mutating func registerBuffers(_ buffers: some Collection<UnsafeMutableRawBufferPointer>) throws(Errno)
|
||||
-> RegisteredResources<RegisteredBuffer.Resource>
|
||||
{
|
||||
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)
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
|
||||
if let regResult {
|
||||
throw regResult
|
||||
}
|
||||
|
||||
_registeredBuffers = iovecs
|
||||
return registeredBuffers
|
||||
}
|
||||
|
||||
/// Registers buffers with the ring for later use in IO operations
|
||||
@inlinable
|
||||
public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno)
|
||||
-> RegisteredResources<RegisteredBuffer.Resource>
|
||||
{
|
||||
try registerBuffers(buffers)
|
||||
}
|
||||
|
||||
/// A view of the registered files or buffers in a ring
|
||||
public struct RegisteredResources<T>: RandomAccessCollection {
|
||||
@usableFromInline let resources: [T]
|
||||
|
||||
@inlinable public var startIndex: Int { 0 }
|
||||
@inlinable public var endIndex: Int { resources.endIndex }
|
||||
@inlinable init(resources: [T]) {
|
||||
self.resources = resources
|
||||
}
|
||||
@inlinable public subscript(position: Int) -> RegisteredResource<T> {
|
||||
RegisteredResource(resource: resources[position], index: position)
|
||||
}
|
||||
@inlinable public subscript(position: UInt16) -> RegisteredResource<T> {
|
||||
RegisteredResource(resource: resources[Int(position)], index: Int(position))
|
||||
}
|
||||
}
|
||||
|
||||
/// Allows access to registered files by index
|
||||
@inlinable
|
||||
public var registeredBuffers: RegisteredResources<RegisteredBuffer.Resource> {
|
||||
RegisteredResources(resources: _registeredBuffers)
|
||||
}
|
||||
|
||||
public func unregisterBuffers() throws {
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.unregisterBuffers.rawValue,
|
||||
nil,
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@inlinable
|
||||
public func submitPreparedRequestsAndConsumeCompletions<Err: Error>(
|
||||
minimumCount: UInt32 = 1,
|
||||
timeout: Duration? = nil,
|
||||
consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void
|
||||
) throws(Err) {
|
||||
//TODO: optimize this to one uring_enter
|
||||
do {
|
||||
try submitPreparedRequests()
|
||||
} catch (let e) {
|
||||
try consumer(nil, e, true)
|
||||
}
|
||||
try blockingConsumeCompletions(
|
||||
minimumCount: minimumCount,
|
||||
timeout: timeout,
|
||||
consumer: consumer
|
||||
)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@inlinable
|
||||
mutating func prepare(linkedRequests: some BidirectionalCollection<Request>) -> Bool {
|
||||
guard linkedRequests.count > 0 else {
|
||||
return true
|
||||
}
|
||||
let freeSQECount = _getRemainingSubmissionQueueCapacity(ring: submissionRing)
|
||||
guard freeSQECount >= linkedRequests.count else {
|
||||
return false
|
||||
}
|
||||
let last = linkedRequests.last!
|
||||
for req in linkedRequests.dropLast() {
|
||||
var raw = req.makeRawRequest()
|
||||
raw.linkToNextRequest()
|
||||
let successfullyAdded = _tryWriteRequest(
|
||||
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
|
||||
assert(successfullyAdded)
|
||||
}
|
||||
let successfullyAdded = _tryWriteRequest(
|
||||
last.makeRawRequest(), ring: &submissionRing,
|
||||
submissionQueueEntries: submissionQueueEntries)
|
||||
assert(successfullyAdded)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
|
||||
@inlinable
|
||||
public mutating func prepare(linkedRequests: Request...) -> Bool {
|
||||
prepare(linkedRequests: linkedRequests)
|
||||
}
|
||||
|
||||
/// Prepares and submits a sequence of requests to the ring. Returns false if the submission queue doesn't have enough available space.
|
||||
@inlinable
|
||||
public mutating func submit(linkedRequests: Request...) throws(Errno) -> Bool {
|
||||
if !prepare(linkedRequests: linkedRequests) {
|
||||
return false
|
||||
}
|
||||
try submitPreparedRequests()
|
||||
return true
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
//IORING_FEAT_SINGLE_MMAP is handled internally
|
||||
@inlinable public static var nonDroppingCompletions: Features { .init(rawValue: UInt32(1) << 1) } //IORING_FEAT_NODROP
|
||||
@inlinable public static var stableSubmissions: Features { .init(rawValue: UInt32(1) << 2) } //IORING_FEAT_SUBMIT_STABLE
|
||||
@inlinable public static var currentFilePosition: Features { .init(rawValue: UInt32(1) << 3) } //IORING_FEAT_RW_CUR_POS
|
||||
@inlinable public static var assumingTaskCredentials: Features { .init(rawValue: UInt32(1) << 4) } //IORING_FEAT_CUR_PERSONALITY
|
||||
@inlinable public static var fastPolling: Features { .init(rawValue: UInt32(1) << 5) } //IORING_FEAT_FAST_POLL
|
||||
@inlinable public static var epoll32BitFlags: Features { .init(rawValue: UInt32(1) << 6) } //IORING_FEAT_POLL_32BITS
|
||||
@inlinable public static var pollNonFixedFiles: Features { .init(rawValue: UInt32(1) << 7) } //IORING_FEAT_SQPOLL_NONFIXED
|
||||
@inlinable public static var extendedArguments: Features { .init(rawValue: UInt32(1) << 8) } //IORING_FEAT_EXT_ARG
|
||||
@inlinable public static var nativeWorkers: Features { .init(rawValue: UInt32(1) << 9) } //IORING_FEAT_NATIVE_WORKERS
|
||||
@inlinable public static var resourceTags: Features { .init(rawValue: UInt32(1) << 10) } //IORING_FEAT_RSRC_TAGS
|
||||
@inlinable public static var allowsSkippingSuccessfulCompletions: Features { .init(rawValue: UInt32(1) << 11) } //IORING_FEAT_CQE_SKIP
|
||||
@inlinable public static var improvedLinkedFiles: Features { .init(rawValue: UInt32(1) << 12) } //IORING_FEAT_LINKED_FILE
|
||||
@inlinable public static var registerRegisteredRings: Features { .init(rawValue: UInt32(1) << 13) } //IORING_FEAT_REG_REG_RING
|
||||
@inlinable public static var minimumTimeout: Features { .init(rawValue: UInt32(1) << 15) } //IORING_FEAT_MIN_TIMEOUT
|
||||
@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
|
||||
public var supportedFeatures: Features {
|
||||
return features
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let ringPtr {
|
||||
munmap(ringPtr, ringSize)
|
||||
} else if let submissionRingPtr, let completionRingPtr {
|
||||
munmap(submissionRingPtr, submissionRingSize)
|
||||
munmap(completionRingPtr, completionRingSize)
|
||||
}
|
||||
munmap(
|
||||
UnsafeMutableRawPointer(submissionQueueEntries.baseAddress!),
|
||||
submissionQueueEntries.count * MemoryLayout<swift_io_uring_sqe>.size
|
||||
)
|
||||
close(ringDescriptor)
|
||||
}
|
||||
}
|
||||
|
||||
extension IORing.RegisteredBuffer {
|
||||
@unsafe @inlinable public var unsafeBuffer: UnsafeMutableRawBufferPointer {
|
||||
return .init(start: resource.iov_base, count: resource.iov_len)
|
||||
}
|
||||
|
||||
@inlinable public var mutableBytes: MutableRawSpan {
|
||||
@_lifetime(&self)
|
||||
mutating get {
|
||||
let span = MutableRawSpan(_unsafeBytes: unsafeBuffer)
|
||||
return unsafe _overrideLifetime(span, mutating: &self)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public var bytes: RawSpan {
|
||||
let span = RawSpan(_unsafeBytes: UnsafeRawBufferPointer(unsafeBuffer))
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,205 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
|
||||
@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()
|
||||
}
|
||||
}
|
||||
|
||||
extension RawIORequest {
|
||||
@usableFromInline
|
||||
enum Operation: UInt8 {
|
||||
case nop = 0
|
||||
case readv = 1
|
||||
case writev = 2
|
||||
case fsync = 3
|
||||
case readFixed = 4
|
||||
case writeFixed = 5
|
||||
case pollAdd = 6
|
||||
case pollRemove = 7
|
||||
case syncFileRange = 8
|
||||
case sendMessage = 9
|
||||
case receiveMessage = 10
|
||||
// ...
|
||||
case asyncCancel = 14
|
||||
case link_timeout = 15
|
||||
// ...
|
||||
case openAt = 18
|
||||
case close = 19
|
||||
case filesUpdate = 20
|
||||
case statx = 21
|
||||
case read = 22
|
||||
case write = 23
|
||||
// ...
|
||||
case openAt2 = 28
|
||||
// ...
|
||||
case unlinkAt = 36
|
||||
}
|
||||
|
||||
public struct Flags: OptionSet, Hashable, Codable {
|
||||
public let rawValue: UInt8
|
||||
|
||||
@inlinable public init(rawValue: UInt8) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@inlinable public static var fixedFile: RawIORequest.Flags { Flags(rawValue: 1 << 0) }
|
||||
@inlinable public static var drainQueue: RawIORequest.Flags { Flags(rawValue: 1 << 1) }
|
||||
@inlinable public static var linkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 2) }
|
||||
@inlinable public static var hardlinkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 3) }
|
||||
@inlinable public static var asynchronous: RawIORequest.Flags { Flags(rawValue: 1 << 4) }
|
||||
@inlinable public static var selectBuffer: RawIORequest.Flags { Flags(rawValue: 1 << 5) }
|
||||
@inlinable public static var skipSuccess: RawIORequest.Flags { Flags(rawValue: 1 << 6) }
|
||||
}
|
||||
|
||||
@inlinable var operation: Operation {
|
||||
get { Operation(rawValue: rawValue.opcode)! }
|
||||
set { rawValue.opcode = newValue.rawValue }
|
||||
}
|
||||
|
||||
@inlinable var cancel_flags: UInt32 {
|
||||
get { rawValue.cancel_flags }
|
||||
set { rawValue.cancel_flags = newValue }
|
||||
}
|
||||
|
||||
@inlinable var addr: UInt64 {
|
||||
get { rawValue.addr }
|
||||
set { rawValue.addr = newValue }
|
||||
}
|
||||
|
||||
@inlinable public var flags: Flags {
|
||||
get { Flags(rawValue: rawValue.flags) }
|
||||
set { rawValue.flags = newValue.rawValue }
|
||||
}
|
||||
|
||||
@inlinable public mutating func linkToNextRequest() {
|
||||
flags = Flags(rawValue: flags.rawValue | Flags.linkRequest.rawValue)
|
||||
}
|
||||
|
||||
@inlinable public var fileDescriptor: FileDescriptor {
|
||||
get { FileDescriptor(rawValue: rawValue.fd) }
|
||||
set { rawValue.fd = newValue.rawValue }
|
||||
}
|
||||
|
||||
@inlinable public var offset: UInt64? {
|
||||
get {
|
||||
if (rawValue.off == UInt64.max) {
|
||||
return nil
|
||||
} else {
|
||||
return rawValue.off
|
||||
}
|
||||
}
|
||||
set {
|
||||
if let val = newValue {
|
||||
rawValue.off = val
|
||||
} else {
|
||||
rawValue.off = UInt64.max
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable public var buffer: UnsafeMutableRawBufferPointer {
|
||||
get {
|
||||
let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!)
|
||||
return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len))
|
||||
}
|
||||
|
||||
set {
|
||||
rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!))
|
||||
rawValue.len = UInt32(exactly: newValue.count)!
|
||||
}
|
||||
}
|
||||
|
||||
public enum RequestFlags {
|
||||
case readWriteFlags(ReadWriteFlags)
|
||||
// case fsyncFlags(FsyncFlags?)
|
||||
// poll_events
|
||||
// poll32_events
|
||||
// sync_range_flags
|
||||
// msg_flags
|
||||
case timeoutFlags(TimeOutFlags)
|
||||
// accept_flags
|
||||
// cancel_flags
|
||||
case openFlags(FileDescriptor.OpenOptions)
|
||||
// statx_flags
|
||||
// fadvise_advice
|
||||
// splice_flags
|
||||
}
|
||||
|
||||
public struct ReadWriteFlags: OptionSet, Hashable, Codable {
|
||||
public var rawValue: UInt32
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@inlinable public static var highPriority: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 0) }
|
||||
|
||||
// sync with only data integrity
|
||||
@inlinable public static var dataSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 1) }
|
||||
|
||||
// sync with full data + file integrity
|
||||
@inlinable public static var fileSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 2) }
|
||||
|
||||
// return -EAGAIN if operation blocks
|
||||
@inlinable public static var noWait: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 3) }
|
||||
|
||||
// append to end of the file
|
||||
@inlinable public static var append: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 4) }
|
||||
}
|
||||
|
||||
public struct TimeOutFlags: OptionSet, Hashable, Codable {
|
||||
public var rawValue: UInt32
|
||||
|
||||
@inlinable public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@inlinable public static var relativeTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 0) }
|
||||
@inlinable public static var absoluteTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 1 << 0) }
|
||||
}
|
||||
}
|
||||
|
||||
extension RawIORequest {
|
||||
@inlinable
|
||||
static func nop() -> RawIORequest {
|
||||
var req: RawIORequest = RawIORequest()
|
||||
req.operation = .nop
|
||||
return req
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func withTimeoutRequest<R>(
|
||||
linkedTo opEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
in timeoutEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
duration: Duration,
|
||||
flags: TimeOutFlags,
|
||||
work: () throws -> R) rethrows -> R {
|
||||
|
||||
opEntry.pointee.flags |= Flags.linkRequest.rawValue
|
||||
opEntry.pointee.off = 1
|
||||
var ts = timespec(
|
||||
tv_sec: Int(duration.components.seconds),
|
||||
tv_nsec: Int(duration.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
return try withUnsafePointer(to: &ts) { tsPtr in
|
||||
var req: RawIORequest = RawIORequest()
|
||||
req.operation = .link_timeout
|
||||
req.rawValue.timeout_flags = flags.rawValue
|
||||
req.rawValue.len = 1
|
||||
req.rawValue.addr = UInt64(UInt(bitPattern: tsPtr))
|
||||
timeoutEntry.pointee = req.rawValue
|
||||
return try work()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
extension String {
|
||||
internal init(
|
||||
_unsafeUninitializedCapacity capacity: Int,
|
||||
initializingUTF8With body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
|
||||
) rethrows {
|
||||
if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
|
||||
self = try String(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: body)
|
||||
return
|
||||
}
|
||||
|
||||
let array = try Array<UInt8>(
|
||||
unsafeUninitializedCapacity: capacity
|
||||
) { buffer, count in
|
||||
count = try body(buffer)
|
||||
}
|
||||
self = String(decoding: array, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,11 @@
|
||||
/*
|
||||
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 - 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
|
||||
*/
|
||||
|
||||
// MARK: - Public typealiases
|
||||
|
||||
/// The C `mode_t` type.
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(*, deprecated, renamed: "CInterop.Mode")
|
||||
public typealias CModeT = CInterop.Mode
|
||||
*/
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
@@ -25,12 +18,31 @@ import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Bionic)
|
||||
import CSystem
|
||||
import Bionic
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Public typealiases
|
||||
|
||||
// FIXME: `CModeT` ought to be deprecated and replaced with `CInterop.Mode`
|
||||
// if/when the compiler becomes less strict about availability checking
|
||||
// of "namespaced" typealiases. (rdar://81722893)
|
||||
#if os(Windows)
|
||||
/// The C `mode_t` type.
|
||||
public typealias CModeT = CInt
|
||||
#else
|
||||
/// The C `mode_t` type.
|
||||
@available(System 0.0.1, *)
|
||||
public typealias CModeT = mode_t
|
||||
#endif
|
||||
|
||||
/// A namespace for C and platform types
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
public enum CInterop {
|
||||
#if os(Windows)
|
||||
public typealias Mode = CInt
|
||||
@@ -67,3 +79,17 @@ public enum CInterop {
|
||||
public typealias PlatformUnicodeEncoding = UTF8
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(System 99, *)
|
||||
extension CInterop {
|
||||
public typealias Stat = stat
|
||||
public typealias DeviceID = dev_t
|
||||
public typealias Inode = ino_t
|
||||
public typealias UserID = uid_t
|
||||
public typealias GroupID = gid_t
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
public typealias FileFlags = UInt32
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +1,11 @@
|
||||
/*
|
||||
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 - 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
|
||||
*/
|
||||
*/
|
||||
|
||||
// For platform constants redefined in Swift. We define them here so that
|
||||
// they can be used anywhere without imports and without confusion to
|
||||
@@ -17,10 +17,16 @@ import Darwin
|
||||
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
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -73,7 +79,7 @@ internal var _EACCES: CInt { EACCES }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFAULT: CInt { EFAULT }
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(Windows) && !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTBLK: CInt { ENOTBLK }
|
||||
#endif
|
||||
@@ -141,7 +147,13 @@ internal var _ERANGE: CInt { ERANGE }
|
||||
internal var _EAGAIN: CInt { EAGAIN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EWOULDBLOCK: CInt { EWOULDBLOCK }
|
||||
internal var _EWOULDBLOCK: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_EWOULDBLOCK()
|
||||
#else
|
||||
EWOULDBLOCK
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINPROGRESS: CInt { EINPROGRESS }
|
||||
@@ -167,6 +179,7 @@ internal var _ENOPROTOOPT: CInt { ENOPROTOOPT }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTONOSUPPORT: CInt { EPROTONOSUPPORT }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESOCKTNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
@@ -175,6 +188,7 @@ internal var _ESOCKTNOSUPPORT: CInt {
|
||||
return ESOCKTNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSUP: CInt {
|
||||
@@ -185,6 +199,7 @@ internal var _ENOTSUP: CInt {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPFNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
@@ -193,6 +208,7 @@ internal var _EPFNOSUPPORT: CInt {
|
||||
return EPFNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT }
|
||||
@@ -227,6 +243,7 @@ internal var _EISCONN: CInt { EISCONN }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCONN: CInt { ENOTCONN }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHUTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
@@ -244,6 +261,7 @@ internal var _ETOOMANYREFS: CInt {
|
||||
return ETOOMANYREFS
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIMEDOUT: CInt { ETIMEDOUT }
|
||||
@@ -257,6 +275,7 @@ internal var _ELOOP: CInt { ELOOP }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAMETOOLONG: CInt { ENAMETOOLONG }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
@@ -265,6 +284,7 @@ internal var _EHOSTDOWN: CInt {
|
||||
return EHOSTDOWN
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
|
||||
@@ -277,6 +297,7 @@ internal var _ENOTEMPTY: CInt { ENOTEMPTY }
|
||||
internal var _EPROCLIM: CInt { EPROCLIM }
|
||||
#endif
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUSERS: CInt {
|
||||
#if os(Windows)
|
||||
@@ -285,6 +306,7 @@ internal var _EUSERS: CInt {
|
||||
return EUSERS
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDQUOT: CInt {
|
||||
@@ -304,6 +326,7 @@ internal var _ESTALE: CInt {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTE: CInt {
|
||||
#if os(Windows)
|
||||
@@ -312,6 +335,7 @@ internal var _EREMOTE: CInt {
|
||||
return EREMOTE
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -336,7 +360,7 @@ internal var _ENOLCK: CInt { ENOLCK }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSYS: CInt { ENOSYS }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFTYPE: CInt { EFTYPE }
|
||||
|
||||
@@ -345,7 +369,9 @@ internal var _EAUTH: CInt { EAUTH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENEEDAUTH: CInt { ENEEDAUTH }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPWROFF: CInt { EPWROFF }
|
||||
|
||||
@@ -386,7 +412,7 @@ internal var _ENOMSG: CInt { ENOMSG }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EILSEQ: CInt { EILSEQ }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOATTR: CInt { ENOATTR }
|
||||
#endif
|
||||
@@ -395,30 +421,45 @@ internal var _ENOATTR: CInt { ENOATTR }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMSG: CInt { EBADMSG }
|
||||
|
||||
#if !os(OpenBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMULTIHOP: CInt { EMULTIHOP }
|
||||
|
||||
#if !os(WASI) && !os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODATA: CInt { ENODATA }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLINK: CInt { ENOLINK }
|
||||
|
||||
#if !os(WASI) && !os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSR: CInt { ENOSR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSTR: CInt { ENOSTR }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTO: CInt { EPROTO }
|
||||
|
||||
#if !os(OpenBSD) && !os(WASI) && !os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIME: CInt { ETIME }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
|
||||
internal var _EOPNOTSUPP: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_EOPNOTSUPP()
|
||||
#else
|
||||
EOPNOTSUPP
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -433,10 +474,23 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
|
||||
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCAPABLE: CInt { ENOTCAPABLE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECAPMODE: CInt { ECAPMODE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINTEGRITY: CInt { EINTEGRITY }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EQFULL: CInt { EQFULL }
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELAST: CInt { ELAST }
|
||||
#endif
|
||||
@@ -458,17 +512,35 @@ internal var _O_ACCMODE: CInt { 0x03|O_SEARCH }
|
||||
#else
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ACCMODE: CInt { O_ACCMODE }
|
||||
internal var _O_ACCMODE: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_ACCMODE()
|
||||
#else
|
||||
O_ACCMODE
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
|
||||
internal var _O_NONBLOCK: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_NONBLOCK()
|
||||
#else
|
||||
O_NONBLOCK
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt { O_APPEND }
|
||||
internal var _O_APPEND: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_APPEND()
|
||||
#else
|
||||
O_APPEND
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SHLOCK: CInt { O_SHLOCK }
|
||||
|
||||
@@ -477,22 +549,50 @@ internal var _O_EXLOCK: CInt { O_EXLOCK }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(WASI)
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ASYNC: CInt { O_ASYNC }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOFOLLOW: CInt { O_NOFOLLOW }
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CREAT: CInt { O_CREAT }
|
||||
internal var _O_FSYNC: CInt { O_FSYNC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt { O_TRUNC }
|
||||
internal var _O_SYNC: CInt { O_SYNC }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt { O_EXCL }
|
||||
internal var _O_CREAT: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_CREAT()
|
||||
#else
|
||||
O_CREAT
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_TRUNC()
|
||||
#else
|
||||
O_TRUNC
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_EXCL()
|
||||
#else
|
||||
O_EXCL
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -505,7 +605,13 @@ internal var _O_EVTONLY: CInt { O_EVTONLY }
|
||||
internal var _O_NOCTTY: CInt { O_NOCTTY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECTORY: CInt { O_DIRECTORY }
|
||||
internal var _O_DIRECTORY: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_DIRECTORY()
|
||||
#else
|
||||
O_DIRECTORY
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@@ -527,7 +633,7 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_END: CInt { SEEK_END }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
|
||||
|
||||
@@ -535,3 +641,144 @@ internal var _SEEK_HOLE: CInt { SEEK_HOLE }
|
||||
internal var _SEEK_DATA: CInt { SEEK_DATA }
|
||||
#endif
|
||||
|
||||
// MARK: - File System
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_FDCWD: CInt { AT_FDCWD }
|
||||
|
||||
// MARK: - fstatat Flags
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_SYMLINK_NOFOLLOW: CInt { AT_SYMLINK_NOFOLLOW }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_SYMLINK_NOFOLLOW_ANY: CInt { AT_SYMLINK_NOFOLLOW_ANY }
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin, _version: 346) || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _AT_RESOLVE_BENEATH: CInt { AT_RESOLVE_BENEATH }
|
||||
#endif
|
||||
|
||||
// MARK: - File Mode / File Type
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MODE_FILETYPE_MASK: mode_t { S_IFMT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _MODE_PERMISSIONS_MASK: mode_t { 0o7777 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFDIR: mode_t { S_IFDIR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFCHR: mode_t { S_IFCHR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFBLK: mode_t { S_IFBLK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFREG: mode_t { S_IFREG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFIFO: mode_t { S_IFIFO }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFLNK: mode_t { S_IFLNK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFSOCK: mode_t { S_IFSOCK }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _S_IFWHT: mode_t { S_IFWHT }
|
||||
#endif
|
||||
|
||||
// MARK: - stat/chflags File Flags
|
||||
|
||||
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_NODUMP: UInt32 { UInt32(bitPattern: UF_NODUMP) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_IMMUTABLE: UInt32 { UInt32(bitPattern: UF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_APPEND: UInt32 { UInt32(bitPattern: UF_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_ARCHIVED: UInt32 { UInt32(bitPattern: SF_ARCHIVED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_IMMUTABLE: UInt32 { UInt32(bitPattern: SF_IMMUTABLE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_APPEND: UInt32 { UInt32(bitPattern: SF_APPEND) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin and FreeBSD
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_OPAQUE: UInt32 { UInt32(bitPattern: UF_OPAQUE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_HIDDEN: UInt32 { UInt32(bitPattern: UF_HIDDEN) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_NOUNLINK: UInt32 { UInt32(bitPattern: SF_NOUNLINK) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on Darwin Only
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_COMPRESSED: UInt32 { UInt32(bitPattern: UF_COMPRESSED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_TRACKED: UInt32 { UInt32(bitPattern: UF_TRACKED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_DATAVAULT: UInt32 { UInt32(bitPattern: UF_DATAVAULT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_RESTRICTED: UInt32 { UInt32(bitPattern: SF_RESTRICTED) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_FIRMLINK: UInt32 { UInt32(bitPattern: SF_FIRMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_DATALESS: UInt32 { UInt32(bitPattern: SF_DATALESS) }
|
||||
#endif
|
||||
|
||||
// MARK: Flags Available on FreeBSD Only
|
||||
|
||||
#if os(FreeBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_NOUNLINK: UInt32 { UInt32(bitPattern: UF_NOUNLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_OFFLINE: UInt32 { UInt32(bitPattern: UF_OFFLINE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_READONLY: UInt32 { UInt32(bitPattern: UF_READONLY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_REPARSE: UInt32 { UInt32(bitPattern: UF_REPARSE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_SPARSE: UInt32 { UInt32(bitPattern: UF_SPARSE) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _UF_SYSTEM: UInt32 { UInt32(bitPattern: UF_SYSTEM) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) }
|
||||
#endif
|
||||
|
||||
#endif // !os(Windows)
|
||||
@@ -1,11 +1,11 @@
|
||||
/*
|
||||
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 - 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
|
||||
*/
|
||||
*/
|
||||
|
||||
// Internal wrappers and typedefs which help reduce #if littering in System's
|
||||
// code base.
|
||||
@@ -23,6 +23,11 @@ import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -58,6 +63,16 @@ internal var system_errno: CInt {
|
||||
get { Musl.errno }
|
||||
set { Musl.errno = newValue }
|
||||
}
|
||||
#elseif canImport(WASILibc)
|
||||
internal var system_errno: CInt {
|
||||
get { WASILibc.errno }
|
||||
set { WASILibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Android)
|
||||
internal var system_errno: CInt {
|
||||
get { Android.errno }
|
||||
set { Android.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: C stdlib decls
|
||||
@@ -68,9 +83,31 @@ internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>!
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
internal func system_strlen(_ s: UnsafePointer<Int8>) -> Int {
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@available(System 99, *)
|
||||
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
stat(p, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
internal func system_lstat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
lstat(p, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
|
||||
fstat(fd, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 {
|
||||
fstatat(fd, p, &s, flags)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Convention: `system_platform_foo` is a
|
||||
// platform-representation-abstracted wrapper around `foo`-like functionality.
|
||||
@@ -86,6 +123,16 @@ internal func system_platform_strlen(_ s: UnsafePointer<CInterop.PlatformChar>)
|
||||
#endif
|
||||
}
|
||||
|
||||
// memset for raw buffers
|
||||
// FIXME: Do we really not have something like this in the stdlib already?
|
||||
internal func system_memset(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
to byte: UInt8
|
||||
) {
|
||||
guard buffer.count > 0 else { return }
|
||||
memset(buffer.baseAddress!, CInt(byte), buffer.count)
|
||||
}
|
||||
|
||||
// Interop between String and platfrom string
|
||||
extension String {
|
||||
internal func _withPlatformString<Result>(
|
||||
@@ -112,7 +159,7 @@ extension String {
|
||||
return
|
||||
|
||||
#else
|
||||
self.init(validatingUTF8: platformString)
|
||||
self.init(validatingCString: platformString)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -136,6 +183,24 @@ 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 {
|
||||
fileprivate init() {}
|
||||
}
|
||||
private final class TLSStorage: @unchecked Sendable {
|
||||
var storage = [ObjectIdentifier: UnsafeMutableRawPointer]()
|
||||
}
|
||||
private let sharedTLSStorage = TLSStorage()
|
||||
|
||||
func pthread_setspecific(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) -> Int {
|
||||
sharedTLSStorage.storage[ObjectIdentifier(key)] = p
|
||||
return 0
|
||||
}
|
||||
|
||||
func pthread_getspecific(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
|
||||
sharedTLSStorage.storage[ObjectIdentifier(key)]
|
||||
}
|
||||
#else
|
||||
internal typealias _PlatformTLSKey = pthread_key_t
|
||||
#endif
|
||||
@@ -147,6 +212,8 @@ internal func makeTLSKey() -> _PlatformTLSKey {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
|
||||
return _PlatformTLSKey()
|
||||
#else
|
||||
var raw = pthread_key_t()
|
||||
guard 0 == pthread_key_create(&raw, nil) else {
|
||||
|
||||
@@ -19,9 +19,10 @@
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
internal struct Trace {
|
||||
internal struct Entry: Hashable {
|
||||
private var name: String
|
||||
private var arguments: [AnyHashable]
|
||||
internal struct Entry {
|
||||
|
||||
internal var name: String
|
||||
internal var arguments: [AnyHashable]
|
||||
|
||||
internal init(name: String, _ arguments: [AnyHashable]) {
|
||||
self.name = name
|
||||
@@ -62,7 +63,7 @@ internal class MockingDriver {
|
||||
|
||||
// Whether we should pretend to be Windows for syntactic operations
|
||||
// inside FilePath
|
||||
fileprivate var forceWindowsSyntaxForPaths = false
|
||||
fileprivate var forceWindowsSyntaxForPaths: Bool? = nil
|
||||
}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
@@ -109,8 +110,8 @@ private var contextualMockingEnabled: Bool {
|
||||
extension MockingDriver {
|
||||
internal static var enabled: Bool { mockingEnabled }
|
||||
|
||||
internal static var forceWindowsPaths: Bool {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
|
||||
internal static var forceWindowsPaths: Bool? {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +128,9 @@ internal var mockingEnabled: Bool {
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var forceWindowsPaths: Bool {
|
||||
internal var forceWindowsPaths: Bool? {
|
||||
#if !ENABLE_MOCKING
|
||||
return false
|
||||
return nil
|
||||
#else
|
||||
return MockingDriver.forceWindowsPaths
|
||||
#endif
|
||||
@@ -195,15 +196,11 @@ internal func _mockOffT(
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
// Force paths to be treated as Windows syntactically if `enabled` is
|
||||
// true.
|
||||
// true, and as POSIX syntactically if not.
|
||||
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
|
||||
#if ENABLE_MOCKING
|
||||
guard enabled else {
|
||||
body()
|
||||
return
|
||||
}
|
||||
MockingDriver.withMockingEnabled { driver in
|
||||
driver.forceWindowsSyntaxForPaths = true
|
||||
driver.forceWindowsSyntaxForPaths = enabled
|
||||
body()
|
||||
}
|
||||
#else
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// A copy-on-write fixed-size buffer of raw memory.
|
||||
internal struct _RawBuffer {
|
||||
internal var _storage: Storage?
|
||||
|
||||
internal init() {
|
||||
self._storage = nil
|
||||
}
|
||||
|
||||
internal init(minimumCapacity: Int) {
|
||||
if minimumCapacity > 0 {
|
||||
self._storage = Storage.create(minimumCapacity: minimumCapacity)
|
||||
} else {
|
||||
self._storage = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal var capacity: Int {
|
||||
_storage?.header ?? 0 // Note: not capacity!
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique() {
|
||||
guard _storage != nil else { return }
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique {
|
||||
_storage = _copy(capacity: capacity)
|
||||
}
|
||||
}
|
||||
|
||||
internal func _grow(desired: Int) -> Int {
|
||||
let next = Int(1.75 * Double(self.capacity))
|
||||
return Swift.max(next, desired)
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique(capacity: Int) {
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique || self.capacity < capacity {
|
||||
_storage = _copy(capacity: _grow(desired: capacity))
|
||||
}
|
||||
}
|
||||
|
||||
internal func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let storage = _storage else {
|
||||
return try body(UnsafeRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
return try storage.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func withUnsafeMutableBytes<R>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard _storage != nil else {
|
||||
return try body(UnsafeMutableRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
ensureUnique()
|
||||
return try _storage!.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeMutableRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal class Storage: ManagedBuffer<Int, UInt8> {
|
||||
internal static func create(minimumCapacity: Int) -> Storage {
|
||||
Storage.create(
|
||||
minimumCapacity: minimumCapacity,
|
||||
makingHeaderWith: {
|
||||
#if os(OpenBSD)
|
||||
minimumCapacity
|
||||
#else
|
||||
$0.capacity
|
||||
#endif
|
||||
}
|
||||
) as! Storage
|
||||
}
|
||||
}
|
||||
|
||||
internal func _copy(capacity: Int) -> Storage {
|
||||
let copy = Storage.create(minimumCapacity: capacity)
|
||||
copy.withUnsafeMutablePointers { dstlen, dst in
|
||||
self.withUnsafeBytes { src in
|
||||
guard src.count > 0 else { return }
|
||||
assert(src.count <= dstlen.pointee)
|
||||
UnsafeMutableRawPointer(dst)
|
||||
.copyMemory(
|
||||
from: src.baseAddress!,
|
||||
byteCount: Swift.min(src.count, dstlen.pointee))
|
||||
}
|
||||
}
|
||||
return copy
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -13,8 +13,13 @@ import Darwin
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import CSystem
|
||||
import WASILibc
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -56,7 +61,7 @@ internal func system_close(_ fd: Int32) -> Int32 {
|
||||
|
||||
// read
|
||||
internal func system_read(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
|
||||
@@ -66,7 +71,7 @@ internal func system_read(
|
||||
|
||||
// pread
|
||||
internal func system_pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
|
||||
@@ -94,7 +99,7 @@ internal func system_lseek(
|
||||
|
||||
// write
|
||||
internal func system_write(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
|
||||
@@ -104,7 +109,7 @@ internal func system_write(
|
||||
|
||||
// pwrite
|
||||
internal func system_pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
|
||||
@@ -120,6 +125,7 @@ internal func system_pwrite(
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
internal func system_dup(_ fd: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
@@ -133,8 +139,9 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
#endif
|
||||
return dup2(fd, fd2)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(WASI)
|
||||
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fds) }
|
||||
@@ -143,11 +150,122 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, length) }
|
||||
#endif
|
||||
return ftruncate(fd, length)
|
||||
}
|
||||
|
||||
internal func system_mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path: path, mode) }
|
||||
#endif
|
||||
return mkdir(path, mode)
|
||||
}
|
||||
|
||||
internal func system_rmdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(path: path) }
|
||||
#endif
|
||||
return rmdir(path)
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
internal let SYSTEM_CS_DARWIN_USER_TEMP_DIR = _CS_DARWIN_USER_TEMP_DIR
|
||||
|
||||
internal func system_confstr(
|
||||
_ name: CInt,
|
||||
_ buf: UnsafeMutablePointer<CInterop.PlatformChar>,
|
||||
_ len: Int
|
||||
) -> Int {
|
||||
return confstr(name, buf, len)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR
|
||||
#if os(WASI)
|
||||
internal let SYSTEM_DT_DIR = _getConst_DT_DIR()
|
||||
internal typealias system_dirent = _system_dirent
|
||||
#else
|
||||
internal let SYSTEM_DT_DIR = DT_DIR
|
||||
internal typealias system_dirent = dirent
|
||||
#endif
|
||||
#if os(Linux) || os(Android) || os(FreeBSD) || os(OpenBSD) || os(WASI)
|
||||
internal typealias system_DIRPtr = OpaquePointer
|
||||
#else
|
||||
internal typealias system_DIRPtr = UnsafeMutablePointer<DIR>
|
||||
#endif
|
||||
|
||||
internal func system_unlinkat(
|
||||
_ fd: CInt,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flag: CInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, path, flag) }
|
||||
#endif
|
||||
return unlinkat(fd, path, flag)
|
||||
}
|
||||
|
||||
internal func system_fdopendir(
|
||||
_ fd: CInt
|
||||
) -> system_DIRPtr? {
|
||||
return fdopendir(fd)
|
||||
}
|
||||
|
||||
internal func system_readdir(
|
||||
_ dir: system_DIRPtr
|
||||
) -> UnsafeMutablePointer<system_dirent>? {
|
||||
#if os(WASI)
|
||||
return _system_dirent_from_wasi_dirent(readdir(dir))
|
||||
#else
|
||||
return readdir(dir)
|
||||
#endif
|
||||
}
|
||||
|
||||
internal func system_rewinddir(
|
||||
_ dir: system_DIRPtr
|
||||
) {
|
||||
return rewinddir(dir)
|
||||
}
|
||||
|
||||
internal func system_closedir(
|
||||
_ dir: system_DIRPtr
|
||||
) -> CInt {
|
||||
return closedir(dir)
|
||||
}
|
||||
|
||||
internal func system_openat(
|
||||
_ fd: CInt,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ oflag: Int32
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
return openat(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(WASI) // WASI has no umask
|
||||
internal func system_umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
return umask(mode)
|
||||
}
|
||||
#endif
|
||||
|
||||
internal func system_getenv(
|
||||
_ name: UnsafePointer<CChar>
|
||||
) -> UnsafeMutablePointer<CChar>? {
|
||||
return getenv(name)
|
||||
}
|
||||
@@ -12,13 +12,45 @@
|
||||
import ucrt
|
||||
import WinSDK
|
||||
|
||||
fileprivate var _umask: CInterop.Mode = 0o22
|
||||
|
||||
@inline(__always)
|
||||
func umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
let oldMask = _umask
|
||||
_umask = mode
|
||||
return oldMask
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
|
||||
) -> CInt {
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
let decodedFlags = DecodedOpenFlags(oflag)
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: nil,
|
||||
bInheritHandle: decodedFlags.bInheritHandle
|
||||
)
|
||||
|
||||
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
|
||||
CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
DWORD(FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE),
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
nil)
|
||||
}), hFile != INVALID_HANDLE_VALUE else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -26,10 +58,41 @@ internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
// TODO(compnerd): Apply read/write permissions
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
let actualMode = mode & ~_umask
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
defer {
|
||||
pSD.deallocate()
|
||||
}
|
||||
|
||||
let decodedFlags = DecodedOpenFlags(oflag)
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: pSD,
|
||||
bInheritHandle: decodedFlags.bInheritHandle
|
||||
)
|
||||
|
||||
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
|
||||
CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
DWORD(FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE),
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
nil)
|
||||
}), hFile != INVALID_HANDLE_VALUE else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -58,12 +121,33 @@ internal func write(
|
||||
Int(_write(fd, buf, numericCast(nbyte)))
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func lseek(
|
||||
_ fd: Int32, _ off: off_t, _ whence: Int32
|
||||
) -> off_t {
|
||||
_lseek(fd, off, whence)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func dup(_ fd: Int32) -> Int32 {
|
||||
_dup(fd)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
// _dup2 returns 0 to indicate success.
|
||||
if _dup2(fd, fd2) == 0 {
|
||||
return fd2
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
@@ -74,8 +158,7 @@ internal func pread(
|
||||
|
||||
var nNumberOfBytesRead: DWORD = 0
|
||||
if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesRead)
|
||||
@@ -86,7 +169,7 @@ internal func pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
@@ -98,11 +181,482 @@ internal func pwrite(
|
||||
var nNumberOfBytesWritten: DWORD = 0
|
||||
if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten,
|
||||
&ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesWritten)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func pipe(
|
||||
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 4096
|
||||
) -> CInt {
|
||||
return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
let liDesiredLength = LARGE_INTEGER(QuadPart: LONGLONG(length))
|
||||
var liCurrentOffset = LARGE_INTEGER(QuadPart: 0)
|
||||
|
||||
// Save the current position and restore it when we're done
|
||||
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
|
||||
DWORD(FILE_CURRENT)) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
defer {
|
||||
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN));
|
||||
}
|
||||
|
||||
// Truncate (or extend) the file
|
||||
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN))
|
||||
|| !SetEndOfFile(hFile) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
let actualMode = mode & ~_umask
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode,
|
||||
for: .directory) else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
defer {
|
||||
pSD.deallocate()
|
||||
}
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: pSD,
|
||||
bInheritHandle: false
|
||||
)
|
||||
|
||||
guard (try? path.withCanonicalPathRepresentation({ path in CreateDirectoryW(path, &saAttrs) })) == true else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func rmdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
guard (try? path.withCanonicalPathRepresentation({ path in RemoveDirectoryW(path) })) == true else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
|
||||
switch Int32(errorCode) {
|
||||
case ERROR_SUCCESS:
|
||||
return 0
|
||||
case ERROR_INVALID_FUNCTION,
|
||||
ERROR_INVALID_ACCESS,
|
||||
ERROR_INVALID_DATA,
|
||||
ERROR_INVALID_PARAMETER,
|
||||
ERROR_NEGATIVE_SEEK:
|
||||
return EINVAL
|
||||
case ERROR_FILE_NOT_FOUND,
|
||||
ERROR_PATH_NOT_FOUND,
|
||||
ERROR_INVALID_DRIVE,
|
||||
ERROR_NO_MORE_FILES,
|
||||
ERROR_BAD_NETPATH,
|
||||
ERROR_BAD_NET_NAME,
|
||||
ERROR_BAD_PATHNAME,
|
||||
ERROR_FILENAME_EXCED_RANGE:
|
||||
return ENOENT
|
||||
case ERROR_TOO_MANY_OPEN_FILES:
|
||||
return EMFILE
|
||||
case ERROR_ACCESS_DENIED,
|
||||
ERROR_CURRENT_DIRECTORY,
|
||||
ERROR_LOCK_VIOLATION,
|
||||
ERROR_NETWORK_ACCESS_DENIED,
|
||||
ERROR_CANNOT_MAKE,
|
||||
ERROR_FAIL_I24,
|
||||
ERROR_DRIVE_LOCKED,
|
||||
ERROR_SEEK_ON_DEVICE,
|
||||
ERROR_NOT_LOCKED,
|
||||
ERROR_LOCK_FAILED,
|
||||
ERROR_WRITE_PROTECT...ERROR_SHARING_BUFFER_EXCEEDED:
|
||||
return EACCES
|
||||
case ERROR_INVALID_HANDLE,
|
||||
ERROR_INVALID_TARGET_HANDLE,
|
||||
ERROR_DIRECT_ACCESS_HANDLE:
|
||||
return EBADF
|
||||
case ERROR_ARENA_TRASHED,
|
||||
ERROR_NOT_ENOUGH_MEMORY,
|
||||
ERROR_INVALID_BLOCK,
|
||||
ERROR_NOT_ENOUGH_QUOTA:
|
||||
return ENOMEM
|
||||
case ERROR_BAD_ENVIRONMENT:
|
||||
return E2BIG
|
||||
case ERROR_BAD_FORMAT,
|
||||
ERROR_INVALID_STARTING_CODESEG...ERROR_INFLOOP_IN_RELOC_CHAIN:
|
||||
return ENOEXEC
|
||||
case ERROR_NOT_SAME_DEVICE:
|
||||
return EXDEV
|
||||
case ERROR_FILE_EXISTS,
|
||||
ERROR_ALREADY_EXISTS:
|
||||
return EEXIST
|
||||
case ERROR_NO_PROC_SLOTS,
|
||||
ERROR_MAX_THRDS_REACHED,
|
||||
ERROR_NESTING_NOT_ALLOWED:
|
||||
return EAGAIN
|
||||
case ERROR_BROKEN_PIPE:
|
||||
return EPIPE
|
||||
case ERROR_DISK_FULL:
|
||||
return ENOSPC
|
||||
case ERROR_WAIT_NO_CHILDREN,
|
||||
ERROR_CHILD_NOT_COMPLETE:
|
||||
return ECHILD
|
||||
case ERROR_DIR_NOT_EMPTY:
|
||||
return ENOTEMPTY
|
||||
case ERROR_NO_UNICODE_TRANSLATION:
|
||||
return EILSEQ
|
||||
default:
|
||||
return EINVAL
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func rightsFromModeBits(
|
||||
_ bits: Int,
|
||||
sticky: Bool = false,
|
||||
for fileOrDirectory: _FileOrDirectory
|
||||
) -> DWORD {
|
||||
var rights: DWORD = 0
|
||||
|
||||
if (bits & 0o4) != 0 {
|
||||
rights |= DWORD(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)
|
||||
if fileOrDirectory == .directory && !sticky {
|
||||
rights |= DWORD(FILE_DELETE_CHILD)
|
||||
}
|
||||
}
|
||||
if (bits & 0o1) != 0 {
|
||||
rights |= DWORD(FILE_EXECUTE
|
||||
| FILE_READ_ATTRIBUTES
|
||||
| STANDARD_RIGHTS_EXECUTE
|
||||
| SYNCHRONIZE)
|
||||
}
|
||||
|
||||
return rights
|
||||
}
|
||||
|
||||
fileprivate func getTokenInformation<T>(
|
||||
of: T.Type,
|
||||
hToken: HANDLE,
|
||||
ticTokenClass: TOKEN_INFORMATION_CLASS
|
||||
) -> UnsafePointer<T>? {
|
||||
var capacity = 1024
|
||||
for _ in 0..<2 {
|
||||
let buffer = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: capacity,
|
||||
alignment: MemoryLayout<T>.alignment
|
||||
)
|
||||
|
||||
var dwLength = DWORD(0)
|
||||
|
||||
if GetTokenInformation(hToken,
|
||||
ticTokenClass,
|
||||
buffer,
|
||||
DWORD(capacity),
|
||||
&dwLength) {
|
||||
return UnsafePointer(buffer.assumingMemoryBound(to: T.self))
|
||||
}
|
||||
|
||||
buffer.deallocate()
|
||||
|
||||
capacity = Int(dwLength)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
internal enum _FileOrDirectory {
|
||||
case file
|
||||
case directory
|
||||
}
|
||||
|
||||
/// Build a SECURITY_DESCRIPTOR from UNIX-style "mode" bits. This only
|
||||
/// takes account of the rwx and sticky bits; there's really nothing that
|
||||
/// we can do about setuid/setgid.
|
||||
internal func _createSecurityDescriptor(from mode: CInterop.Mode,
|
||||
for fileOrDirectory: _FileOrDirectory)
|
||||
-> PSECURITY_DESCRIPTOR? {
|
||||
let ownerPerm = (Int(mode) >> 6) & 0o7
|
||||
let groupPerm = (Int(mode) >> 3) & 0o7
|
||||
let otherPerm = Int(mode) & 0o7
|
||||
|
||||
let ownerRights = rightsFromModeBits(ownerPerm, for: fileOrDirectory)
|
||||
let groupRights = rightsFromModeBits(groupPerm,
|
||||
sticky: (mode & 0o1000) != 0,
|
||||
for: fileOrDirectory)
|
||||
let otherRights = rightsFromModeBits(otherPerm,
|
||||
sticky: (mode & 0o1000) != 0,
|
||||
for: fileOrDirectory)
|
||||
|
||||
// If group or other permissions are *more* permissive, then we need
|
||||
// some DENY ACEs as well to implement the expected semantics
|
||||
let ownerDenyRights = ((ownerRights ^ groupRights) & groupRights) |
|
||||
((ownerRights ^ otherRights) & otherRights)
|
||||
let groupDenyRights = (groupRights ^ otherRights) & otherRights
|
||||
|
||||
var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1))
|
||||
var everyone: PSID? = nil
|
||||
|
||||
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
|
||||
DWORD(SECURITY_WORLD_RID),
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
&everyone) else {
|
||||
return nil
|
||||
}
|
||||
guard let everyone = everyone else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
FreeSid(everyone)
|
||||
}
|
||||
|
||||
let hToken = GetCurrentThreadEffectiveToken()!
|
||||
|
||||
guard let pTokenUser = getTokenInformation(of: TOKEN_USER.self,
|
||||
hToken: hToken,
|
||||
ticTokenClass: TokenUser) else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
pTokenUser.deallocate()
|
||||
}
|
||||
|
||||
guard let pTokenPrimaryGroup = getTokenInformation(
|
||||
of: TOKEN_PRIMARY_GROUP.self,
|
||||
hToken: hToken,
|
||||
ticTokenClass: TokenPrimaryGroup
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
pTokenPrimaryGroup.deallocate()
|
||||
}
|
||||
|
||||
let user = pTokenUser.pointee.User.Sid!
|
||||
let group = pTokenPrimaryGroup.pointee.PrimaryGroup!
|
||||
|
||||
var eas = [
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: ownerRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_USER,
|
||||
ptstrName:
|
||||
user.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
),
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: groupRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
group.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
),
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: otherRights,
|
||||
grfAccessMode: GRANT_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
everyone.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
)
|
||||
]
|
||||
|
||||
if ownerDenyRights != 0 {
|
||||
eas.append(
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: ownerDenyRights,
|
||||
grfAccessMode: DENY_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_USER,
|
||||
ptstrName:
|
||||
user.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
if groupDenyRights != 0 {
|
||||
eas.append(
|
||||
EXPLICIT_ACCESS_W(
|
||||
grfAccessPermissions: groupDenyRights,
|
||||
grfAccessMode: DENY_ACCESS,
|
||||
grfInheritance: DWORD(NO_INHERITANCE),
|
||||
Trustee: TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
group.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var pACL: PACL? = nil
|
||||
guard SetEntriesInAclW(ULONG(eas.count),
|
||||
&eas,
|
||||
nil,
|
||||
&pACL) == ERROR_SUCCESS else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
LocalFree(pACL)
|
||||
}
|
||||
|
||||
// Create the security descriptor, making sure that inherited ACEs don't
|
||||
// take effect, since that wouldn't match the behaviour of mode bits.
|
||||
var descriptor = SECURITY_DESCRIPTOR()
|
||||
|
||||
guard InitializeSecurityDescriptor(&descriptor,
|
||||
DWORD(SECURITY_DESCRIPTOR_REVISION)) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard SetSecurityDescriptorControl(&descriptor,
|
||||
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED),
|
||||
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED))
|
||||
&& SetSecurityDescriptorOwner(&descriptor, user, false)
|
||||
&& SetSecurityDescriptorGroup(&descriptor, group, false)
|
||||
&& SetSecurityDescriptorDacl(&descriptor,
|
||||
true,
|
||||
pACL,
|
||||
false) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Make it self-contained (up to this point it uses pointers)
|
||||
var dwRelativeSize = DWORD(0)
|
||||
|
||||
guard !MakeSelfRelativeSD(&descriptor, nil, &dwRelativeSize)
|
||||
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let pDescriptor = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: Int(dwRelativeSize),
|
||||
alignment: MemoryLayout<SECURITY_DESCRIPTOR>.alignment
|
||||
).assumingMemoryBound(to: SECURITY_DESCRIPTOR.self)
|
||||
|
||||
guard MakeSelfRelativeSD(&descriptor, pDescriptor, &dwRelativeSize) else {
|
||||
pDescriptor.deallocate()
|
||||
return nil
|
||||
}
|
||||
|
||||
return UnsafeMutableRawPointer(pDescriptor)
|
||||
}
|
||||
|
||||
fileprivate struct DecodedOpenFlags {
|
||||
var dwDesiredAccess: DWORD
|
||||
var dwCreationDisposition: DWORD
|
||||
var bInheritHandle: WindowsBool
|
||||
var dwFlagsAndAttributes: DWORD
|
||||
|
||||
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)
|
||||
case _O_CREAT:
|
||||
dwCreationDisposition = DWORD(OPEN_ALWAYS)
|
||||
case _O_CREAT | _O_TRUNC:
|
||||
dwCreationDisposition = DWORD(CREATE_ALWAYS)
|
||||
case _O_TRUNC:
|
||||
dwCreationDisposition = DWORD(TRUNCATE_EXISTING)
|
||||
default:
|
||||
dwCreationDisposition = DWORD(OPEN_EXISTING)
|
||||
}
|
||||
|
||||
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
|
||||
// on Windows; in particular, _O_RDONLY is zero, which means we can't
|
||||
// test for it by AND-ing.
|
||||
dwDesiredAccess = 0
|
||||
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
|
||||
case _O_RDONLY:
|
||||
dwDesiredAccess |= DWORD(GENERIC_READ)
|
||||
case _O_WRONLY:
|
||||
dwDesiredAccess |= DWORD(GENERIC_WRITE)
|
||||
case _O_RDWR:
|
||||
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE)
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
bInheritHandle = WindowsBool((oflag & _O_NOINHERIT) == 0)
|
||||
|
||||
dwFlagsAndAttributes = 0
|
||||
if (oflag & _O_SEQUENTIAL) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN)
|
||||
}
|
||||
if (oflag & _O_RANDOM) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS)
|
||||
}
|
||||
if (oflag & _O_TEMPORARY) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE)
|
||||
}
|
||||
|
||||
if (oflag & _O_SHORT_LIVED) != 0 {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY)
|
||||
} else {
|
||||
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,377 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2022 - 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 SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
import Darwin.Mach
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
public protocol MachPortRight {}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
@inlinable
|
||||
internal func _machPrecondition(
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line,
|
||||
_ body: @autoclosure () -> kern_return_t
|
||||
) {
|
||||
let kr = body()
|
||||
let expected = KERN_SUCCESS
|
||||
precondition(kr == expected, file: file, line: line)
|
||||
}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
@frozen
|
||||
public enum Mach {
|
||||
@available(System 1.4.0, *)
|
||||
public struct Port<RightType: MachPortRight>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _name: mach_port_name_t
|
||||
|
||||
@usableFromInline
|
||||
internal var _context: mach_port_context_t
|
||||
|
||||
/// Transfer ownership of an existing unmanaged Mach port right into a
|
||||
/// `Mach.Port` by name.
|
||||
///
|
||||
/// This initializer traps if `name` is `MACH_PORT_NULL`, or if `name` is
|
||||
/// `MACH_PORT_DEAD` and the `RightType` is `Mach.ReceiveRight`.
|
||||
///
|
||||
/// If the type of the right does not match the `RightType` of the
|
||||
/// `Mach.Port` being constructed, behavior is undefined.
|
||||
///
|
||||
/// The underlying port right will be automatically deallocated at the
|
||||
/// end of the `Mach.Port` instance's lifetime.
|
||||
///
|
||||
/// This initializer makes a syscall to guard the right.
|
||||
public init(name: mach_port_name_t) {
|
||||
precondition(name != mach_port_name_t(MACH_PORT_NULL),
|
||||
"Mach.Port cannot be initialized with MACH_PORT_NULL")
|
||||
self._name = name
|
||||
|
||||
if RightType.self == ReceiveRight.self {
|
||||
precondition(
|
||||
_name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */,
|
||||
"Receive rights cannot be dead names"
|
||||
)
|
||||
|
||||
let secret = mach_port_context_t(arc4random())
|
||||
_machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0))
|
||||
self._context = secret
|
||||
}
|
||||
else {
|
||||
self._context = 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrow access to the port name in a block that can perform
|
||||
/// non-consuming operations.
|
||||
///
|
||||
/// Take care when using this function; many operations consume rights,
|
||||
/// and send-once rights are easily consumed.
|
||||
///
|
||||
/// If the right is consumed, behavior is undefined.
|
||||
///
|
||||
/// The body block may optionally return something, which will then be
|
||||
/// returned to the caller of withBorrowedName.
|
||||
@inlinable
|
||||
public func withBorrowedName<ReturnType>(
|
||||
body: (mach_port_name_t) -> ReturnType
|
||||
) -> ReturnType {
|
||||
return body(_name)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if RightType.self == ReceiveRight.self {
|
||||
precondition(
|
||||
_name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */,
|
||||
"Receive rights cannot be dead names"
|
||||
)
|
||||
_machPrecondition(
|
||||
mach_port_destruct(mach_task_self_, _name, 0, _context)
|
||||
)
|
||||
} else {
|
||||
assert(
|
||||
RightType.self == SendRight.self ||
|
||||
RightType.self == SendOnceRight.self
|
||||
)
|
||||
_machPrecondition(mach_port_deallocate(mach_task_self_, _name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Possible errors that can be thrown by Mach.Port operations.
|
||||
public enum PortRightError : Error {
|
||||
/// Returned when an operation cannot be completed, because the Mach
|
||||
/// port right has become a dead name. This is caused by deallocation of the
|
||||
/// receive right on the other end.
|
||||
case deadName
|
||||
}
|
||||
|
||||
/// The MachPortRight type used to manage a receive right.
|
||||
@frozen
|
||||
public struct ReceiveRight: MachPortRight {}
|
||||
|
||||
/// The MachPortRight type used to manage a send right.
|
||||
@frozen
|
||||
public struct SendRight: MachPortRight {}
|
||||
|
||||
/// The MachPortRight type used to manage a send-once right.
|
||||
///
|
||||
/// Send-once rights are the most restrictive type of Mach port rights.
|
||||
/// They cannot create other rights, and are consumed upon use.
|
||||
///
|
||||
/// Upon destruction a send-once notification will be sent to the
|
||||
/// receiving end.
|
||||
@frozen
|
||||
public struct SendOnceRight: MachPortRight {}
|
||||
}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
extension Mach.Port where RightType == Mach.ReceiveRight {
|
||||
/// Transfer ownership of an existing, unmanaged, but already guarded,
|
||||
/// Mach port right into a Mach.Port by name.
|
||||
///
|
||||
/// This initializer aborts if name is MACH_PORT_NULL.
|
||||
///
|
||||
/// If the type of the right does not match the type T of Mach.Port<T>
|
||||
/// being constructed, the behavior is undefined.
|
||||
///
|
||||
/// The underlying port right will be automatically deallocated when
|
||||
/// the Mach.Port object is destroyed.
|
||||
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")
|
||||
self._name = name
|
||||
self._context = context
|
||||
}
|
||||
|
||||
/// Allocate a new Mach port with a receive right, creating a
|
||||
/// Mach.Port<Mach.ReceiveRight> to manage it.
|
||||
///
|
||||
/// This initializer will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public init() {
|
||||
var storage: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
|
||||
_machPrecondition(
|
||||
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &storage)
|
||||
)
|
||||
|
||||
// name-only init will guard ReceiveRights
|
||||
self.init(name: storage)
|
||||
}
|
||||
|
||||
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
/// Returns a tuple containing the Mach port name representing the right,
|
||||
/// and the context value used to guard the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// 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) {
|
||||
let destructured = (name: _name, context: _context)
|
||||
discard self
|
||||
return destructured
|
||||
}
|
||||
|
||||
/// Remove guard and transfer ownership of the underlying port right to
|
||||
/// the caller.
|
||||
///
|
||||
/// Returns the Mach port name representing the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
///
|
||||
/// This function makes a syscall to remove the guard from
|
||||
/// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract
|
||||
/// the context value along with the port name.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public consuming func unguardAndRelinquish() -> mach_port_name_t {
|
||||
let (name, context) = self.relinquish()
|
||||
_machPrecondition(mach_port_unguard(mach_task_self_, name, context))
|
||||
return name
|
||||
}
|
||||
|
||||
/// Borrow access to the port name in a block that can perform
|
||||
/// non-consuming operations.
|
||||
///
|
||||
/// Take care when using this function; many operations consume rights.
|
||||
///
|
||||
/// If the right is consumed, behavior is undefined.
|
||||
///
|
||||
/// The body block may optionally return something, which will then be
|
||||
/// returned to the caller of withBorrowedName.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func withBorrowedName<ReturnType>(
|
||||
body: (mach_port_name_t, mach_port_context_t) -> ReturnType
|
||||
) -> ReturnType {
|
||||
return body(_name, _context)
|
||||
}
|
||||
|
||||
/// Create a send-once right for a given receive right.
|
||||
///
|
||||
/// This does not affect the makeSendCount of the receive right.
|
||||
///
|
||||
/// This function will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func makeSendOnceRight() -> Mach.Port<Mach.SendOnceRight> {
|
||||
// send once rights do not coalesce
|
||||
var newRight: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
|
||||
var newRightType: mach_port_type_t = MACH_PORT_TYPE_NONE
|
||||
|
||||
_machPrecondition(
|
||||
mach_port_extract_right(
|
||||
mach_task_self_,
|
||||
_name,
|
||||
mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE),
|
||||
&newRight,
|
||||
&newRightType
|
||||
)
|
||||
)
|
||||
|
||||
// The value of newRight is validated by the Mach.Port initializer
|
||||
precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE)
|
||||
|
||||
return Mach.Port(name: newRight)
|
||||
}
|
||||
|
||||
/// Create a send right for a given receive right.
|
||||
///
|
||||
/// This increments the makeSendCount of the receive right.
|
||||
///
|
||||
/// This function will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func makeSendRight() -> Mach.Port<Mach.SendRight> {
|
||||
let how = MACH_MSG_TYPE_MAKE_SEND
|
||||
|
||||
// name is the same because send and recv rights are coalesced
|
||||
_machPrecondition(
|
||||
mach_port_insert_right(
|
||||
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
|
||||
)
|
||||
)
|
||||
|
||||
return Mach.Port(name: _name)
|
||||
}
|
||||
|
||||
/// Access the make-send count.
|
||||
///
|
||||
/// Each get/set of this property makes a syscall.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public var makeSendCount: mach_port_mscount_t {
|
||||
get {
|
||||
var status: mach_port_status = mach_port_status()
|
||||
var size = mach_msg_type_number_t(
|
||||
MemoryLayout<mach_port_status>.size / MemoryLayout<natural_t>.size
|
||||
)
|
||||
|
||||
withUnsafeMutablePointer(to: &status) {
|
||||
[ _name = self._name ] in
|
||||
let status = UnsafeMutableBufferPointer(start: $0, count: 1)
|
||||
status.withMemoryRebound(to: integer_t.self) {
|
||||
let info = $0.baseAddress
|
||||
_machPrecondition(
|
||||
mach_port_get_attributes(
|
||||
mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, &size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return status.mps_mscount
|
||||
}
|
||||
|
||||
set {
|
||||
_machPrecondition(mach_port_set_mscount(mach_task_self_, _name, newValue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
extension Mach.Port where RightType == Mach.SendRight {
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
/// Returns the Mach port name representing the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
@inlinable
|
||||
public consuming func relinquish() -> mach_port_name_t {
|
||||
let name = _name
|
||||
discard self
|
||||
return name
|
||||
}
|
||||
|
||||
/// Create another send right from a given send right.
|
||||
///
|
||||
/// This does not affect the makeSendCount of the receive right.
|
||||
///
|
||||
/// If the send right being copied has become a dead name, meaning the
|
||||
/// receiving side has been deallocated, then copySendRight() will throw
|
||||
/// a Mach.PortRightError.deadName error.
|
||||
@inlinable
|
||||
@available(System 1.4.0, *)
|
||||
public func copySendRight() throws -> Mach.Port<Mach.SendRight> {
|
||||
let how = MACH_MSG_TYPE_COPY_SEND
|
||||
|
||||
// name is the same because send rights are coalesced
|
||||
let kr = mach_port_insert_right(
|
||||
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
|
||||
)
|
||||
if kr == KERN_INVALID_NAME || kr == KERN_INVALID_CAPABILITY {
|
||||
throw Mach.PortRightError.deadName
|
||||
}
|
||||
_machPrecondition(kr)
|
||||
|
||||
return Mach.Port(name: _name)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 1.4.0, *)
|
||||
extension Mach.Port where RightType == Mach.SendOnceRight {
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
/// Returns the Mach port name representing the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// 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
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
@@ -165,6 +165,7 @@ extension String {
|
||||
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension CInterop.PlatformChar {
|
||||
internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
#if os(Windows)
|
||||
@@ -174,6 +175,8 @@ extension CInterop.PlatformChar {
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
internal var _platformChar: CInterop.PlatformChar {
|
||||
#if os(Windows)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
/*
|
||||
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 - 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
|
||||
*/
|
||||
|
||||
// A platform-native character representation, currently used for file paths
|
||||
internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable {
|
||||
internal struct SystemChar:
|
||||
RawRepresentable, Sendable, Comparable, Hashable, Codable {
|
||||
internal typealias RawValue = CInterop.PlatformChar
|
||||
|
||||
internal var rawValue: RawValue
|
||||
@@ -61,7 +62,7 @@ extension SystemChar {
|
||||
// A platform-native string representation, currently for file paths
|
||||
//
|
||||
// Always null-terminated.
|
||||
internal struct SystemString {
|
||||
internal struct SystemString: Sendable {
|
||||
internal typealias Storage = [SystemChar]
|
||||
internal var nullTerminatedStorage: Storage
|
||||
}
|
||||
@@ -196,24 +197,20 @@ extension SystemString: Hashable, Codable {
|
||||
|
||||
extension SystemString {
|
||||
|
||||
// withSystemChars includes the null terminator
|
||||
internal func withSystemChars<T>(
|
||||
internal func withNullTerminatedSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try nullTerminatedStorage.withContiguousStorageIfAvailable(f)!
|
||||
try nullTerminatedStorage.withUnsafeBufferPointer(f)
|
||||
}
|
||||
|
||||
// withCodeUnits does not include the null terminator
|
||||
internal func withCodeUnits<T>(
|
||||
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
let count = length / MemoryLayout<CInterop.PlatformUnicodeEncoding.CodeUnit>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformUnicodeEncoding.CodeUnit.self,
|
||||
capacity: count
|
||||
) { pointer in
|
||||
try f(UnsafeBufferPointer(start: pointer, count: count))
|
||||
try withNullTerminatedSystemChars {
|
||||
try $0.withMemoryRebound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self) {
|
||||
assert($0.last == .zero)
|
||||
return try f(.init(start: $0.baseAddress, count: $0.count&-1))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,7 +226,9 @@ extension Slice where Base == SystemString {
|
||||
}
|
||||
|
||||
internal var string: String {
|
||||
withCodeUnits { String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) }
|
||||
withCodeUnits {
|
||||
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
|
||||
}
|
||||
}
|
||||
|
||||
internal func withPlatformString<T>(
|
||||
@@ -271,7 +270,11 @@ extension SystemString: ExpressibleByStringLiteral {
|
||||
}
|
||||
|
||||
extension SystemString: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
internal var string: String { String(decoding: self) }
|
||||
internal var string: String {
|
||||
self.withCodeUnits {
|
||||
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
|
||||
}
|
||||
}
|
||||
|
||||
internal var description: String { string }
|
||||
internal var debugDescription: String { description.debugDescription }
|
||||
@@ -310,7 +313,7 @@ extension SystemString {
|
||||
internal func withPlatformString<T>(
|
||||
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars { chars in
|
||||
try withNullTerminatedSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformChar.self,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
extension Array where Element == String {
|
||||
internal typealias CStr = UnsafePointer<CChar>?
|
||||
|
||||
/// Call `body` with a buffer of `UnsafePointer<CChar>?` values,
|
||||
/// suitable for passing to a C function that expects a C string array.
|
||||
/// The buffer is guaranteed to be followed by an extra storage slot
|
||||
/// containing a null pointer. (For C functions that expect an array
|
||||
/// terminated with a null pointer.)
|
||||
///
|
||||
/// This function is careful not to heap allocate memory unless there are
|
||||
/// too many strings, or if it needs to copy too much character data.
|
||||
internal func _withCStringArray<R>(
|
||||
_ body: (UnsafeBufferPointer<UnsafePointer<CChar>?>) throws -> R
|
||||
) rethrows -> R {
|
||||
if self.count == 0 {
|
||||
// Fast path: empty array.
|
||||
let p: CStr = nil
|
||||
return try Swift.withUnsafePointer(to: p) { array in
|
||||
try body(UnsafeBufferPointer(start: array, count: 0))
|
||||
}
|
||||
}
|
||||
#if SYSTEM_OS_BUILD // String._guts isn't accessible from SwiftPM or CMake
|
||||
if self.count == 1, self[0]._guts._isLargeZeroTerminatedContiguousUTF8 {
|
||||
// Fast path: Single fast string.
|
||||
let start = self[0]._guts._largeContiguousUTF8CodeUnits.baseAddress!
|
||||
var p: (CStr, CStr) = (
|
||||
UnsafeRawPointer(start).assumingMemoryBound(to: CChar.self),
|
||||
nil
|
||||
)
|
||||
return try Swift.withUnsafeBytes(of: &p) { buffer in
|
||||
let start = buffer.baseAddress!.assumingMemoryBound(to: CStr.self)
|
||||
return try body(UnsafeBufferPointer(start: start, count: 1))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// We need to create a buffer for the C array.
|
||||
return try _withStackBuffer(
|
||||
capacity: (self.count + 1) * MemoryLayout<CStr>.stride
|
||||
) { array in
|
||||
let array = array.bindMemory(to: CStr.self)
|
||||
// Calculate number of bytes we need for character storage
|
||||
let bytes = self.reduce(into: 0) { count, string in
|
||||
#if SYSTEM_OS_BUILD
|
||||
if string._guts._isLargeZeroTerminatedContiguousUTF8 { return }
|
||||
#endif
|
||||
count += string.utf8.count + 1 // Plus one for terminating NUL
|
||||
}
|
||||
#if SYSTEM_OS_BUILD
|
||||
if bytes == 0 {
|
||||
// Fast path: we only contain strings with stable null-terminated storage
|
||||
for i in self.indices {
|
||||
let string = self[i]
|
||||
precondition(string._guts._isLargeZeroTerminatedContiguousUTF8)
|
||||
let address = string._guts._largeContiguousUTF8CodeUnits.baseAddress!
|
||||
array[i] = UnsafeRawPointer(address).assumingMemoryBound(to: CChar.self)
|
||||
}
|
||||
array[self.count] = nil
|
||||
return try body(UnsafeBufferPointer(rebasing: array.dropLast()))
|
||||
}
|
||||
#endif
|
||||
return try _withStackBuffer(capacity: bytes) { chars in
|
||||
var chars = chars
|
||||
for i in self.indices {
|
||||
let (cstr, scratchUsed) = self[i]._getCStr(with: chars)
|
||||
array[i] = cstr.assumingMemoryBound(to: CChar.self)
|
||||
chars = .init(rebasing: chars[scratchUsed...])
|
||||
}
|
||||
array[self.count] = nil
|
||||
return try body(UnsafeBufferPointer(rebasing: array.dropLast()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
fileprivate func _getCStr(
|
||||
with scratch: UnsafeMutableRawBufferPointer
|
||||
) -> (cstr: UnsafeRawPointer, scratchUsed: Int) {
|
||||
#if SYSTEM_OS_BUILD
|
||||
if _guts._isLargeZeroTerminatedContiguousUTF8 {
|
||||
// This is a wonderful string, we can just use its storage address.
|
||||
let address = _guts._largeContiguousUTF8CodeUnits.baseAddress!
|
||||
return (UnsafeRawPointer(address), 0)
|
||||
}
|
||||
#endif
|
||||
let r: (UnsafeRawPointer, Int)? = self.utf8.withContiguousStorageIfAvailable { source in
|
||||
// This is a somewhat okay string -- we need to use memcpy.
|
||||
precondition(source.count <= scratch.count)
|
||||
let start = scratch.baseAddress!
|
||||
start.copyMemory(from: source.baseAddress!, byteCount: source.count)
|
||||
start.storeBytes(of: 0, toByteOffset: source.count, as: UInt8.self)
|
||||
return (UnsafeRawPointer(start), source.count + 1)
|
||||
}
|
||||
if let r = r { return r }
|
||||
|
||||
// What a horrible string; we need to copy individual bytes.
|
||||
precondition(self.utf8.count <= scratch.count)
|
||||
var c = 0
|
||||
for byte in self.utf8 {
|
||||
scratch[c] = byte
|
||||
c += 1
|
||||
}
|
||||
scratch[c] = 0
|
||||
c += 1
|
||||
return (UnsafeRawPointer(scratch.baseAddress!), c)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
/*
|
||||
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 - 2021 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Results in errno if i == -1
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
private func valueOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<I, Errno> {
|
||||
i == -1 ? .failure(Errno.current) : .success(i)
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
private func nothingOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(i).map { _ in () }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<I, Errno> {
|
||||
@@ -36,7 +36,7 @@ internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
} while true
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
internal func nothingOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<(), Errno> {
|
||||
@@ -127,3 +127,38 @@ extension MutableCollection where Element: Equatable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal func _withOptionalUnsafePointerOrNull<T, R>(
|
||||
to value: T?,
|
||||
_ body: (UnsafePointer<T>?) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let value = value else {
|
||||
return try body(nil)
|
||||
}
|
||||
return try withUnsafePointer(to: value, body)
|
||||
}
|
||||
|
||||
/// Calls `body` with a temporary buffer of the indicated size,
|
||||
/// possibly stack-allocated.
|
||||
internal func _withStackBuffer<R>(
|
||||
capacity: Int,
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
typealias StackStorage = (
|
||||
UInt64, UInt64, UInt64, UInt64,
|
||||
UInt64, UInt64, UInt64, UInt64,
|
||||
UInt64, UInt64, UInt64, UInt64,
|
||||
UInt64, UInt64, UInt64, UInt64
|
||||
)
|
||||
if capacity > MemoryLayout<StackStorage>.size {
|
||||
var buffer = _RawBuffer(minimumCapacity: capacity)
|
||||
return try buffer.withUnsafeMutableBytes { buffer in
|
||||
try body(.init(rebasing: buffer[..<capacity]))
|
||||
}
|
||||
} else {
|
||||
var storage: StackStorage = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
return try withUnsafeMutableBytes(of: &storage) { buffer in
|
||||
try body(.init(rebasing: buffer[..<capacity]))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,13 +52,13 @@ extension Slice where Element: Equatable {
|
||||
return self[...idx]
|
||||
}
|
||||
|
||||
// If `e` is present, eat up to first occurence of `e`
|
||||
// If `e` is present, eat up to first occurrence of `e`
|
||||
internal mutating func _eatUntil(_ e: Element) -> Slice? {
|
||||
guard let idx = self.firstIndex(of: e) else { return nil }
|
||||
return _eatUntil(idx)
|
||||
}
|
||||
|
||||
// If `e` is present, eat up to and through first occurence of `e`
|
||||
// If `e` is present, eat up to and through first occurrence of `e`
|
||||
internal mutating func _eatThrough(_ e: Element) -> Slice? {
|
||||
guard let idx = self.firstIndex(of: e) else { return nil }
|
||||
return _eatThrough(idx)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
extension String {
|
||||
internal init(
|
||||
_unsafeUninitializedCapacity capacity: Int,
|
||||
initializingUTF8With body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
|
||||
) rethrows {
|
||||
if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
|
||||
self = try String(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: body)
|
||||
return
|
||||
}
|
||||
|
||||
let array = try Array<UInt8>(
|
||||
unsafeUninitializedCapacity: capacity
|
||||
) { buffer, count in
|
||||
count = try body(buffer)
|
||||
}
|
||||
self = String(decoding: array, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// C interoperability types for socket operations
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
extension CInterop {
|
||||
/// Socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr`.
|
||||
public typealias SockAddr = sockaddr
|
||||
|
||||
/// Socket address length type.
|
||||
///
|
||||
/// The corresponding C type is `socklen_t`.
|
||||
public typealias SockLen = socklen_t
|
||||
|
||||
/// Socket address family type.
|
||||
///
|
||||
/// The corresponding C type is `sa_family_t`.
|
||||
public typealias SAFamily = sa_family_t
|
||||
|
||||
/// IPv4 socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr_in`.
|
||||
public typealias SockAddrIn = sockaddr_in
|
||||
|
||||
/// IPv4 address structure.
|
||||
///
|
||||
/// The corresponding C type is `in_addr`.
|
||||
public typealias InAddr = in_addr
|
||||
|
||||
/// IPv4 address type.
|
||||
///
|
||||
/// The corresponding C type is `in_addr_t`.
|
||||
public typealias InAddrT = in_addr_t
|
||||
|
||||
/// IPv6 address structure.
|
||||
///
|
||||
/// The corresponding C type is `in6_addr`.
|
||||
public typealias In6Addr = in6_addr
|
||||
|
||||
/// Port number type.
|
||||
///
|
||||
/// The corresponding C type is `in_port_t`.
|
||||
public typealias InPort = in_port_t
|
||||
|
||||
/// IPv6 socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr_in6`.
|
||||
public typealias SockAddrIn6 = sockaddr_in6
|
||||
|
||||
/// Unix domain socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr_un`.
|
||||
public typealias SockAddrUn = sockaddr_un
|
||||
|
||||
/// I/O vector structure for scatter/gather I/O.
|
||||
///
|
||||
/// The corresponding C type is `iovec`.
|
||||
public typealias IOVec = iovec
|
||||
|
||||
/// Message header structure for sendmsg/recvmsg.
|
||||
///
|
||||
/// The corresponding C type is `msghdr`.
|
||||
public typealias MsgHdr = msghdr
|
||||
|
||||
/// Control message header structure.
|
||||
///
|
||||
/// The corresponding C type is `cmsghdr`.
|
||||
public typealias CMsgHdr = cmsghdr
|
||||
|
||||
/// Address info structure for getaddrinfo.
|
||||
///
|
||||
/// The corresponding C type is `addrinfo`.
|
||||
public typealias AddrInfo = addrinfo
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Internal wrappers and typedefs for socket operations
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
// MARK: - errno access
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
internal var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Glibc)
|
||||
internal var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Musl)
|
||||
internal var system_errno: CInt {
|
||||
get { Musl.errno }
|
||||
set { Musl.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Android)
|
||||
internal var system_errno: CInt {
|
||||
get { Android.errno }
|
||||
set { Android.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - C stdlib functions
|
||||
|
||||
@usableFromInline
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
internal func system_memset(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
to byte: UInt8
|
||||
) {
|
||||
guard buffer.count > 0 else { return }
|
||||
memset(buffer.baseAddress!, CInt(byte), buffer.count)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Syscall mocking support for SystemSockets
|
||||
//
|
||||
// This mirrors the mocking infrastructure from SystemPackage for use in socket tests.
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
internal struct Trace {
|
||||
internal struct Entry {
|
||||
internal var name: String
|
||||
internal var arguments: [AnyHashable]
|
||||
|
||||
internal init(name: String, _ arguments: [AnyHashable]) {
|
||||
self.name = name
|
||||
self.arguments = arguments
|
||||
}
|
||||
}
|
||||
|
||||
private var entries: [Entry] = []
|
||||
private var firstEntry: Int = 0
|
||||
|
||||
internal var isEmpty: Bool { firstEntry >= entries.count }
|
||||
|
||||
internal mutating func dequeue() -> Entry? {
|
||||
guard !self.isEmpty else { return nil }
|
||||
defer { firstEntry += 1 }
|
||||
return entries[firstEntry]
|
||||
}
|
||||
|
||||
fileprivate mutating func add(_ e: Entry) {
|
||||
entries.append(e)
|
||||
}
|
||||
}
|
||||
|
||||
internal enum ForceErrno: Equatable {
|
||||
case none
|
||||
case always(errno: CInt)
|
||||
case counted(errno: CInt, count: Int)
|
||||
}
|
||||
|
||||
internal class MockingDriver {
|
||||
internal var trace = Trace()
|
||||
internal var forceErrno = ForceErrno.none
|
||||
}
|
||||
|
||||
// TLS support
|
||||
#if os(Windows)
|
||||
internal typealias _PlatformTLSKey = DWORD
|
||||
#else
|
||||
internal typealias _PlatformTLSKey = pthread_key_t
|
||||
#endif
|
||||
|
||||
private func makeTLSKey() -> _PlatformTLSKey {
|
||||
#if os(Windows)
|
||||
let raw: DWORD = FlsAlloc(nil)
|
||||
if raw == FLS_OUT_OF_INDEXES {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#else
|
||||
var raw = pthread_key_t()
|
||||
guard 0 == pthread_key_create(&raw, nil) else {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#endif
|
||||
}
|
||||
|
||||
private func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) {
|
||||
#if os(Windows)
|
||||
guard FlsSetValue(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
#else
|
||||
guard 0 == pthread_setspecific(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
|
||||
#if os(Windows)
|
||||
return FlsGetValue(key)
|
||||
#else
|
||||
return pthread_getspecific(key)
|
||||
#endif
|
||||
}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
|
||||
internal var currentMockingDriver: MockingDriver? {
|
||||
guard let rawPtr = getTLS(driverKey) else { return nil }
|
||||
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
internal static func withMockingEnabled(
|
||||
_ f: (MockingDriver) throws -> ()
|
||||
) rethrows {
|
||||
let priorMocking = currentMockingDriver
|
||||
let driver = MockingDriver()
|
||||
|
||||
defer {
|
||||
if let object = priorMocking {
|
||||
setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
|
||||
} else {
|
||||
setTLS(driverKey, nil)
|
||||
}
|
||||
_fixLifetime(driver)
|
||||
}
|
||||
|
||||
setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
|
||||
return try f(driver)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
private var contextualMockingEnabled: Bool {
|
||||
return currentMockingDriver != nil
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
internal static var enabled: Bool { mockingEnabled }
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
@inline(__always)
|
||||
internal var mockingEnabled: Bool {
|
||||
#if ENABLE_MOCKING
|
||||
return contextualMockingEnabled
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
private func originalSyscallName(_ function: String) -> String {
|
||||
precondition(function.starts(with: "system_"))
|
||||
return String(function.dropFirst("system_".count).prefix { $0 != "(" })
|
||||
}
|
||||
|
||||
private func mockImpl(
|
||||
name: String,
|
||||
_ args: [AnyHashable]
|
||||
) -> CInt {
|
||||
precondition(mockingEnabled)
|
||||
let origName = originalSyscallName(name)
|
||||
guard let driver = currentMockingDriver else {
|
||||
fatalError("Mocking requested from non-mocking context")
|
||||
}
|
||||
driver.trace.add(Trace.Entry(name: origName, args))
|
||||
|
||||
switch driver.forceErrno {
|
||||
case .none: break
|
||||
case .always(let e):
|
||||
system_errno = e
|
||||
return -1
|
||||
case .counted(let e, let count):
|
||||
assert(count >= 1)
|
||||
system_errno = e
|
||||
driver.forceErrno = count > 1 ? .counted(errno: e, count: count - 1) : .none
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
internal func _mock(
|
||||
name: String = #function, _ args: AnyHashable...
|
||||
) -> CInt {
|
||||
return mockImpl(name: name, args)
|
||||
}
|
||||
|
||||
internal func _mockInt(
|
||||
name: String = #function, _ args: AnyHashable...
|
||||
) -> Int {
|
||||
Int(mockImpl(name: name, args))
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
// A copy-on-write fixed-size buffer of raw memory.
|
||||
internal struct _RawBuffer {
|
||||
internal var _storage: Storage?
|
||||
|
||||
internal init() {
|
||||
self._storage = nil
|
||||
}
|
||||
|
||||
internal init(minimumCapacity: Int) {
|
||||
if minimumCapacity > 0 {
|
||||
self._storage = Storage.create(minimumCapacity: minimumCapacity)
|
||||
} else {
|
||||
self._storage = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal var capacity: Int {
|
||||
_storage?.header ?? 0 // Note: not capacity!
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique() {
|
||||
guard _storage != nil else { return }
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique {
|
||||
_storage = _copy(capacity: capacity)
|
||||
}
|
||||
}
|
||||
|
||||
internal func _grow(desired: Int) -> Int {
|
||||
let next = Int(1.75 * Double(self.capacity))
|
||||
return Swift.max(next, desired)
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique(capacity: Int) {
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique || self.capacity < capacity {
|
||||
_storage = _copy(capacity: _grow(desired: capacity))
|
||||
}
|
||||
}
|
||||
|
||||
internal func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let storage = _storage else {
|
||||
return try body(UnsafeRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
return try storage.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func withUnsafeMutableBytes<R>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard _storage != nil else {
|
||||
return try body(UnsafeMutableRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
ensureUnique()
|
||||
return try _storage!.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeMutableRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal class Storage: ManagedBuffer<Int, UInt8> {
|
||||
internal static func create(minimumCapacity: Int) -> Storage {
|
||||
Storage.create(
|
||||
minimumCapacity: minimumCapacity,
|
||||
makingHeaderWith: { $0.capacity }
|
||||
) as! Storage
|
||||
}
|
||||
}
|
||||
|
||||
internal func _copy(capacity: Int) -> Storage {
|
||||
let copy = Storage.create(minimumCapacity: capacity)
|
||||
copy.withUnsafeMutablePointers { dstlen, dst in
|
||||
self.withUnsafeBytes { src in
|
||||
guard src.count > 0 else { return }
|
||||
assert(src.count <= dstlen.pointee)
|
||||
UnsafeMutableRawPointer(dst)
|
||||
.copyMemory(
|
||||
from: src.baseAddress!,
|
||||
byteCount: Swift.min(src.count, dstlen.pointee))
|
||||
}
|
||||
}
|
||||
return copy
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// System call wrappers for socket operations
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
// MARK: - Socket creation and management
|
||||
|
||||
internal func system_socket(_ domain: CInt, _ type: CInt, _ protocol: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(domain, type, `protocol`) }
|
||||
#endif
|
||||
return socket(domain, type, `protocol`)
|
||||
}
|
||||
|
||||
internal func system_shutdown(_ socket: CInt, _ how: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, how) }
|
||||
#endif
|
||||
return shutdown(socket, how)
|
||||
}
|
||||
|
||||
internal func system_close(_ fd: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
#endif
|
||||
return close(fd)
|
||||
}
|
||||
|
||||
// MARK: - Connection operations
|
||||
|
||||
internal func system_bind(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafePointer<sockaddr>?,
|
||||
_ len: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return bind(socket, addr, len)
|
||||
}
|
||||
|
||||
internal func system_listen(_ socket: CInt, _ backlog: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, backlog) }
|
||||
#endif
|
||||
return listen(socket, backlog)
|
||||
}
|
||||
|
||||
internal func system_accept(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafeMutablePointer<sockaddr>?,
|
||||
_ len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return accept(socket, addr, len)
|
||||
}
|
||||
|
||||
internal func system_connect(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafePointer<sockaddr>?,
|
||||
_ len: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return connect(socket, addr, len)
|
||||
}
|
||||
|
||||
// MARK: - Data transfer
|
||||
|
||||
internal func system_send(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeRawPointer?,
|
||||
_ len: Int,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, buffer, len, flags) }
|
||||
#endif
|
||||
return send(socket, buffer, len, flags)
|
||||
}
|
||||
|
||||
internal func system_recv(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeMutableRawPointer?,
|
||||
_ len: Int,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, buffer, len, flags) }
|
||||
#endif
|
||||
return recv(socket, buffer, len, flags)
|
||||
}
|
||||
|
||||
internal func system_sendto(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeRawPointer?,
|
||||
_ length: Int,
|
||||
_ flags: CInt,
|
||||
_ dest_addr: UnsafePointer<sockaddr>?,
|
||||
_ dest_len: socklen_t
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mockInt(socket, buffer, length, flags, dest_addr, dest_len)
|
||||
}
|
||||
#endif
|
||||
return sendto(socket, buffer, length, flags, dest_addr, dest_len)
|
||||
}
|
||||
|
||||
internal func system_recvfrom(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeMutableRawPointer?,
|
||||
_ length: Int,
|
||||
_ flags: CInt,
|
||||
_ address: UnsafeMutablePointer<sockaddr>?,
|
||||
_ address_len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mockInt(socket, buffer, length, flags, address, address_len)
|
||||
}
|
||||
#endif
|
||||
return recvfrom(socket, buffer, length, flags, address, address_len)
|
||||
}
|
||||
|
||||
internal func system_sendmsg(
|
||||
_ socket: CInt,
|
||||
_ message: UnsafePointer<msghdr>?,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, message, flags) }
|
||||
#endif
|
||||
return sendmsg(socket, message, flags)
|
||||
}
|
||||
|
||||
internal func system_recvmsg(
|
||||
_ socket: CInt,
|
||||
_ message: UnsafeMutablePointer<msghdr>?,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, message, flags) }
|
||||
#endif
|
||||
return recvmsg(socket, message, flags)
|
||||
}
|
||||
|
||||
// MARK: - Socket options
|
||||
|
||||
internal func system_getsockopt(
|
||||
_ socket: CInt,
|
||||
_ level: CInt,
|
||||
_ option: CInt,
|
||||
_ value: UnsafeMutableRawPointer?,
|
||||
_ length: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, level, option, value, length) }
|
||||
#endif
|
||||
return getsockopt(socket, level, option, value, length)
|
||||
}
|
||||
|
||||
internal func system_setsockopt(
|
||||
_ socket: CInt,
|
||||
_ level: CInt,
|
||||
_ option: CInt,
|
||||
_ value: UnsafeRawPointer?,
|
||||
_ length: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, level, option, value, length) }
|
||||
#endif
|
||||
return setsockopt(socket, level, option, value, length)
|
||||
}
|
||||
|
||||
internal func system_getsockname(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafeMutablePointer<sockaddr>?,
|
||||
_ len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return getsockname(socket, addr, len)
|
||||
}
|
||||
|
||||
internal func system_getpeername(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafeMutablePointer<sockaddr>?,
|
||||
_ len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return getpeername(socket, addr, len)
|
||||
}
|
||||
|
||||
// MARK: - Address conversion
|
||||
|
||||
@usableFromInline
|
||||
internal func system_inet_ntop(
|
||||
_ af: CInt,
|
||||
_ src: UnsafeRawPointer,
|
||||
_ dst: UnsafeMutablePointer<CChar>,
|
||||
_ size: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(af, src, dst, size) }
|
||||
#endif
|
||||
let res = inet_ntop(af, src, dst, size)
|
||||
if Int(bitPattern: res) == 0 { return -1 }
|
||||
return 0
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func system_inet_pton(
|
||||
_ af: CInt,
|
||||
_ src: UnsafePointer<CChar>,
|
||||
_ dst: UnsafeMutableRawPointer
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(af, src, dst) }
|
||||
#endif
|
||||
return inet_pton(af, src, dst)
|
||||
}
|
||||
|
||||
// MARK: - Name resolution
|
||||
|
||||
internal func system_getaddrinfo(
|
||||
_ hostname: UnsafePointer<CChar>?,
|
||||
_ servname: UnsafePointer<CChar>?,
|
||||
_ hints: UnsafePointer<addrinfo>?,
|
||||
_ res: UnsafeMutablePointer<UnsafeMutablePointer<addrinfo>?>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(
|
||||
hostname.map { String(cString: $0) },
|
||||
servname.map { String(cString: $0) },
|
||||
hints,
|
||||
res
|
||||
)
|
||||
}
|
||||
#endif
|
||||
return getaddrinfo(hostname, servname, hints, res)
|
||||
}
|
||||
|
||||
internal func system_getnameinfo(
|
||||
_ sa: UnsafePointer<sockaddr>?,
|
||||
_ salen: socklen_t,
|
||||
_ host: UnsafeMutablePointer<CChar>?,
|
||||
_ hostlen: socklen_t,
|
||||
_ serv: UnsafeMutablePointer<CChar>?,
|
||||
_ servlen: socklen_t,
|
||||
_ flags: CInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(sa, salen, host, hostlen, serv, servlen, flags)
|
||||
}
|
||||
#endif
|
||||
return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
|
||||
}
|
||||
|
||||
internal func system_freeaddrinfo(
|
||||
_ addrinfo: UnsafeMutablePointer<addrinfo>?
|
||||
) {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
_ = _mock(addrinfo)
|
||||
return
|
||||
}
|
||||
#endif
|
||||
freeaddrinfo(addrinfo)
|
||||
}
|
||||
|
||||
internal func system_gai_strerror(_ error: CInt) -> UnsafePointer<CChar> {
|
||||
gai_strerror(error)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
extension FixedWidthInteger {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
internal var _networkOrder: Self {
|
||||
bigEndian
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
internal init(_networkOrder value: Self) {
|
||||
self.init(bigEndian: value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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 SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
@frozen
|
||||
/// The address family identifier
|
||||
public struct Family: RawRepresentable, Hashable {
|
||||
public let rawValue: CInterop.SAFamily
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.SAFamily) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ rawValue: CInterop.SAFamily) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Unspecified address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_UNSPEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var unspecified: Family { Family(CInterop.SAFamily(AF_UNSPEC)) }
|
||||
|
||||
/// Local address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_LOCAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var local: Family { Family(CInterop.SAFamily(AF_LOCAL)) }
|
||||
|
||||
/// UNIX address family. (Renamed `local`.)
|
||||
///
|
||||
/// The corresponding C constant is `AF_UNIX`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "local")
|
||||
public static var unix: Family { Family(CInterop.SAFamily(AF_UNIX)) }
|
||||
|
||||
/// IPv4 address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_INET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: Family { Family(CInterop.SAFamily(AF_INET)) }
|
||||
|
||||
/// Internal routing address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_ROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var routing: Family { Family(CInterop.SAFamily(AF_ROUTE)) }
|
||||
|
||||
/// IPv6 address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_INET6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: Family { Family(CInterop.SAFamily(AF_INET6)) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// System address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_SYSTEM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var system: Family { Family(CInterop.SAFamily(AF_SYSTEM)) }
|
||||
|
||||
/// Raw network device address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_NDRV`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var networkDevice: Family { Family(CInterop.SAFamily(AF_NDRV)) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress.Family: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .unspecified: return "unspecified"
|
||||
case .local: return "local"
|
||||
case .ipv4: return "ipv4"
|
||||
case .routing: return "routing"
|
||||
case .ipv6: return "ipv6"
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
case .system: return "system"
|
||||
case .networkDevice: return "networkDevice"
|
||||
#endif
|
||||
default:
|
||||
return rawValue.description
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// An IPv4 socket address.
|
||||
///
|
||||
/// An IPv4 address consists of a 32-bit IP address and a 16-bit port number.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct IPv4Address: Sendable, Equatable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_in
|
||||
|
||||
/// Creates an IPv4 address from a raw sockaddr_in.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ sockaddr: sockaddr_in) {
|
||||
_storage = sockaddr
|
||||
}
|
||||
|
||||
/// Creates an IPv4 address from an address string and port.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - address: The IPv4 address string (e.g., "127.0.0.1").
|
||||
/// - port: The port number in host byte order.
|
||||
/// - Returns: `nil` if the address string is invalid.
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(_ address: String, port: UInt16) {
|
||||
var addr = sockaddr_in()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
#endif
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_port = port.bigEndian
|
||||
|
||||
let result = address.withCString { cString in
|
||||
system_inet_pton(AF_INET, cString, &addr.sin_addr)
|
||||
}
|
||||
|
||||
guard result == 1 else { return nil }
|
||||
_storage = addr
|
||||
}
|
||||
|
||||
/// Creates an IPv4 address representing any address (0.0.0.0).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func any(port: UInt16) -> IPv4Address {
|
||||
var addr = sockaddr_in()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
#endif
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_port = port.bigEndian
|
||||
addr.sin_addr.s_addr = INADDR_ANY.bigEndian
|
||||
return IPv4Address(addr)
|
||||
}
|
||||
|
||||
/// Creates an IPv4 address representing the loopback address (127.0.0.1).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func loopback(port: UInt16) -> IPv4Address {
|
||||
var addr = sockaddr_in()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
#endif
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_port = port.bigEndian
|
||||
addr.sin_addr.s_addr = INADDR_LOOPBACK.bigEndian
|
||||
return IPv4Address(addr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv4Address {
|
||||
/// The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public var port: UInt16 {
|
||||
UInt16(bigEndian: _storage.sin_port)
|
||||
}
|
||||
|
||||
/// The IP address as a string.
|
||||
public var addressString: String {
|
||||
var buffer = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
|
||||
var addr = _storage.sin_addr
|
||||
_ = Swift.withUnsafePointer(to: &addr) { ptr in
|
||||
system_inet_ntop(AF_INET, ptr, &buffer, socklen_t(buffer.count))
|
||||
}
|
||||
return String(cString: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv4Address {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, CInterop.SockLen(MemoryLayout<sockaddr_in>.size))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv4Address: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"\(addressString):\(port)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringLiteral
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv4Address: ExpressibleByStringLiteral {
|
||||
/// Creates an IPv4 address from a string literal.
|
||||
///
|
||||
/// The format is "address:port" (e.g., "127.0.0.1:8080").
|
||||
/// If no port is specified, port 0 is used.
|
||||
public init(stringLiteral value: String) {
|
||||
let parts = value.split(separator: ":", maxSplits: 1)
|
||||
let address = String(parts[0])
|
||||
let port: UInt16 = parts.count > 1 ? UInt16(parts[1]) ?? 0 : 0
|
||||
|
||||
guard let addr = IPv4Address(address, port: port) else {
|
||||
fatalError("Invalid IPv4 address literal: \(value)")
|
||||
}
|
||||
self = addr
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv4Address {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: IPv4Address, rhs: IPv4Address) -> Bool {
|
||||
lhs._storage.sin_family == rhs._storage.sin_family &&
|
||||
lhs._storage.sin_port == rhs._storage.sin_port &&
|
||||
lhs._storage.sin_addr.s_addr == rhs._storage.sin_addr.s_addr
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_storage.sin_family)
|
||||
hasher.combine(_storage.sin_port)
|
||||
hasher.combine(_storage.sin_addr.s_addr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from an IPv4 address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(ipv4: IPv4Address) {
|
||||
self.init()
|
||||
ipv4.withUnsafePointer { addr, len in
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
|
||||
}
|
||||
_length = len
|
||||
}
|
||||
}
|
||||
|
||||
/// The address as an IPv4 address, if applicable.
|
||||
@_alwaysEmitIntoClient
|
||||
public var ipv4: IPv4Address? {
|
||||
guard family == .ipv4 else { return nil }
|
||||
return Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
buffer.baseAddress!.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { ptr in
|
||||
IPv4Address(ptr.pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// An IPv6 socket address.
|
||||
///
|
||||
/// 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, *)
|
||||
public struct IPv6Address: Sendable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_in6
|
||||
|
||||
/// Creates an IPv6 address from a raw sockaddr_in6.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ sockaddr: sockaddr_in6) {
|
||||
_storage = sockaddr
|
||||
}
|
||||
|
||||
/// Creates an IPv6 address from an address string and port.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - address: The IPv6 address string (e.g., "::1" or "2001:db8::1").
|
||||
/// - port: The port number in host byte order.
|
||||
/// - Returns: `nil` if the address string is invalid.
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(_ address: String, port: UInt16) {
|
||||
var addr = sockaddr_in6()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
|
||||
#endif
|
||||
addr.sin6_family = sa_family_t(AF_INET6)
|
||||
addr.sin6_port = port.bigEndian
|
||||
|
||||
let result = address.withCString { cString in
|
||||
system_inet_pton(AF_INET6, cString, &addr.sin6_addr)
|
||||
}
|
||||
|
||||
guard result == 1 else { return nil }
|
||||
_storage = addr
|
||||
}
|
||||
|
||||
/// Creates an IPv6 address representing any address (::).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func any(port: UInt16) -> IPv6Address {
|
||||
var addr = sockaddr_in6()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
|
||||
#endif
|
||||
addr.sin6_family = sa_family_t(AF_INET6)
|
||||
addr.sin6_port = port.bigEndian
|
||||
addr.sin6_addr = in6addr_any
|
||||
return IPv6Address(addr)
|
||||
}
|
||||
|
||||
/// Creates an IPv6 address representing the loopback address (::1).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func loopback(port: UInt16) -> IPv6Address {
|
||||
var addr = sockaddr_in6()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
|
||||
#endif
|
||||
addr.sin6_family = sa_family_t(AF_INET6)
|
||||
addr.sin6_port = port.bigEndian
|
||||
addr.sin6_addr = in6addr_loopback
|
||||
return IPv6Address(addr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv6Address {
|
||||
/// The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public var port: UInt16 {
|
||||
UInt16(bigEndian: _storage.sin6_port)
|
||||
}
|
||||
|
||||
/// The flow label.
|
||||
@_alwaysEmitIntoClient
|
||||
public var flowLabel: UInt32 {
|
||||
_storage.sin6_flowinfo
|
||||
}
|
||||
|
||||
/// The scope ID.
|
||||
@_alwaysEmitIntoClient
|
||||
public var scopeID: UInt32 {
|
||||
_storage.sin6_scope_id
|
||||
}
|
||||
|
||||
/// The IP address as a string.
|
||||
public var addressString: String {
|
||||
var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
|
||||
var addr = _storage.sin6_addr
|
||||
_ = Swift.withUnsafePointer(to: &addr) { ptr in
|
||||
system_inet_ntop(AF_INET6, ptr, &buffer, socklen_t(buffer.count))
|
||||
}
|
||||
return String(cString: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv6Address {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, CInterop.SockLen(MemoryLayout<sockaddr_in6>.size))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv6Address: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"[\(addressString)]:\(port)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringLiteral
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv6Address: ExpressibleByStringLiteral {
|
||||
/// Creates an IPv6 address from a string literal.
|
||||
///
|
||||
/// The format is "[address]:port" (e.g., "[::1]:8080") or "address"
|
||||
/// for port 0.
|
||||
public init(stringLiteral value: String) {
|
||||
var address = value
|
||||
var port: UInt16 = 0
|
||||
|
||||
// Handle [address]:port format
|
||||
if value.hasPrefix("[") {
|
||||
if let closeBracket = value.lastIndex(of: "]") {
|
||||
address = String(value[value.index(after: value.startIndex)..<closeBracket])
|
||||
let afterBracket = value.index(after: closeBracket)
|
||||
if afterBracket < value.endIndex && value[afterBracket] == ":" {
|
||||
let portStart = value.index(after: afterBracket)
|
||||
if let p = UInt16(value[portStart...]) {
|
||||
port = p
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
guard let addr = IPv6Address(address, port: port) else {
|
||||
fatalError("Invalid IPv6 address literal: \(value)")
|
||||
}
|
||||
self = addr
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
extension IPv6Address {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: IPv6Address, rhs: IPv6Address) -> Bool {
|
||||
Swift.withUnsafeBytes(of: lhs._storage) { lhsBytes in
|
||||
Swift.withUnsafeBytes(of: rhs._storage) { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
Swift.withUnsafeBytes(of: _storage) { bytes in
|
||||
hasher.combine(bytes: bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from an IPv6 address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(ipv6: IPv6Address) {
|
||||
self.init()
|
||||
ipv6.withUnsafePointer { addr, len in
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
|
||||
}
|
||||
_length = len
|
||||
}
|
||||
}
|
||||
|
||||
/// The address as an IPv6 address, if applicable.
|
||||
@_alwaysEmitIntoClient
|
||||
public var ipv6: IPv6Address? {
|
||||
guard family == .ipv6 else { return nil }
|
||||
return Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
buffer.baseAddress!.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { ptr in
|
||||
IPv6Address(ptr.pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Address Resolution Error
|
||||
|
||||
/// An error returned by address resolution functions.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct AddressResolutionError: Error, Hashable, Sendable {
|
||||
/// The error code returned by getaddrinfo or getnameinfo.
|
||||
public let code: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(code: CInt) {
|
||||
self.code = code
|
||||
}
|
||||
|
||||
/// A human-readable error message.
|
||||
public var message: String {
|
||||
String(cString: system_gai_strerror(code))
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension AddressResolutionError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"AddressResolutionError(\(code)): \(message)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Resolution Hints
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Hints for address resolution.
|
||||
public struct ResolutionHints: Sendable {
|
||||
/// The protocol family to search for.
|
||||
public var family: SocketDescriptor.Domain?
|
||||
|
||||
/// The socket type to search for.
|
||||
public var socketType: SocketDescriptor.ConnectionType?
|
||||
|
||||
/// The protocol to search for.
|
||||
public var `protocol`: SocketDescriptor.ProtocolID?
|
||||
|
||||
/// Resolution flags.
|
||||
public var flags: ResolutionFlags
|
||||
|
||||
/// Creates resolution hints with the given parameters.
|
||||
public init(
|
||||
family: SocketDescriptor.Domain? = nil,
|
||||
socketType: SocketDescriptor.ConnectionType? = nil,
|
||||
protocol: SocketDescriptor.ProtocolID? = nil,
|
||||
flags: ResolutionFlags = []
|
||||
) {
|
||||
self.family = family
|
||||
self.socketType = socketType
|
||||
self.protocol = `protocol`
|
||||
self.flags = flags
|
||||
}
|
||||
}
|
||||
|
||||
/// Flags for address resolution.
|
||||
@frozen
|
||||
public struct ResolutionFlags: OptionSet, Sendable {
|
||||
public var rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Use passive socket for binding.
|
||||
///
|
||||
/// The corresponding C constant is `AI_PASSIVE`.
|
||||
public static var passive: ResolutionFlags { ResolutionFlags(rawValue: AI_PASSIVE) }
|
||||
|
||||
/// Return canonical name.
|
||||
///
|
||||
/// The corresponding C constant is `AI_CANONNAME`.
|
||||
public static var canonicalName: ResolutionFlags { ResolutionFlags(rawValue: AI_CANONNAME) }
|
||||
|
||||
/// Address must be numeric.
|
||||
///
|
||||
/// The corresponding C constant is `AI_NUMERICHOST`.
|
||||
public static var numericHost: ResolutionFlags { ResolutionFlags(rawValue: AI_NUMERICHOST) }
|
||||
|
||||
/// Service must be numeric.
|
||||
///
|
||||
/// The corresponding C constant is `AI_NUMERICSERV`.
|
||||
public static var numericService: ResolutionFlags { ResolutionFlags(rawValue: AI_NUMERICSERV) }
|
||||
|
||||
/// Return IPv4-mapped IPv6 addresses.
|
||||
///
|
||||
/// The corresponding C constant is `AI_V4MAPPED`.
|
||||
public static var v4Mapped: ResolutionFlags { ResolutionFlags(rawValue: AI_V4MAPPED) }
|
||||
|
||||
/// Return both IPv4 and IPv6 addresses.
|
||||
///
|
||||
/// The corresponding C constant is `AI_ALL`.
|
||||
public static var all: ResolutionFlags { ResolutionFlags(rawValue: AI_ALL) }
|
||||
|
||||
/// Return addresses only if configured.
|
||||
///
|
||||
/// The corresponding C constant is `AI_ADDRCONFIG`.
|
||||
public static var addressConfigured: ResolutionFlags { ResolutionFlags(rawValue: AI_ADDRCONFIG) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Resolution Result
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// A result from address resolution.
|
||||
public struct ResolvedAddress: Sendable {
|
||||
/// The socket domain.
|
||||
public let family: SocketDescriptor.Domain
|
||||
|
||||
/// The socket type.
|
||||
public let socketType: SocketDescriptor.ConnectionType
|
||||
|
||||
/// The socket protocol.
|
||||
public let `protocol`: SocketDescriptor.ProtocolID
|
||||
|
||||
/// The resolved socket address.
|
||||
public let address: SocketAddress
|
||||
|
||||
/// The canonical name, if requested and available.
|
||||
public let canonicalName: String?
|
||||
|
||||
internal init(
|
||||
family: SocketDescriptor.Domain,
|
||||
socketType: SocketDescriptor.ConnectionType,
|
||||
protocol: SocketDescriptor.ProtocolID,
|
||||
address: SocketAddress,
|
||||
canonicalName: String?
|
||||
) {
|
||||
self.family = family
|
||||
self.socketType = socketType
|
||||
self.protocol = `protocol`
|
||||
self.address = address
|
||||
self.canonicalName = canonicalName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Address Resolution
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Resolves a hostname and service to a list of socket addresses.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hostname: The hostname to resolve, or `nil` for the local host.
|
||||
/// - service: The service name or port number, or `nil`.
|
||||
/// - hints: Hints to narrow the search.
|
||||
/// - Returns: An array of resolved addresses.
|
||||
/// - Throws: `AddressResolutionError` if resolution fails.
|
||||
///
|
||||
/// The corresponding C function is `getaddrinfo`.
|
||||
public static func resolve(
|
||||
hostname: String? = nil,
|
||||
service: String? = nil,
|
||||
hints: ResolutionHints = ResolutionHints()
|
||||
) throws -> [ResolvedAddress] {
|
||||
var hintsStruct = addrinfo()
|
||||
hintsStruct.ai_flags = hints.flags.rawValue
|
||||
if let family = hints.family {
|
||||
hintsStruct.ai_family = family.rawValue
|
||||
}
|
||||
if let socketType = hints.socketType {
|
||||
hintsStruct.ai_socktype = socketType.rawValue
|
||||
}
|
||||
if let proto = hints.protocol {
|
||||
hintsStruct.ai_protocol = proto.rawValue
|
||||
}
|
||||
|
||||
var result: UnsafeMutablePointer<addrinfo>?
|
||||
|
||||
let errorCode: CInt = hostname._withOptionalCString { hostnamePtr in
|
||||
service._withOptionalCString { servicePtr in
|
||||
system_getaddrinfo(hostnamePtr, servicePtr, &hintsStruct, &result)
|
||||
}
|
||||
}
|
||||
|
||||
guard errorCode == 0 else {
|
||||
throw AddressResolutionError(code: errorCode)
|
||||
}
|
||||
|
||||
defer { system_freeaddrinfo(result) }
|
||||
|
||||
var addresses: [ResolvedAddress] = []
|
||||
var current = result
|
||||
|
||||
while let info = current {
|
||||
let family = SocketDescriptor.Domain(rawValue: info.pointee.ai_family)
|
||||
let socketType = SocketDescriptor.ConnectionType(rawValue: info.pointee.ai_socktype)
|
||||
let proto = SocketDescriptor.ProtocolID(rawValue: info.pointee.ai_protocol)
|
||||
|
||||
let address: SocketAddress
|
||||
if let addr = info.pointee.ai_addr {
|
||||
address = SocketAddress(
|
||||
address: addr,
|
||||
length: info.pointee.ai_addrlen
|
||||
)
|
||||
} else {
|
||||
address = SocketAddress()
|
||||
}
|
||||
|
||||
let canonicalName: String?
|
||||
if let name = info.pointee.ai_canonname {
|
||||
canonicalName = String(cString: name)
|
||||
} else {
|
||||
canonicalName = nil
|
||||
}
|
||||
|
||||
addresses.append(ResolvedAddress(
|
||||
family: family,
|
||||
socketType: socketType,
|
||||
protocol: proto,
|
||||
address: address,
|
||||
canonicalName: canonicalName
|
||||
))
|
||||
|
||||
current = info.pointee.ai_next
|
||||
}
|
||||
|
||||
return addresses
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Reverse Resolution
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Flags for reverse resolution.
|
||||
@frozen
|
||||
public struct ReverseResolutionFlags: OptionSet, Sendable {
|
||||
public var rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Return numeric host.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NUMERICHOST`.
|
||||
public static var numericHost: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NUMERICHOST) }
|
||||
|
||||
/// Return numeric service.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NUMERICSERV`.
|
||||
public static var numericService: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NUMERICSERV) }
|
||||
|
||||
/// Look up datagram service.
|
||||
///
|
||||
/// The corresponding C constant is `NI_DGRAM`.
|
||||
public static var datagram: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_DGRAM) }
|
||||
|
||||
/// Return only the hostname part of FQDN.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NOFQDN`.
|
||||
public static var noFullyQualified: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NOFQDN) }
|
||||
|
||||
/// Fail if name cannot be determined.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NAMEREQD`.
|
||||
public static var nameRequired: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NAMEREQD) }
|
||||
}
|
||||
|
||||
/// A result from reverse resolution.
|
||||
public struct ReverseLookupResult: Sendable {
|
||||
/// The hostname.
|
||||
public let hostname: String?
|
||||
|
||||
/// The service name.
|
||||
public let service: String?
|
||||
}
|
||||
|
||||
/// Resolves this address to a hostname and service.
|
||||
///
|
||||
/// - Parameter flags: Flags controlling the resolution.
|
||||
/// - Returns: The hostname and service.
|
||||
/// - Throws: `AddressResolutionError` if resolution fails.
|
||||
///
|
||||
/// The corresponding C function is `getnameinfo`.
|
||||
public func reverseLookup(
|
||||
flags: ReverseResolutionFlags = []
|
||||
) throws -> ReverseLookupResult {
|
||||
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
var service = [CChar](repeating: 0, count: Int(NI_MAXSERV))
|
||||
|
||||
let errorCode = withUnsafePointer { addr, len in
|
||||
system_getnameinfo(
|
||||
addr,
|
||||
len,
|
||||
&hostname,
|
||||
socklen_t(hostname.count),
|
||||
&service,
|
||||
socklen_t(service.count),
|
||||
flags.rawValue
|
||||
)
|
||||
}
|
||||
|
||||
guard errorCode == 0 else {
|
||||
throw AddressResolutionError(code: errorCode)
|
||||
}
|
||||
|
||||
let hostnameStr = hostname[0] != 0 ? String(cString: hostname) : nil
|
||||
let serviceStr = service[0] != 0 ? String(cString: service) : nil
|
||||
|
||||
return ReverseLookupResult(hostname: hostnameStr, service: serviceStr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
extension Optional where Wrapped == String {
|
||||
func _withOptionalCString<R>(_ body: (UnsafePointer<CChar>?) throws -> R) rethrows -> R {
|
||||
switch self {
|
||||
case .none:
|
||||
return try body(nil)
|
||||
case .some(let string):
|
||||
return try string.withCString(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// A Unix domain socket address.
|
||||
///
|
||||
/// Unix domain socket addresses use a filesystem path to identify the socket.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct UnixAddress: Sendable, Equatable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_un
|
||||
|
||||
/// The length of the path (not including null terminator).
|
||||
@usableFromInline
|
||||
internal var _pathLength: Int
|
||||
|
||||
/// Creates a Unix address from a raw sockaddr_un.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ sockaddr: sockaddr_un) {
|
||||
_storage = sockaddr
|
||||
// Calculate path length from the stored data
|
||||
_pathLength = withUnsafeBytes(of: sockaddr.sun_path) { bytes in
|
||||
bytes.prefix(while: { $0 != 0 }).count
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a Unix address from a path string.
|
||||
///
|
||||
/// - Parameter path: The filesystem path for the socket.
|
||||
/// - Returns: `nil` if the path is too long.
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(_ path: String) {
|
||||
var addr = sockaddr_un()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
|
||||
#endif
|
||||
addr.sun_family = sa_family_t(AF_UNIX)
|
||||
|
||||
let maxPathLength = MemoryLayout.size(ofValue: addr.sun_path) - 1 // Leave room for null
|
||||
|
||||
let copied = path.withCString { cString in
|
||||
let len = system_strlen(cString)
|
||||
guard len <= maxPathLength else { return -1 }
|
||||
|
||||
withUnsafeMutableBytes(of: &addr.sun_path) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: cString, count: len + 1))
|
||||
}
|
||||
return len
|
||||
}
|
||||
|
||||
guard copied >= 0 else { return nil }
|
||||
|
||||
_storage = addr
|
||||
_pathLength = copied
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
extension UnixAddress {
|
||||
/// The path as a string.
|
||||
public var path: String {
|
||||
withUnsafeBytes(of: _storage.sun_path) { bytes in
|
||||
let pathBytes = bytes.prefix(_pathLength)
|
||||
return pathBytes.withMemoryRebound(to: CChar.self) { chars in
|
||||
String(cString: chars.baseAddress!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 99, *)
|
||||
extension UnixAddress {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
// Length includes sun_family plus the path (including null terminator)
|
||||
let length = MemoryLayout<sa_family_t>.size + _pathLength + 1
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
let actualLength = MemoryLayout<UInt8>.size + length // Include sun_len
|
||||
#else
|
||||
let actualLength = length
|
||||
#endif
|
||||
return try body(sockaddr, CInterop.SockLen(actualLength))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
extension UnixAddress: CustomStringConvertible {
|
||||
public var description: String {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
extension UnixAddress {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: UnixAddress, rhs: UnixAddress) -> Bool {
|
||||
lhs._pathLength == rhs._pathLength &&
|
||||
Swift.withUnsafeBytes(of: lhs._storage.sun_path) { lhsBytes in
|
||||
Swift.withUnsafeBytes(of: rhs._storage.sun_path) { rhsBytes in
|
||||
lhsBytes.prefix(lhs._pathLength).elementsEqual(rhsBytes.prefix(rhs._pathLength))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_pathLength)
|
||||
Swift.withUnsafeBytes(of: _storage.sun_path) { bytes in
|
||||
hasher.combine(bytes: UnsafeRawBufferPointer(rebasing: bytes.prefix(_pathLength)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from a Unix address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(unix: UnixAddress) {
|
||||
self.init()
|
||||
unix.withUnsafePointer { addr, len in
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
|
||||
}
|
||||
_length = len
|
||||
}
|
||||
}
|
||||
|
||||
/// The address as a Unix address, if applicable.
|
||||
@_alwaysEmitIntoClient
|
||||
public var unix: UnixAddress? {
|
||||
guard family == .local else { return nil }
|
||||
return Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
buffer.baseAddress!.withMemoryRebound(to: sockaddr_un.self, capacity: 1) { ptr in
|
||||
UnixAddress(ptr.pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// An opaque type representing a socket address.
|
||||
///
|
||||
/// `SocketAddress` is a type-erased container that can hold any socket address,
|
||||
/// including IPv4, IPv6, and Unix domain addresses. It provides a unified
|
||||
/// interface for socket operations that work with different address families.
|
||||
///
|
||||
/// To create a socket address for a specific family, use one of the convenience
|
||||
/// initializers:
|
||||
///
|
||||
/// ```swift
|
||||
/// // IPv4 address
|
||||
/// let ipv4 = SocketAddress(ipv4: IPv4Address("127.0.0.1", port: 8080)!)
|
||||
///
|
||||
/// // IPv6 address
|
||||
/// let ipv6 = SocketAddress(ipv6: IPv6Address.loopback(port: 80))
|
||||
///
|
||||
/// // Unix domain socket
|
||||
/// let local = SocketAddress(unix: UnixAddress("/tmp/socket.sock")!)
|
||||
/// ```
|
||||
///
|
||||
/// `SocketAddress` uses `sockaddr_storage` internally, which is large enough
|
||||
/// to hold any socket address type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct SocketAddress: Sendable {
|
||||
/// The underlying storage using sockaddr_storage.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_storage
|
||||
|
||||
/// The actual length of the address data.
|
||||
@usableFromInline
|
||||
internal var _length: CInterop.SockLen
|
||||
|
||||
/// Creates an empty socket address with unspecified family.
|
||||
@_alwaysEmitIntoClient
|
||||
public init() {
|
||||
_storage = sockaddr_storage()
|
||||
_length = 0
|
||||
}
|
||||
|
||||
/// Creates a socket address from raw bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - address: Pointer to the socket address.
|
||||
/// - length: The length of the address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
address: UnsafePointer<CInterop.SockAddr>,
|
||||
length: CInterop.SockLen
|
||||
) {
|
||||
_storage = sockaddr_storage()
|
||||
_length = min(length, CInterop.SockLen(MemoryLayout<sockaddr_storage>.size))
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: address, count: Int(_length)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a socket address from a raw buffer.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ buffer: UnsafeRawBufferPointer) {
|
||||
_storage = sockaddr_storage()
|
||||
_length = CInterop.SockLen(min(buffer.count, MemoryLayout<sockaddr_storage>.size))
|
||||
if buffer.count > 0 {
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer.prefix(Int(_length))))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// The address family of this socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
public var family: SocketDescriptor.Domain {
|
||||
Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
let sockaddr = buffer.baseAddress!.assumingMemoryBound(to: sockaddr.self)
|
||||
return SocketDescriptor.Domain(rawValue: CInt(sockaddr.pointee.sa_family))
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of this socket address in bytes.
|
||||
@_alwaysEmitIntoClient
|
||||
public var length: Int {
|
||||
Int(_length)
|
||||
}
|
||||
|
||||
/// Whether this address is empty (length is 0).
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool {
|
||||
_length == 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Accessing Raw Bytes
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress {
|
||||
/// Calls the given closure with a pointer to the underlying socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, _length)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure with a mutable pointer to the underlying storage.
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func _withUnsafeMutablePointer<R>(
|
||||
_ body: (UnsafeMutablePointer<sockaddr>, inout CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
var len = CInterop.SockLen(MemoryLayout<sockaddr_storage>.size)
|
||||
let result = try Swift.withUnsafeMutablePointer(to: &_storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, &len)
|
||||
}
|
||||
}
|
||||
_length = len
|
||||
return result
|
||||
}
|
||||
|
||||
/// Accesses the raw bytes of the socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
try body(UnsafeRawBufferPointer(rebasing: buffer.prefix(Int(_length))))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets this address to an empty state.
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func clear() {
|
||||
_storage = sockaddr_storage()
|
||||
_length = 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: SocketAddress, rhs: SocketAddress) -> Bool {
|
||||
guard lhs._length == rhs._length else { return false }
|
||||
return lhs.withUnsafeBytes { lhsBytes in
|
||||
rhs.withUnsafeBytes { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_length)
|
||||
withUnsafeBytes { buffer in
|
||||
hasher.combine(bytes: buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketAddress: CustomStringConvertible {
|
||||
public var description: String {
|
||||
if isEmpty {
|
||||
return "SocketAddress(empty)"
|
||||
}
|
||||
|
||||
switch family {
|
||||
case .ipv4:
|
||||
if let ipv4 = self.ipv4 {
|
||||
return "SocketAddress(\(ipv4))"
|
||||
}
|
||||
case .ipv6:
|
||||
if let ipv6 = self.ipv6 {
|
||||
return "SocketAddress(\(ipv6))"
|
||||
}
|
||||
case .local:
|
||||
if let unix = self.unix {
|
||||
return "SocketAddress(\(unix))"
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
return "SocketAddress(family: \(family), length: \(_length))"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// A socket descriptor.
|
||||
///
|
||||
/// A `SocketDescriptor` is a type-safe wrapper around an operating system
|
||||
/// socket handle. It provides a strongly-typed interface for socket operations.
|
||||
///
|
||||
/// Unlike `FileDescriptor`, a `SocketDescriptor` explicitly represents a
|
||||
/// socket rather than a general file descriptor, enabling socket-specific
|
||||
/// operations like `bind`, `listen`, `accept`, and `connect`.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
public struct SocketDescriptor: RawRepresentable, Hashable, Codable, Sendable {
|
||||
/// The raw C socket handle.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a strongly-typed socket descriptor from a raw C socket handle.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// The file descriptor for this socket.
|
||||
///
|
||||
/// On POSIX systems, sockets are file descriptors and can be used with
|
||||
/// file descriptor operations like `read`, `write`, and `close`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var fileDescriptor: FileDescriptor {
|
||||
FileDescriptor(rawValue: rawValue)
|
||||
}
|
||||
|
||||
/// Creates a socket descriptor from a file descriptor without verification.
|
||||
///
|
||||
/// This initializer does not verify that the file descriptor actually
|
||||
/// refers to a socket. Use with caution.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(unchecked fd: FileDescriptor) {
|
||||
self.init(rawValue: fd.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Domain (Protocol Family)
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Communications domain, identifying the protocol family.
|
||||
///
|
||||
/// The domain specifies the protocol family to be used for communication.
|
||||
/// Common domains include `.ipv4` for IPv4, `.ipv6` for IPv6, and `.local`
|
||||
/// for Unix domain sockets.
|
||||
@frozen
|
||||
public struct Domain: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Unspecified protocol.
|
||||
///
|
||||
/// The corresponding C constant is `PF_UNSPEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var unspecified: Domain { Domain(PF_UNSPEC) }
|
||||
|
||||
/// Local (Unix domain) communication.
|
||||
///
|
||||
/// The corresponding C constant is `PF_LOCAL` (also known as `PF_UNIX`).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var local: Domain { Domain(PF_LOCAL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "local")
|
||||
public static var unix: Domain { Domain(PF_UNIX) }
|
||||
|
||||
/// Internet Protocol version 4.
|
||||
///
|
||||
/// The corresponding C constant is `PF_INET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: Domain { Domain(PF_INET) }
|
||||
|
||||
/// Internet Protocol version 6.
|
||||
///
|
||||
/// The corresponding C constant is `PF_INET6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: Domain { Domain(PF_INET6) }
|
||||
|
||||
/// Internal routing protocol.
|
||||
///
|
||||
/// The corresponding C constant is `PF_ROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var routing: Domain { Domain(PF_ROUTE) }
|
||||
|
||||
/// Internal key-management function.
|
||||
///
|
||||
/// The corresponding C constant is `PF_KEY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keyManagement: Domain { Domain(PF_KEY) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// System domain.
|
||||
///
|
||||
/// The corresponding C constant is `PF_SYSTEM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var system: Domain { Domain(PF_SYSTEM) }
|
||||
|
||||
/// Raw access to network device.
|
||||
///
|
||||
/// The corresponding C constant is `PF_NDRV`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var networkDevice: Domain { Domain(PF_NDRV) }
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .unspecified: return "unspecified"
|
||||
case .local: return "local"
|
||||
case .ipv4: return "ipv4"
|
||||
case .ipv6: return "ipv6"
|
||||
case .routing: return "routing"
|
||||
case .keyManagement: return "keyManagement"
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
case .system: return "system"
|
||||
case .networkDevice: return "networkDevice"
|
||||
#endif
|
||||
default: return "Domain(\(rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Connection Type (Socket Type)
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// The socket type, specifying the semantics of communication.
|
||||
///
|
||||
/// The connection type determines how data is transmitted. Stream sockets
|
||||
/// provide reliable, ordered byte streams, while datagram sockets provide
|
||||
/// connectionless, unreliable messages.
|
||||
@frozen
|
||||
public struct ConnectionType: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Sequenced, reliable, two-way, connection-based byte streams.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_STREAM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var stream: ConnectionType { ConnectionType(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) }
|
||||
|
||||
/// Raw network protocol access.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_RAW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var raw: ConnectionType { ConnectionType(SOCK_RAW) }
|
||||
|
||||
/// Reliably-delivered message.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_RDM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reliablyDeliveredMessage: ConnectionType {
|
||||
ConnectionType(SOCK_RDM)
|
||||
}
|
||||
|
||||
/// Sequenced packet stream.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_SEQPACKET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sequencedPacketStream: ConnectionType {
|
||||
ConnectionType(SOCK_SEQPACKET)
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .stream: return "stream"
|
||||
case .datagram: return "datagram"
|
||||
case .raw: return "raw"
|
||||
case .reliablyDeliveredMessage: return "rdm"
|
||||
case .sequencedPacketStream: return "seqpacket"
|
||||
default: return "ConnectionType(\(rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Protocol ID
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Identifies a particular protocol to use for communication.
|
||||
///
|
||||
/// Protocol numbers are specific to the communication domain. Some symbolic
|
||||
/// names may have the same underlying value in different contexts.
|
||||
@frozen
|
||||
public struct ProtocolID: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Default protocol for the socket type.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var `default`: ProtocolID { Self(0) }
|
||||
|
||||
/// Internet Protocol (IP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ip: ProtocolID { Self(IPPROTO_IP) }
|
||||
|
||||
/// Transmission Control Protocol (TCP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_TCP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tcp: ProtocolID { Self(IPPROTO_TCP) }
|
||||
|
||||
/// User Datagram Protocol (UDP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_UDP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var udp: ProtocolID { Self(IPPROTO_UDP) }
|
||||
|
||||
/// IPv4 encapsulation.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV4`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: ProtocolID { Self(IPPROTO_IPV4) }
|
||||
|
||||
/// IPv6 header.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: ProtocolID { Self(IPPROTO_IPV6) }
|
||||
|
||||
/// Raw IP packet.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_RAW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var raw: ProtocolID { Self(IPPROTO_RAW) }
|
||||
|
||||
public var description: String {
|
||||
rawValue.description
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Message Flags
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Flags for send and receive operations.
|
||||
@frozen
|
||||
public struct MessageFlags: OptionSet, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInt) { self.init(rawValue: raw) }
|
||||
|
||||
/// No flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var none: MessageFlags { MessageFlags(0) }
|
||||
|
||||
/// Process out-of-band data.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_OOB`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var outOfBand: MessageFlags { MessageFlags(MSG_OOB) }
|
||||
|
||||
/// Bypass routing, use direct interface.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_DONTROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var doNotRoute: MessageFlags { MessageFlags(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) }
|
||||
|
||||
/// Wait for full request or error.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_WAITALL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var waitForAll: MessageFlags { MessageFlags(MSG_WAITALL) }
|
||||
|
||||
/// End-of-record marker.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_EOR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var endOfRecord: MessageFlags { MessageFlags(MSG_EOR) }
|
||||
|
||||
/// Data was truncated.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_TRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataTruncated: MessageFlags { MessageFlags(MSG_TRUNC) }
|
||||
|
||||
/// Control data was truncated.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_CTRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var controlTruncated: MessageFlags { MessageFlags(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) }
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
var descriptions: [(Element, StaticString)] = [
|
||||
(.outOfBand, ".outOfBand"),
|
||||
(.doNotRoute, ".doNotRoute"),
|
||||
(.peek, ".peek"),
|
||||
(.waitForAll, ".waitForAll"),
|
||||
(.endOfRecord, ".endOfRecord"),
|
||||
(.dataTruncated, ".dataTruncated"),
|
||||
(.controlTruncated, ".controlTruncated"),
|
||||
]
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
descriptions.append((.noSignal, ".noSignal"))
|
||||
#endif
|
||||
return _buildDescription(descriptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Shutdown Kind
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Specifies which parts of a full-duplex connection to shut down.
|
||||
@frozen
|
||||
public struct ShutdownKind: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Disallow further receives.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_RD`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var read: ShutdownKind { ShutdownKind(rawValue: SHUT_RD) }
|
||||
|
||||
/// Disallow further sends.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_WR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var write: ShutdownKind { ShutdownKind(rawValue: 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 var description: String {
|
||||
switch self {
|
||||
case .read: return "read"
|
||||
case .write: return "write"
|
||||
case .readWrite: return "readWrite"
|
||||
default: return "ShutdownKind(\(rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket Option
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// A generic socket option identifier.
|
||||
///
|
||||
/// This type represents raw socket option constants that can be used
|
||||
/// with ancillary messages or generic get/set socket option operations.
|
||||
@frozen
|
||||
public struct Option: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
public var description: String { "Option(\(rawValue))" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Writes a sequence of bytes to the socket
|
||||
///
|
||||
/// This is equivalent to calling `fileDescriptor.writeAll(_:)`
|
||||
///
|
||||
/// - Parameter sequence: The bytes to write.
|
||||
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func writeAll<S: Sequence>(
|
||||
_ sequence: S
|
||||
) throws -> Int where S.Element == UInt8 {
|
||||
try fileDescriptor.writeAll(sequence)
|
||||
}
|
||||
|
||||
/// Runs a closure and then closes the socket, even if an error occurs.
|
||||
///
|
||||
/// This is equivalent to calling `fileDescriptor.closeAfter(_:)`
|
||||
///
|
||||
/// - Parameter body: The closure to run.
|
||||
/// If the closure throws an error,
|
||||
/// this method closes the socket before it rethrows that error.
|
||||
///
|
||||
/// - Returns: The value returned by the closure.
|
||||
///
|
||||
/// If `body` throws an error
|
||||
/// or an error occurs while closing the socket,
|
||||
/// this method rethrows that error.
|
||||
@_alwaysEmitIntoClient
|
||||
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
|
||||
try fileDescriptor.closeAfter(body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// A reusable collection of variable-sized ancillary messages
|
||||
/// sent or received over a socket. These represent protocol control
|
||||
/// related messages or other miscellaneous ancillary data.
|
||||
///
|
||||
/// Corresponds to a buffer of `struct cmsghdr` messages in C, as used
|
||||
/// by `sendmsg` and `recmsg`.
|
||||
public struct AncillaryMessageBuffer {
|
||||
internal var _buffer: _RawBuffer
|
||||
internal var _endOffset: Int
|
||||
|
||||
/// Initialize a new empty ancillary message buffer with no preallocated
|
||||
/// storage.
|
||||
public init() {
|
||||
_buffer = _RawBuffer()
|
||||
_endOffset = 0
|
||||
}
|
||||
|
||||
/// Initialize a new empty ancillary message buffer of the
|
||||
/// specified minimum capacity (in bytes).
|
||||
internal init(minimumCapacity: Int) {
|
||||
let headerSize = MemoryLayout<CInterop.CMsgHdr>.size
|
||||
let capacity = Swift.max(headerSize + 1, minimumCapacity)
|
||||
_buffer = _RawBuffer(minimumCapacity: capacity)
|
||||
_endOffset = 0
|
||||
}
|
||||
|
||||
internal var _headerSize: Int { MemoryLayout<CInterop.CMsgHdr>.size }
|
||||
internal var _capacity: Int { _buffer.capacity }
|
||||
|
||||
/// Remove all messages currently in this buffer, preserving storage
|
||||
/// capacity.
|
||||
///
|
||||
/// This invalidates all indices in the collection.
|
||||
///
|
||||
/// - Complexity: O(1). Does not reallocate the buffer.
|
||||
public mutating func removeAll() {
|
||||
_endOffset = 0
|
||||
}
|
||||
|
||||
/// Reserve enough storage capacity to hold `minimumCapacity` bytes' worth
|
||||
/// of messages without having to reallocate storage.
|
||||
///
|
||||
/// This does not invalidate any indices.
|
||||
///
|
||||
/// - Complexity: O(max(`minimumCapacity`, `capacity`)), where `capacity` is
|
||||
/// the current storage capacity. This potentially needs to reallocate
|
||||
/// the buffer and copy existing messages.
|
||||
public mutating func reserveCapacity(_ minimumCapacity: Int) {
|
||||
_buffer.ensureUnique(capacity: minimumCapacity)
|
||||
}
|
||||
|
||||
/// Append a message with the specified data to the end of this buffer,
|
||||
/// resizing it if necessary.
|
||||
///
|
||||
/// This does not invalidate any existing indices, but it updates `endIndex`.
|
||||
///
|
||||
/// - Complexity: Amortized O(`data.count`), when averaged over multiple
|
||||
/// calls. This method reallocates the buffer if there isn't enough
|
||||
/// capacity or if the storage is shared with another value.
|
||||
public mutating func appendMessage(
|
||||
level: SocketDescriptor.ProtocolID,
|
||||
type: SocketDescriptor.Option,
|
||||
bytes: UnsafeRawBufferPointer
|
||||
) {
|
||||
appendMessage(
|
||||
level: level,
|
||||
type: type,
|
||||
unsafeUninitializedCapacity: bytes.count
|
||||
) { buffer in
|
||||
assert(buffer.count >= bytes.count)
|
||||
if bytes.count > 0 {
|
||||
buffer.baseAddress!.copyMemory(
|
||||
from: bytes.baseAddress!,
|
||||
byteCount: bytes.count)
|
||||
}
|
||||
return bytes.count
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a message with the supplied data to the end of this buffer,
|
||||
/// resizing it if necessary. The message payload is initialized with the
|
||||
/// supplied closure, which needs to return the final message length.
|
||||
///
|
||||
/// This does not invalidate any existing indices, but it updates `endIndex`.
|
||||
///
|
||||
/// - Complexity: Amortized O(`data.count`), when averaged over multiple
|
||||
/// calls. This method reallocates the buffer if there isn't enough
|
||||
/// capacity or if the storage is shared with another value.
|
||||
public mutating func appendMessage(
|
||||
level: SocketDescriptor.ProtocolID,
|
||||
type: SocketDescriptor.Option,
|
||||
unsafeUninitializedCapacity capacity: Int,
|
||||
initializingWith body: (UnsafeMutableRawBufferPointer) throws -> Int
|
||||
) rethrows {
|
||||
precondition(capacity >= 0)
|
||||
let headerSize = _headerSize
|
||||
let delta = _headerSize + capacity
|
||||
_buffer.ensureUnique(capacity: _endOffset + delta)
|
||||
let messageLength: Int = try _buffer.withUnsafeMutableBytes { buffer in
|
||||
assert(buffer.count >= _endOffset + delta)
|
||||
let p = buffer.baseAddress! + _endOffset
|
||||
let header = p.bindMemory(to: CInterop.CMsgHdr.self, capacity: 1)
|
||||
header.pointee = CInterop.CMsgHdr()
|
||||
header.pointee.cmsg_level = level.rawValue
|
||||
header.pointee.cmsg_type = type.rawValue
|
||||
let length = try body(
|
||||
UnsafeMutableRawBufferPointer(start: p + headerSize, count: capacity))
|
||||
precondition(length >= 0 && length <= capacity)
|
||||
header.pointee.cmsg_len = CInterop.SockLen(headerSize + length)
|
||||
return headerSize + length
|
||||
}
|
||||
_endOffset += messageLength
|
||||
}
|
||||
|
||||
internal func _withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try _buffer.withUnsafeBytes { buffer in
|
||||
assert(buffer.count >= _endOffset)
|
||||
let buffer = UnsafeRawBufferPointer(rebasing: buffer.prefix(_endOffset))
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func _withUnsafeMutableBytes<R>(
|
||||
entireCapacity: Bool,
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
return try _buffer.withUnsafeMutableBytes { buffer in
|
||||
assert(buffer.count >= _endOffset)
|
||||
if entireCapacity {
|
||||
return try body(buffer)
|
||||
} else {
|
||||
return try body(.init(rebasing: buffer.prefix(_endOffset)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func _withMutableCInterop<R>(
|
||||
entireCapacity: Bool,
|
||||
_ body: (UnsafeMutableRawPointer?, inout CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
let (result, length): (R, Int) = try _withUnsafeMutableBytes(
|
||||
entireCapacity: entireCapacity
|
||||
) { buffer in
|
||||
var length = CInterop.SockLen(buffer.count)
|
||||
let result = try body(buffer.baseAddress, &length)
|
||||
precondition(length >= 0 && length <= buffer.count)
|
||||
return (result, Int(length))
|
||||
}
|
||||
_endOffset = length
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor.AncillaryMessageBuffer: Collection {
|
||||
/// The index type in an ancillary message buffer.
|
||||
@frozen
|
||||
public struct Index: Comparable, Hashable {
|
||||
@usableFromInline
|
||||
var _offset: Int
|
||||
|
||||
@inlinable
|
||||
internal init(_offset: Int) {
|
||||
self._offset = _offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (left: Self, right: Self) -> Bool {
|
||||
left._offset == right._offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (left: Self, right: Self) -> Bool {
|
||||
left._offset < right._offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_offset)
|
||||
}
|
||||
}
|
||||
|
||||
/// An individual message inside an ancillary message buffer.
|
||||
///
|
||||
/// Note that this is merely a reference to a slice of the underlying buffer,
|
||||
/// so it contains a shared copy of its entire storage. To prevent buffer
|
||||
/// reallocations due to copy-on-write copies, do not save instances
|
||||
/// of this type. Instead, immediately copy out any data you need to hold onto
|
||||
/// into standalone buffers.
|
||||
public struct Message {
|
||||
internal var _base: SocketDescriptor.AncillaryMessageBuffer
|
||||
internal var _offset: Int
|
||||
|
||||
internal init(_base: SocketDescriptor.AncillaryMessageBuffer, offset: Int) {
|
||||
self._base = _base
|
||||
self._offset = offset
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the first message in the collection, or `endIndex` if
|
||||
/// the collection contains no messages.
|
||||
///
|
||||
/// This roughly corresponds to the C macro `CMSG_FIRSTHDR`.
|
||||
public var startIndex: Index { Index(_offset: 0) }
|
||||
|
||||
/// The index after the last message in the collection.
|
||||
public var endIndex: Index { Index(_offset: _endOffset) }
|
||||
|
||||
/// True if the collection contains no elements.
|
||||
public var isEmpty: Bool { _endOffset == 0 }
|
||||
|
||||
/// Return the length (in bytes) of the message at the specified index, or
|
||||
/// nil if the index isn't valid, or it addresses a corrupt message.
|
||||
internal func _length(at i: Index) -> Int? {
|
||||
_withUnsafeBytes { buffer in
|
||||
guard i._offset >= 0 && i._offset + _headerSize <= buffer.count else {
|
||||
return nil
|
||||
}
|
||||
let p = (buffer.baseAddress! + i._offset)
|
||||
.assumingMemoryBound(to: CInterop.CMsgHdr.self)
|
||||
let length = Int(p.pointee.cmsg_len)
|
||||
|
||||
// Cut the list short at the first sign of corrupt data.
|
||||
// Messages must not be shorter than their header, and they must fit
|
||||
// entirely in the buffer.
|
||||
if length < _headerSize || i._offset + length > buffer.count {
|
||||
return nil
|
||||
}
|
||||
return length
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the index immediately following `i` in the collection.
|
||||
///
|
||||
/// This roughly corresponds to the C macro `CMSG_NXTHDR`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i._offset != _endOffset, "Can't advance past endIndex")
|
||||
precondition(i._offset >= 0 && i._offset + _headerSize <= _endOffset,
|
||||
"Invalid index")
|
||||
guard let length = _length(at: i) else { return endIndex }
|
||||
return Index(_offset: i._offset + length)
|
||||
}
|
||||
|
||||
/// Returns the message at the given position, which must be a valid index
|
||||
/// in this collection.
|
||||
///
|
||||
/// The returned value merely refers to a slice of the entire buffer, so
|
||||
/// it contains a shared regerence to it.
|
||||
///
|
||||
/// To reduce memory use and to prevent unnecessary copy-on-write copying, do
|
||||
/// not save `Message` values -- instead, copy out the data you need to hold
|
||||
/// on to into standalone storage.
|
||||
public subscript(position: Index) -> Message {
|
||||
guard let _ = _length(at: position) else {
|
||||
preconditionFailure("Invalid index")
|
||||
}
|
||||
return Element(_base: self, offset: position._offset)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor.AncillaryMessageBuffer.Message {
|
||||
internal var _header: CInterop.CMsgHdr {
|
||||
_base._withUnsafeBytes { buffer in
|
||||
assert(_offset + _base._headerSize <= buffer.count)
|
||||
let p = buffer.baseAddress! + _offset
|
||||
let header = p.assumingMemoryBound(to: CInterop.CMsgHdr.self)
|
||||
return header.pointee
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol level of the message. Socket-level command messages
|
||||
/// use the special protocol value `SocketDescriptor.ProtocolID.socketOption`.
|
||||
public var level: SocketDescriptor.ProtocolID {
|
||||
.init(rawValue: _header.cmsg_level)
|
||||
}
|
||||
|
||||
/// The protocol-specific type of the message.
|
||||
public var type: SocketDescriptor.Option {
|
||||
.init(rawValue: _header.cmsg_type)
|
||||
}
|
||||
|
||||
/// Calls `body` with an unsafe raw buffer pointer containing the
|
||||
/// message payload.
|
||||
///
|
||||
/// This roughly corresponds to the C macro `CMSG_DATA`.
|
||||
///
|
||||
/// - Note: The buffer passed to `body` does not include storage reserved
|
||||
/// for holding the message header, such as the `level` and `type` values.
|
||||
/// To access header information, you have to use the corresponding
|
||||
/// properties.
|
||||
public func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try _base._withUnsafeBytes { buffer in
|
||||
let headerSize = _base._headerSize
|
||||
assert(_offset + headerSize <= buffer.count)
|
||||
let p = buffer.baseAddress! + _offset
|
||||
let header = p.assumingMemoryBound(to: CInterop.CMsgHdr.self)
|
||||
let data = p + headerSize
|
||||
let count = Swift.min(Int(header.pointee.cmsg_len) - headerSize,
|
||||
buffer.count)
|
||||
return try body(UnsafeRawBufferPointer(start: data, count: count))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Socket Creation and Lifecycle
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Creates an endpoint for communication.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - domain: The protocol family for communication.
|
||||
/// - type: The semantics of communication.
|
||||
/// - protocol: The particular protocol to use. The default is `.default`,
|
||||
/// which typically selects the appropriate protocol for the domain/type
|
||||
/// combination (e.g., TCP for IPv4/stream).
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted. The default is `true`.
|
||||
/// - Returns: A new socket descriptor.
|
||||
///
|
||||
/// The corresponding C function is `socket`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ domain: Domain,
|
||||
_ type: ConnectionType,
|
||||
protocol: ProtocolID = .default,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> SocketDescriptor {
|
||||
try _open(domain, type, protocol: `protocol`, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _open(
|
||||
_ domain: Domain,
|
||||
_ type: ConnectionType,
|
||||
protocol: ProtocolID,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<SocketDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_socket(domain.rawValue, type.rawValue, `protocol`.rawValue)
|
||||
}.map(SocketDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
/// Closes the socket.
|
||||
///
|
||||
/// The corresponding C function is `close`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func close() throws {
|
||||
try _close().get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _close() -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_close(self.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shuts down part of a full-duplex connection.
|
||||
///
|
||||
/// - Parameter how: Which parts of the connection to shut down.
|
||||
///
|
||||
/// The corresponding C function is `shutdown`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func shutdown(_ how: ShutdownKind) throws {
|
||||
try _shutdown(how).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _shutdown(_ how: ShutdownKind) -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_shutdown(self.rawValue, how.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Connection Operations
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Binds a socket to an address.
|
||||
///
|
||||
/// - Parameter address: The socket address to bind to.
|
||||
///
|
||||
/// The corresponding C function is `bind`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func bind(to address: SocketAddress) throws {
|
||||
try _bind(to: address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _bind(to address: SocketAddress) -> Result<(), Errno> {
|
||||
address.withUnsafePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_bind(self.rawValue, addr, len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Listens for connections on the socket.
|
||||
///
|
||||
/// Only applies to sockets of type `.stream`.
|
||||
///
|
||||
/// - Parameter backlog: The maximum length of the pending connections queue.
|
||||
///
|
||||
/// The corresponding C function is `listen`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func listen(backlog: Int) throws {
|
||||
try _listen(backlog: backlog).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _listen(backlog: Int) -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_listen(self.rawValue, CInt(backlog))
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a connection on the socket.
|
||||
///
|
||||
/// - Parameter retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: A new socket descriptor for the accepted connection.
|
||||
///
|
||||
/// The corresponding C function is `accept`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func accept(retryOnInterrupt: Bool = true) throws -> SocketDescriptor {
|
||||
try _accept(retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _accept(retryOnInterrupt: Bool) -> Result<SocketDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_accept(self.rawValue, nil, nil)
|
||||
}.map(SocketDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
/// Accepts a connection and returns the client's address.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - client: A socket address buffer to receive the client's address.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: A new socket descriptor for the accepted connection.
|
||||
///
|
||||
/// The corresponding C function is `accept`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func accept(
|
||||
client: inout SocketAddress,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> SocketDescriptor {
|
||||
try _accept(client: &client, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _accept(
|
||||
client: inout SocketAddress,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<SocketDescriptor, Errno> {
|
||||
client._withUnsafeMutablePointer { addr, len in
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_accept(self.rawValue, addr, &len)
|
||||
}.map(SocketDescriptor.init(rawValue:))
|
||||
}
|
||||
}
|
||||
|
||||
/// Initiates a connection on the socket.
|
||||
///
|
||||
/// - Parameter address: The address to connect to.
|
||||
///
|
||||
/// The corresponding C function is `connect`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func connect(to address: SocketAddress) throws {
|
||||
try _connect(to: address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _connect(to address: SocketAddress) -> Result<(), Errno> {
|
||||
address.withUnsafePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_connect(self.rawValue, addr, len)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Send and Receive
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Sends data on the socket.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The data to send.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes sent.
|
||||
///
|
||||
/// The corresponding C function is `send`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _send(buffer, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_send(self.rawValue, buffer.baseAddress, buffer.count, flags.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives data from the socket.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The buffer to receive data into.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes received.
|
||||
///
|
||||
/// The corresponding C function is `recv`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _receive(into: buffer, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_recv(self.rawValue, buffer.baseAddress, buffer.count, flags.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends data to a specific address.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The data to send.
|
||||
/// - address: The destination address.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes sent.
|
||||
///
|
||||
/// The corresponding C function is `sendto`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to address: SocketAddress,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _send(buffer, to: address, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to address: SocketAddress,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
address.withUnsafePointer { addr, addrlen in
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_sendto(
|
||||
self.rawValue,
|
||||
buffer.baseAddress,
|
||||
buffer.count,
|
||||
flags.rawValue,
|
||||
addr,
|
||||
addrlen
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives data and returns the sender's address.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The buffer to receive data into.
|
||||
/// - sender: A buffer to receive the sender's address.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes received.
|
||||
///
|
||||
/// The corresponding C function is `recvfrom`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
sender: inout SocketAddress,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _receive(into: buffer, sender: &sender, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
sender: inout SocketAddress,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
sender._withUnsafeMutablePointer { addr, len in
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_recvfrom(
|
||||
self.rawValue,
|
||||
buffer.baseAddress,
|
||||
buffer.count,
|
||||
flags.rawValue,
|
||||
addr,
|
||||
&len
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket Information
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets the local address of the socket.
|
||||
///
|
||||
/// - Parameter address: A buffer to receive the local address.
|
||||
///
|
||||
/// The corresponding C function is `getsockname`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getLocalAddress(into address: inout SocketAddress) throws {
|
||||
try _getLocalAddress(into: &address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getLocalAddress(into address: inout SocketAddress) -> Result<(), Errno> {
|
||||
address._withUnsafeMutablePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getsockname(self.rawValue, addr, &len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the remote address of the socket.
|
||||
///
|
||||
/// - Parameter address: A buffer to receive the peer address.
|
||||
///
|
||||
/// The corresponding C function is `getpeername`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getPeerAddress(into address: inout SocketAddress) throws {
|
||||
try _getPeerAddress(into: &address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getPeerAddress(into address: inout SocketAddress) -> Result<(), Errno> {
|
||||
address._withUnsafeMutablePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getpeername(self.rawValue, addr, &len)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Option Level
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Socket option levels.
|
||||
@frozen
|
||||
public struct OptionLevel: RawRepresentable, Hashable, Sendable {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Socket-level options.
|
||||
///
|
||||
/// The corresponding C constant is `SOL_SOCKET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var socket: OptionLevel { OptionLevel(rawValue: SOL_SOCKET) }
|
||||
|
||||
/// IPv4 protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ip: OptionLevel { OptionLevel(rawValue: IPPROTO_IP) }
|
||||
|
||||
/// IPv6 protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: OptionLevel { OptionLevel(rawValue: IPPROTO_IPV6) }
|
||||
|
||||
/// TCP protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_TCP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tcp: OptionLevel { OptionLevel(rawValue: IPPROTO_TCP) }
|
||||
|
||||
/// UDP protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_UDP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var udp: OptionLevel { OptionLevel(rawValue: IPPROTO_UDP) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket-Level Options
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Socket-level options for use with `getOption` and `setOption`.
|
||||
@frozen
|
||||
public struct SocketOption: RawRepresentable, Hashable, Sendable {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Enable debugging.
|
||||
///
|
||||
/// The corresponding C constant is `SO_DEBUG`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var debug: SocketOption { SocketOption(rawValue: SO_DEBUG) }
|
||||
|
||||
/// Allow local address reuse.
|
||||
///
|
||||
/// The corresponding C constant is `SO_REUSEADDR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reuseAddress: SocketOption { SocketOption(rawValue: SO_REUSEADDR) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux)
|
||||
/// Allow local port reuse.
|
||||
///
|
||||
/// The corresponding C constant is `SO_REUSEPORT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reusePort: SocketOption { SocketOption(rawValue: SO_REUSEPORT) }
|
||||
#endif
|
||||
|
||||
/// Keep connections alive.
|
||||
///
|
||||
/// The corresponding C constant is `SO_KEEPALIVE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAlive: SocketOption { SocketOption(rawValue: SO_KEEPALIVE) }
|
||||
|
||||
/// Don't route, use direct interface.
|
||||
///
|
||||
/// The corresponding C constant is `SO_DONTROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dontRoute: SocketOption { SocketOption(rawValue: SO_DONTROUTE) }
|
||||
|
||||
/// Linger on close if data present.
|
||||
///
|
||||
/// The corresponding C constant is `SO_LINGER`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var linger: SocketOption { SocketOption(rawValue: SO_LINGER) }
|
||||
|
||||
/// Permit sending of broadcast messages.
|
||||
///
|
||||
/// The corresponding C constant is `SO_BROADCAST`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var broadcast: SocketOption { SocketOption(rawValue: SO_BROADCAST) }
|
||||
|
||||
/// Send buffer size.
|
||||
///
|
||||
/// The corresponding C constant is `SO_SNDBUF`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sendBufferSize: SocketOption { SocketOption(rawValue: SO_SNDBUF) }
|
||||
|
||||
/// Receive buffer size.
|
||||
///
|
||||
/// The corresponding C constant is `SO_RCVBUF`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var receiveBufferSize: SocketOption { SocketOption(rawValue: SO_RCVBUF) }
|
||||
|
||||
/// Send low water mark.
|
||||
///
|
||||
/// The corresponding C constant is `SO_SNDLOWAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sendLowWaterMark: SocketOption { SocketOption(rawValue: SO_SNDLOWAT) }
|
||||
|
||||
/// Receive low water mark.
|
||||
///
|
||||
/// The corresponding C constant is `SO_RCVLOWAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var receiveLowWaterMark: SocketOption { SocketOption(rawValue: SO_RCVLOWAT) }
|
||||
|
||||
/// Get socket error.
|
||||
///
|
||||
/// The corresponding C constant is `SO_ERROR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var error: SocketOption { SocketOption(rawValue: SO_ERROR) }
|
||||
|
||||
/// Get socket type.
|
||||
///
|
||||
/// The corresponding C constant is `SO_TYPE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var type: SocketOption { SocketOption(rawValue: SO_TYPE) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Don't generate SIGPIPE on broken pipe.
|
||||
///
|
||||
/// The corresponding C constant is `SO_NOSIGPIPE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSigPipe: SocketOption { SocketOption(rawValue: SO_NOSIGPIPE) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TCP Options
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// TCP-level options for use with `getOption` and `setOption`.
|
||||
@frozen
|
||||
public struct TCPOption: RawRepresentable, Hashable, Sendable {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Disable Nagle algorithm.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_NODELAY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDelay: TCPOption { TCPOption(rawValue: TCP_NODELAY) }
|
||||
|
||||
/// Maximum segment size.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_MAXSEG`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var maxSegmentSize: TCPOption { TCPOption(rawValue: TCP_MAXSEG) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(Linux)
|
||||
/// Keep alive idle time.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_KEEPIDLE` on Linux
|
||||
/// or `TCP_KEEPALIVE` on Darwin.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAliveIdle: TCPOption {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
TCPOption(rawValue: TCP_KEEPALIVE)
|
||||
#else
|
||||
TCPOption(rawValue: TCP_KEEPIDLE)
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(Linux)
|
||||
/// Keep alive interval.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_KEEPINTVL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAliveInterval: TCPOption { TCPOption(rawValue: TCP_KEEPINTVL) }
|
||||
|
||||
/// Keep alive probe count.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_KEEPCNT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAliveCount: TCPOption { TCPOption(rawValue: TCP_KEEPCNT) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Get and Set Options
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets a socket option value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The protocol level.
|
||||
/// - option: The option to get.
|
||||
/// - Returns: The option value.
|
||||
///
|
||||
/// The corresponding C function is `getsockopt`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt
|
||||
) throws -> T {
|
||||
try _getOption(level, option).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt
|
||||
) -> Result<T, Errno> {
|
||||
// Allocate zeroed storage for the option value
|
||||
var storage = [UInt8](repeating: 0, count: MemoryLayout<T>.size)
|
||||
var length = socklen_t(MemoryLayout<T>.size)
|
||||
|
||||
let result = storage.withUnsafeMutableBytes { buffer in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getsockopt(
|
||||
self.rawValue,
|
||||
level.rawValue,
|
||||
option,
|
||||
buffer.baseAddress,
|
||||
&length
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return result.map {
|
||||
storage.withUnsafeBytes { buffer in
|
||||
buffer.load(as: T.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a socket option value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The protocol level.
|
||||
/// - option: The option to set.
|
||||
/// - value: The value to set.
|
||||
///
|
||||
/// The corresponding C function is `setsockopt`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt,
|
||||
to value: T
|
||||
) throws {
|
||||
try _setOption(level, option, to: value).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _setOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt,
|
||||
to value: T
|
||||
) -> Result<(), Errno> {
|
||||
withUnsafePointer(to: value) { valuePtr in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_setsockopt(
|
||||
self.rawValue,
|
||||
level.rawValue,
|
||||
option,
|
||||
valuePtr,
|
||||
socklen_t(MemoryLayout<T>.size)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Convenience Methods
|
||||
|
||||
@available(System 99, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets a socket-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getSocketOption(_ option: SocketOption) throws -> CInt {
|
||||
try getOption(.socket, option.rawValue)
|
||||
}
|
||||
|
||||
/// Sets a socket-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setSocketOption(_ option: SocketOption, to value: CInt) throws {
|
||||
try setOption(.socket, option.rawValue, to: value)
|
||||
}
|
||||
|
||||
/// Gets a TCP-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getTCPOption(_ option: TCPOption) throws -> CInt {
|
||||
try getOption(.tcp, option.rawValue)
|
||||
}
|
||||
|
||||
/// Sets a TCP-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setTCPOption(_ option: TCPOption, to value: CInt) throws {
|
||||
try setOption(.tcp, option.rawValue, to: value)
|
||||
}
|
||||
|
||||
/// Enables reuse of local addresses.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setReuseAddress(_ enabled: Bool = true) throws {
|
||||
try setSocketOption(.reuseAddress, to: enabled ? 1 : 0)
|
||||
}
|
||||
|
||||
/// Disables the Nagle algorithm.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setNoDelay(_ enabled: Bool = true) throws {
|
||||
try setTCPOption(.noDelay, to: enabled ? 1 : 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Utility functions for socket operations
|
||||
|
||||
import SystemPackage
|
||||
|
||||
extension Errno {
|
||||
internal static var current: Errno {
|
||||
get { Errno(rawValue: system_errno) }
|
||||
set { system_errno = newValue.rawValue }
|
||||
}
|
||||
}
|
||||
|
||||
// Results in errno if i == -1
|
||||
@available(System 0.0.1, *)
|
||||
private func valueOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<I, Errno> {
|
||||
i == -1 ? .failure(Errno.current) : .success(i)
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
private func nothingOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(i).map { _ in () }
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<I, Errno> {
|
||||
repeat {
|
||||
switch valueOrErrno(f()) {
|
||||
case .success(let r): return .success(r)
|
||||
case .failure(let err):
|
||||
guard retryOnInterrupt && err == .interrupted else { return .failure(err) }
|
||||
break
|
||||
}
|
||||
} while true
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
internal func nothingOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () }
|
||||
}
|
||||
|
||||
// Run a precondition for debug client builds
|
||||
internal func _debugPrecondition(
|
||||
_ condition: @autoclosure () -> Bool,
|
||||
_ message: StaticString = StaticString(),
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) {
|
||||
if _slowPath(_isDebugAssertConfiguration()) {
|
||||
precondition(
|
||||
condition(), String(describing: message), file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
extension OptionSet {
|
||||
@inline(never)
|
||||
internal func _buildDescription(
|
||||
_ descriptions: [(Element, StaticString)]
|
||||
) -> String {
|
||||
var copy = self
|
||||
var result = "["
|
||||
|
||||
for (option, name) in descriptions {
|
||||
if _slowPath(copy.contains(option)) {
|
||||
result += name.description
|
||||
copy.remove(option)
|
||||
if !copy.isEmpty { result += ", " }
|
||||
}
|
||||
}
|
||||
|
||||
if _slowPath(!copy.isEmpty) {
|
||||
result += "\(Self.self)(rawValue: \(copy.rawValue))"
|
||||
}
|
||||
result += "]"
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
internal func _withOptionalUnsafePointerOrNull<T, R>(
|
||||
to value: T?,
|
||||
_ body: (UnsafePointer<T>?) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let value = value else {
|
||||
return try body(nil)
|
||||
}
|
||||
return try withUnsafePointer(to: value, body)
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import XCTest
|
||||
|
||||
import SystemTests
|
||||
|
||||
var tests = [XCTestCaseEntry]()
|
||||
tests += SystemTests.__allTests()
|
||||
|
||||
XCTMain(tests)
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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
|
||||
*/
|
||||
|
||||
import Testing
|
||||
import SystemPackage
|
||||
@testable import SystemSockets
|
||||
|
||||
@Suite("Ancillary Message Buffer")
|
||||
struct AncillaryMessageBufferTests {
|
||||
@Test("Append and iterate messages")
|
||||
func testAppend() {
|
||||
// Create a buffer of 100 messages, with varying payload lengths.
|
||||
var buffer = SocketDescriptor.AncillaryMessageBuffer(minimumCapacity: 0)
|
||||
for i in 0 ..< 100 {
|
||||
let bytes = UnsafeMutableRawBufferPointer.allocate(byteCount: i, alignment: 1)
|
||||
defer { bytes.deallocate() }
|
||||
system_memset(bytes, to: UInt8(i))
|
||||
buffer.appendMessage(level: .init(rawValue: CInt(100 * i)),
|
||||
type: .init(rawValue: CInt(1000 * i)),
|
||||
bytes: UnsafeRawBufferPointer(bytes))
|
||||
}
|
||||
// Check that we can access appended messages.
|
||||
var i = 0
|
||||
for message in buffer {
|
||||
#expect(Int(message.level.rawValue) == 100 * i)
|
||||
#expect(Int(message.type.rawValue) == 1000 * i)
|
||||
message.withUnsafeBytes { buffer in
|
||||
#expect(buffer.count == i)
|
||||
for idx in buffer.indices {
|
||||
#expect(buffer[idx] == UInt8(i), "byte #\(idx)")
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
#expect(i == 100, "Too many messages in buffer")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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 !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
@Suite("Socket Addresses")
|
||||
private struct SocketAddressTests {
|
||||
|
||||
// MARK: - IPv4 Address Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv4BasicCreation() {
|
||||
let addr = IPv4Address("127.0.0.1", port: 8080)
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.port == 8080)
|
||||
#expect(addr?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv4InvalidAddress() {
|
||||
let addr = IPv4Address("not.an.ip.address", port: 8080)
|
||||
#expect(addr == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv4Any() {
|
||||
let addr = IPv4Address.any(port: 0)
|
||||
#expect(addr.port == 0)
|
||||
#expect(addr.addressString == "0.0.0.0")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv4Loopback() {
|
||||
let addr = IPv4Address.loopback(port: 80)
|
||||
#expect(addr.port == 80)
|
||||
#expect(addr.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@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, *)
|
||||
@Test func ipv4Equality() {
|
||||
let addr1 = IPv4Address("10.0.0.1", port: 8080)!
|
||||
let addr2 = IPv4Address("10.0.0.1", port: 8080)!
|
||||
let addr3 = IPv4Address("10.0.0.2", port: 8080)!
|
||||
let addr4 = IPv4Address("10.0.0.1", port: 9090)!
|
||||
|
||||
#expect(addr1 == addr2)
|
||||
#expect(addr1 != addr3)
|
||||
#expect(addr1 != addr4)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv4Description() {
|
||||
let addr = IPv4Address("8.8.8.8", port: 53)!
|
||||
#expect(addr.description == "8.8.8.8:53")
|
||||
}
|
||||
|
||||
// MARK: - IPv6 Address Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv6BasicCreation() {
|
||||
let addr = IPv6Address("::1", port: 8080)
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.port == 8080)
|
||||
#expect(addr?.addressString == "::1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv6InvalidAddress() {
|
||||
let addr = IPv6Address("not:an:ipv6:address", port: 8080)
|
||||
#expect(addr == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv6Any() {
|
||||
let addr = IPv6Address.any(port: 0)
|
||||
#expect(addr.port == 0)
|
||||
#expect(addr.addressString == "::")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv6Loopback() {
|
||||
let addr = IPv6Address.loopback(port: 80)
|
||||
#expect(addr.port == 80)
|
||||
#expect(addr.addressString == "::1")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv6Description() {
|
||||
let addr = IPv6Address("2001:db8::1", port: 443)!
|
||||
#expect(addr.description == "[2001:db8::1]:443")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func ipv6StringLiteral() {
|
||||
let addr: IPv6Address = "[::1]:8080"
|
||||
#expect(addr.port == 8080)
|
||||
#expect(addr.addressString == "::1")
|
||||
}
|
||||
|
||||
// MARK: - Unix Address Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func unixBasicCreation() {
|
||||
let addr = UnixAddress("/tmp/test.sock")
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.path == "/tmp/test.sock")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func unixDescription() {
|
||||
let addr = UnixAddress("/var/run/daemon.sock")!
|
||||
#expect(addr.description == "/var/run/daemon.sock")
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func unixEquality() {
|
||||
let addr1 = UnixAddress("/tmp/a.sock")!
|
||||
let addr2 = UnixAddress("/tmp/a.sock")!
|
||||
let addr3 = UnixAddress("/tmp/b.sock")!
|
||||
|
||||
#expect(addr1 == addr2)
|
||||
#expect(addr1 != addr3)
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Container Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func socketAddressFromIPv4() {
|
||||
let ipv4 = IPv4Address.loopback(port: 8080)
|
||||
let sockAddr = SocketAddress(ipv4: ipv4)
|
||||
|
||||
#expect(sockAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
#expect(sockAddr.ipv4 != nil)
|
||||
#expect(sockAddr.ipv4?.port == 8080)
|
||||
#expect(sockAddr.ipv6 == nil)
|
||||
#expect(sockAddr.unix == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func socketAddressFromIPv6() {
|
||||
let ipv6 = IPv6Address.loopback(port: 443)
|
||||
let sockAddr = SocketAddress(ipv6: ipv6)
|
||||
|
||||
#expect(sockAddr.family == SocketDescriptor.Domain.ipv6)
|
||||
#expect(sockAddr.ipv6 != nil)
|
||||
#expect(sockAddr.ipv6?.port == 443)
|
||||
#expect(sockAddr.ipv4 == nil)
|
||||
#expect(sockAddr.unix == nil)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func socketAddressFromUnix() {
|
||||
let unix = UnixAddress("/tmp/test.sock")!
|
||||
let sockAddr = SocketAddress(unix: unix)
|
||||
|
||||
#expect(sockAddr.family == SocketDescriptor.Domain.local)
|
||||
#expect(sockAddr.unix != nil)
|
||||
#expect(sockAddr.unix?.path == "/tmp/test.sock")
|
||||
#expect(sockAddr.ipv4 == nil)
|
||||
#expect(sockAddr.ipv6 == nil)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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 !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
@Suite("Socket Descriptor")
|
||||
private struct SocketDescriptorTests {
|
||||
|
||||
// MARK: - Type Tests
|
||||
|
||||
@Test func domainValues() {
|
||||
#expect(SocketDescriptor.Domain.ipv4.rawValue == AF_INET)
|
||||
#expect(SocketDescriptor.Domain.ipv6.rawValue == AF_INET6)
|
||||
#expect(SocketDescriptor.Domain.local.rawValue == AF_UNIX)
|
||||
}
|
||||
|
||||
@Test func connectionTypeValues() {
|
||||
#expect(SocketDescriptor.ConnectionType.stream.rawValue == SOCK_STREAM)
|
||||
#expect(SocketDescriptor.ConnectionType.datagram.rawValue == SOCK_DGRAM)
|
||||
}
|
||||
|
||||
@Test func protocolValues() {
|
||||
#expect(SocketDescriptor.ProtocolID.tcp.rawValue == CInt(IPPROTO_TCP))
|
||||
#expect(SocketDescriptor.ProtocolID.udp.rawValue == CInt(IPPROTO_UDP))
|
||||
}
|
||||
|
||||
// MARK: - Socket Creation Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func createTCPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func createUDPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func createIPv6TCPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func createUnixSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.local, .stream)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
// MARK: - Shutdown Tests
|
||||
|
||||
@Test func shutdownKindValues() {
|
||||
#expect(SocketDescriptor.ShutdownKind.read.rawValue == SHUT_RD)
|
||||
#expect(SocketDescriptor.ShutdownKind.write.rawValue == SHUT_WR)
|
||||
#expect(SocketDescriptor.ShutdownKind.readWrite.rawValue == SHUT_RDWR)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,225 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 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 !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
@Suite("Socket Operations")
|
||||
private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Bind Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func bindToAnyPort() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let address = SocketAddress(ipv4: IPv4Address.any(port: 0))
|
||||
try socket.bind(to: address)
|
||||
|
||||
// Verify we can get the local address after binding
|
||||
var localAddr = SocketAddress()
|
||||
try socket.getLocalAddress(into: &localAddr)
|
||||
#expect(localAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
#expect(localAddr.ipv4?.port != 0) // Port should be assigned
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func bindToLoopback() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let address = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try socket.bind(to: address)
|
||||
|
||||
var localAddr = SocketAddress()
|
||||
try socket.getLocalAddress(into: &localAddr)
|
||||
#expect(localAddr.ipv4?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
// MARK: - Listen Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func listenWithDefaultBacklog() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let address = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try socket.bind(to: address)
|
||||
try socket.listen(backlog: 5)
|
||||
}
|
||||
|
||||
// MARK: - Connect and Accept Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func tcpConnectAndAccept() throws {
|
||||
// Create server socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? server.close() }
|
||||
|
||||
let serverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try server.bind(to: serverAddr)
|
||||
try server.listen(backlog: 1)
|
||||
|
||||
// Get the actual port
|
||||
var boundAddr = SocketAddress()
|
||||
try server.getLocalAddress(into: &boundAddr)
|
||||
let port = boundAddr.ipv4!.port
|
||||
|
||||
// Create client socket and connect
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
let connectAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
|
||||
try client.connect(to: connectAddr)
|
||||
|
||||
// Accept connection
|
||||
var peerAddr = SocketAddress()
|
||||
let acceptedSocket = try server.accept(client: &peerAddr)
|
||||
defer { try? acceptedSocket.close() }
|
||||
|
||||
#expect(peerAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
#expect(peerAddr.ipv4?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
// MARK: - Send and Receive Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func tcpSendReceive() throws {
|
||||
// Create server socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? server.close() }
|
||||
|
||||
let serverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try server.bind(to: serverAddr)
|
||||
try server.listen(backlog: 1)
|
||||
|
||||
var boundAddr = SocketAddress()
|
||||
try server.getLocalAddress(into: &boundAddr)
|
||||
let port = boundAddr.ipv4!.port
|
||||
|
||||
// Create client socket and connect
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
let connectAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
|
||||
try client.connect(to: connectAddr)
|
||||
|
||||
// Accept connection
|
||||
let acceptedSocket = try server.accept()
|
||||
defer { try? acceptedSocket.close() }
|
||||
|
||||
// Send data from client
|
||||
let message = "Hello, World!"
|
||||
let messageBytes = Array(message.utf8)
|
||||
let sent = try messageBytes.withUnsafeBytes { buffer in
|
||||
try client.send(UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
#expect(sent == messageBytes.count)
|
||||
|
||||
// Receive data on server
|
||||
var buffer = [UInt8](repeating: 0, count: 1024)
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try acceptedSocket.receive(into: buffer)
|
||||
}
|
||||
#expect(received == messageBytes.count)
|
||||
|
||||
let receivedMessage = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
#expect(receivedMessage == message)
|
||||
}
|
||||
|
||||
// MARK: - UDP Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func udpSendReceive() throws {
|
||||
// Create receiver socket
|
||||
let receiver = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
defer { try? receiver.close() }
|
||||
|
||||
let receiverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try receiver.bind(to: receiverAddr)
|
||||
|
||||
var boundAddr = SocketAddress()
|
||||
try receiver.getLocalAddress(into: &boundAddr)
|
||||
let port = boundAddr.ipv4!.port
|
||||
|
||||
// Create sender socket
|
||||
let sender = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
defer { try? sender.close() }
|
||||
|
||||
// Send datagram
|
||||
let message = "UDP Message"
|
||||
let messageBytes = Array(message.utf8)
|
||||
let targetAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
|
||||
let sent = try messageBytes.withUnsafeBytes { buffer in
|
||||
try sender.send(UnsafeRawBufferPointer(buffer), to: targetAddr)
|
||||
}
|
||||
#expect(sent == messageBytes.count)
|
||||
|
||||
// Receive datagram
|
||||
var buffer = [UInt8](repeating: 0, count: 1024)
|
||||
var fromAddr = SocketAddress()
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try receiver.receive(into: buffer, sender: &fromAddr)
|
||||
}
|
||||
#expect(received == messageBytes.count)
|
||||
#expect(fromAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
|
||||
let receivedMessage = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
#expect(receivedMessage == message)
|
||||
}
|
||||
|
||||
// MARK: - Socket Options Tests
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func setReuseAddress() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
try socket.setReuseAddress(true)
|
||||
let value = try socket.getSocketOption(SocketDescriptor.SocketOption.reuseAddress)
|
||||
#expect(value != 0)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func getSendBufferSize() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let size = try socket.getSocketOption(SocketDescriptor.SocketOption.sendBufferSize)
|
||||
#expect(size > 0)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func getReceiveBufferSize() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let size = try socket.getSocketOption(SocketDescriptor.SocketOption.receiveBufferSize)
|
||||
#expect(size > 0)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -15,7 +15,11 @@ import SystemPackage
|
||||
import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
#if os(Windows)
|
||||
import WinSDK
|
||||
#endif
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
final class ErrnoTest: XCTestCase {
|
||||
func testConstants() {
|
||||
XCTAssert(EPERM == Errno.notPermitted.rawValue)
|
||||
@@ -32,7 +36,9 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(ENOMEM == Errno.noMemory.rawValue)
|
||||
XCTAssert(EACCES == Errno.permissionDenied.rawValue)
|
||||
XCTAssert(EFAULT == Errno.badAddress.rawValue)
|
||||
#if !os(Windows) && !os(WASI)
|
||||
XCTAssert(ENOTBLK == Errno.notBlockDevice.rawValue)
|
||||
#endif
|
||||
XCTAssert(EBUSY == Errno.resourceBusy.rawValue)
|
||||
XCTAssert(EEXIST == Errno.fileExists.rawValue)
|
||||
XCTAssert(EXDEV == Errno.improperLink.rawValue)
|
||||
@@ -42,8 +48,10 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(EINVAL == Errno.invalidArgument.rawValue)
|
||||
XCTAssert(ENFILE == Errno.tooManyOpenFilesInSystem.rawValue)
|
||||
XCTAssert(EMFILE == Errno.tooManyOpenFiles.rawValue)
|
||||
#if !os(Windows)
|
||||
XCTAssert(ENOTTY == Errno.inappropriateIOCTLForDevice.rawValue)
|
||||
XCTAssert(ETXTBSY == Errno.textFileBusy.rawValue)
|
||||
#endif
|
||||
XCTAssert(EFBIG == Errno.fileTooLarge.rawValue)
|
||||
XCTAssert(ENOSPC == Errno.noSpace.rawValue)
|
||||
XCTAssert(ESPIPE == Errno.illegalSeek.rawValue)
|
||||
@@ -61,9 +69,17 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(EPROTOTYPE == Errno.protocolWrongTypeForSocket.rawValue)
|
||||
XCTAssert(ENOPROTOOPT == Errno.protocolNotAvailable.rawValue)
|
||||
XCTAssert(EPROTONOSUPPORT == Errno.protocolNotSupported.rawValue)
|
||||
XCTAssert(ESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
|
||||
XCTAssert(WSAEOPNOTSUPP == Errno.notSupported.rawValue)
|
||||
XCTAssert(WSAEPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
|
||||
#else
|
||||
XCTAssert(ENOTSUP == Errno.notSupported.rawValue)
|
||||
#if !os(WASI)
|
||||
XCTAssert(ESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
|
||||
XCTAssert(EPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
|
||||
#endif
|
||||
#endif
|
||||
XCTAssert(EAFNOSUPPORT == Errno.addressFamilyNotSupported.rawValue)
|
||||
XCTAssert(EADDRINUSE == Errno.addressInUse.rawValue)
|
||||
XCTAssert(EADDRNOTAVAIL == Errno.addressNotAvailable.rawValue)
|
||||
@@ -75,12 +91,20 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(ENOBUFS == Errno.noBufferSpace.rawValue)
|
||||
XCTAssert(EISCONN == Errno.socketIsConnected.rawValue)
|
||||
XCTAssert(ENOTCONN == Errno.socketNotConnected.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAESHUTDOWN == Errno.socketShutdown.rawValue)
|
||||
#elseif !os(WASI)
|
||||
XCTAssert(ESHUTDOWN == Errno.socketShutdown.rawValue)
|
||||
#endif
|
||||
XCTAssert(ETIMEDOUT == Errno.timedOut.rawValue)
|
||||
XCTAssert(ECONNREFUSED == Errno.connectionRefused.rawValue)
|
||||
XCTAssert(ELOOP == Errno.tooManySymbolicLinkLevels.rawValue)
|
||||
XCTAssert(ENAMETOOLONG == Errno.fileNameTooLong.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAEHOSTDOWN == Errno.hostIsDown.rawValue)
|
||||
#elseif !os(WASI)
|
||||
XCTAssert(EHOSTDOWN == Errno.hostIsDown.rawValue)
|
||||
#endif
|
||||
XCTAssert(EHOSTUNREACH == Errno.noRouteToHost.rawValue)
|
||||
XCTAssert(ENOTEMPTY == Errno.directoryNotEmpty.rawValue)
|
||||
|
||||
@@ -88,9 +112,17 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(EPROCLIM == Errno.tooManyProcesses.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAEUSERS == Errno.tooManyUsers.rawValue)
|
||||
XCTAssert(WSAEDQUOT == Errno.diskQuotaExceeded.rawValue)
|
||||
XCTAssert(WSAESTALE == Errno.staleNFSFileHandle.rawValue)
|
||||
#else
|
||||
#if !os(WASI)
|
||||
XCTAssert(EUSERS == Errno.tooManyUsers.rawValue)
|
||||
#endif
|
||||
XCTAssert(EDQUOT == Errno.diskQuotaExceeded.rawValue)
|
||||
XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue)
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EBADRPC == Errno.rpcUnsuccessful.rawValue)
|
||||
@@ -103,15 +135,20 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(ENOLCK == Errno.noLocks.rawValue)
|
||||
XCTAssert(ENOSYS == Errno.noFunction.rawValue)
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
XCTAssert(EFTYPE == Errno.badFileTypeOrFormat.rawValue)
|
||||
XCTAssert(EAUTH == Errno.authenticationError.rawValue)
|
||||
XCTAssert(ENEEDAUTH == Errno.needAuthenticator.rawValue)
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EPWROFF == Errno.devicePowerIsOff.rawValue)
|
||||
XCTAssert(EDEVERR == Errno.deviceError.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssert(EOVERFLOW == Errno.overflow.rawValue)
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EBADEXEC == Errno.badExecutable.rawValue)
|
||||
@@ -121,35 +158,58 @@ final class ErrnoTest: XCTestCase {
|
||||
#endif
|
||||
|
||||
XCTAssert(ECANCELED == Errno.canceled.rawValue)
|
||||
#if !os(Windows)
|
||||
XCTAssert(EIDRM == Errno.identifierRemoved.rawValue)
|
||||
XCTAssert(ENOMSG == Errno.noMessage.rawValue)
|
||||
#endif
|
||||
XCTAssert(EILSEQ == Errno.illegalByteSequence.rawValue)
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(ENOATTR == Errno.attributeNotFound.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssert(EBADMSG == Errno.badMessage.rawValue)
|
||||
XCTAssert(EMULTIHOP == Errno.multiHop.rawValue)
|
||||
XCTAssert(ENODATA == Errno.noData.rawValue)
|
||||
XCTAssert(ENOLINK == Errno.noLink.rawValue)
|
||||
XCTAssert(EPROTO == Errno.protocolError.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows) && !os(FreeBSD) && !os(WASI)
|
||||
XCTAssert(ENODATA == Errno.noData.rawValue)
|
||||
XCTAssert(ENOSR == Errno.noStreamResources.rawValue)
|
||||
XCTAssert(ENOSTR == Errno.notStream.rawValue)
|
||||
XCTAssert(EPROTO == Errno.protocolError.rawValue)
|
||||
XCTAssert(ETIME == Errno.timeout.rawValue)
|
||||
#endif
|
||||
|
||||
XCTAssert(EOPNOTSUPP == Errno.notSupportedOnSocket.rawValue)
|
||||
|
||||
// From headers but not man page
|
||||
#if !os(WASI) // Would need to use _getConst func from CSystem
|
||||
XCTAssert(EWOULDBLOCK == Errno.wouldBlock.rawValue)
|
||||
#endif
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAETOOMANYREFS == Errno.tooManyReferences.rawValue)
|
||||
XCTAssert(WSAEREMOTE == Errno.tooManyRemoteLevels.rawValue)
|
||||
#elseif !os(WASI)
|
||||
XCTAssert(ETOOMANYREFS == Errno.tooManyReferences.rawValue)
|
||||
XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue)
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(ENOPOLICY == Errno.noSuchPolicy.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssert(ENOTRECOVERABLE == Errno.notRecoverable.rawValue)
|
||||
XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(FreeBSD)
|
||||
XCTAssert(ENOTCAPABLE == Errno.notCapable.rawValue)
|
||||
XCTAssert(ECAPMODE == Errno.capabilityMode.rawValue)
|
||||
XCTAssert(EINTEGRITY == Errno.integrityCheckFailed.rawValue)
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EQFULL == Errno.outputQueueFull.rawValue)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 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 !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#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
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
@Suite("FileMode")
|
||||
private struct FileModeTests {
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func basics() async throws {
|
||||
var mode = FileMode(rawValue: S_IFREG | 0o644) // Regular file, rw-r--r--
|
||||
#expect(mode.type == .regular)
|
||||
#expect(mode.permissions == [.ownerReadWrite, .groupRead, .otherRead])
|
||||
|
||||
mode.type = .directory // Directory, rw-r--r--
|
||||
#expect(mode.type == .directory)
|
||||
#expect(mode.permissions == [.ownerReadWrite, .groupRead, .otherRead])
|
||||
|
||||
mode.permissions.insert([.ownerExecute, .groupExecute, .otherExecute]) // Directory, rwxr-xr-x
|
||||
#expect(mode.type == .directory)
|
||||
#expect(mode.permissions == [.ownerReadWriteExecute, .groupReadExecute, .otherReadExecute])
|
||||
|
||||
mode.type = .symbolicLink // Symbolic link, rwxr-xr-x
|
||||
#expect(mode.type == .symbolicLink)
|
||||
#expect(mode.permissions == [.ownerReadWriteExecute, .groupReadExecute, .otherReadExecute])
|
||||
|
||||
let mode1 = FileMode(rawValue: S_IFLNK | 0o755) // Symbolic link, rwxr-xr-x
|
||||
let mode2 = FileMode(type: .symbolicLink, permissions: [.ownerReadWriteExecute, .groupReadExecute, .otherReadExecute])
|
||||
#expect(mode == mode1)
|
||||
#expect(mode1 == mode2)
|
||||
|
||||
mode.permissions.remove([.otherReadExecute]) // Symbolic link, rwxr-x---
|
||||
#expect(mode.permissions == [.ownerReadWriteExecute, .groupReadExecute])
|
||||
#expect(mode != mode1)
|
||||
#expect(mode != mode2)
|
||||
#expect(mode.type == mode1.type)
|
||||
#expect(mode.type == mode2.type)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@Test func invalidInput() async throws {
|
||||
// No permissions, all other bits set
|
||||
var invalidMode = FileMode(rawValue: ~0o7777)
|
||||
#expect(invalidMode.permissions.isEmpty)
|
||||
#expect(invalidMode.type != .directory)
|
||||
#expect(invalidMode.type != .characterSpecial)
|
||||
#expect(invalidMode.type != .blockSpecial)
|
||||
#expect(invalidMode.type != .regular)
|
||||
#expect(invalidMode.type != .fifo)
|
||||
#expect(invalidMode.type != .symbolicLink)
|
||||
#expect(invalidMode.type != .socket)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
#expect(invalidMode.type != .whiteout)
|
||||
#endif
|
||||
|
||||
// All file-type bits set
|
||||
invalidMode = FileMode(rawValue: S_IFMT)
|
||||
#expect(invalidMode.type != .directory)
|
||||
#expect(invalidMode.type != .characterSpecial)
|
||||
#expect(invalidMode.type != .blockSpecial)
|
||||
#expect(invalidMode.type != .regular)
|
||||
#expect(invalidMode.type != .fifo)
|
||||
#expect(invalidMode.type != .symbolicLink)
|
||||
#expect(invalidMode.type != .socket)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
#expect(invalidMode.type != .whiteout)
|
||||
#endif
|
||||
|
||||
// FileMode(type:permissions:) masks its inputs so
|
||||
// they don't accidentally modify the other bits.
|
||||
let emptyPermissions = FileMode(type: FileType(rawValue: ~0), permissions: [])
|
||||
#expect(emptyPermissions.permissions.isEmpty)
|
||||
#expect(emptyPermissions.type == FileType(rawValue: S_IFMT))
|
||||
#expect(emptyPermissions == invalidMode)
|
||||
|
||||
let regularFile = FileMode(type: .regular, permissions: FilePermissions(rawValue: ~0))
|
||||
#expect(regularFile.type == .regular)
|
||||
#expect(regularFile.permissions == FilePermissions(rawValue: 0o7777))
|
||||
#expect(regularFile.permissions == [
|
||||
.ownerReadWriteExecute,
|
||||
.groupReadWriteExecute,
|
||||
.otherReadWriteExecute,
|
||||
.setUserID, .setGroupID, .saveText
|
||||
])
|
||||
|
||||
// Setting properties should not modify the other bits, either.
|
||||
var mode = FileMode(rawValue: 0)
|
||||
mode.type = FileType(rawValue: ~0)
|
||||
#expect(mode.type == FileType(rawValue: S_IFMT))
|
||||
#expect(mode.permissions.isEmpty)
|
||||
|
||||
mode.type.rawValue = 0
|
||||
#expect(mode.type == FileType(rawValue: 0))
|
||||
#expect(mode.permissions.isEmpty)
|
||||
|
||||
mode.permissions = FilePermissions(rawValue: ~0)
|
||||
#expect(mode.permissions == FilePermissions(rawValue: 0o7777))
|
||||
#expect(mode.type == FileType(rawValue: 0))
|
||||
|
||||
mode.permissions = []
|
||||
#expect(mode.permissions.isEmpty)
|
||||
#expect(mode.type == FileType(rawValue: 0))
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -10,13 +10,19 @@
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
import System
|
||||
@testable import System
|
||||
#endif
|
||||
#if canImport(Android)
|
||||
import Android
|
||||
#elseif os(WASI)
|
||||
import CSystem
|
||||
#endif
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(System 0.0.1, *)
|
||||
final class FileOperationsTest: XCTestCase {
|
||||
#if ENABLE_MOCKING && !os(WASI) // Would need to use _getConst funcs from CSystem
|
||||
func testSyscalls() {
|
||||
let fd = FileDescriptor(rawValue: 1)
|
||||
|
||||
@@ -85,9 +91,14 @@ final class FileOperationsTest: XCTestCase {
|
||||
|
||||
for test in syscallTestCases { test.runAllTests() }
|
||||
}
|
||||
#endif // ENABLE_MOCKING && !os(WASI)
|
||||
|
||||
func testWriteFromEmptyBuffer() throws {
|
||||
#if os(Windows)
|
||||
let fd = try FileDescriptor.open(FilePath("NUL"), .writeOnly)
|
||||
#else
|
||||
let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly)
|
||||
#endif
|
||||
let written1 = try fd.write(toAbsoluteOffset: 0, .init(start: nil, count: 0))
|
||||
XCTAssertEqual(written1, 0)
|
||||
|
||||
@@ -98,23 +109,55 @@ final class FileOperationsTest: XCTestCase {
|
||||
XCTAssertEqual(written2, 0)
|
||||
}
|
||||
|
||||
func testReadToEmptyBuffer() throws {
|
||||
let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly)
|
||||
let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0))
|
||||
XCTAssertEqual(read1, 0)
|
||||
#if os(Windows)
|
||||
// Generate a file containing random bytes; this should not be used
|
||||
// for cryptography, it's just for testing.
|
||||
func generateRandomData(at path: FilePath, count: Int) throws {
|
||||
let fd = try FileDescriptor.open(path, .readWrite,
|
||||
options: [.create, .truncate])
|
||||
defer {
|
||||
try! fd.close()
|
||||
}
|
||||
let data = [UInt8](
|
||||
sequence(first: 0,
|
||||
next: {
|
||||
_ in UInt8.random(in: UInt8.min...UInt8.max)
|
||||
}).dropFirst().prefix(count)
|
||||
)
|
||||
|
||||
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
|
||||
defer { pointer.deallocate() }
|
||||
let empty = UnsafeMutableRawBufferPointer(start: pointer, count: 0)
|
||||
let read2 = try fd.read(fromAbsoluteOffset: 0, into: empty)
|
||||
XCTAssertEqual(read2, 0)
|
||||
try data.withUnsafeBytes {
|
||||
_ = try fd.write($0)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testReadToEmptyBuffer() throws {
|
||||
try withTemporaryFilePath(basename: "testReadToEmptyBuffer") { path in
|
||||
#if os(Windows)
|
||||
// Windows doesn't have an equivalent to /dev/random, so generate
|
||||
// some random bytes and write them to a file for the next step.
|
||||
let randomPath = path.appending("random.txt")
|
||||
try generateRandomData(at: randomPath, count: 16)
|
||||
let fd = try FileDescriptor.open(randomPath, .readOnly)
|
||||
#else // !os(Windows)
|
||||
let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly)
|
||||
#endif
|
||||
let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0))
|
||||
XCTAssertEqual(read1, 0)
|
||||
|
||||
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
|
||||
defer { pointer.deallocate() }
|
||||
let empty = UnsafeMutableRawBufferPointer(start: pointer, count: 0)
|
||||
let read2 = try fd.read(fromAbsoluteOffset: 0, into: empty)
|
||||
XCTAssertEqual(read2, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testHelpers() {
|
||||
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
#if !os(WASI) // WASI has no pipe
|
||||
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`.
|
||||
@@ -133,33 +176,35 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
func testAdHocOpen() {
|
||||
// Ad-hoc test touching a file system.
|
||||
do {
|
||||
// TODO: Test this against a virtual in-memory file system
|
||||
let fd = try FileDescriptor.open("/tmp/b.txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
try fd.closeAfter {
|
||||
try fd.writeAll("abc".utf8)
|
||||
var def = "def"
|
||||
try def.withUTF8 {
|
||||
_ = try fd.write(UnsafeRawBufferPointer($0))
|
||||
}
|
||||
try fd.seek(offset: 1, from: .start)
|
||||
try withTemporaryFilePath(basename: "testAdhocOpen") { path in
|
||||
let fd = try FileDescriptor.open(path.appending("b.txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
try fd.closeAfter {
|
||||
try fd.writeAll("abc".utf8)
|
||||
var def = "def"
|
||||
try def.withUTF8 {
|
||||
_ = try fd.write(UnsafeRawBufferPointer($0))
|
||||
}
|
||||
try fd.seek(offset: 1, from: .start)
|
||||
|
||||
let readLen = 3
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
let preadBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
|
||||
count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
let readLen = 3
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
let preadBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
|
||||
count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
|
||||
XCTAssertEqual(readBytes.first!, "b".utf8.first!)
|
||||
XCTAssertEqual(readBytes, preadBytes)
|
||||
XCTAssertEqual(readBytes.first!, "b".utf8.first!)
|
||||
XCTAssertEqual(readBytes, preadBytes)
|
||||
|
||||
// TODO: seek
|
||||
// TODO: seek
|
||||
}
|
||||
}
|
||||
} catch let err as Errno {
|
||||
print("caught \(err))")
|
||||
@@ -170,10 +215,16 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
func testGithubIssues() {
|
||||
// https://github.com/apple/swift-system/issues/26
|
||||
#if os(WASI)
|
||||
let openOptions = _getConst_O_WRONLY() | _getConst_O_CREAT()
|
||||
#else
|
||||
let openOptions = O_WRONLY | O_CREAT
|
||||
#endif
|
||||
let issue26 = MockTestCase(
|
||||
name: "open", .interruptable, "a path", O_WRONLY | O_CREAT, 0o020
|
||||
name: "open", .interruptable, "a path", openOptions, 0o020
|
||||
) {
|
||||
retryOnInterrupt in
|
||||
_ = try FileDescriptor.open(
|
||||
@@ -182,51 +233,51 @@ final class FileOperationsTest: XCTestCase {
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
issue26.runAllTests()
|
||||
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
#if !os(Windows)
|
||||
func testResizeFile() throws {
|
||||
let fd = try FileDescriptor.open("/tmp/\(UUID().uuidString).txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
try fd.closeAfter {
|
||||
// File should be empty initially.
|
||||
XCTAssertEqual(try fd.fileSize(), 0)
|
||||
// Write 3 bytes.
|
||||
try fd.writeAll("abc".utf8)
|
||||
// File should now be 3 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 3)
|
||||
// Resize to 6 bytes.
|
||||
try fd.resize(to: 6)
|
||||
// File should now be 6 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 6)
|
||||
// Read in the 6 bytes.
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
// Should have read all 6 bytes.
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
XCTAssertEqual(count, 6)
|
||||
try withTemporaryFilePath(basename: "testResizeFile") { path in
|
||||
let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
try fd.closeAfter {
|
||||
// File should be empty initially.
|
||||
XCTAssertEqual(try fd.fileSize(), 0)
|
||||
// Write 3 bytes.
|
||||
try fd.writeAll("abc".utf8)
|
||||
// File should now be 3 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 3)
|
||||
// Resize to 6 bytes.
|
||||
try fd.resize(to: 6)
|
||||
// File should now be 6 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 6)
|
||||
// Read in the 6 bytes.
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
// Should have read all 6 bytes.
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
XCTAssertEqual(count, 6)
|
||||
}
|
||||
// First 3 bytes should be unaffected by resize.
|
||||
XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8))
|
||||
// Extension should be padded with zeros.
|
||||
XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3))
|
||||
// File should still be 6 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 6)
|
||||
// Resize to 2 bytes.
|
||||
try fd.resize(to: 2)
|
||||
// File should now be 2 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 2)
|
||||
// Read in file with a buffer big enough for 6 bytes.
|
||||
let readBytesAfterTruncation = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
// Should only have read 2 bytes.
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
// Written content was trunctated.
|
||||
XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8))
|
||||
}
|
||||
// First 3 bytes should be unaffected by resize.
|
||||
XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8))
|
||||
// Extension should be padded with zeros.
|
||||
XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3))
|
||||
// File should still be 6 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 6)
|
||||
// Resize to 2 bytes.
|
||||
try fd.resize(to: 2)
|
||||
// File should now be 2 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 2)
|
||||
// Read in file with a buffer big enough for 6 bytes.
|
||||
let readBytesAfterTruncation = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
// Should only have read 2 bytes.
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
// Written content was trunctated.
|
||||
XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
import WinSDK
|
||||
|
||||
@available(iOS 8, *)
|
||||
final class FileOperationsTestWindows: XCTestCase {
|
||||
private let r = ACCESS_MASK(
|
||||
FILE_READ_ATTRIBUTES
|
||||
| FILE_READ_DATA
|
||||
| FILE_READ_EA
|
||||
| STANDARD_RIGHTS_READ
|
||||
| SYNCHRONIZE
|
||||
)
|
||||
private let w = ACCESS_MASK(
|
||||
FILE_APPEND_DATA
|
||||
| FILE_WRITE_ATTRIBUTES
|
||||
| FILE_WRITE_DATA
|
||||
| FILE_WRITE_EA
|
||||
| STANDARD_RIGHTS_WRITE
|
||||
| SYNCHRONIZE
|
||||
)
|
||||
private let x = ACCESS_MASK(
|
||||
FILE_EXECUTE
|
||||
| FILE_READ_ATTRIBUTES
|
||||
| STANDARD_RIGHTS_EXECUTE
|
||||
| SYNCHRONIZE
|
||||
)
|
||||
|
||||
private struct Test {
|
||||
var permissions: CModeT
|
||||
var ownerAccess: ACCESS_MASK
|
||||
var groupAccess: ACCESS_MASK
|
||||
var otherAccess: ACCESS_MASK
|
||||
|
||||
init(_ permissions: CModeT,
|
||||
_ ownerAccess: ACCESS_MASK,
|
||||
_ groupAccess: ACCESS_MASK,
|
||||
_ otherAccess: ACCESS_MASK) {
|
||||
self.permissions = permissions
|
||||
self.ownerAccess = ownerAccess
|
||||
self.groupAccess = groupAccess
|
||||
self.otherAccess = otherAccess
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve the owner, group and other access masks for a given file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to the file to inspect
|
||||
/// - Returns: A tuple of ACCESS_MASK values.
|
||||
func getAccessMasks(
|
||||
path: FilePath
|
||||
) -> (ACCESS_MASK, ACCESS_MASK, ACCESS_MASK) {
|
||||
var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1))
|
||||
var psidEveryone: PSID? = nil
|
||||
|
||||
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
|
||||
DWORD(SECURITY_WORLD_RID),
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
&psidEveryone))
|
||||
defer {
|
||||
FreeSid(psidEveryone)
|
||||
}
|
||||
|
||||
var everyone = TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
psidEveryone!.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
|
||||
return path.withPlatformString { objectName in
|
||||
var psidOwner: PSID? = nil
|
||||
var psidGroup: PSID? = nil
|
||||
var pDacl: PACL? = nil
|
||||
var pSD: PSECURITY_DESCRIPTOR? = nil
|
||||
|
||||
XCTAssertEqual(GetNamedSecurityInfoW(
|
||||
objectName,
|
||||
SE_FILE_OBJECT,
|
||||
SECURITY_INFORMATION(
|
||||
DACL_SECURITY_INFORMATION
|
||||
| GROUP_SECURITY_INFORMATION
|
||||
| OWNER_SECURITY_INFORMATION
|
||||
),
|
||||
&psidOwner,
|
||||
&psidGroup,
|
||||
&pDacl,
|
||||
nil,
|
||||
&pSD), DWORD(ERROR_SUCCESS))
|
||||
defer {
|
||||
LocalFree(pSD)
|
||||
}
|
||||
|
||||
var owner = TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_USER,
|
||||
ptstrName:
|
||||
psidOwner!.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
var group = TRUSTEE_W(
|
||||
pMultipleTrustee: nil,
|
||||
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
|
||||
TrusteeForm: TRUSTEE_IS_SID,
|
||||
TrusteeType: TRUSTEE_IS_GROUP,
|
||||
ptstrName:
|
||||
psidGroup!.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
)
|
||||
|
||||
var ownerAccess = ACCESS_MASK(0)
|
||||
var groupAccess = ACCESS_MASK(0)
|
||||
var otherAccess = ACCESS_MASK(0)
|
||||
|
||||
XCTAssertEqual(GetEffectiveRightsFromAclW(
|
||||
pDacl,
|
||||
&owner,
|
||||
&ownerAccess), DWORD(ERROR_SUCCESS))
|
||||
XCTAssertEqual(GetEffectiveRightsFromAclW(
|
||||
pDacl,
|
||||
&group,
|
||||
&groupAccess), DWORD(ERROR_SUCCESS))
|
||||
XCTAssertEqual(GetEffectiveRightsFromAclW(
|
||||
pDacl,
|
||||
&everyone,
|
||||
&otherAccess), DWORD(ERROR_SUCCESS))
|
||||
|
||||
return (ownerAccess, groupAccess, otherAccess)
|
||||
}
|
||||
}
|
||||
|
||||
private func runTests(_ tests: [Test], at path: FilePath) throws {
|
||||
for test in tests {
|
||||
let octal = String(test.permissions, radix: 8)
|
||||
let testPath = path.appending("test-\(octal).txt")
|
||||
let fd = try FileDescriptor.open(
|
||||
testPath,
|
||||
.readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: FilePermissions(rawValue: test.permissions)
|
||||
)
|
||||
_ = try fd.closeAfter {
|
||||
try fd.writeAll("Hello World".utf8)
|
||||
}
|
||||
|
||||
let (ownerAccess, groupAccess, otherAccess)
|
||||
= getAccessMasks(path: testPath)
|
||||
|
||||
XCTAssertEqual(ownerAccess, test.ownerAccess)
|
||||
XCTAssertEqual(groupAccess, test.groupAccess)
|
||||
XCTAssertEqual(otherAccess, test.otherAccess)
|
||||
}
|
||||
}
|
||||
|
||||
/// Test that the umask works properly
|
||||
func testUmask() throws {
|
||||
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
|
||||
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
|
||||
|
||||
// Default mask should be 0o022
|
||||
XCTAssertEqual(FilePermissions.creationMask, [.groupWrite, .otherWrite])
|
||||
|
||||
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(0o777, r|w|x, r|x, r|x)
|
||||
]
|
||||
|
||||
try runTests(tests, at: path)
|
||||
}
|
||||
|
||||
try FilePermissions.withCreationMask([.groupWrite, .groupExecute,
|
||||
.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(0o777, r|w|x, r, r)
|
||||
]
|
||||
|
||||
try runTests(tests, at: path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Test that setting permissions on a file works as expected
|
||||
func testPermissions() throws {
|
||||
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
|
||||
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
|
||||
|
||||
try FilePermissions.withCreationMask([]) {
|
||||
try withTemporaryFilePath(basename: "testPermissions") { path in
|
||||
let tests = [
|
||||
Test(0o000, 0, 0, 0),
|
||||
|
||||
Test(0o400, r, 0, 0),
|
||||
Test(0o200, w, 0, 0),
|
||||
Test(0o100, x, 0, 0),
|
||||
Test(0o040, 0, r, 0),
|
||||
Test(0o020, 0, w, 0),
|
||||
Test(0o010, 0, x, 0),
|
||||
Test(0o004, 0, 0, r),
|
||||
Test(0o002, 0, 0, w),
|
||||
Test(0o001, 0, 0, x),
|
||||
|
||||
Test(0o700, r|w|x, 0, 0),
|
||||
Test(0o770, r|w|x, r|w|x, 0),
|
||||
Test(0o777, r|w|x, r|w|x, r|w|x),
|
||||
|
||||
Test(0o755, r|w|x, r|x, r|x),
|
||||
Test(0o644, r|w, r, r),
|
||||
|
||||
Test(0o007, 0, 0, r|w|x),
|
||||
Test(0o070, 0, r|w|x, 0),
|
||||
Test(0o077, 0, r|w|x, r|w|x),
|
||||
]
|
||||
|
||||
try runTests(tests, at: path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // os(Windows)
|
||||
@@ -15,7 +15,7 @@ import XCTest
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
struct TestPathComponents: TestCase {
|
||||
var path: FilePath
|
||||
var expectedRoot: FilePath.Root?
|
||||
@@ -100,14 +100,14 @@ struct TestPathComponents: TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
final class FilePathComponentsTest: XCTestCase {
|
||||
func testAdHocRRC() {
|
||||
var path: FilePath = "/usr/local/bin"
|
||||
|
||||
func expect(
|
||||
_ s: String,
|
||||
_ file: StaticString = #file,
|
||||
_ file: StaticString = #filePath,
|
||||
_ line: UInt = #line
|
||||
) {
|
||||
if path == FilePath(s) { return }
|
||||
@@ -231,7 +231,7 @@ final class FilePathComponentsTest: XCTestCase {
|
||||
}
|
||||
|
||||
func testCases() {
|
||||
let testPaths: Array<TestPathComponents> = [
|
||||
var testPaths: Array<TestPathComponents> = [
|
||||
TestPathComponents("", root: nil, []),
|
||||
TestPathComponents("/", root: "/", []),
|
||||
TestPathComponents("foo", root: nil, ["foo"]),
|
||||
@@ -240,16 +240,28 @@ final class FilePathComponentsTest: XCTestCase {
|
||||
TestPathComponents("foo/bar", root: nil, ["foo", "bar"]),
|
||||
TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]),
|
||||
TestPathComponents("/foo/bar", root: "/", ["foo", "bar"]),
|
||||
TestPathComponents("///foo//", root: "/", ["foo"]),
|
||||
TestPathComponents("/foo///bar", root: "/", ["foo", "bar"]),
|
||||
TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]),
|
||||
TestPathComponents("foo///bar/baz/", root: nil, ["foo", "bar", "baz"]),
|
||||
TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"]),
|
||||
TestPathComponents("./", root: nil, ["."]),
|
||||
TestPathComponents("./..", root: nil, [".", ".."]),
|
||||
TestPathComponents("/./..//", root: "/", [".", ".."]),
|
||||
]
|
||||
testPaths.forEach { $0.runAllTests() }
|
||||
#if !os(Windows)
|
||||
testPaths.append(contentsOf:[
|
||||
TestPathComponents("///foo//", root: "/", ["foo"]),
|
||||
TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"])
|
||||
])
|
||||
#else
|
||||
// On Windows, these are UNC paths
|
||||
testPaths.append(contentsOf:[
|
||||
TestPathComponents("///foo//", root: "///foo//", []),
|
||||
TestPathComponents("//foo///bar/baz/", root: "//foo//", ["bar", "baz"])
|
||||
])
|
||||
#endif
|
||||
testPaths.forEach {
|
||||
$0.runAllTests()
|
||||
}
|
||||
}
|
||||
|
||||
func testSeparatorNormalization() {
|
||||
|
||||
@@ -15,7 +15,7 @@ import XCTest
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
@available(System 0.0.1, *)
|
||||
final class FilePathDecodableTest: XCTestCase {
|
||||
func testInvalidFilePath() {
|
||||
// _storage is a valid SystemString, but the invariants of FilePath are
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#endif
|
||||
|
||||
// Why can't I write this extension on `FilePath.ComponentView.SubSequence`?
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension Slice where Base == FilePath.ComponentView {
|
||||
internal var _storageSlice: SystemString.SubSequence {
|
||||
base._path._storage[self.startIndex._storage ..< self.endIndex._storage]
|
||||
@@ -15,7 +15,7 @@ extension Slice where Base == FilePath.ComponentView {
|
||||
|
||||
|
||||
// Proposed API that didn't make the cut, but we stil want to keep our testing for
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension FilePath {
|
||||
/// Returns `self` relative to `base`.
|
||||
/// This does not cosult the file system or resolve symlinks.
|
||||
@@ -51,7 +51,6 @@ extension FilePath {
|
||||
|
||||
/// Whether a lexically-normalized `self` contains a lexically-normalized
|
||||
/// `other`.
|
||||
///
|
||||
public func lexicallyContains(_ other: FilePath) -> Bool {
|
||||
guard !other.isEmpty else { return true }
|
||||
guard !isEmpty else { return false }
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@@ -68,7 +69,7 @@ extension ParsingTestCase {
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
final class FilePathParsingTest: XCTestCase {
|
||||
func testNormalization() {
|
||||
let unixPaths: Array<ParsingTestCase> = [
|
||||
@@ -105,3 +106,4 @@ final class FilePathParsingTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
@@ -7,6 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@@ -146,7 +147,7 @@ extension SyntaxTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension SyntaxTestCase {
|
||||
func testComponents(_ path: FilePath, expected: [String]) {
|
||||
let expectedComponents = expected.map { FilePath.Component($0)! }
|
||||
@@ -342,7 +343,7 @@ private struct WindowsRootTestCase: TestCase {
|
||||
var line: UInt
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
extension WindowsRootTestCase {
|
||||
func runAllTests() {
|
||||
withWindowsPaths(enabled: true) {
|
||||
@@ -357,7 +358,7 @@ extension WindowsRootTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@available(System 0.0.2, *)
|
||||
final class FilePathSyntaxTest: XCTestCase {
|
||||
func testPathSyntax() {
|
||||
let unixPaths: Array<SyntaxTestCase> = [
|
||||
@@ -849,7 +850,7 @@ final class FilePathSyntaxTest: XCTestCase {
|
||||
|
||||
func expect(
|
||||
_ s: String,
|
||||
_ file: StaticString = #file,
|
||||
_ file: StaticString = #filePath,
|
||||
_ line: UInt = #line
|
||||
) {
|
||||
if path == FilePath(s) { return }
|
||||
@@ -1064,7 +1065,10 @@ final class FilePathSyntaxTest: XCTestCase {
|
||||
XCTAssert(path.lexicallyContains("usr"))
|
||||
XCTAssert(path.lexicallyContains("/usr"))
|
||||
XCTAssert(path.lexicallyContains("local/bin"))
|
||||
#if !os(Windows)
|
||||
// On Windows, this is a relative path and is still contained
|
||||
XCTAssert(!path.lexicallyContains("/local/bin"))
|
||||
#endif
|
||||
path.append("..")
|
||||
XCTAssert(!path.lexicallyContains("local/bin"))
|
||||
XCTAssert(path.lexicallyContains("local/bin/.."))
|
||||
@@ -1235,3 +1239,4 @@ final class FilePathSyntaxTest: XCTestCase {
|
||||
}
|
||||
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user