Compare commits

..
Author SHA1 Message Date
Michael Ilseman 81fded4dd9 [staging] Add Span-based file I/O APIs (#290)
* Add Span-based file I/O APIs

Implement read/write methods accepting RawSpan and OutputRawSpan,
with support for absolute offset operations and fill-until-complete
semantics. Refactor buffer handling into reusable helpers.

* wip: cleanup

* wip: cleanup
2026-01-23 15:15:19 -07:00
Michael Ilseman 774c7eb5a0 [staging] Sockets 2026 (#281)
Add socket APIs to swift-system (#281)

Port the long-standing sockets implementation from #30 to the new
staging branch. This adds comprehensive low-level Swift APIs for
POSIX socket programming.

Original Co-authored-by: Karoy Lorentey <karoly@apple.com>
2026-01-09 21:25:40 -07:00
Guillaume Lessard 2e372aa16c Merge pull request #277 from glessard/dev/adjust-gh-actions
[ci] adjust the pull-request action
2026-01-06 17:07:27 -08:00
Guillaume Lessard 4956c2c512 [ci] adjust the pull-request action 2026-01-06 13:29:46 -08:00
Jonathan Flat b083113aef Merge pull request #270 from jrflat/fix-android-stat
Fix Stat build on Android
2025-11-04 10:29:45 -07:00
Jonathan Flat f9a2b9443b Exclude focal for Android build 2025-11-03 18:29:15 -07:00
Jonathan Flat b252c123a7 Enable Android SDK build 2025-11-03 18:11:02 -07:00
Jonathan Flat e133abb3e0 Fix Stat build on Android 2025-11-03 18:05:50 -07:00
Jonathan Flat b11b33ab57 Merge pull request #256 from jrflat/stat-implementation
Stat implementation for Swift System
2025-11-03 11:47:40 -07:00
Jonathan Flat 55350cd06d Add availability to new CInterop typealiases 2025-11-02 22:31:37 -07:00
Jonathan Flat 87f8e49ba7 Assign rawValue instead of self 2025-10-30 14:11:45 -06:00
Guillaume Lessard d5f59fe404 Merge pull request #267 from incertum/chore/workflow-permissions
chore: restrict GitHub workflow permissions - future-proof
2025-10-29 11:03:22 -07:00
Jonathan Flat c2e385e849 Remove commented-out code pt. 2 2025-10-29 12:01:13 -06:00
Jonathan Flat 4911642226 Add availability, fix CInterop availability issue on old Darwin platforms 2025-10-29 12:01:01 -06:00
Jonathan Flat 40e1deb663 Consolidate internal Stat functions 2025-10-29 11:47:32 -06:00
Jonathan Flat eee0145671 Standardize on "file system" 2025-10-28 22:52:34 -06:00
Jonathan Flat 90dba1dc68 AT_SYMLINK_FOLLOW -> AT_SYMLINK_NOFOLLOW 2025-10-28 22:31:34 -06:00
Jonathan Flat 501bb7d052 Remove commented-out code for future directions 2025-10-28 22:30:47 -06:00
Melissa Kilby 67a2fd2ca1 chore: restrict GitHub workflow permissions - future-proof
Signed-off-by: Melissa Kilby <mkilby@apple.com>
2025-10-17 16:28:56 -07:00
Stephen Canon bc16a3c120 Merge pull request #257 from jrflat/stat-proposal
[Proposal] Stat for Swift System
2025-10-13 12:14:18 -04:00
Jonathan Flat 98712f67f2 Remove _GNU_SOURCE define and AT_EMPTY_PATH for now 2025-10-06 13:32:29 -06:00
Jonathan Flat 2f5b12b854 Updates for proposal v3 2025-09-29 12:02:59 -06:00
Jonathan Flat 905f9f842d Expose C timespec properties until UTCClock can be used 2025-09-29 11:34:04 -06:00
Jonathan Flat a07696ace3 Fix AT_RESOLVE_BENEATH availability 2025-09-29 11:34:03 -06:00
Jonathan Flat 57d515e1d0 Stat implementation 2025-09-29 11:34:02 -06:00
Jonathan Flat 2f4c8c216c Create Proposals directory 2025-09-29 11:26:15 -06:00
Jonathan Flat 70f197f036 Address feedback (v3) 2025-09-29 11:19:36 -06:00
Guillaume Lessard f477389569 Merge pull request #264 from apple/adjust-toolchain-support
Adjust toolchain support
2025-09-19 09:06:44 -07:00
Guillaume Lessard bc4e6e3bea Use Swift 5 language mode
`MachPort` is fine with Swift 6.1 and up, but does not compile with Swift 6.0’s Swift 6 language mode.
`import CSystem` is a problem in the Linux version (inconsistently imported as implementation-only.)
The Wasm implementation seems not concurrency-safe.
2025-09-18 17:52:01 -07:00
Guillaume Lessard d8dd95176b adjust pull-request workflow 2025-09-18 17:30:36 -07:00
Guillaume Lessard 2ae0c650be Make shared state constant as intended. 2025-09-18 17:01:26 -07:00
Guillaume Lessard 478da393fa Use new names for Swift 6 mode 2025-09-18 16:59:28 -07:00
Guillaume Lessard 80587df07f Require Swift 6.0 2025-09-18 16:58:21 -07:00
Guillaume Lessard 4bbe3f3eeb Merge pull request #261 from apple/release/1.6.0
Merge back tag 1.6.3
2025-09-18 11:41:27 -07:00
Guillaume Lessard 9ddc89964b Merge pull request #263 from apple/workflow-edits-1.6.0
[1.6.0] Apply GitHub workflow edits
2025-09-18 11:14:47 -07:00
Guillaume Lessard 18a52c4729 [workflows] declare 2D exclusions 2025-09-18 10:47:41 -07:00
Guillaume Lessard 1c1ad1d3f4 [workflows] change ubuntus to test against 2025-09-18 10:09:02 -07:00
Guillaume Lessard 2fdd948a28 Merge pull request #262 from glessard/workflow-edits
[workflows] change ubuntus to test against
2025-09-18 09:47:02 -07:00
Guillaume Lessard 227ebbbe2d [workflows] declare 2D exclusions 2025-09-18 08:00:59 -07:00
Guillaume Lessard b6bd66889b [workflows] change ubuntus to test against 2025-09-17 15:46:21 -07:00
Guillaume Lessard 395a77f0aa Merge pull request #260 from apple/eng/PR-duplicate-as-release/1.6.0
[1.6] Fix: FileDescriptor.duplicate(as:) returns an invalid file descriptor on Windows
2025-09-15 10:31:53 -07:00
Jake Petroules b1618475cc [1.6] Fix: FileDescriptor.duplicate(as:) returns an invalid file descriptor on Windows
FileDescriptor.duplicate(as:) is backed by dup2 on Unix, and _dup2 on Windows.
On Unix, dup2 returns its second argument. On Windows, _dup2 instead returns
0 on success and -1 on error. This results in the newly returned FileDescriptor
object always containing a '0' file descriptor rather than the newly created
file descriptor, in violation of the documented behavior.

Account for the platform difference in the syscall wrapper to fix this.

Closes #192

(cherry picked from commit b2711a872a)
2025-09-15 10:16:15 -07:00
Jake Petroules b2711a872a Fix: FileDescriptor.duplicate(as:) returns an invalid file descriptor on Windows
FileDescriptor.duplicate(as:) is backed by dup2 on Unix, and _dup2 on Windows.
On Unix, dup2 returns its second argument. On Windows, _dup2 instead returns
0 on success and -1 on error. This results in the newly returned FileDescriptor
object always containing a '0' file descriptor rather than the newly created
file descriptor, in violation of the documented behavior.

Account for the platform difference in the syscall wrapper to fix this.

Closes #192
2025-09-12 22:11:45 -07:00
Guillaume Lessard b6a7776360 Merge pull request #255 from lamtrinhdev/Fix_typo_issues
Fix spelling errors in some comments.
2025-08-12 15:00:43 -07:00
Jonathan Flat 0b3b691d0b Update pitch link 2025-08-12 12:36:17 -06:00
Jonathan Flat 0610d8f893 Stat proposal 2025-08-12 12:16:13 -06:00
LamTrinh.Dev 0ea6743c17 Fix spelling errors in some comments. 2025-08-11 00:56:26 +07:00
Guillaume Lessard 890830fff1 Merge pull request #254 from jrflat/fix-generic-int-typedefs-1.6.0 2025-08-03 17:11:41 -07:00
Jonathan Flat a5f13c77b8 Fix typedef errors on platforms with _ASM_GENERIC_INT headers 2025-08-03 11:24:24 -06:00
Jonathan Flat 086219bf62 Merge pull request #253 from jrflat/static-and-wasm-sdk-builds
[CI] Enable Linux static SDK and Wasm SDK builds
2025-08-01 16:21:21 -06:00
Jonathan Flat 11d9d4a78e [CI] Enable Linux static SDK and Wasm SDK builds 2025-08-01 14:51:27 -06:00
Jonathan Flat 0c11feadd4 Merge pull request #252 from jrflat/release-mode-testing
Support testing in release mode
2025-07-31 10:11:32 -06:00
Guillaume Lessard 2410aed341 Merge pull request #251 from apple/release/1.6.0
Merge 1.6.x into main
2025-07-31 09:05:02 -07:00
Jonathan Flat 9ec41a667c Support testing in release mode 2025-07-30 18:47:26 -06:00
Guillaume Lessard 9226c72b3a Merge pull request #232 from apple/availability-macros
Replace bespoke availability system
2025-07-30 17:10:32 -07:00
Guillaume Lessard d9d138a88e Merge pull request #250 from glessard/five-nine-required
[gardening] Swift 5.9 is required
2025-07-30 16:08:07 -07:00
Guillaume Lessard 13ad3fe4ac Update copyright dates 2025-07-30 14:29:52 -07:00
Guillaume Lessard 2610d66a52 This package requires Swift 5.9
Accordingly, these conditions would always be true
2025-07-30 14:29:52 -07:00
Guillaume Lessard e0d9cb0638 Merge pull request #249 from glessard/feature-flag-condition
Gate 6.2 features by feature flag
2025-07-30 09:46:08 -07:00
Guillaume Lessard c4fef8b59a Disable non-escapable API by feature flag 2025-07-30 09:21:05 -07:00
Rauhul Varma f97a80426c update readme 2025-07-30 08:53:33 -07:00
Rauhul Varma e5198c2b2d disable 16.0 and 16.1 2025-07-30 08:50:14 -07:00
Rauhul Varma 9a1530813e Replace bespoke availability system
Removes the script based availability system with the experimental
availability macro feature.
2025-07-30 08:40:08 -07:00
Guillaume Lessard b63d24d465 Merge pull request #248 from glessard/updates-1.6.1
Updates for 1.6.1 tag
2025-07-29 23:11:20 -07:00
Guillaume Lessard a717516d69 Merge branch 'main' into updates-1.6.1 2025-07-29 18:50:55 -07:00
Jonathan Flat d89ca1d511 Merge pull request #247 from jrflat/ioring-for-older-kernels
Fix IORing build for older Linux kernels
2025-07-29 19:38:33 -06:00
Jonathan Flat d32abd8c6e Fix warning: will never be executed 2025-07-29 15:35:30 -06:00
Guillaume Lessard d75acaac3a [ci] expand github actions 2025-07-29 14:26:38 -06:00
Jonathan Flat 5fedb102b5 Fix IORing build for older Linux kernel versions 2025-07-29 14:24:17 -06:00
Guillaume Lessard 960067d31a Merge pull request #245 from glessard/update-readme-main
Update README
2025-07-29 11:06:18 -07:00
Guillaume Lessard 0bb855ac35 Merge pull request #244 from glessard/update-readme-1.6.x
Update README
2025-07-29 08:10:23 -07:00
Guillaume Lessard 3f68d42246 Update Readme 2025-07-28 17:42:40 -07:00
Guillaume Lessard c72c758953 Update Readme 2025-07-28 17:41:23 -07:00
Jonathan Flat a067a0751a Merge pull request #242 from jrflat/fix-ioring-static-linux-sdk
Fix IORing static Linux SDK
2025-07-28 14:31:18 -06:00
Jonathan Flat e1191b2ba5 Merge pull request #241 from jrflat/fix-ioring-release-build
Fix IORing release build
2025-07-28 14:30:41 -06:00
Jonathan Flat c7eaf63462 Merge pull request #239 from jrflat/fix-wasi-build
Fix WASI build (dirent, umask, errno and open flag tests)
2025-07-28 12:18:40 -06:00
Jonathan Flat 4f5b5fb40d Fix IORing static Linux SDK 2025-07-28 12:08:37 -06:00
Jonathan Flat 5059730d24 Fix IORing release build 2025-07-28 10:52:35 -06:00
Jonathan Flat 8de80270cb Fix WASI build (dirent, umask, errno and open flag tests) 2025-07-25 14:03:59 -06:00
David Smith 41daa93a5d Merge pull request #235 from apple/merge-1.5.0-into-main
Merge 1.5.0 into main
2025-07-24 22:18:56 +00:00
David Smith 2adb6b41cc Merge branch 'release/1.5.0' into merge-1.5.0-into-main 2025-07-24 14:29:18 -07:00
Guillaume Lessard 6ee9a58c36 Merge pull request #234 from azarovalex/fix-api-docs
Fix API documentation links in README.md
2025-07-14 15:18:35 -07:00
David Smith 7f9dba80cf Merge pull request #208 from apple/david/ioring
Add io_uring support to System
2025-07-12 00:39:04 +00:00
David Smith 08ed962064 Don't abort the test if we can't open /proc/sys/kernel/io_uring_disabled 2025-07-11 23:05:26 +00:00
David Smith 08ea3343a5 Merge branch 'david/ioring' of https://github.com/apple/swift-system into david/ioring 2025-07-11 22:42:41 +00:00
David Smith a66176f518 Only run IORing tests if io_uring support is enabled 2025-07-11 22:42:35 +00:00
David Smith 33b58a8110 Fix excludes harder 2025-07-11 13:44:46 -07:00
David Smith 52d9c99a94 Fix excludes 2025-07-11 13:42:49 -07:00
David Smith b93169b8e2 Work around windows bugs harder 2025-07-11 20:37:23 +00:00
David Smith 9a046498d0 Try adding newlines to the ends of files to work around a compiler bug 2025-07-11 19:23:24 +00:00
David Smith a56bcda3c1 Un-combine conditionals but flip their order. This should fix the Windows build with older compilers 2025-07-11 19:07:04 +00:00
David Smith f7c05e1fb8 Combine platform conditionals 2025-07-11 18:53:55 +00:00
David Smith 7fc787e6ba Move IORing files to a subdirectory 2025-07-11 17:00:32 +00:00
David Smith 779c9ac628 Fix misuse of _CANCEL_ANY, and add support for non-redicated cancellation 2025-07-11 16:50:58 +00:00
David Smith 2f6c4e0f03 Add support for non-IORING_FEAT_SINGLE_MMAP kernels 2025-07-11 16:14:36 +00:00
David Smith d121081c01 More Ubuntu 22 workarounds. This should error at runtime rather than not compiling, since we don't have Linux version checks at compile time 2025-07-10 23:30:42 +00:00
David Smith a6675d7e5c timespec should be compatible here, let's try it to fix the Ubuntu 22 build 2025-07-10 23:22:11 +00:00
David Smith 329c5f59a2 Conditionalize IORing on compiler >= 6.2 2025-07-09 21:17:42 +00:00
David Smith 6dd0eba8e3 Merge branch 'david/ioring' of https://github.com/apple/swift-system into david/ioring 2025-07-09 20:53:28 +00:00
David Smith 4b70ffe375 Fix short submits and also fix the registration ops enum, which somehow stopped compiling overnight 2025-07-09 20:53:23 +00:00
David Smith 8757fae97c Remove some stray commas the API breakage test complains about 2025-07-08 16:57:30 -07:00
David Smith d2b78f801b Remove unneeded defines 2025-07-08 23:53:50 +00:00
David Smith d6687d2bbb Add deleted file back 2025-07-08 16:51:24 -07:00
David Smith 528e7485ba Document completion flags and disable ones we don't currently support 2025-07-08 16:38:21 -07:00
David Smith a6c5a39ca5 Remove the proposal doc 2025-07-08 16:24:28 -07:00
David Smith 55e55c1978 Add test and fix submission queue capacity check 2025-07-08 23:15:17 +00:00
David Smith bc097e91dc Remove more blocking enqueue infrastructure 2025-07-08 22:42:15 +00:00
David Smith 227a38f230 Remove blocking enqueue 2025-07-08 22:41:06 +00:00
David Smith bbe2f1c192 Add doc comments, Span/MutableSpan support, unregistering registered fds, variants of submission operations that don't block, address various TODOs 2025-07-08 00:41:50 +00:00
David Smith e580c13ca8 Merge branch 'david/ioring' of https://github.com/apple/swift-system into david/ioring 2025-07-04 00:11:17 +00:00
David Smith a6149c215e Cleanup, implement buffer unregistering, inline almost everything because we're not ABI stable on Linux 2025-07-04 00:09:19 +00:00
David Smith de2d6e2d39 Conditionalize tests too 2025-07-03 16:17:51 -07:00
David Smith 0d4c6fc971 Fix Musl 2025-07-03 16:12:56 -07:00
David Smith 27ccce55db Conditionalize IORing stuff for Linux 2025-07-03 16:04:52 -07:00
David Smith 321a71c2e9 Expand test coverage 2025-07-03 00:13:29 +00:00
David Smith 131326c8ae Fix tests 2025-07-01 01:02:40 +00:00
Alex Azarov c0273af7e5 Fix API documentation links in README.md 2025-06-28 17:49:11 +02:00
David Smith f91cb6b8de Improve tests. Not quite working but close 2025-06-27 00:39:35 +00:00
David Smith f9c2a2b8e7 Work around io_uring.h in ways that will work on both versions 2025-06-18 23:08:45 +00:00
Guillaume Lessard 61e4ca4b81 Merge pull request #231 from apple/main
Merge main into release/1.5.0
2025-05-28 16:25:04 -07:00
Guillaume Lessard f3154e33ec Merge branch 'release/1.4.0' into release/1.5.0 2025-05-23 15:09:25 -07:00
Guillaume Lessard 99feed67fe Merge pull request #225 from marcprux/main
Add Android imports to tests
2025-05-22 10:07:29 -07:00
Guillaume Lessard 40d22dace6 Merge pull request #230 from owenv/owenv/windows-release-path-parsing
Fix Windows path parsing when the package is built in release configuration
2025-05-22 09:48:39 -07:00
Owen Voorhees 595c862c19 Fix Windows path parsing when the package is built in release configuration
forceWindowsPaths can be used to force Windows path parsing both on and off.
Instead of defaulting it to false in release builds, we should not express any preference
2025-05-21 21:12:58 -07:00
David Smith 3d6cba22b6 Work around compiler bugs harder 2025-04-28 23:03:26 +00:00
David Smith f5b8e02ba7 Merge remote-tracking branch 'origin/main' into david/ioring 2025-04-28 22:33:21 +00:00
David Smith 7e2f797fb4 Fix some errors on newer linux systems 2025-04-28 22:30:00 +00:00
David Smith 3a649e32a6 Fix type of features, and make it clear that Completion is a nested type 2025-04-24 16:39:41 -07:00
Jake Petroules 5695a8831b Transparently add the \\?\ prefix to Win32 calls for extended length path handling
On Windows, there is a built-in maximum path limitation of 260 characters under most conditions. This can be extended to 32767 characters under either of the following two conditions:

- Adding the longPathAware attribute to the executable's manifest AND enabling the LongPathsEnabled system-wide registry key or group policy.
- Ensuring fully qualified paths passed to Win32 APIs are prefixed with \\?\

Unfortunately, the former is not realistic for the Swift ecosystem, since it requires developers to have awareness of this specific Windows limitation, AND set longPathAware in their apps' manifest AND expect end users of those apps to change their system configuration.

Instead, this patch transparently prefixes all eligible paths in calls to Win32 APIs with the \\?\ prefix to allow them to work with paths longer than 260 characters without requiring the caller of System to manually prefix the paths.

See https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation for more info.
2025-04-23 14:52:03 -07:00
David Smith f38d72f310 Nested types, some renames, misc other updates 2025-04-22 16:32:12 -07:00
David Smith a49ba8a8b3 Give flags a default value 2025-04-22 23:20:37 +00:00
David Smith c47779fac0 Try making requests and completions nested types 2025-04-22 23:07:01 +00:00
David Smith 344b3b85f8 Proposal updates 2025-04-21 16:59:39 -07:00
David Smith a98cd3f2da Build fix and rename IOResource 2025-04-21 23:47:00 +00:00
David Smith 3760dc265a Nest IOResource, and update proposal to match 2025-04-21 16:35:08 -07:00
David Smith baa3d62569 API tweak 2025-04-21 23:26:14 +00:00
David Smith ea77ef8a21 Minor cleanup 2025-04-21 23:24:09 +00:00
David Smith 9d325b29ce Change IORingFileSlot and IORingBuffer to be nested types in IORing 2025-04-21 23:23:26 +00:00
David Smith 7798f0c957 Add cancellation support and drop gerunds 2025-04-21 23:18:33 +00:00
Guillaume Lessard 5691e92a4b Merge pull request #227 from apple/enable-windows-ci 2025-04-19 09:59:09 -07:00
Jake Petroules 28ce835363 Enable Windows CI
FileOperationsTestWindows.testPermissions fails on Windows in a container environment with Hyper-V isolated containers; see https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions for some potentially-relevant information.

Skip it if we detect we're in a container.

Closes #223
2025-04-19 00:23:55 -07:00
David Smith 05eac87c08 It compiles again! 2025-04-18 23:38:43 +00:00
David Smith c029c1bfbd Proposal updates and a minor change to setup flags 2025-04-18 15:22:17 -07:00
David Smith 261ca250fe Centralize on Errno for errors, and work around lifetime compiler crash. There's a second compiler crash still to work around though. 2025-04-18 22:20:09 +00:00
David Smith 014f8b78eb Rename userData to context 2025-04-17 23:36:51 +00:00
David Smith 41f9676907 WIP, crashes the compiler 2025-04-17 23:31:01 +00:00
David Smith d4ca203c09 Most of feature querying and setup flags 2025-04-17 00:26:13 +00:00
David Smith 2f91217c90 Fix a few things I missed 2025-04-16 23:44:21 +00:00
David Smith 27275f843a Merge remote-tracking branch 'refs/remotes/origin/david/ioring' into david/ioring 2025-04-16 23:38:35 +00:00
David Smith b40b09440c Revamp error handling 2025-04-16 23:37:50 +00:00
David Smith 0e652c4d25 Naming updates, cancellation support, IOResources are structs now, other editorial updates 2025-04-04 16:42:33 -07:00
Marc Prud'hommeaux 009b07e140 Add Android imports to tests 2025-03-13 08:59:59 -04:00
Karoy Lorentey 1b8167d354 Merge pull request #222 from apple/github-actions-support
[CI] Add support for GitHub Actions
2025-03-10 14:50:35 -07:00
Mishal Shah 2ac80d6f4e Disable a few checks 2025-03-09 18:29:05 -07:00
David Smith 7fff872441 Add the draft proposal so I can link to it 2025-03-06 12:09:57 -08:00
Mishal Shah d6b40a7284 [CI] Add support for GitHub Actions 2025-03-04 23:22:34 -08:00
David Smith 72c316ba86 Make completions noncopyable again 2025-03-03 23:59:36 +00:00
David Smith 48455a9135 Fix plumbing 2025-03-03 23:04:52 +00:00
David Smith 880ec9086e Add a pointer convenience for getting the user data 2025-03-03 22:51:35 +00:00
David Smith 9ad16c0aae Plumb through userData 2025-03-03 22:37:51 +00:00
David Smith 91155fd527 Plumb error handling through completion consumers 2025-03-03 22:15:32 +00:00
David Smith 49dd7977ca Add a combined "submit and consume" operation 2025-03-03 22:07:28 +00:00
David Smith 5e24673259 Switch from unsafe pointers to FilePaths, using hacks 2025-03-03 21:53:26 +00:00
David Smith d338de1478 Only get one completion if we asked for one completion 2025-02-28 00:49:31 +00:00
David Smith f3b8cc473d Actually consume events we waited for 2025-02-28 00:45:31 +00:00
Guillaume Lessard a34201439c Merge pull request #220 from glessard/1.4.2
[1.4.x] Support for FreeBSD and OpenBSD
2025-02-18 15:35:23 -08:00
Guillaume Lessard 12573bfb88 Merge branch 'main' into 1.4.2 2025-02-17 17:03:43 -08:00
Guillaume Lessard 3a1b4a8e05 Merge pull request #219 from glessard/1.4.1
[1.4.x] Use GetTempPathW for better compatibility
2025-02-17 14:04:33 -08:00
Guillaume Lessard d9b03016dc Merge pull request #218 from glessard/1.4.1
[1.4.x] Use GetTempPathW for better compatibility
2025-02-17 11:52:53 -08:00
xuty f18ed75481 Use GetTempPathW for better compatibility 2025-02-17 11:43:11 -08:00
David Smith d895f2a828 Revert "Reapply "Turn on single issuer as an experiment""
This reverts commit 283e8d6b7b.
2025-02-14 18:27:17 +00:00
David Smith 283e8d6b7b Reapply "Turn on single issuer as an experiment"
This reverts commit 901f4c80c4.
2025-02-14 18:26:31 +00:00
David Smith 901f4c80c4 Revert "Turn on single issuer as an experiment"
This reverts commit 0064649631.
2025-02-14 18:25:46 +00:00
David Smith 0064649631 Turn on single issuer as an experiment 2025-02-14 18:24:09 +00:00
David Smith 5ba137703c Dubious approach to this, but I want to try it out a bit 2025-02-13 23:43:19 +00:00
David Smith 6983196ad6 Add unlinkAt support 2025-02-13 23:31:06 +00:00
David Smith a22e5f6858 Add a version of registerBuffers that isn't varargs 2025-02-13 22:09:42 +00:00
David Smith 0c6ef16ca9 Fix type 2025-02-12 23:45:18 +00:00
David Smith 7f6e673750 Adjust registered resources API 2025-02-12 23:43:29 +00:00
David Smith 74366c3341 Improve submit API 2025-02-12 20:18:51 +00:00
David Smith 5bfed03c97 Switch to static methods for constructing requests 2025-02-11 23:27:03 +00:00
David Smith d4ca4129a0 Some renaming, and implement linked requests 2025-02-11 23:01:33 +00:00
David Smith a396967e3a More registration tweaks 2025-02-11 22:38:01 +00:00
David Smith bb03f0fba3 Redesign registered resources API 2025-02-11 22:33:10 +00:00
David Smith 02481e0daa More import fixes 2025-02-11 21:06:16 +00:00
David Smith 7107a570b4 Fix import visibility 2025-02-11 21:01:49 +00:00
Guillaume Lessard b1b7b60a55 Merge pull request #215 from 3405691582/openbsd
OpenBSD support.
2025-02-10 14:41:18 -08:00
Guillaume Lessard 2228d64644 Merge pull request #213 from Steelskin/fabrice/cmake-install-paths
[cmake] Install libraries in standard directories
2025-02-07 11:00:22 -08:00
David Smith fdbcecab0b Eliminate internal locking and add multiple consume support 2025-02-06 00:42:21 +00:00
David Smith e5fdf9ea96 Remove managed abstractions for now 2025-02-06 00:41:30 +00:00
3405691582 3b053e055b ManagedBuffer.capacity is unavailable on OpenBSD.
`.capacity` is backed by malloc introspection (`malloc_size`), which is
not available on all platforms. The workaround is straightforward here,
thankfully: instead, use the minimum capacity already specified.
2025-02-04 19:44:35 -05:00
3405691582 90702d6d15 Typealias system_DIRPtr for OpenBSD. 2025-02-04 19:44:32 -05:00
Guillaume Lessard 849d005b2b Merge pull request #211 from ShaftUI/temp-path-w
[Windows] Use GetTempPathW in _getTemporaryDirectory for better compatibility
2025-01-30 15:00:27 -08:00
Guillaume Lessard 8790e47013 Merge pull request #214 from michael-yuji/freebsd-wip
Add FreeBSD errno and open options
2025-01-29 15:50:13 -08:00
Guillaume Lessard f27874d762 Merge pull request #209 from ADKaster/install-interface
CSystem: Set build and install interfaces on included headers
2025-01-28 13:49:12 -08:00
Michael Chiu df7341ee2b fix cmake x86_64 build 2025-01-26 21:29:19 -08:00
Michael Chiu 4d735a6631 Add FreeBSD errnos and open options 2025-01-26 21:29:13 -08:00
Fabrice de Gans bebd7c146e [cmake] Install libraries in standard directories
Previously, libs were installed under `lib/swift/${os}`. They should be
installed in the default library directory for the relevant target
system.
In addition, swiftmodules were installed in the older layout format.
This changes to use the standard modern layout format for swiftmodules.
2025-01-23 11:45:17 -08:00
michael-yuji 4fa2a719c5 Merge pull request #212 from michael-yuji/freebsd-wip
Guard errnos not available on FreeBSD
2025-01-17 21:52:07 -08:00
Michael Chiu 0d824eee86 refactor ifdef in test 2025-01-17 15:06:28 -08:00
Michael Chiu eb566de2d3 Fix tests on FreeBSD 2025-01-17 14:43:40 -08:00
Michael Chiu a4fb6cb206 Keep order consistent 2025-01-17 14:43:34 -08:00
Michael Chiu 7e73a336fb Guard errnos not available on FreeBSD 2025-01-17 14:30:51 -08:00
xuty 85b83fddb1 Use GetTempPathW for better compatibility 2024-12-17 15:13:15 +08:00
David Smith 55fd6e7150 Add support for timeout-on-wait to IORing, don't have tests yet 2024-12-12 01:20:24 +00:00
David Smith 7ea32aefce More refactoring, and working timeout support on ManagedIORing 2024-12-11 23:00:50 +00:00
David Smith ef94a37193 Refactoring, and give up on resources being noncopyable structs 2024-12-05 03:11:11 +00:00
Guillaume Lessard 61a2af5e8b Merge pull request #210 from ADKaster/remove-nbsp
Internals: Remove non-breaking spaces from Windows syscall adapter
2024-11-22 19:38:54 -05:00
Andrew Kaster eb3b1fa54b Internals: Remove non-breaking spaces from Windows syscall adapter
This was causing a warning with Swift 6.0.2
2024-11-21 15:03:28 -07:00
Andrew Kaster f1393b76f3 CSystem: Set build and install interfaces on included headers 2024-11-21 14:48:57 -07:00
David Smith f369347b73 Fix mismerge 2024-10-28 17:25:31 -07:00
David Smith 1a3e37d791 Fix mismerge 2024-10-28 17:24:46 -07:00
David Smith a9f92a6e31 Delete stray Package.resolved changes 2024-10-28 17:23:25 -07:00
David Smith 6f793cfe60 Merge branch 'main' into david/ioring 2024-10-29 00:21:42 +00:00
David Smith fcb0b69df6 Merge branch 'main' into david/ioring 2024-10-28 17:20:36 -07:00
David Smith 822e4814d1 Adopt isolation parameters 2024-10-28 23:49:37 +00:00
David Smith 32966f975d It builds again! With some horrible hacks 2024-10-28 23:43:59 +00:00
David Smith 10c070abd6 WIP, more ~Copyable adoption 2024-10-28 20:00:07 +00:00
David Smith 60299362ed One more noncopyable struct 2024-10-24 21:27:22 +00:00
David Smith baab9b26b7 Starting to move to noncopyable structs, and away from swift-atomics 2024-10-24 21:21:07 +00:00
Guillaume Lessard fbd61a676d Merge pull request #207 from glessard/merge-1.4.0-into-main
Merge 1.4.0 into main
2024-10-18 22:39:45 -07:00
Guillaume Lessard f21f6a8866 Merge branch 'release/1.4.0' into merge-1.4.0-into-main
# Conflicts:
#	.gitignore
#	.swiftci/5_10_ubuntu2204
#	.swiftci/5_8_ubuntu2204
#	.swiftci/5_9_ubuntu2204
#	.swiftci/nightly_6_0_macos
#	.swiftci/nightly_6_0_ubuntu2204
#	.swiftci/nightly_main_macos
#	.swiftci/nightly_main_ubuntu2204
#	.swiftci/nightly_main_windows
#	Package.swift
#	Sources/System/FileOperations.swift
#	Sources/System/FilePath/FilePath.swift
#	Sources/System/Internals/WindowsSyscallAdapters.swift
2024-10-17 17:24:38 -07:00
Guillaume Lessard c8a44d836f Merge pull request #206 from glessard/1.4.0-readme
[1.4.0] Updates to the README file
2024-10-17 16:12:10 -07:00
Guillaume Lessard b80d743dab Update README.md 2024-10-17 15:52:41 -07:00
Guillaume Lessard eeeb81d0cd [readme] update usage example, reword stability 2024-10-17 15:14:38 -07:00
Guillaume Lessard 234e15320e Merge pull request #204 from glessard/1.4.0-ci-adjustment
[1.4.0] Swift 5.8 is not supported on this branch
2024-10-17 15:01:46 -07:00
Guillaume Lessard 154cbf7c95 Merge pull request #205 from glessard/1.4.0-pipe-correction
[windows] expose pipe’s buffer size parameter
2024-10-17 14:57:49 -07:00
Guillaume Lessard 3f4e7cb45c [windows] expose pipe’s buffer size parameter 2024-10-17 14:31:37 -07:00
Guillaume Lessard 11d481252d [1.4.0] Updates to the README file 2024-10-17 13:17:08 -07:00
Guillaume Lessard 2e8f58ac41 [1.4.0] Swift 5.8 is not supported on this branch 2024-10-17 08:49:29 -07:00
Guillaume Lessard 5cd7eade6d Merge pull request #203 from glessard/systemstring-tweaks-1.4.0
[1.4.0] SystemString consistency improvements
2024-10-16 23:25:29 -07:00
Guillaume Lessard b2d4917ebe Update copyright notices 2024-10-16 23:09:09 -07:00
Guillaume Lessard d96435c72b Rename withSystemChars
- `withNullTerminatedSystemChars` makes it clear that the null-termination is included. Operations where the null-termination is included should be obvious.
2024-10-16 23:09:09 -07:00
Guillaume Lessard 95784d018f Fix behaviour of withCodeUnits()
- The original implementation includes a trailing zero with the full collection, but the implementation for a slice does not. As a result, given a `let s: SystemString`, `s.string` was not equal to `s[…].string`
2024-10-16 23:09:09 -07:00
Guillaume Lessard 448bef7c38 Test SystemString.string property consistency 2024-10-16 23:09:09 -07:00
Guillaume Lessard 69e737de3d Generate SystemString.string consistently
- SystemString.string and Slice<SystemString>.string should be generated in the same manner. Now they are.
2024-10-16 23:09:09 -07:00
Guillaume Lessard afeecb6c28 Merge pull request #201 from glessard/32-are-too-few-bits-1.4.0
[1.4.0] fix a 32-bit overflow issue
2024-10-16 18:30:16 -07:00
Guillaume Lessard 69eee996ac Merge pull request #202 from glessard/platform-support-1.4.0
[1.4.0] cherry-pick platform support changes
2024-10-16 18:29:59 -07:00
Finagolfin 209dfeacb8 Import new Android overlay
Use Bionic module instead where possible
2024-10-16 18:22:35 -07:00
Finagolfin b2b60a6b94 Android: DIR* is an OpaquePointer in Bionic too 2024-10-16 18:22:19 -07:00
Max Desiatov e11703d915 Add support for WASILibc module (#159)
Quoting the [wasi.dev landing page](https://wasi.dev):
> The WebAssembly System Interface (WASI) is a group of standard API specifications for software compiled to the W3C WebAssembly (Wasm) standard. WASI is designed to provide a secure standard interface for applications that can be compiled to Wasm from any language, and that may run anywhere—from browsers to clouds to embedded devices.

Currently support for WASI in Swift is based on [`wasi-libc`](https://github.com/WebAssembly/wasi-libc).

Adding support for `wasi-libc` mostly amounted to excluding unsupported errnos, adding TLS dictionary storage shim for single-threaded environment, and adding constants in C headers for macros that Clang importer currently doesn't support.

Co-authored-by: Guillaume Lessard <guillaume.lessard@apple.com>

# Conflicts:
#	Sources/System/FileOperations.swift
#	Sources/System/Internals/Syscalls.swift
2024-10-16 18:22:19 -07:00
Guillaume Lessard 8df901cb24 fix a 32-bit overflow issue
- ensures compatibility with watchOS
2024-10-16 17:57:36 -07:00
Guillaume Lessard 938fda53e2 Merge pull request #200 from glessard/private-aeic-init-removal-1.4.0
[1.4.0] backport #191
2024-10-16 17:41:50 -07:00
Guillaume Lessard e7ffa45882 Remove private-and-@_aEIC initializers
These were just passthroughs.
2024-10-16 17:38:24 -07:00
Guillaume Lessard 607542a559 Merge pull request #198 from glessard/1.4.0-backport-158&176 2024-10-16 17:28:28 -07:00
Guillaume Lessard b9e4d2b2ba Remove more accidentally public functions 2024-10-16 17:03:59 -07:00
Guillaume Lessard 473b493ab0 Merge pull request #199 from glessard/1.4.0-backport-193
Add support for macCatalyst
2024-10-16 14:15:25 -07:00
George Barnett 9eb1f34cbf Add support for macCatalyst
Building swift-system for macCatalyst fails as there is no import of the
Darwin module.

# Conflicts:
#	Package.swift
2024-10-16 14:00:47 -07:00
Guillaume Lessard 7a18b4bf34 Merge pull request #193 from glbrntt/mac-catalyst
Add support for macCatalyst
2024-10-16 13:57:03 -07:00
Alastair Houghton 6c64372b85 [Windows] Add a comment to explain the O_RDONLY/O_WRONLY/O_RDWR logic.
The values of these flags on Windows do not overlap, and more
particularly, `O_RDONLY` is actually zero on Windows, which means we
cannot test for it by AND-ing.
2024-10-14 16:01:01 -07:00
Alastair Houghton 3a4e2f8071 [Windows] Fix tests.
We need to use `@testable` when importing `SystemPackage` in order to
let us test the `internal` functions.

Also, use `NUL` instead of `/dev/null`, and generate random bytes in a
file instead of reading from `/dev/random`.
2024-10-14 16:01:01 -07:00
Alastair Houghton 53471ce33b [Windows] Fix a problem with opening files read only.
`_O_RDONLY` is zero, so we can't test for it by AND-ing.
2024-10-14 16:01:01 -07:00
Alastair Houghton f1d7eb52c6 Remove accidentally public functions.
These can't be new API as they haven't been reviewed.
2024-10-14 16:01:01 -07:00
Alastair Houghton cf7530848e [Linux] Glibc's DIR doesn't get imported into Swift.
Swift ends up with OpaquePointer instead of a typed pointer.

rdar://125087707
2024-10-14 15:59:36 -07:00
Alastair Houghton 5ae5d5a3af Refactor FilePathTemp, add tests for permission code.
Broke `FilePathTemp.swift` into separate files for POSIX and
Windows.

Added tests for permissions code on Windows.

Added leading underscores to some function names.

Made some other functions `fileprivate`.

rdar://125087707
2024-10-14 15:59:36 -07:00
Alastair HoughtonandKaroy Lorentey bcc7f6d569 Update Sources/System/FilePath/FilePathTemp.swift
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2024-10-14 15:59:36 -07:00
Alastair Houghton e293300430 Map mode bits to Windows ACLs.
This adds support for mapping POSIX-style mode bits to Windows ACLs when
calling `open()` or `mkdir()`.

rdar://125087707
2024-10-14 15:59:36 -07:00
Alastair Houghton 4cafcc96f6 Changes after comments from Saleem.
Use idiomatic Swift notation, not `Optional<Bool>`.

Prefer Win32 APIs to UCRT APIs.

rdar://125087707
2024-10-14 15:59:36 -07:00
Alastair Houghton 85de4e51e2 Use the proper temporary directory on Darwin.
It seems we can get the temporary directory from confstr().

rdar://125087707
2024-10-14 15:59:36 -07:00
Alastair Houghton d4e2b09c37 Fix swift-system to work on Windows.
The swift-system tests were not passing, for various reasons, mostly
to do with path related confusion.

As part of this, add a function to create a temporary directory, as that
was one of the problems.

Also add Windows support for pipe() and ftruncate(), which was missing.

rdar://125087707
2024-10-14 15:59:36 -07:00
Guillaume Lessard 5ea5b2e89a Merge pull request #197 from lorentey/merge-1.3.0→1.4.0
Merge release/1.3.0 to release/1.4.0
2024-10-14 11:02:40 -07:00
Karoy Lorentey 8564f96d1f Merge branch 'release/1.3.0' into release/1.4.0
# Conflicts:
#	.gitignore
#	.swiftci/5_10_ubuntu2204
#	.swiftci/5_8_ubuntu2204
#	.swiftci/5_9_ubuntu2204
#	.swiftci/nightly_6_0_macos
#	.swiftci/nightly_6_0_ubuntu2204
#	.swiftci/nightly_main_macos
#	.swiftci/nightly_main_ubuntu2204
#	.swiftci/nightly_main_windows
#	Package.swift
#	Sources/System/FilePath/FilePath.swift
#	Sources/System/Internals/CInterop.swift
2024-09-19 16:50:34 -07:00
Karoy Lorentey b85a788897 Merge pull request #196 from lorentey/metadata-updates
[1.4] Metadata updates
2024-09-19 15:31:34 -07:00
Karoy Lorentey 88a60e08b3 Update README
- Clarify swift-system’s stance on cross-platform abstractions. Stop using the term “multi-platform”.
- Expand source stability section.
- Add a section on our branching strategy.
- Link to the Code of Conduct document.
2024-09-19 13:01:48 -07:00
Karoy Lorentey 4c612a1e29 Bump required toolchain version to 5.9. Sanitize Package manifest
- Don’t define _CRT_SECURE_NO_WARNINGS outside Windows
- Let all targets share the same settings
2024-09-19 12:57:57 -07:00
Karoy Lorentey 603c451818 Add code of conduct 2024-09-19 12:49:08 -07:00
George Barnett 2662793bd6 Add support for macCatalyst
Building swift-system for macCatalyst fails as there is no import of the
Darwin module.
2024-08-19 10:20:12 +01:00
Guillaume Lessard d581098eeb Merge pull request #191 from glessard/private-aeic-init-removal
Remove private-and-@_aEIC initializers
2024-07-31 16:56:38 -07:00
Guillaume Lessard edbc9e4fdc Remove private-and-@_aEIC initializers
These were just passthroughs.
2024-07-31 16:30:25 -07:00
Guillaume Lessard d2ba781702 Merge pull request #190 from glessard/enforce-file-path-invariants-in-decode-1.3.x
Cherry-pick: ensure invariants are enforced when decoding
2024-07-23 12:42:13 -07:00
Stephen Canon a1f77d0e1a Cherry-pick: ensure invariants are enforced when decoding
Ensure that FilePath and SystemString's invariants are enforced when decoding.

Cherry-pick of merge-commit 9c42c54644
from PR #189

# Conflicts:
#	Sources/System/FilePath/FilePath.swift
2024-07-23 11:26:26 -07:00
Stephen Canon 9c42c54644 Merge pull request #189 from stephentyrone/enforce-file-path-invariants-in-decode
Ensure that FilePath and SystemString's invariants are enforced when …
2024-07-17 14:49:19 -04:00
Stephen Canon 3841a7531f Add some notes explaining what invariants are violated. 2024-07-17 13:49:15 -04:00
Stephen Canon 3b43b391b5 Add some comments and remove leftover WIP noise. 2024-07-17 12:49:37 -04:00
Stephen Canon c64775ef71 Another invariant to check 2024-07-17 12:25:34 -04:00
Stephen Canon 4c96faa6d8 Insure that FilePath and SystemString's invariants are enforced when decoding. 2024-07-17 12:14:43 -04:00
Guillaume Lessard 19e7f0fdd4 Merge pull request #187 from finagolfin/droid
Import new Android overlay
2024-07-08 17:20:28 -07:00
Finagolfin 02811ea6b4 Import new Android overlay
Use Bionic module instead where possible
2024-07-08 17:53:39 +05:30
Guillaume Lessard 2ce971a831 Merge pull request #155 from glessard/system-string-api-consistency
SystemString api consistency improvements
2024-07-05 14:26:21 -07:00
Guillaume Lessard 80788529b5 Merge pull request #170 from glessard/platform-flags
Make a platform-specific flag explicitly platform-specific
2024-07-05 14:24:12 -07:00
Guillaume Lessard 05fb1f1142 Merge pull request #178 from apple/dev/merge-1.3.0-back-to-main
[gardening] Merge the release/1.3.0 branch back into main
2024-07-03 16:22:44 -07:00
Guillaume Lessard 8d2dda76fa Merge pull request #186 from futurejones/add-riscv64-support
add support for riscv64
2024-06-18 16:21:38 -07:00
Neil Jones c1789e0525 add support for riscv64 2024-06-18 10:45:08 +09:00
Guillaume Lessard 6a9e38e7bd Merge pull request #185 from glessard/disfavoredOverload-1.3.0
[1.3.x] Disfavor String.init(platformString: UnsafePointer<CChar>)
2024-06-07 17:43:21 -07:00
Yuta Saito 848a927122 Merge pull request #184 from kateinoigakukun/katei/suppress-cmakelists-warning-1.4
[1.4] Suppress unhandled CMakeLists.txt warning by SwiftPM
2024-06-07 11:46:19 +09:00
Guillaume Lessard 2b30f8820c Merge pull request #183 from kateinoigakukun/katei/suppress-cmakelists-warning-1.3
[1.3] Suppress unhandled CMakeLists.txt warning by SwiftPM
2024-06-06 13:44:13 -07:00
Yuta Saito 318d2159d1 Merge pull request #182 from kateinoigakukun/katei/suppress-cmakelists-warning
Suppress unhandled CMakeLists.txt warning by SwiftPM
2024-06-06 03:08:41 +09:00
Yuta Saito 1a8d472f35 Suppress unhandled CMakeLists.txt warning by SwiftPM 2024-06-05 18:06:54 +00:00
Yuta Saito f9d6b48027 Suppress unhandled CMakeLists.txt warning by SwiftPM 2024-06-05 18:05:57 +00:00
Karoy Lorentey d82bccbb17 Merge pull request #164 from lorentey/retarget-to-1.4.0
Retarget pending changes to 1.4.0
2024-06-05 09:15:44 -07:00
Yuta Saito 9c17c8562d Suppress unhandled CMakeLists.txt warning by SwiftPM 2024-06-03 02:15:29 +00:00
Guillaume Lessard 0d6be7ac22 Merge branch 'release/1.3.0'
# Conflicts:
#	.gitignore
#	.swiftci/5_10_ubuntu2204
#	.swiftci/5_8_ubuntu2204
#	.swiftci/5_9_ubuntu2204
#	.swiftci/nightly_6_0_macos
#	.swiftci/nightly_6_0_ubuntu2204
#	.swiftci/nightly_main_macos
#	.swiftci/nightly_main_ubuntu2204
#	.swiftci/nightly_main_windows
#	Package.swift
#	Sources/System/Internals/CInterop.swift
#	Sources/System/Internals/Constants.swift
#	Sources/System/Internals/Exports.swift
#	Sources/System/Internals/Syscalls.swift
#	Tests/SystemTests/FileOperationsTest.swift
2024-05-16 11:51:10 -07:00
Karoy Lorentey f9266c8518 Merge pull request #177 from lorentey/fix-cmake
[1.3][CMake] Restore to working order on Apple platforms
2024-05-15 14:48:03 -07:00
Karoy Lorentey b7dc8e8e41 [CMake] Restore to working order on Apple platforms 2024-05-15 14:30:14 -07:00
Guillaume Lessard b642f54526 Merge pull request #175 from glessard/32-are-too-few-bits
fix a 32-bit overflow issue
2024-05-14 11:32:44 -07:00
Alastair Houghton 36987d6d37 Merge pull request #176 from al45tair/remove-unintended-public
Remove unintentional public functions and fix a couple of Windows issues.
2024-05-14 14:52:12 +01:00
Alastair Houghton 082adfe732 [Windows] Add a comment to explain the O_RDONLY/O_WRONLY/O_RDWR logic.
The values of these flags on Windows do not overlap, and more
particularly, `O_RDONLY` is actually zero on Windows, which means we
cannot test for it by AND-ing.
2024-05-14 14:42:57 +01:00
Alastair Houghton abc0a6d26f [Windows] Fix tests.
We need to use `@testable` when importing `SystemPackage` in order to
let us test the `internal` functions.

Also, use `NUL` instead of `/dev/null`, and generate random bytes in a
file instead of reading from `/dev/random`.
2024-05-13 15:13:31 +01:00
Alastair Houghton c3559ecd61 [Windows] Fix a problem with opening files read only.
`_O_RDONLY` is zero, so we can't test for it by AND-ing.
2024-05-13 14:18:17 +01:00
Alastair Houghton 8e09ede76d Remove accidentally public functions.
These can't be new API as they haven't been reviewed.
2024-05-13 11:19:43 +01:00
Guillaume Lessard 25c4b1ad75 fix a 32-bit overflow issue
- ensures compatibility with watchOS
2024-05-12 14:07:11 -07:00
Guillaume Lessard 7d45e0dd46 Update README.md to refer to 1.3.0 2024-05-12 11:40:14 -07:00
Karoy Lorentey aac7f54e89 Merge pull request #174 from lorentey/codeowners
Add CODEOWNERS
2024-05-10 17:17:48 -07:00
Karoy Lorentey 62e62b3a7c Add CODEOWNERS 2024-05-10 17:10:08 -07:00
Guillaume Lessard ab09f04cfe Merge pull request #173 from lorentey/codeowners-1.3.0
Add CODEOWNERS
2024-05-10 17:07:55 -07:00
Karoy Lorentey a6fd8ba9ba Add CODEOWNERS 2024-05-10 17:06:59 -07:00
Karoy Lorentey 0cf079efea Add CODEOWNERS 2024-05-10 17:05:37 -07:00
Mishal Shah 3433699e6e [CI] Remove support for Swift 5.7 2024-05-10 16:32:21 -07:00
Mishal Shah 52f603c6b3 [CI] Remove support for Swift 5.7 2024-05-10 16:31:46 -07:00
Mishal Shah d18980c960 [CI] Remove support for Swift 5.7 2024-05-10 16:30:41 -07:00
Mishal Shah 08800445eb Add support for Swift CI on release/1.4.0 2024-05-10 16:27:47 -07:00
Guillaume Lessard de1f8bce5e Merge pull request #172 from glessard/visionOS-support-for-1.3.0
[1.3.0] visionOS support for 1.3.0
2024-05-10 16:23:53 -07:00
Mishal Shah 0368ce547b Add support for Swift CI on release/1.3.0 2024-05-10 16:18:08 -07:00
Guillaume Lessard 7b14e48d0d Remove the repeated list of Darwin-based platforms
Replaced with a constant defined in the package manifest.
2024-05-10 16:09:22 -07:00
Guillaume Lessard c456f4186e Change the package manifest to support visionOS 2024-05-10 16:02:32 -07:00
Karoy Lorentey ec395a7aa2 Merge pull request #171 from lorentey/require-5.8
[1.3.0] Require Swift 5.8
2024-05-10 15:59:40 -07:00
Karoy Lorentey f1f59e148f Update gitignore 2024-05-10 15:55:04 -07:00
Karoy Lorentey 37a5bbb965 Require Swift 5.8 or better 2024-05-10 15:54:56 -07:00
Guillaume Lessard d8c0e24651 Merge pull request #169 from glessard/manifest-fix
Improved compatibility for visionOS support
2024-05-10 15:42:15 -07:00
Karoy Lorentey f07d14ddb1 Merge pull request #168 from glessard/cherry-pick-pr148
Cherry-pick changes from PR148
2024-05-10 15:41:26 -07:00
Guillaume Lessard 63b05e24e8 Improved compatibility for visionOS support 2024-05-10 15:37:04 -07:00
Guillaume Lessard b0e2a510ed Make a platform-specific flag explicitly platform-specific 2024-05-10 15:28:43 -07:00
Guillaume LessardandFinagolfin 9620c1d30e Cherry-pick changes from PR148
Co-authored-by: Finagolfin <finagolfin@tuta.io>
2024-05-09 22:24:04 -07:00
Guillaume LessardandHiroshi Yamauchi c7259554b5 Cherry-pick changes from PR151
Co-authored-by: Hiroshi Yamauchi <hjyamauchi@gmail.com>
2024-05-09 22:10:26 -07:00
Guillaume LessardandMax Desiatov c3a7235bf7 Cherry-pick changes from PR133
Co-authored-by: Max Desiatov <m_desiatov@apple.com>
2024-05-09 19:10:58 -07:00
Guillaume Lessard e5a56da50e Cherry-pick changes from PR154 2024-05-09 16:03:48 -07:00
Karoy Lorentey 73baf1113d Retarget pending changes to 1.4.0
We decided to spend the 1.3.0 version number on a small interim release; retarget the currently pending changes to 1.4.0.
2024-05-09 14:31:11 -07:00
Guillaume Lessard cf5e688e70 Merge pull request #162 from finagolfin/droid
Android: DIR* is an OpaquePointer in Bionic too
2024-05-09 09:31:47 -07:00
Guillaume Lessard 93d600b5c9 Merge pull request #161 from jmschonfeld/string-init-ambiguity
Disfavor String.init(platformString: UnsafePointer<CChar>)
2024-05-09 09:26:56 -07:00
Finagolfin 7fe8e6cfc2 Android: DIR* is an OpaquePointer in Bionic too 2024-05-09 19:29:36 +05:30
Mishal Shah 84077b3b4b Add Swift CI Support 2024-05-08 15:21:09 -07:00
Alastair Houghton 027c936a26 Merge pull request #158 from al45tair/eng/PR-125087707
Fix swift-system to work on Windows.
2024-05-08 16:13:21 +01:00
Alastair Houghton f5ad5e57fb [Linux] Glibc's DIR doesn't get imported into Swift.
Swift ends up with OpaquePointer instead of a typed pointer.

rdar://125087707
2024-05-08 16:09:56 +01:00
Alastair Houghton 2357d6932c Refactor FilePathTemp, add tests for permission code.
Broke `FilePathTemp.swift` into separate files for POSIX and
Windows.

Added tests for permissions code on Windows.

Added leading underscores to some function names.

Made some other functions `fileprivate`.

rdar://125087707
2024-05-08 16:09:56 +01:00
Alastair HoughtonandKaroy Lorentey 33773a8eb9 Update Sources/System/FilePath/FilePathTemp.swift
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2024-05-08 16:09:56 +01:00
Alastair Houghton 21638a06b1 Map mode bits to Windows ACLs.
This adds support for mapping POSIX-style mode bits to Windows ACLs when
calling `open()` or `mkdir()`.

rdar://125087707
2024-05-08 16:09:56 +01:00
Alastair Houghton ec7d406cd4 Changes after comments from Saleem.
Use idiomatic Swift notation, not `Optional<Bool>`.

Prefer Win32 APIs to UCRT APIs.

rdar://125087707
2024-05-08 16:09:56 +01:00
Alastair Houghton c6456a9c03 Use the proper temporary directory on Darwin.
It seems we can get the temporary directory from confstr().

rdar://125087707
2024-05-08 16:09:56 +01:00
Alastair Houghton cfd3f9da90 Fix swift-system to work on Windows.
The swift-system tests were not passing, for various reasons, mostly
to do with path related confusion.

As part of this, add a function to create a temporary directory, as that
was one of the problems.

Also add Windows support for pipe() and ftruncate(), which was missing.

rdar://125087707
2024-05-08 16:09:54 +01:00
Jeremy Schonfeld dd45c80062 Disfavor String.init(platformString: UnsafePointer<CChar>) 2024-05-02 13:25:04 -07:00
Max DesiatovandGuillaume Lessard 40b6b0ef8c Add support for WASILibc module (#159)
Quoting the [wasi.dev landing page](https://wasi.dev):
> The WebAssembly System Interface (WASI) is a group of standard API specifications for software compiled to the W3C WebAssembly (Wasm) standard. WASI is designed to provide a secure standard interface for applications that can be compiled to Wasm from any language, and that may run anywhere—from browsers to clouds to embedded devices.

Currently support for WASI in Swift is based on [`wasi-libc`](https://github.com/WebAssembly/wasi-libc).

Adding support for `wasi-libc` mostly amounted to excluding unsupported errnos, adding TLS dictionary storage shim for single-threaded environment, and adding constants in C headers for macros that Clang importer currently doesn't support.

Co-authored-by: Guillaume Lessard <guillaume.lessard@apple.com>
2024-04-30 17:11:39 +01:00
Guillaume Lessard dae787c199 Merge pull request #148 from finagolfin/droid
Android: update pread/pwrite for nullability annotations in NDK 26
2024-03-19 18:23:38 -07:00
Guillaume Lessard 5ca37e7d39 Android: more targeted approach to unusual nullabilities 2024-03-11 09:10:11 -07:00
Guillaume Lessard 14597334dc [test] test reading and writing empty, nil-based buffers 2024-03-08 16:28:11 -08:00
Guillaume Lessard 403776dc2a Merge pull request #152 from noahpistilli/visionPro
Add support for visionOS
2024-03-08 14:54:35 -08:00
Guillaume Lessard 6609a401b9 Update copyright notices 2024-03-08 12:16:44 -08:00
Guillaume Lessard 17e9790792 Rename withSystemChars
- `withNullTerminatedSystemChars` makes it clear that the null-termination is included. Operations where the null-termination is included should be obvious.
2024-03-08 12:16:43 -08:00
Guillaume Lessard def7b1a70c Fix behaviour of withCodeUnits()
- The original implementation includes a trailing zero with the full collection, but the implementation for a slice does not. As a result, given a `let s: SystemString`, `s.string` was not equal to `s[…].string`
2024-03-08 12:13:04 -08:00
Guillaume Lessard c86758849a Test SystemString.string property consistency 2024-03-08 12:13:04 -08:00
Guillaume Lessard afb7fa4eef Generate SystemString.string consistently
- SystemString.string and Slice<SystemString>.string should be generated in the same manner. Now they are.
2024-03-08 12:13:04 -08:00
Sketch f59a0b73ce Add support for visionOS 2024-03-08 10:39:54 -05:00
Guillaume Lessard 8441d4a310 Merge pull request #154 from glessard/system-string-collection-fix 2024-03-07 18:20:02 -08:00
Guillaume Lessard adca1f70b1 Fix SystemString.withCSIA()
- The original implementation simply forwarded to the underlying `nullTerminatedStorage`, which contains one element – a null terminator – more than the actual `String`.
- This isn’t in keeping with the sperit of `withContiguousStorageIfAvailable()`, which should present exactly the elements of the collection.
2024-03-07 15:15:56 -08:00
Saleem Abdulrasool cc1962b882 Merge pull request #151 from hjyamauchi/arm64
Support Windows ARM64
2024-02-14 07:54:19 -08:00
Hiroshi Yamauchi 6b15689813 Support Windows ARM64 2024-02-13 10:32:39 -08:00
Guillaume Lessard 51f6be041f Merge pull request #149 from Kyle-Ye/optimize/doc
Enable Swift Package Index documentation and add API doc link
2024-02-02 15:56:58 -08:00
KyleandMax Desiatov e49d2b9bd2 Update .spi.yml
Co-authored-by: Max Desiatov <m_desiatov@apple.com>
2024-01-22 17:23:31 +08:00
Kyle c6b2119c81 Enable SPI documentation and add API doc link 2024-01-22 17:00:46 +08:00
Guillaume Lessard c2e8f24c7c avoid passing null pointer to pread() or pwrite() 2024-01-04 17:53:38 -08:00
Finagolfin 5c3617b9e9 Android: update pread/pwrite for nullability annotations in NDK 26 2023-11-24 19:01:31 +05:30
Guillaume Lessard 9a812b5fef Merge pull request #147 from glessard/availability 2023-10-13 22:11:51 -07:00
Guillaume Lessard 882466a730 apply missing availability attributes to Mach.Port 2023-10-13 18:55:23 -07:00
Guillaume Lessard 11f1c6da5a Merge pull request #146 from glessard/availability
Update availability declarations for swift-system 1.1.0 API
2023-10-13 18:53:06 -07:00
Guillaume Lessard b92be8a02a Update availability declarations for swift-system 1.1.0 API 2023-10-13 10:21:57 -07:00
Guillaume Lessard c81d5f35e1 Merge pull request #145 from glessard/reenable-mach-port 2023-10-12 19:40:03 -07:00
Guillaume Lessard fb0efe832c [gardening] finish cleaning up old test files
This should have been removed alongside XCTestManifests.swift
2023-10-12 15:02:31 -07:00
Guillaume Lessard 495f729347 [noncopyability] explicitly prevent a capture
This may be needed because of a bug involving resilient structs.
2023-10-12 15:01:08 -07:00
Guillaume Lessard 7654f14f8c [gardening] add some more availability annotations 2023-10-11 14:28:43 -07:00
Guillaume Lessard 0e060b7a7a Merge pull request #144 from kateinoigakukun/katei/fix-rename-typo
Fix typos in renaming message for `Errno`
2023-09-07 15:21:20 -07:00
Yuta Saito 1ccaee141c Fix typos in renaming message for Errno 2023-09-05 11:36:08 -07:00
Guillaume Lessard 8a8552f617 Merge pull request #129 from glessard/reenable-mach-port
Re-enable Mach.Port
2023-08-16 16:04:53 -07:00
Guillaume Lessard ad407249fe make test expression return Void
- It can’t return `Mach.Port<SendRight>`, because a noncopyable type cannot currently be a generic type argument.
2023-08-16 13:34:41 -07:00
Guillaume Lessardandloffgren faffb9a15a Apply suggestions from code review
This better communicates the intention.

Co-authored-by: loffgren <117697138+loffgren@users.noreply.github.com>
2023-08-16 13:19:52 -07:00
Guillaume Lessard 547b2a5828 Merge pull request #141 from glessard/requirement-update 2023-08-16 11:52:22 -07:00
Guillaume Lessard 87e68fca36 declare Sendable conformances along with the types
- `Sendable` is fundamental, it is preferably not declared as an extension.
2023-08-16 11:19:06 -07:00
Guillaume Lessard f32faad415 remove code depending on Swift older than 5.6 2023-08-16 11:02:51 -07:00
Guillaume Lessard a3aff2f913 require Swift 5.6 2023-08-16 11:01:36 -07:00
Guillaume Lessard 8730f2cf25 [gardening] 80-column enforcement 2023-08-15 09:34:05 -07:00
Guillaume Lessard 65693b8b80 improve memory rebinding for mach_port_get_attributes call 2023-08-15 09:11:46 -07:00
Guillaume Lessard f5edd720bd clarify some tests 2023-08-11 18:03:24 -07:00
Guillaume Lessard 6189c1f553 fix copySendRight() for send rights that become dead names 2023-08-11 14:09:44 -07:00
Lucy Satheesan 6b4084c69f introduce IORing unit tests 2023-08-11 09:08:43 -07:00
Lucy Satheesan b596783bd9 implement closing 2023-08-11 09:07:47 -07:00
Lucy Satheesan b58450413e fix off-by-one in IORequest.openat 2023-08-11 09:07:08 -07:00
Lucy Satheesan d099546787 fix access control 2023-08-11 09:06:17 -07:00
Lucy Satheesan 0762f57d80 migrate CSystem to systemLibrary
for some reason, the linker on my linux machine fails
to link the tests otherwise. investigate / fix before merging.
2023-08-10 16:03:21 -07:00
Guillaume Lessard e4d06ae3ea simplify deinit 2023-08-10 15:35:27 -07:00
Guillaume Lessard d259ef476e test two-parameter withBorrowedName 2023-08-10 15:35:27 -07:00
Guillaume Lessard 5e03246e4e test copies of dead mach port names 2023-08-10 15:32:19 -07:00
Guillaume Lessard 40b5b3068b test all the relinquish() methods 2023-08-10 15:32:19 -07:00
Guillaume Lessard e8bb779909 use inout conversion
- this is the situation where it is appropriate
2023-08-10 15:32:19 -07:00
Guillaume Lessard 6ee96ffdb5 modify consuming methods to call discard self 2023-08-09 15:58:56 -07:00
Guillaume Lessard 0539daa364 fix test of receive-right deallocation 2023-08-09 15:58:56 -07:00
Guillaume Lessard 669dcf2c25 ensure Mach.Port lives until the function returns 2023-08-09 15:58:56 -07:00
Guillaume Lessard 9123120c08 destroy Send rights with mach_port_deallocate 2023-08-09 15:58:56 -07:00
Guillaume Lessard bf16d3da30 [test] use XCTAssertEqual or XCTAssertNotEqual 2023-08-09 15:58:56 -07:00
Daniel Loffgren 2df5b0b031 srdelta argument to mach_port_destruct should be zero
This should never have been -1, as there is no send right for
it to balance when `RightType.self == ReceiveRight.self`.
2023-08-09 15:58:56 -07:00
Guillaume Lessard af4544c869 Re-enable Mach.Port 2023-08-09 15:58:56 -07:00
Lucy Satheesan 1f821a8539 AsyncSequence draft implementation 2023-08-08 09:44:32 -07:00
Lucy Satheesan 996e940942 initial AsyncFileDescriptor work 2023-07-31 22:28:54 -07:00
Lucy Satheesan 6338029b74 stage 2: IORequest enum 2023-07-31 22:28:43 -07:00
Lucy Satheesan 15794f5cad ioring pitch: first steps 2023-07-18 21:04:39 -07:00
Saleem Abdulrasool 164fe8ce93 Merge pull request #136 from compnerd/singularity
Tests: avoid unnecessary duplication (NFCI)
2023-07-13 10:11:23 -07:00
Saleem Abdulrasool e1ab868059 Tests: avoid unnecessary duplication (NFCI)
Rather than specialising the function with the same implementation,
prefer to use the `CInterop.PlatformUnicodeEncoding` to determine the
correct code point encoding.  This allows us to share the implementation
across the platforms.
2023-07-13 10:00:45 -07:00
Saleem Abdulrasool 022a7fe638 Merge pull request #135 from compnerd/encoding
Tests: adjust the `FilePathTest.testFilePath` to build on Windows
2023-07-13 08:56:56 -07:00
Saleem Abdulrasool 32026456ba Tests: adjust the FilePathTest.testFilePath to build on Windows
UTF-8 is not the universal encoding for file systems.  Use a platform
specific invalid string encoding for testing the sequence.  The internal
representation of a `FilePath` is dependent on the system, and Windows
uses UTF-16 as the base encoding for C interoperability.  Adjust the
test to use an invalid sequence in the proper encoding.  This allows the
tests to now build on Windows once again.
2023-07-13 08:42:12 -07:00
Max Desiatov 0062c82c90 Add support for Musl libc (#133)
Since Musl is sufficiently different from Glibc (see https://wiki.musl-libc.org/functional-differences-from-glibc.html), it requires a different import, which now should be applied to files that have `import Glibc` in them.
2023-07-04 16:50:13 +01:00
Guillaume Lessard 4116b8cbfb Merge pull request #131 from glessard/sendable-availability
Add availability attributes to `Sendable` conformances
2023-06-21 16:47:51 -07:00
Guillaume Lessard adbf8d2856 Add availability attributes to Sendable conformances 2023-06-21 14:50:47 -07:00
Guillaume Lessard a87eaf71f6 Merge pull request #130 from amartini51/abstracts
Fix abstracts to follow reference style
2023-06-21 14:11:40 -07:00
Alex Martini 1d1bef36c9 Fix abstracts to follow reference style.
- Use a present tense verb phrase
- Avoid repeating the symbol's name
2023-06-21 10:26:04 -07:00
137 changed files with 13893 additions and 4006 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Lines starting with '#' are comments.
# Each line is a case-sensitive file pattern followed by one or more owners.
# Order is important. The last matching pattern has the most precedence.
# More information: https://docs.github.com/en/articles/about-code-owners
#
# Please mirror the repository's file hierarchy in case-sensitive lexicographic
# order.
# Default owners
* @glessard @lorentey @milseman
# Swift CI configuration files
.swiftci/ @shahmishal
+83
View File
@@ -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
+4 -2
View File
@@ -2,7 +2,9 @@
/.swiftpm
/.build
/Packages
swift-system.xcodeproj
/*.xcodeproj
xcuserdata/
.*.sw?
.docc-build
/.swiftpm
.docc-build
Package.resolved
+4
View File
@@ -0,0 +1,4 @@
version: 1
builder:
configs:
- documentation_targets: [SystemPackage]
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.10-jammy"
repo = "swift-system"
branch = "main"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.9-jammy"
repo = "swift-system"
branch = "main"
}
+5
View File
@@ -0,0 +1,5 @@
macOSSwiftPackageJob {
swift_version = "6.0"
repo = "swift-system"
branch = "main"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-6.0-jammy"
repo = "swift-system"
branch = "main"
}
+5
View File
@@ -0,0 +1,5 @@
macOSSwiftPackageJob {
swift_version = "main"
repo = "swift-system"
branch = "main"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-jammy"
repo = "swift-system"
branch = "main"
}
+7
View File
@@ -0,0 +1,7 @@
WindowsSwiftPackageWithDockerImageJob {
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
repo = "swift-system"
branch = "main"
sub_dir = "swift-system"
label = "windows-server-2019"
}
+2
View File
@@ -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)
+38
View File
@@ -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/).
+165 -38
View File
@@ -1,43 +1,170 @@
// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// 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
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
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: []),
.target(
name: "SystemPackage",
dependencies: ["CSystem"],
path: "Sources/System",
cSettings: [
.define("_CRT_SECURE_NO_WARNINGS")
],
swiftSettings: [
.define("SYSTEM_PACKAGE"),
.define("ENABLE_MOCKING", .when(configuration: .debug))
]),
.testTarget(
name: "SystemTests",
dependencies: ["SystemPackage"],
swiftSettings: [
.define("SYSTEM_PACKAGE")
]),
]
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]
)
+982
View File
@@ -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 |
+71 -9
View File
@@ -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.0.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.0.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
+2 -2
View File
@@ -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
+1
View File
@@ -21,5 +21,6 @@
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include "io_uring.h"
#endif
+66
View File
@@ -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
+247
View File
@@ -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
View File
@@ -1,5 +1,6 @@
module CSystem {
header "CSystemLinux.h"
header "CSystemWASI.h"
header "CSystemWindows.h"
export *
}
+71
View File
@@ -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!")
}
}
+80
View File
@@ -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")
}
}
+102
View File
@@ -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))"
}
}
}
+84
View File
@@ -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)"
}
}
}
+64
View File
@@ -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
}
}
+25
View File
@@ -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()
+4
View File
@@ -41,6 +41,10 @@ target_sources(SystemPackage PRIVATE
target_link_libraries(SystemPackage PUBLIC
CSystem)
set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS")
if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS)
target_compile_definitions(SystemPackage PRIVATE SYSTEM_PACKAGE_DARWIN)
endif()
_install_target(SystemPackage)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage)
+181 -135
View File
File diff suppressed because it is too large. Load diff
+20
View File
@@ -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
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
public struct FileDescriptor: RawRepresentable, Hashable, Codable {
/// The raw C file handle.
@_alwaysEmitIntoClient
@@ -26,7 +26,7 @@ public struct FileDescriptor: RawRepresentable, Hashable, Codable {
}
// Standard file descriptors.
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FileDescriptor {
/// The standard input file descriptor, with a numeric value of 0.
@_alwaysEmitIntoClient
@@ -41,11 +41,12 @@ extension FileDescriptor {
public static var standardError: FileDescriptor { .init(rawValue: 2) }
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@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
@@ -87,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
@@ -96,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.
@@ -115,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")
@@ -131,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")
@@ -141,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")
@@ -155,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")
@@ -177,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 os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Indicates that opening the file
/// atomically obtains a shared lock on the file.
///
@@ -195,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")
@@ -212,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")
@@ -230,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")
@@ -244,14 +243,30 @@ 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(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#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.
///
@@ -263,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")
@@ -279,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")
@@ -301,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")
@@ -311,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
@@ -354,7 +370,7 @@ extension FileDescriptor {
// TODO: These are available on some versions of Linux with appropriate
// macro defines.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Indicates that the offset should be set
/// to the next hole after the specified number of bytes.
///
@@ -386,7 +402,7 @@ extension FileDescriptor {
}
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FileDescriptor.AccessMode
: CustomStringConvertible, CustomDebugStringConvertible
{
@@ -405,7 +421,7 @@ extension FileDescriptor.AccessMode
public var debugDescription: String { self.description }
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FileDescriptor.SeekOrigin
: CustomStringConvertible, CustomDebugStringConvertible
{
@@ -416,7 +432,7 @@ extension FileDescriptor.SeekOrigin
case .start: return "start"
case .current: return "current"
case .end: return "end"
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
case .nextHole: return "nextHole"
case .nextData: return "nextData"
#endif
@@ -428,14 +444,14 @@ extension FileDescriptor.SeekOrigin
public var debugDescription: String { self.description }
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FileDescriptor.OpenOptions
: CustomStringConvertible, CustomDebugStringConvertible
{
/// A textual representation of the open options.
@inline(never)
public var description: String {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
let descriptions: [(Element, StaticString)] = [
(.nonBlocking, ".nonBlocking"),
(.append, ".append"),
@@ -456,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"),
@@ -475,13 +504,7 @@ extension FileDescriptor.OpenOptions
public var debugDescription: String { self.description }
}
#if compiler(>=5.5) && canImport(_Concurrency)
// 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 {}
extension FileDescriptor.AccessMode: Sendable {}
extension FileDescriptor.OpenOptions: Sendable {}
extension FileDescriptor.SeekOrigin: Sendable {}
#endif
@@ -1,122 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor {
/// Runs a closure and then closes the file descriptor, even if an error occurs.
///
/// - Parameter body: The closure to run.
/// If the closure throws an error,
/// this method closes the file descriptor before it rethrows that error.
///
/// - Returns: The value returned by the closure.
///
/// If `body` throws an error
/// or an error occurs while closing the file descriptor,
/// this method rethrows that error.
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
// No underscore helper, since the closure's throw isn't necessarily typed.
let result: R
do {
result = try body()
} catch {
_ = try? self.close() // Squash close error and throw closure's
throw error
}
try self.close()
return result
}
/// Writes a sequence of bytes to the current offset
/// and then updates the offset.
///
/// - Parameter sequence: The bytes to write.
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
///
/// This method either writes the entire contents of `sequence`,
/// or throws an error if only part of the content was written.
///
/// Writes to the position associated with this file descriptor, and
/// increments that position by the number of bytes written.
/// See also ``seek(offset:from:)``.
///
/// If `sequence` doesn't implement
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
/// temporary space will be allocated as needed.
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
_ sequence: S
) throws -> Int where S.Element == UInt8 {
return try _writeAll(sequence).get()
}
@usableFromInline
internal func _writeAll<S: Sequence>(
_ 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)
}
}
/// Writes a sequence of bytes to the given offset.
///
/// - Parameters:
/// - offset: The file offset where writing begins.
/// - sequence: The bytes to write.
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
///
/// This method either writes the entire contents of `sequence`,
/// or throws an error if only part of the content was written.
/// Unlike ``writeAll(_:)``,
/// this method preserves the file descriptor's existing offset.
///
/// If `sequence` doesn't implement
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
/// temporary space will be allocated as needed.
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
toAbsoluteOffset offset: Int64, _ sequence: S
) throws -> Int where S.Element == UInt8 {
try _writeAll(toAbsoluteOffset: offset, sequence).get()
}
@usableFromInline
internal func _writeAll<S: Sequence>(
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)
}
}
}
+260
View File
@@ -0,0 +1,260 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
@available(System 0.0.1, *)
extension FileDescriptor {
/// Runs a closure and then closes the file descriptor, even if an error occurs.
///
/// - Parameter body: The closure to run.
/// If the closure throws an error,
/// this method closes the file descriptor before it rethrows that error.
///
/// - Returns: The value returned by the closure.
///
/// If `body` throws an error
/// or an error occurs while closing the file descriptor,
/// this method rethrows that error.
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
// No underscore helper, since the closure's throw isn't necessarily typed.
let result: R
do {
result = try body()
} catch {
_ = try? self.close() // Squash close error and throw closure's
throw error
}
try self.close()
return result
}
/// Writes a sequence of bytes to the current offset
/// and then updates the offset.
///
/// - Parameter sequence: The bytes to write.
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
///
/// This method either writes the entire contents of `sequence`,
/// or throws an error if only part of the content was written.
///
/// Writes to the position associated with this file descriptor, and
/// increments that position by the number of bytes written.
/// See also ``seek(offset:from:)``.
///
/// If `sequence` doesn't implement
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
/// temporary space will be allocated as needed.
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
_ sequence: S
) throws -> Int where S.Element == UInt8 {
return try _writeAll(sequence).get()
}
@usableFromInline
internal func _writeAll<S: Sequence>(
_ sequence: S
) -> Result<Int, Errno> where S.Element == UInt8 {
sequence._withRawBufferPointer { buffer in
_writeAllBuffer(buffer)
}
}
@_alwaysEmitIntoClient
internal func _writeAllBuffer(
_ buffer: UnsafeRawBufferPointer
) -> Result<Int, Errno> {
var idx = 0
while idx < buffer.count {
switch _write(
UnsafeRawBufferPointer(rebasing: buffer[idx...]), retryOnInterrupt: true
) {
case .success(let numBytes): idx += numBytes
case .failure(let err): return .failure(err)
}
}
assert(idx == buffer.count)
return .success(buffer.count)
}
/// Writes a sequence of bytes to the given offset.
///
/// - Parameters:
/// - offset: The file offset where writing begins.
/// - sequence: The bytes to write.
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
///
/// This method either writes the entire contents of `sequence`,
/// or throws an error if only part of the content was written.
/// Unlike ``writeAll(_:)``,
/// this method preserves the file descriptor's existing offset.
///
/// If `sequence` doesn't implement
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
/// temporary space will be allocated as needed.
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
toAbsoluteOffset offset: Int64, _ sequence: S
) throws -> Int where S.Element == UInt8 {
try _writeAll(toAbsoluteOffset: offset, sequence).get()
}
@usableFromInline
internal func _writeAll<S: Sequence>(
toAbsoluteOffset offset: Int64, _ sequence: S
) -> Result<Int, Errno> where S.Element == UInt8 {
sequence._withRawBufferPointer { buffer in
_writeAllBuffer(toAbsoluteOffset: offset, buffer)
}
}
@_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
*/
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FileDescriptor {
/// Opens or creates a file for reading or writing.
///
@@ -135,8 +135,6 @@ 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) }
@@ -158,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.
@@ -367,11 +365,156 @@ extension FileDescriptor {
buffer,
retryOnInterrupt: retryOnInterrupt)
}
/// 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")
}
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
#if !os(WASI)
@available(System 0.0.2, *)
extension FileDescriptor {
/// Duplicate this file descriptor and return the newly created copy.
/// Duplicates this file descriptor and return the newly created copy.
///
/// - Parameters:
/// - `target`: The desired target file descriptor, or `nil`, in which case
@@ -399,7 +542,7 @@ extension FileDescriptor {
///
/// The corresponding C functions are `dup` and `dup2`.
@_alwaysEmitIntoClient
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
public func duplicate(
as target: FileDescriptor? = nil,
retryOnInterrupt: Bool = true
@@ -407,7 +550,7 @@ extension FileDescriptor {
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor?,
@@ -433,22 +576,23 @@ extension FileDescriptor {
fatalError("Not implemented")
}
}
#endif
#if !os(Windows)
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
#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
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.1.0, *)
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe().get()
}
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.1.0, *)
@usableFromInline
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
var fds: (Int32, Int32) = (-1, -1)
@@ -463,10 +607,9 @@ extension FileDescriptor {
}
#endif
#if !os(Windows)
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@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.
@@ -486,7 +629,7 @@ extension FileDescriptor {
/// associated with the file.
///
/// The corresponding C function is `ftruncate`.
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.2.0, *)
@_alwaysEmitIntoClient
public func resize(
to newSize: Int64,
@@ -498,7 +641,7 @@ extension FileDescriptor {
).get()
}
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.2.0, *)
@usableFromInline
internal func _resize(
to newSize: Int64,
@@ -509,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
+25 -8
View File
@@ -37,8 +37,8 @@
/// However, the rules for path equivalence
/// are file-system–specific and have additional considerations
/// like case insensitivity, Unicode normalization, and symbolic links.
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
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
@@ -59,15 +59,32 @@ public struct FilePath {
}
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
/// The length of the file path, excluding the null terminator.
public var length: Int { _storage.length }
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath: Hashable, Codable {}
@available(System 0.0.1, *)
extension FilePath: Hashable {}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePath: Sendable {}
#endif
@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 {
let container = try decoder.container(keyedBy: CodingKeys.self)
self._storage = try container.decode(SystemString.self, forKey: ._storage)
guard _invariantsSatisfied() else {
throw DecodingError.dataCorruptedError(
forKey: ._storage,
in: container,
debugDescription:
"Encoding does not satisfy the invariants of FilePath"
)
}
}
}
@@ -9,7 +9,7 @@
// MARK: - API
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath {
/// A bidirectional, range replaceable collection of the non-root components
/// that make up a file path.
@@ -28,7 +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
@@ -39,30 +40,6 @@ extension FilePath {
}
}
#if SYSTEM_PACKAGE // Workaround for a __consuming getter bug in Swift 5.3.3
/// 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) }
@@ -85,13 +62,14 @@ extension FilePath {
yield &comp
}
}
#endif
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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
@@ -122,7 +100,7 @@ extension FilePath.ComponentView: BidirectionalCollection {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.ComponentView: RangeReplaceableCollection {
public init() {
self.init(FilePath())
@@ -172,7 +150,7 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath {
/// Create a file path from a root and a collection of components.
public init<C: Collection>(
@@ -201,7 +179,7 @@ extension FilePath {
// MARK: - Internals
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.ComponentView: _PathSlice {
internal var _range: Range<SystemString.Index> {
_start ..< _path._storage.endIndex
@@ -214,7 +192,7 @@ extension FilePath.ComponentView: _PathSlice {
// MARK: - Invariants
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.ComponentView {
internal func _invariantCheck() {
#if DEBUG
@@ -239,8 +217,3 @@ extension FilePath.ComponentView {
#endif // DEBUG
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePath.ComponentView: Sendable {}
extension FilePath.ComponentView.Index: Sendable {}
#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 - 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
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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,7 +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>
@@ -72,13 +74,14 @@ extension FilePath {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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
@@ -97,7 +100,7 @@ extension FilePath.Component {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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,17 +186,17 @@ extension _PathSlice {
internal var _storage: SystemString { _path._storage }
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component: _PathSlice {
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath: _PlatformStringable {
func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
try _storage.withPlatformString(body)
@@ -205,7 +208,7 @@ extension FilePath: _PlatformStringable {
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component {
// The index of the `.` denoting an extension
internal func _extensionIndex() -> SystemString.Index? {
@@ -234,7 +237,7 @@ internal func _makeExtension(_ ext: String) -> SystemString {
return result
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component {
internal init?(_ str: SystemString) {
// FIXME: explicit null root? Or something else?
@@ -247,7 +250,7 @@ extension FilePath.Component {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root {
internal init?(_ str: SystemString) {
// FIXME: explicit null root? Or something else?
@@ -262,7 +265,7 @@ extension FilePath.Root {
// MARK: - Invariants
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component {
// TODO: ensure this all gets easily optimized away in release...
internal func _invariantCheck() {
@@ -275,7 +278,7 @@ extension FilePath.Component {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root {
internal func _invariantCheck() {
#if DEBUG
@@ -285,9 +288,3 @@ extension FilePath.Root {
#endif
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePath.Root: Sendable {}
extension FilePath.Component: Sendable {}
extension FilePath.Component.Kind: Sendable {}
#endif
+27 -14
View File
@@ -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,7 +116,7 @@ extension SystemString {
}
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
internal mutating func _removeTrailingSeparator() {
_storage._removeTrailingSeparator()
@@ -192,7 +197,7 @@ extension SystemString {
}
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
internal var _relativeStart: SystemString.Index {
_storage._relativePathStart
@@ -204,7 +209,7 @@ extension FilePath {
// Parse separators
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
internal typealias _Index = SystemString.Index
@@ -268,7 +273,7 @@ extension FilePath {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.ComponentView {
// TODO: Store this...
internal var _relativeStart: SystemString.Index {
@@ -293,7 +298,7 @@ extension SystemString {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root {
// Asserting self is a root, returns whether this is an
// absolute root.
@@ -318,7 +323,7 @@ extension FilePath.Root {
}
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
internal var _portableDescription: String {
guard _windowsPaths else { return description }
@@ -330,14 +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: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
// Whether we should add a separator when doing an append
internal var _needsSeparatorForAppend: Bool {
@@ -365,15 +373,20 @@ extension FilePath {
}
// MARK: - Invariants
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
internal func _invariantCheck() {
#if DEBUG
internal func _invariantsSatisfied() -> Bool {
var normal = self
normal._normalizeSeparators()
precondition(self == normal)
precondition(!self._storage._hasTrailingSeparator())
precondition(_hasRoot == (self.root != nil))
guard self == normal else { return false }
guard !self._storage._hasTrailingSeparator() else { return false }
guard _hasRoot == (self.root != nil) else { return false }
return true
}
internal func _invariantCheck() {
#if DEBUG
precondition(_invariantsSatisfied())
#endif // DEBUG
}
}
+17 -17
View File
@@ -9,7 +9,7 @@
// MARK: - Platform string
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath {
/// Creates a file path by copying bytes from a null-terminated platform
/// string.
@@ -109,7 +109,7 @@ extension FilePath {
#endif
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component {
/// Creates a file path component by copying bytes from a null-terminated
/// platform string.
@@ -198,7 +198,7 @@ extension FilePath.Component {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root {
/// Creates a file path root by copying bytes from a null-terminated platform
/// string.
@@ -287,7 +287,7 @@ extension FilePath.Root {
// MARK: - String literals
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath: ExpressibleByStringLiteral {
/// Creates a file path from a string literal.
///
@@ -306,7 +306,7 @@ extension FilePath: ExpressibleByStringLiteral {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component: ExpressibleByStringLiteral {
/// Create a file path component from a string literal.
///
@@ -331,7 +331,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root: ExpressibleByStringLiteral {
/// Create a file path root from a string literal.
///
@@ -356,7 +356,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
// MARK: - Printing and dumping
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the file path.
///
@@ -372,7 +372,7 @@ extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
public var debugDescription: String { description.debugDescription }
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the path component.
@@ -389,7 +389,7 @@ extension FilePath.Component: CustomStringConvertible, CustomDebugStringConverti
public var debugDescription: String { description.debugDescription }
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the path root.
@@ -409,7 +409,7 @@ extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Convenience helpers
// Convenience helpers
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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.
@@ -420,7 +420,7 @@ extension FilePath {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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.
@@ -431,7 +431,7 @@ extension FilePath.Component {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Root {
/// On Unix, this returns `"/"`.
///
@@ -445,7 +445,7 @@ extension FilePath.Root {
// MARK: - Decoding and validating
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@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.
@@ -475,7 +475,7 @@ extension String {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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.
@@ -505,7 +505,7 @@ extension String {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension String {
/// On Unix, creates the string `"/"`
///
@@ -558,7 +558,7 @@ extension String {
// MARK: - Deprecations
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension String {
@available(*, deprecated, renamed: "init(decoding:)")
public init(_ path: FilePath) { self.init(decoding: path) }
@@ -568,7 +568,7 @@ extension String {
}
#if !os(Windows)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePath {
/// For backwards compatibility only. This initializer is equivalent to
/// the preferred `FilePath(platformString:)`.
+8 -8
View File
@@ -9,7 +9,7 @@
// MARK: - Query API
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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.
@@ -99,7 +99,7 @@ extension FilePath {
}
// MARK: - Decompose a path
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath {
/// Returns the root of a path if there is one, otherwise `nil`.
///
@@ -182,7 +182,7 @@ extension FilePath {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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.
@@ -252,7 +252,7 @@ extension FilePath {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath.Component {
/// The extension of this file or directory component.
///
@@ -283,7 +283,7 @@ extension FilePath.Component {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension FilePath {
/// The extension of the file or directory last component.
@@ -349,7 +349,7 @@ extension FilePath {
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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
@@ -430,7 +430,7 @@ extension FilePath {
}
// Modification and concatenation API
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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`.
@@ -583,7 +583,7 @@ extension FilePath {
}
// MARK - Renamed
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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)
@@ -461,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,8 +17,8 @@
/// let perms = FilePermissions(rawValue: 0o644)
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
@frozen
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
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: CModeT
@@ -27,104 +27,101 @@ public struct FilePermissions: OptionSet, Hashable, Codable {
@_alwaysEmitIntoClient
public init(rawValue: CModeT) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CModeT) { self.init(rawValue: raw) }
/// 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) }
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
extension FilePermissions
: CustomStringConvertible, CustomDebugStringConvertible
{
@@ -175,7 +172,3 @@ extension FilePermissions
/// A textual representation of the file permissions, suitable for debugging.
public var debugDescription: String { self.description }
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePermissions: Sendable {}
#endif
+250
View File
@@ -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
+54
View File
@@ -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
+108
View File
@@ -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)
+632
View File
@@ -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)
+71
View File
@@ -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
+497
View File
@@ -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
+904
View File
@@ -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: &params) {
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
+205
View File
@@ -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
+36 -8
View File
@@ -1,20 +1,28 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
@_implementationOnly import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
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
@@ -29,13 +37,19 @@ import ucrt
public typealias CModeT = CInt
#else
/// The C `mode_t` type.
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
public typealias CModeT = mode_t
#endif
/// A namespace for C and platform types
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
public enum CInterop {
#if os(Windows)
public typealias Mode = CInt
#else
public typealias Mode = mode_t
#endif
/// The C `char` type
public typealias Char = CChar
@@ -65,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
+284 -34
View File
@@ -1,29 +1,38 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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
// unavailable local decls.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
import CSystem
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#elseif canImport(WASILibc)
import CSystem
import WASILibc
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: - errno
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: errno
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _ERRNO_NOT_USED: CInt { 0 }
#endif
@@ -70,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
@@ -138,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 }
@@ -164,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)
@@ -172,6 +188,7 @@ internal var _ESOCKTNOSUPPORT: CInt {
return ESOCKTNOSUPPORT
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _ENOTSUP: CInt {
@@ -182,6 +199,7 @@ internal var _ENOTSUP: CInt {
#endif
}
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EPFNOSUPPORT: CInt {
#if os(Windows)
@@ -190,6 +208,7 @@ internal var _EPFNOSUPPORT: CInt {
return EPFNOSUPPORT
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT }
@@ -224,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)
@@ -241,6 +261,7 @@ internal var _ETOOMANYREFS: CInt {
return ETOOMANYREFS
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _ETIMEDOUT: CInt { ETIMEDOUT }
@@ -254,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)
@@ -262,6 +284,7 @@ internal var _EHOSTDOWN: CInt {
return EHOSTDOWN
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
@@ -269,11 +292,12 @@ internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
@_alwaysEmitIntoClient
internal var _ENOTEMPTY: CInt { ENOTEMPTY }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EPROCLIM: CInt { EPROCLIM }
#endif
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EUSERS: CInt {
#if os(Windows)
@@ -282,6 +306,7 @@ internal var _EUSERS: CInt {
return EUSERS
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _EDQUOT: CInt {
@@ -301,6 +326,7 @@ internal var _ESTALE: CInt {
#endif
}
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EREMOTE: CInt {
#if os(Windows)
@@ -309,8 +335,9 @@ internal var _EREMOTE: CInt {
return EREMOTE
#endif
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EBADRPC: CInt { EBADRPC }
@@ -333,7 +360,7 @@ internal var _ENOLCK: CInt { ENOLCK }
@_alwaysEmitIntoClient
internal var _ENOSYS: CInt { ENOSYS }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _EFTYPE: CInt { EFTYPE }
@@ -342,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 }
@@ -355,7 +384,7 @@ internal var _EDEVERR: CInt { EDEVERR }
internal var _EOVERFLOW: CInt { EOVERFLOW }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EBADEXEC: CInt { EBADEXEC }
@@ -383,7 +412,7 @@ internal var _ENOMSG: CInt { ENOMSG }
@_alwaysEmitIntoClient
internal var _EILSEQ: CInt { EILSEQ }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENOATTR: CInt { ENOATTR }
#endif
@@ -396,32 +425,43 @@ internal var _EBADMSG: CInt { EBADMSG }
@_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
#endif
@_alwaysEmitIntoClient
internal var _EPROTO: CInt { EPROTO }
#if !os(OpenBSD)
#if !os(OpenBSD) && !os(WASI) && !os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ETIME: CInt { ETIME }
#endif
#endif
@_alwaysEmitIntoClient
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _EOPNOTSUPP: CInt {
#if os(WASI)
_getConst_EOPNOTSUPP()
#else
EOPNOTSUPP
#endif
}
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _ENOPOLICY: CInt { ENOPOLICY }
#endif
@@ -434,15 +474,28 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#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
// MARK: - File Operations
// MARK: File Operations
@_alwaysEmitIntoClient
internal var _O_RDONLY: CInt { O_RDONLY }
@@ -454,18 +507,40 @@ internal var _O_WRONLY: CInt { O_WRONLY }
internal var _O_RDWR: CInt { O_RDWR }
#if !os(Windows)
#if canImport(Musl)
internal var _O_ACCMODE: CInt { 0x03|O_SEARCH }
#else
// TODO: API?
@_alwaysEmitIntoClient
internal var _O_ACCMODE: CInt { O_ACCMODE }
@_alwaysEmitIntoClient
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
internal var _O_ACCMODE: CInt {
#if os(WASI)
_getConst_O_ACCMODE()
#else
O_ACCMODE
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _O_APPEND: CInt { O_APPEND }
internal var _O_NONBLOCK: CInt {
#if os(WASI)
_getConst_O_NONBLOCK()
#else
O_NONBLOCK
#endif
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _O_APPEND: CInt {
#if os(WASI)
_getConst_O_APPEND()
#else
O_APPEND
#endif
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _O_SHLOCK: CInt { O_SHLOCK }
@@ -474,24 +549,52 @@ 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
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_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
internal var _O_EVTONLY: CInt { O_EVTONLY }
#endif
@@ -502,10 +605,16 @@ 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 os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _O_SYMLINK: CInt { O_SYMLINK }
#endif
@@ -524,7 +633,7 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
@_alwaysEmitIntoClient
internal var _SEEK_END: CInt { SEEK_END }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
@@ -532,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)
+71 -9
View File
@@ -1,25 +1,33 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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.
// TODO: Should CSystem just include all the header files we need?
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
@_implementationOnly import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
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
@@ -28,7 +36,7 @@ internal typealias _COffT = off_t
// MARK: syscalls and variables
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
internal var system_errno: CInt {
get { Darwin.errno }
set { Darwin.errno = newValue }
@@ -45,11 +53,26 @@ internal var system_errno: CInt {
_ = ucrt._set_errno(newValue)
}
}
#else
#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(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
@@ -67,6 +90,25 @@ 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.
// Type and layout differences such as the `char` vs `wchar` are abstracted.
@@ -117,7 +159,7 @@ extension String {
return
#else
self.init(validatingUTF8: platformString)
self.init(validatingCString: platformString)
#endif
}
@@ -141,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
@@ -152,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 {
+7 -18
View File
@@ -63,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() }()
@@ -110,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
}
}
@@ -128,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
@@ -193,25 +193,14 @@ internal func _mockOffT(
) -> _COffT {
_COffT(mockImpl(name: name, path: path, args))
}
internal func _mockModeT(
name: String = #function, _ args: AnyHashable...
) -> CInterop.Mode {
CInterop.Mode(mockImpl(name: name, path: nil, args))
}
#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
+7 -1
View File
@@ -80,7 +80,13 @@ extension _RawBuffer {
internal static func create(minimumCapacity: Int) -> Storage {
Storage.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: { $0.capacity }
makingHeaderWith: {
#if os(OpenBSD)
minimumCapacity
#else
$0.capacity
#endif
}
) as! Storage
}
}
+141 -5
View File
@@ -1,18 +1,25 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
#elseif canImport(Glibc)
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
@@ -69,7 +76,15 @@ internal func system_pread(
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pread has a non-nullable `buf` pointer
pread(fd, buf ?? UnsafeMutableRawPointer($0), nbyte, offset)
}
#else
return pread(fd, buf, nbyte, offset)
#endif
}
// lseek
@@ -99,9 +114,18 @@ internal func system_pwrite(
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pwrite has a non-nullable `buf` pointer
pwrite(fd, buf ?? UnsafeRawPointer($0), nbyte, offset)
}
#else
return pwrite(fd, buf, nbyte, offset)
#endif
}
#if !os(WASI)
internal func system_dup(_ fd: Int32) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd) }
@@ -115,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) }
@@ -125,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)
@@ -72,7 +135,11 @@ internal func dup(_ fd: Int32) -> Int32 {
@inline(__always)
internal func dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
_dup2(fd, fd2)
// _dup2 returns 0 to indicate success.
if _dup2(fd, fd2) == 0 {
return fd2
}
return -1
}
@inline(__always)
@@ -80,7 +147,7 @@ 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)!
@@ -91,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)
@@ -103,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)!
@@ -115,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
+90 -47
View File
@@ -1,18 +1,20 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2022 Apple Inc. and the Swift System project authors
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 false && swift(>=5.8) && $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
#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,
@@ -24,9 +26,10 @@ internal func _machPrecondition(
precondition(kr == expected, file: file, line: line)
}
@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@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
@@ -48,11 +51,15 @@ public enum Mach {
///
/// 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")
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 /* MACH_PORT_DEAD */, "Receive rights cannot be dead names")
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))
@@ -81,17 +88,20 @@ public enum Mach {
}
deinit {
if _name == 0xFFFFFFFF /* MACH_PORT_DEAD */ {
precondition(RightType.self != ReceiveRight.self, "Receive rights cannot be dead names")
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_DEAD_NAME, -1))
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 {
if RightType.self == ReceiveRight.self {
_machPrecondition(mach_port_destruct(mach_task_self_, _name, -1, _context))
} else if RightType.self == SendRight.self {
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND, -1))
} else if RightType.self == SendOnceRight.self {
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND_ONCE, -1))
}
assert(
RightType.self == SendRight.self ||
RightType.self == SendOnceRight.self
)
_machPrecondition(mach_port_deallocate(mach_task_self_, _name))
}
}
}
@@ -123,6 +133,7 @@ public enum Mach {
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.
@@ -135,6 +146,8 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// 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
}
@@ -145,11 +158,12 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// 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)
withUnsafeMutablePointer(to: &storage) { storage in
_machPrecondition(mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage))
}
_machPrecondition(
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &storage)
)
// name-only init will guard ReceiveRights
self.init(name: storage)
@@ -167,9 +181,12 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
public __consuming func relinquish(
@available(System 1.4.0, *)
public consuming func relinquish(
) -> (name: mach_port_name_t, context: mach_port_context_t) {
return (name: _name, context: _context)
let destructured = (name: _name, context: _context)
discard self
return destructured
}
/// Remove guard and transfer ownership of the underlying port right to
@@ -187,9 +204,11 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract
/// the context value along with the port name.
@inlinable
public __consuming func unguardAndRelinquish() -> mach_port_name_t {
_machPrecondition(mach_port_unguard(mach_task_self_, _name, _context))
return _name
@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
@@ -202,6 +221,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// 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 {
@@ -215,22 +235,21 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// 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
withUnsafeMutablePointer(to: &newRight) { newRight in
withUnsafeMutablePointer(to: &newRightType) { newRightType in
_machPrecondition(
mach_port_extract_right(mach_task_self_,
_name,
mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE),
newRight,
newRightType)
)
}
}
_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)
@@ -245,11 +264,16 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// 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)))
_machPrecondition(
mach_port_insert_right(
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
)
)
return Mach.Port(name: _name)
}
@@ -258,14 +282,24 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// 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 = mach_msg_type_number_t(MemoryLayout<mach_port_status>.size / MemoryLayout<natural_t>.size)
withUnsafeMutablePointer(to: &size) { size in
withUnsafeMutablePointer(to: &status) { status in
let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1)
_machPrecondition(mach_port_get_attributes(mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, size))
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
@@ -277,6 +311,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
}
}
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.SendRight {
/// Transfer ownership of the underlying port right to the caller.
///
@@ -288,8 +323,10 @@ extension Mach.Port where RightType == Mach.SendRight {
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
public __consuming func relinquish() -> mach_port_name_t {
return _name
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
return name
}
/// Create another send right from a given send right.
@@ -300,12 +337,15 @@ extension Mach.Port where RightType == Mach.SendRight {
/// 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_CAPABILITY {
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)
@@ -314,7 +354,7 @@ extension Mach.Port where RightType == Mach.SendRight {
}
}
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.SendOnceRight {
/// Transfer ownership of the underlying port right to the caller.
///
@@ -326,8 +366,11 @@ extension Mach.Port where RightType == Mach.SendOnceRight {
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
public __consuming func relinquish() -> mach_port_name_t {
return _name
@available(System 1.4.0, *)
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
return name
}
}
+4 -3
View File
@@ -7,7 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@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.
@@ -20,6 +20,7 @@ extension String {
/// This means that, depending on the semantics of the specific platform,
/// conversion to a string and back might result in a value that's different
/// from the original platform string.
@_disfavoredOverload
public init(platformString: UnsafePointer<CInterop.PlatformChar>) {
self.init(_errorCorrectingPlatformString: platformString)
}
@@ -164,7 +165,7 @@ extension String {
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension CInterop.PlatformChar {
internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
#if os(Windows)
@@ -175,7 +176,7 @@ extension CInterop.PlatformChar {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
extension CInterop.PlatformUnicodeEncoding.CodeUnit {
internal var _platformChar: CInterop.PlatformChar {
#if os(Windows)
@@ -1,19 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
extension CInterop {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The C `int` type
public typealias Signal = CInt
#endif
}
@@ -1,114 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// hangup
@_alwaysEmitIntoClient
internal var _SIGHUP: CInterop.Signal { SIGHUP }
/// interrupt
@_alwaysEmitIntoClient
internal var _SIGINT: CInterop.Signal { SIGINT }
/// quit
@_alwaysEmitIntoClient
internal var _SIGQUIT: CInterop.Signal { SIGQUIT }
/// illegal instruction (not reset when caught)
@_alwaysEmitIntoClient
internal var _SIGILL: CInterop.Signal { SIGILL }
/// trace trap (not reset when caught)
@_alwaysEmitIntoClient
internal var _SIGTRAP: CInterop.Signal { SIGTRAP }
/// abort()
@_alwaysEmitIntoClient
internal var _SIGABRT: CInterop.Signal { SIGABRT }
#if false
/// pollable event
@_alwaysEmitIntoClient
internal var _SIGPOLL: CInterop.Signal { SIGPOLL }
#endif
/// compatibility
@_alwaysEmitIntoClient
internal var _SIGIOT: CInterop.Signal { SIGIOT }
/// EMT instruction
@_alwaysEmitIntoClient
internal var _SIGEMT: CInterop.Signal { SIGEMT }
/// floating point exception
@_alwaysEmitIntoClient
internal var _SIGFPE: CInterop.Signal { SIGFPE }
/// kill (cannot be caught or ignored)
@_alwaysEmitIntoClient
internal var _SIGKILL: CInterop.Signal { SIGKILL }
/// bus error
@_alwaysEmitIntoClient
internal var _SIGBUS: CInterop.Signal { SIGBUS }
/// segmentation violation
@_alwaysEmitIntoClient
internal var _SIGSEGV: CInterop.Signal { SIGSEGV }
/// bad argument to system call
@_alwaysEmitIntoClient
internal var _SIGSYS: CInterop.Signal { SIGSYS }
/// write on a pipe with no one to read it
@_alwaysEmitIntoClient
internal var _SIGPIPE: CInterop.Signal { SIGPIPE }
/// alarm clock
@_alwaysEmitIntoClient
internal var _SIGALRM: CInterop.Signal { SIGALRM }
/// software termination signal from kill
@_alwaysEmitIntoClient
internal var _SIGTERM: CInterop.Signal { SIGTERM }
/// urgent condition on IO channel
@_alwaysEmitIntoClient
internal var _SIGURG: CInterop.Signal { SIGURG }
/// sendable stop signal not from tty
@_alwaysEmitIntoClient
internal var _SIGSTOP: CInterop.Signal { SIGSTOP }
/// stop signal from tty
@_alwaysEmitIntoClient
internal var _SIGTSTP: CInterop.Signal { SIGTSTP }
/// continue a stopped process
@_alwaysEmitIntoClient
internal var _SIGCONT: CInterop.Signal { SIGCONT }
/// to parent on child stop or exit
@_alwaysEmitIntoClient
internal var _SIGCHLD: CInterop.Signal { SIGCHLD }
/// to readers pgrp upon background tty read
@_alwaysEmitIntoClient
internal var _SIGTTIN: CInterop.Signal { SIGTTIN }
/// like TTIN for output if (tp->t_local&LTOSTOP)
@_alwaysEmitIntoClient
internal var _SIGTTOU: CInterop.Signal { SIGTTOU }
/// input/output possible signal
@_alwaysEmitIntoClient
internal var _SIGIO: CInterop.Signal { SIGIO }
/// exceeded CPU time limit
@_alwaysEmitIntoClient
internal var _SIGXCPU: CInterop.Signal { SIGXCPU }
/// exceeded file size limit
@_alwaysEmitIntoClient
internal var _SIGXFSZ: CInterop.Signal { SIGXFSZ }
/// virtual time alarm
@_alwaysEmitIntoClient
internal var _SIGVTALRM: CInterop.Signal { SIGVTALRM }
/// profiling time alarm
@_alwaysEmitIntoClient
internal var _SIGPROF: CInterop.Signal { SIGPROF }
/// window size changes
@_alwaysEmitIntoClient
internal var _SIGWINCH: CInterop.Signal { SIGWINCH }
/// information request
@_alwaysEmitIntoClient
internal var _SIGINFO: CInterop.Signal { SIGINFO }
/// user defined signal 1
@_alwaysEmitIntoClient
internal var _SIGUSR1: CInterop.Signal { SIGUSR1 }
/// user defined signal 2
@_alwaysEmitIntoClient
internal var _SIGUSR2: CInterop.Signal { SIGUSR2 }
#endif
-296
View File
@@ -1,296 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public struct Signal: RawRepresentable {
/// The raw C signal value.
@_alwaysEmitIntoClient
public let rawValue: CInterop.Signal
/// Creates a strongly typed signal from a raw C signal value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Signal) { self.rawValue = rawValue }
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
extension Signal {
/// The corresponding C signal is `SIGHUP`.
@_alwaysEmitIntoClient
internal static var hangup: Self { Self(rawValue: _SIGHUP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "hangup")
internal static var SIGHUP: Self { hangup }
/// The corresponding C signal is `SIGINT`.
@_alwaysEmitIntoClient
internal static var interrupt: Self { Self(rawValue: _SIGINT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "interrupt")
internal static var SIGINT: Self { interrupt }
/// The corresponding C signal is `SIGQUIT`.
@_alwaysEmitIntoClient
internal static var quit: Self { Self(rawValue: _SIGQUIT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "quit")
internal static var SIGQUIT: Self { quit }
/// The corresponding C signal is `SIGILL`.
@_alwaysEmitIntoClient
internal static var illegalInstruction: Self { Self(rawValue: _SIGILL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "illegalInstruction")
internal static var SIGILL: Self { illegalInstruction }
/// The corresponding C signal is `SIGTRAP`.
@_alwaysEmitIntoClient
internal static var trap: Self { Self(rawValue: _SIGTRAP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "trap")
internal static var SIGTRAP: Self { trap }
/// The corresponding C signal is `SIGABRT`.
@_alwaysEmitIntoClient
internal static var abort: Self { Self(rawValue: _SIGABRT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "abort")
internal static var SIGABRT: Self { abort }
#if false
/// The corresponding C signal is `SIGPOLL`.
@_alwaysEmitIntoClient
internal static var pollableEvent: Self { Self(rawValue: _SIGPOLL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "pollableEvent")
internal static var SIGPOLL: Self { pollableEvent }
#endif
/// The corresponding C signal is `SIGIOT`.
@_alwaysEmitIntoClient
@available(*, deprecated, renamed: "abort")
internal static var inputOutputTrap: Self { Self(rawValue: _SIGIOT) }
@_alwaysEmitIntoClient
@available(*, deprecated)
@available(*, unavailable, renamed: "inputOutputTrap")
internal static var SIGIOT: Self { inputOutputTrap }
/// The corresponding C signal is `SIGEMT`.
@_alwaysEmitIntoClient
internal static var emulatorTrap: Self { Self(rawValue: _SIGEMT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "emulatorTrap")
internal static var SIGEMT: Self { emulatorTrap }
/// The corresponding C signal is `SIGFPE`.
@_alwaysEmitIntoClient
internal static var floatingPointException: Self { Self(rawValue: _SIGFPE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "floatingPointException")
internal static var SIGFPE: Self { floatingPointException }
/// The corresponding C signal is `SIGKILL`.
@_alwaysEmitIntoClient
internal static var kill: Self { Self(rawValue: _SIGKILL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "kill")
internal static var SIGKILL: Self { kill }
/// The corresponding C signal is `SIGBUS`.
@_alwaysEmitIntoClient
internal static var busError: Self { Self(rawValue: _SIGBUS) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "busError")
internal static var SIGBUS: Self { busError }
/// The corresponding C signal is `SIGSEGV`.
@_alwaysEmitIntoClient
internal static var segmentationViolation: Self { Self(rawValue: _SIGSEGV) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "segmentationViolation")
internal static var SIGSEGV: Self { segmentationViolation }
/// The corresponding C signal is `SIGSYS`.
@_alwaysEmitIntoClient
internal static var badSystemCall: Self { Self(rawValue: _SIGSYS) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "badSystemCall")
internal static var SIGSYS: Self { badSystemCall }
/// The corresponding C signal is `SIGPIPE`.
@_alwaysEmitIntoClient
internal static var brokenPipe: Self { Self(rawValue: _SIGPIPE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "brokenPipe")
internal static var SIGPIPE: Self { brokenPipe }
/// The corresponding C signal is `SIGALRM`.
@_alwaysEmitIntoClient
internal static var alarm: Self { Self(rawValue: _SIGALRM) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "alarm")
internal static var SIGALRM: Self { alarm }
/// The corresponding C signal is `SIGTERM`.
@_alwaysEmitIntoClient
internal static var terminationRequest: Self { Self(rawValue: _SIGTERM) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "terminationRequest")
internal static var SIGTERM: Self { terminationRequest }
/// The corresponding C signal is `SIGURG`.
@_alwaysEmitIntoClient
internal static var urgentInputOutput: Self { Self(rawValue: _SIGURG) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "urgentInputOutput")
internal static var SIGURG: Self { urgentInputOutput }
/// The corresponding C signal is `SIGSTOP`.
@_alwaysEmitIntoClient
internal static var stop: Self { Self(rawValue: _SIGSTOP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "stop")
internal static var SIGSTOP: Self { stop }
/// The corresponding C signal is `SIGTSTP`.
@_alwaysEmitIntoClient
internal static var interactiveStop: Self { Self(rawValue: _SIGTSTP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "interactiveStop")
internal static var SIGTSTP: Self { interactiveStop }
/// The corresponding C signal is `SIGCONT`.
@_alwaysEmitIntoClient
internal static var `continue`: Self { Self(rawValue: _SIGCONT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "continue")
internal static var SIGCONT: Self { `continue` }
/// The corresponding C signal is `SIGCHLD`.
@_alwaysEmitIntoClient
internal static var childStopOrExit: Self { Self(rawValue: _SIGCHLD) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "childStopOrExit")
internal static var SIGCHLD: Self { childStopOrExit }
/// The corresponding C signal is `SIGTTIN`.
@_alwaysEmitIntoClient
internal static var backgroundRead: Self { Self(rawValue: _SIGTTIN) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "backgroundRead")
internal static var SIGTTIN: Self { backgroundRead }
/// The corresponding C signal is `SIGTTOU`.
@_alwaysEmitIntoClient
internal static var backgroundWrite: Self { Self(rawValue: _SIGTTOU) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "backgroundWrite")
internal static var SIGTTOU: Self { backgroundWrite }
/// The corresponding C signal is `SIGIO`.
@_alwaysEmitIntoClient
internal static var possibleInputOutput: Self { Self(rawValue: _SIGIO) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "possibleInputOutput")
internal static var SIGIO: Self { possibleInputOutput }
/// The corresponding C signal is `SIGXCPU`.
@_alwaysEmitIntoClient
internal static var exceededCPUTimeLimit: Self { Self(rawValue: _SIGXCPU) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "exceededCPUTimeLimit")
internal static var SIGXCPU: Self { exceededCPUTimeLimit }
/// The corresponding C signal is `SIGXFSZ`.
@_alwaysEmitIntoClient
internal static var exceededFileSizeLimit: Self { Self(rawValue: _SIGXFSZ) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "exceededFileSizeLimit")
internal static var SIGXFSZ: Self { exceededFileSizeLimit }
/// The corresponding C signal is `SIGVTALRM`.
@_alwaysEmitIntoClient
internal static var virtualAlarm: Self { Self(rawValue: _SIGVTALRM) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "virtualAlarm")
internal static var SIGVTALRM: Self { virtualAlarm }
/// The corresponding C signal is `SIGPROF`.
@_alwaysEmitIntoClient
internal static var profilingAlarm: Self { Self(rawValue: _SIGPROF) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "profilingAlarm")
internal static var SIGPROF: Self { profilingAlarm }
/// The corresponding C signal is `SIGWINCH`.
@_alwaysEmitIntoClient
internal static var windowSizeChange: Self { Self(rawValue: _SIGWINCH) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "windowSizeChange")
internal static var SIGWINCH: Self { windowSizeChange }
/// The corresponding C signal is `SIGINFO`.
@_alwaysEmitIntoClient
internal static var informationRequest: Self { Self(rawValue: _SIGINFO) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "informationRequest")
internal static var SIGINFO: Self { informationRequest }
/// The corresponding C signal is `SIGUSR1`.
@_alwaysEmitIntoClient
internal static var userDefined1: Self { Self(rawValue: _SIGUSR1) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "userDefined1")
internal static var SIGUSR1: Self { userDefined1 }
/// The corresponding C signal is `SIGUSR2`.
@_alwaysEmitIntoClient
internal static var userDefined2: Self { Self(rawValue: _SIGUSR2) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "userDefined2")
internal static var SIGUSR2: Self { userDefined2 }
}
#endif
-18
View File
@@ -1,18 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public struct SignalSet {
}
#endif
-20
View File
@@ -1,20 +0,0 @@
//
// File.swift
//
//
// Created by Rauhul Varma on 6/16/23.
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: this is wrong and should be done with wrapping fcntrl
// FIXME: go through and figure out the right way to express `at` methods
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
public struct ControlFlags {
let rawValue: Int32
// Test stub
public static var none: ControlFlags = ControlFlags(rawValue: 0)
// Out of scope of this sketch
}
}
#endif
-234
View File
@@ -1,234 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: Document
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileFlags: OptionSet, Hashable, Codable {
/// The raw C file flags.
@_alwaysEmitIntoClient
public let rawValue: CInterop.FileFlags
/// Create a strongly-typed file flags from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.FileFlags) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInterop.FileFlags) { self.init(rawValue: raw) }
/// Do not dump the file. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_NODUMP`
@_alwaysEmitIntoClient
public static var noDump: FileFlags { FileFlags(_UF_NODUMP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "noDump")
public static var UF_NODUMP: FileFlags { noDump }
/// The file may not be changed. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_IMMUTABLE`
@_alwaysEmitIntoClient
public static var immutable: FileFlags { FileFlags(_UF_IMMUTABLE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "immutable")
public static var UF_IMMUTABLE: FileFlags { immutable }
/// The file may only be appended to. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_APPEND`
@_alwaysEmitIntoClient
public static var appendOnly: FileFlags { FileFlags(_UF_APPEND) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "appendOnly")
public static var UF_APPEND: FileFlags { appendOnly }
/// The directory is opaque when viewed through a union stack. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_OPAQUE`
@_alwaysEmitIntoClient
public static var opaque: FileFlags { FileFlags(_UF_OPAQUE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "opaque")
public static var UF_OPAQUE: FileFlags { opaque }
// #if os(FreeBSD)
// /// The file may not be removed or renamed. Modifiable by file owner or super-user.
// ///
// /// The corresponding C constant is `UF_NOUNLINK`
// @_alwaysEmitIntoClient
// public static var noUnlink: FileFlags { FileFlags(_UF_NOUNLINK) }
//
// @_alwaysEmitIntoClient
// @available(*, unavailable, renamed: "noUnlink")
// public static var UF_NOUNLINK: FileFlags { noUnlink }
// #endif
/// The file is compressed (some file-systems). Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_COMPRESSED`
@_alwaysEmitIntoClient
public static var compressed: FileFlags { FileFlags(_UF_COMPRESSED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "compressed")
public static var UF_COMPRESSED: FileFlags { compressed }
/// No notifications will be issued for deletes or renames. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_TRACKED`
@_alwaysEmitIntoClient
public static var tracked: FileFlags { FileFlags(_UF_TRACKED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "tracked")
public static var UF_TRACKED: FileFlags { tracked }
/// The file requires entitlement required for reading and writing. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_DATAVAULT`
@_alwaysEmitIntoClient
public static var dataVault: FileFlags { FileFlags(_UF_DATAVAULT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "dataVault")
public static var UF_DATAVAULT: FileFlags { dataVault }
/// The file or directory is not intended to be displayed to the user. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_HIDDEN`
@_alwaysEmitIntoClient
public static var hidden: FileFlags { FileFlags(_UF_HIDDEN) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "hidden")
public static var UF_HIDDEN: FileFlags { hidden }
/// The file has been archived. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_ARCHIVED`
@_alwaysEmitIntoClient
public static var superUserArchived: FileFlags { FileFlags(_SF_ARCHIVED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserArchived")
public static var SF_ARCHIVED: FileFlags { superUserArchived }
/// The file may not be changed. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_IMMUTABLE`
@_alwaysEmitIntoClient
public static var superUserImmutable: FileFlags { FileFlags(_SF_IMMUTABLE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserImmutable")
public static var SF_IMMUTABLE: FileFlags { superUserImmutable }
/// The file may only be appended to. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_APPEND`
@_alwaysEmitIntoClient
public static var superUserAppend: FileFlags { FileFlags(_SF_APPEND) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserAppend")
public static var SF_APPEND: FileFlags { superUserAppend }
/// The file requires entitlement required for reading and writing. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_RESTRICTED`
@_alwaysEmitIntoClient
public static var superUserRestricted: FileFlags { FileFlags(_SF_RESTRICTED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserRestricted")
public static var SF_RESTRICTED: FileFlags { superUserRestricted }
/// The file may not be removed, renamed or mounted on. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_NOUNLINK`
@_alwaysEmitIntoClient
public static var superUserNoUnlink: FileFlags { FileFlags(_SF_NOUNLINK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserNoUnlink")
public static var SF_NOUNLINK: FileFlags { superUserNoUnlink }
// #if os(FreeBSD)
// /// The file is a snapshot file. Only modifiable by the super-user.
// ///
// /// The corresponding C constant is `SF_SNAPSHOT`
// @_alwaysEmitIntoClient
// public static var superUserSnapshot: FileFlags { FileFlags(_SF_SNAPSHOT) }
//
// @_alwaysEmitIntoClient
// @available(*, unavailable, renamed: "superUserSnapshot")
// public static var SF_SNAPSHOT: FileFlags { superUserSnapshot }
// #endif
/// The file is a firmlink. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_FIRMLINK`
@_alwaysEmitIntoClient
public static var superUserFirmlink: FileFlags { FileFlags(_SF_FIRMLINK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserFirmlink")
public static var SF_FIRMLINK: FileFlags { superUserFirmlink }
/// The file is a dataless placeholder. The system will attempt to materialize it when accessed according to the dataless file materialization policy of the accessing thread or process. Cannot be modified in user-space.
///
/// The corresponding C constant is `SF_DATALESS`
@_alwaysEmitIntoClient
public static var kernelDataless: FileFlags { FileFlags(_SF_DATALESS) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "kernelDataless")
public static var SF_DATALESS: FileFlags { kernelDataless }
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileFlags
: CustomStringConvertible, CustomDebugStringConvertible
{
/// A textual representation of the file permissions.
@inline(never)
public var description: String {
let descriptions: [(Element, StaticString)] = [
(.noDump, ".noDump"),
(.immutable, ".immutable"),
(.appendOnly, ".appendOnly"),
(.opaque, ".opaque"),
(.compressed, ".compressed"),
(.tracked, ".tracked"),
(.dataVault, ".dataVault"),
(.hidden, ".hidden"),
(.superUserArchived, ".superUserArchived"),
(.superUserImmutable, ".superUserImmutable"),
(.superUserAppend, ".superUserAppend"),
(.superUserRestricted, ".superUserRestricted"),
(.superUserNoUnlink, ".superUserNoUnlink"),
(.superUserFirmlink, ".superUserFirmlink"),
(.kernelDataless, ".kernelDataless"),
]
return _buildDescription(descriptions)
}
/// A textual representation of the file permissions, suitable for debugging.
public var debugDescription: String { self.description }
}
#endif
-47
View File
@@ -1,47 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: should the subtypes of Mode mask their rawValues to only allow their bits to be changed?
/// The superset of access permissions and type for a file.
///
/// The following example creates an instance of the `FileMode` structure
/// from a raw octal literal and reads the file type from it:
///
/// let mode = FileMode(rawValue: 0o140000)
/// mode.type == .socket // true
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileMode: RawRepresentable {
/// The raw C file mode.
@_alwaysEmitIntoClient
public var rawValue: CInterop.Mode
/// Create a strongly-typed file mode from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
/// Subset of mode for accessing and modifying file permissions.
@_alwaysEmitIntoClient
public var permissions: FilePermissions {
get { FilePermissions(rawValue: rawValue & _MODE_PERMISSIONS) }
set { rawValue = (rawValue & ~_MODE_PERMISSIONS) | (newValue.rawValue & _MODE_PERMISSIONS ) }
}
/// Subset of mode for accessing and modifying file type.
@_alwaysEmitIntoClient
public var type: FileType {
get { FileType(rawValue: rawValue & _MODE_TYPE) }
set { rawValue = (rawValue & ~_MODE_TYPE) | (newValue.rawValue & _MODE_TYPE ) }
}
}
#endif
-90
View File
@@ -1,90 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
// FIXME: Document
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileStatus: RawRepresentable {
/// The raw C file status.
@_alwaysEmitIntoClient
public let rawValue: CInterop.Stat
/// Create a strongly-typed file status from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Stat) { self.rawValue = rawValue }
// FIXME: replace with swift type DeviceID that splits out major/minor
/// ID of device containing file.
@_alwaysEmitIntoClient
public var deviceID: CInterop.DeviceID { rawValue.st_dev }
/// Mode of file.
@_alwaysEmitIntoClient
public var mode: FileMode { FileMode(rawValue: rawValue.st_mode) }
/// Number of hard links.
@_alwaysEmitIntoClient
public var hardLinkCount: CInterop.NumberOfLinks { rawValue.st_nlink }
/// File serial number.
@_alwaysEmitIntoClient
public var inodeNumber: CInterop.INodeNumber { rawValue.st_ino }
/// User ID of the file.
@_alwaysEmitIntoClient
public var userID: CInterop.UserID { rawValue.st_uid }
/// Group ID of the file.
@_alwaysEmitIntoClient
public var groupID: CInterop.GroupID { rawValue.st_gid }
/// Device ID.
@_alwaysEmitIntoClient
public var rDeviceID: CInterop.DeviceID { rawValue.st_rdev }
/// Time of last access.
@_alwaysEmitIntoClient
public var accessTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_atimespec) }
/// Time of last data modification.
@_alwaysEmitIntoClient
public var modifyTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_mtimespec) }
/// Time of last status change.
@_alwaysEmitIntoClient
public var statusChangeTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_ctimespec) }
/// Time of file creation.
@_alwaysEmitIntoClient
public var creationTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_birthtimespec) }
/// File size, in bytes.
@_alwaysEmitIntoClient
public var fileSize: CInterop.Offset { rawValue.st_size }
/// Blocks allocated for file.
@_alwaysEmitIntoClient
public var blockCount: CInterop.BlockCount { rawValue.st_blocks }
/// Optimal block size for I/O.
@_alwaysEmitIntoClient
public var blockSize: CInterop.BlockSize { rawValue.st_blksize }
/// User defined flags for file.
@_alwaysEmitIntoClient
public var fileFlags: FileFlags { FileFlags(rawValue: rawValue.st_flags) }
/// File generation number.
@_alwaysEmitIntoClient
public var generationID: CInterop.GenerationID { rawValue.st_gen }
}
#endif
-109
View File
@@ -1,109 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: Document
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileType: RawRepresentable {
/// The raw C file type.
@_alwaysEmitIntoClient
public var rawValue: CInterop.Mode
/// Create a strongly-typed file type from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
/// Named pipe (fifo)
///
/// The corresponding C constant is `S_IFIFO`
@_alwaysEmitIntoClient
public static var fifo: FileType { FileType(_S_IFIFO) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "fifo")
public static var S_IFIFO: FileType { fifo }
/// Character special
///
/// The corresponding C constant is `S_IFCHR`
@_alwaysEmitIntoClient
public static var characterDevice: FileType { FileType(_S_IFCHR) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "characterDevice")
public static var S_IFCHR: FileType { characterDevice }
/// Directory
///
/// The corresponding C constant is `S_IFDIR`
@_alwaysEmitIntoClient
public static var directory: FileType { FileType(_S_IFDIR) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "directory")
public static var S_IFDIR: FileType { directory }
/// Block special
///
/// The corresponding C constant is `S_IFBLK`
@_alwaysEmitIntoClient
public static var blockDevice: FileType { FileType(_S_IFBLK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "blockDevice")
public static var S_IFBLK: FileType { blockDevice }
/// Regular
///
/// The corresponding C constant is `S_IFREG`
@_alwaysEmitIntoClient
public static var regular: FileType { FileType(_S_IFREG) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "regular")
public static var S_IFREG: FileType { regular }
/// Symbolic link
///
/// The corresponding C constant is `S_IFLNK`
@_alwaysEmitIntoClient
public static var symbolicLink: FileType { FileType(_S_IFLNK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "symbolicLink")
public static var S_IFLNK: FileType { symbolicLink }
/// Socket
///
/// The corresponding C constant is `S_IFSOCK`
@_alwaysEmitIntoClient
public static var socket: FileType { FileType(_S_IFSOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "socket")
public static var S_IFSOCK: FileType { socket }
/// Whiteout
///
/// The corresponding C constant is `S_IFWHT`
@_alwaysEmitIntoClient
// FIXME: rename with inclusive language
public static var whiteout: FileType { FileType(_S_IFWHT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "whiteout")
public static var S_IFWHT: FileType { whiteout }
}
#endif
@@ -1,162 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - stat
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
/// Obtain information about the file pointed to by the FileDescriptor.
///
/// - Parameters:
/// - 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: A `FileStatus` for the file pointed to by `self`.
///
/// The corresponding C function is `fstat`.
@_alwaysEmitIntoClient
public func getFileStatus(
retryOnInterrupt: Bool = true
) throws -> FileStatus {
try _getFileStatus(
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _getFileStatus(
retryOnInterrupt: Bool = true
) -> Result<FileStatus, Errno> {
var result = CInterop.Stat()
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fstat(self.rawValue, &result)
}.map { FileStatus(rawValue: result) }
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chmod
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
public func changeFileMode(
to mode: FileMode,
retryOnInterrupt: Bool = true
) throws {
try _changeFileMode(
to: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileMode(
to mode: FileMode,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchmod(self.rawValue, mode.rawValue)
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chown
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
public func changeFileOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
retryOnInterrupt: Bool = true
) throws {
try _changeFileOwner(
to: owner,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchown(self.rawValue, owner.userID, owner.groupID)
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chflags
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
internal func changeFileFlags(
to flags: FileFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileFlags(
to: flags,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileFlags(
to flags: FileFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchflags(self.rawValue, flags.rawValue)
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - utimens
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
public func changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
retryOnInterrupt: Bool = true
) throws {
try _changeFileTimes(
to: times,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
if let times = times {
return withUnsafePointer(to: times) { tuplePtr in
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
timespecPtr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_futimens(self.rawValue, timespecPtr)
}
}
}
} else {
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_futimens(self.rawValue, nil)
}
}
}
}
#endif
@@ -1,24 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - umask
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileMode {
@_alwaysEmitIntoClient
func updateProcessMask() -> Self {
_updateProcessMask()
}
@usableFromInline
func _updateProcessMask() -> Self {
Self(rawValue: system_umask(self.rawValue))
}
}
#endif
@@ -1,544 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - stat
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
/// Obtain information about the file pointed to by the FilePath.
///
/// - Parameters:
/// - followSymlinks: Whether to follow symlinks.
/// The default is `true`.
/// - 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: A `FileStatus` for the file pointed to by `self`.
///
/// Read, write or execute permission of the pointed to file is not required,
/// but all intermediate directories must be searchable.
///
/// The corresponding C functions are `stat` and `lstat`.
@_alwaysEmitIntoClient
public func getFileStatus(
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws -> FileStatus {
try _getFileStatus(
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _getFileStatus(
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<FileStatus, Errno> {
var result = CInterop.Stat()
let fn = followSymlinks ? system_lstat : system_stat
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, &result)
}.map { FileStatus(rawValue: result) }
}
}
/// Obtain information about the file pointed to by the FilePath relative to
/// the provided FileDescriptor.
///
/// - Parameters:
/// - relativeTo: if `self` is relative, treat it as relative to this file descriptor
/// rather than relative to the current working directory.
/// - followSymlinks: Whether to follow symlinks.
/// The default is `true`.
/// - 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: A `FileStatus` for the file pointed to by `self`.
///
/// Read, write or execute permission of the pointed to file is not required,
/// but all intermediate directories must be searchable.
///
/// The corresponding C function is `fstatat`.
@_alwaysEmitIntoClient
public func getFileStatus(
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws -> FileStatus {
try _getFileStatus(
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _getFileStatus(
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<FileStatus, Errno> {
var result = CInterop.Stat()
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fstatat(fd.rawValue, ptr, &result, fcntrl.rawValue)
}.map { FileStatus(rawValue: result) }
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chmod
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func changeFileMode(
to mode: FileMode,
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeFileMode(
to: mode,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileMode(
to mode: FileMode,
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_lchmod : system_chmod
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, mode.rawValue)
}
}
}
// valid flags: AT_SYMLINK_NOFOLLOW | AT_REALDEV | AT_FDONLY
@_alwaysEmitIntoClient
public func changeFileMode(
to mode: FileMode,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileMode(
to: mode,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileMode(
to mode: FileMode,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
self.withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchmodat(fd.rawValue, ptr, mode.rawValue, fcntrl.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chown
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeOwner(
to: owner,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_lchown : system_chown
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, owner.userID, owner.groupID)
}
}
}
@_alwaysEmitIntoClient
public func changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeOwner(
to: owner,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
self.withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchownat(
fd.rawValue, ptr, owner.userID, owner.groupID, fcntrl.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chflags
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func changeFileFlags(
to flags: FileFlags,
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeFileFlags(
to: flags,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileFlags(
to flags: FileFlags,
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_lchflags : system_chflags
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, flags.rawValue)
}
}
}
#if os(FreeBSD)
@_alwaysEmitIntoClient
public func changeFileFlags(
to flags: FileFlags,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileFlags(
to: flags,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileFlags(
to flags: FileFlags,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_chflagsat(fd.rawValue, ptr, flags.rawValue, fcntrl.rawValue)
}
}
}
#endif
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mkfifo
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func makeFIFO(
withMode mode: FileMode,
retryOnInterrupt: Bool = true) throws {
try _makeFIFO(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _makeFIFO(
withMode mode: FileMode,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkfifo(ptr, mode.rawValue)
}
}
}
@available(macOS 13.0, *)
@_alwaysEmitIntoClient
public func makeFIFO(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool = true) throws {
try _makeFIFO(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(macOS 13.0, *)
@usableFromInline
internal func _makeFIFO(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkfifoat(fd.rawValue, ptr, mode.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mknod
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
retryOnInterrupt: Bool = true) throws {
try _makeNode(
withMode: mode,
andDeviceID: deviceID,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mknod(ptr, mode.rawValue, deviceID)
}
}
}
@available(macOS 13.0, *)
@_alwaysEmitIntoClient
public func makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool = true) throws {
try _makeNode(
withMode: mode,
andDeviceID: deviceID,
relativeTo: fd,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(macOS 13.0, *)
@usableFromInline
internal func _makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mknodat(fd.rawValue, ptr, mode.rawValue, deviceID)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mkdir
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func makeDirectory(
withMode mode: FileMode,
retryOnInterrupt: Bool = true) throws {
try _makeDirectory(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _makeDirectory(
withMode mode: FileMode,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkdir(ptr, mode.rawValue)
}
}
}
@available(macOS 13.0, *)
@_alwaysEmitIntoClient
public func makeDirectory(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool = true) throws {
try _makeDirectory(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(macOS 13.0, *)
@usableFromInline
internal func _makeDirectory(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkdirat(fd.rawValue, ptr, mode.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mkdir
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
#if os(FreeBSD)
@_alwaysEmitIntoClient
public func changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeFileTimes(
to: times,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_utimens : system_lutimens
return withPlatformString { ptr in
if let times = times {
return withUnsafePointer(to: times) { tuplePtr in
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
timespecPtr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, timespecPtr)
}
}
}
} else {
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, nil)
}
}
}
}
#endif
@_alwaysEmitIntoClient
public func changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileTimes(
to: times,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
self.withPlatformString { ptr in
if let times = times {
return withUnsafePointer(to: times) { tuplePtr in
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
timespecPtr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_utimensat(fd.rawValue, ptr, timespecPtr, fcntrl.rawValue)
}
}
}
} else {
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_utimensat(fd.rawValue, ptr, nil, fcntrl.rawValue)
}
}
}
}
}
#endif
-52
View File
@@ -1,52 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(Windows)
import CSystem
import ucrt
#endif
extension CInterop {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The C `stat` type.
public typealias Stat = stat
/// The C `mode_t` type.
public typealias Mode = mode_t
/// The C `uid_t` type.
public typealias UserID = uid_t
/// The C `gid_t` type.
public typealias GroupID = gid_t
/// The C `dev_t` type.
public typealias DeviceID = dev_t
/// The C `nlink_t` type.
public typealias NumberOfLinks = nlink_t
/// The C `ino_t` type.
public typealias INodeNumber = ino_t
/// The C `timespec` type.
public typealias TimeSpec = timespec
/// The C `off_t` type.
public typealias Offset = off_t
/// The C `blkcnt_t` type.
public typealias BlockCount = blkcnt_t
/// The C `blksize_t` type.
public typealias BlockSize = blksize_t
/// The C `UInt32` type.
public typealias GenerationID = UInt32
/// The C `UInt32` type.
public typealias FileFlags = UInt32
#endif
#if os(Windows)
public typealias Mode = CInt
#endif
}
-116
View File
@@ -1,116 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
// MARK: - Mode Masks
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// mode_t: type ugs rwx rwx rwx
@_alwaysEmitIntoClient
internal var _MODE_PERMISSIONS: CInterop.Mode { 0b0000_111_111_111_111 }
@_alwaysEmitIntoClient
internal var _MODE_TYPE: CInterop.Mode { 0b1111_000_000_000_000 }
#endif
// MARK: - File Type
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _S_IFIFO: CInterop.Mode { S_IFIFO }
@_alwaysEmitIntoClient
internal var _S_IFCHR: CInterop.Mode { S_IFCHR }
@_alwaysEmitIntoClient
internal var _S_IFDIR: CInterop.Mode { S_IFDIR }
@_alwaysEmitIntoClient
internal var _S_IFBLK: CInterop.Mode { S_IFBLK }
@_alwaysEmitIntoClient
internal var _S_IFREG: CInterop.Mode { S_IFREG }
@_alwaysEmitIntoClient
internal var _S_IFLNK: CInterop.Mode { S_IFLNK }
@_alwaysEmitIntoClient
internal var _S_IFSOCK: CInterop.Mode { S_IFSOCK }
@_alwaysEmitIntoClient
internal var _S_IFWHT: CInterop.Mode { S_IFWHT }
#endif
// MARK: - File Flags
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _UF_NODUMP: CInterop.FileFlags { UInt32(bitPattern: UF_NODUMP) }
@_alwaysEmitIntoClient
internal var _UF_IMMUTABLE: CInterop.FileFlags { UInt32(bitPattern: UF_IMMUTABLE) }
@_alwaysEmitIntoClient
internal var _UF_APPEND: CInterop.FileFlags { UInt32(bitPattern: UF_APPEND) }
@_alwaysEmitIntoClient
internal var _UF_OPAQUE: CInterop.FileFlags { UInt32(bitPattern: UF_OPAQUE) }
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _UF_NOUNLINK: CInterop.FileFlags { UInt32(bitPattern: UF_NOUNLINK) }
#endif
@_alwaysEmitIntoClient
internal var _UF_COMPRESSED: CInterop.FileFlags { UInt32(bitPattern: UF_COMPRESSED) }
@_alwaysEmitIntoClient
internal var _UF_TRACKED: CInterop.FileFlags { UInt32(bitPattern: UF_TRACKED) }
@_alwaysEmitIntoClient
internal var _UF_DATAVAULT: CInterop.FileFlags { UInt32(bitPattern: UF_DATAVAULT) }
@_alwaysEmitIntoClient
internal var _UF_HIDDEN: CInterop.FileFlags { UInt32(bitPattern: UF_HIDDEN) }
@_alwaysEmitIntoClient
internal var _SF_ARCHIVED: CInterop.FileFlags { UInt32(bitPattern: SF_ARCHIVED) }
@_alwaysEmitIntoClient
internal var _SF_IMMUTABLE: CInterop.FileFlags { UInt32(bitPattern: SF_IMMUTABLE) }
@_alwaysEmitIntoClient
internal var _SF_APPEND: CInterop.FileFlags { UInt32(bitPattern: SF_APPEND) }
@_alwaysEmitIntoClient
internal var _SF_RESTRICTED: CInterop.FileFlags { UInt32(bitPattern: SF_RESTRICTED) }
@_alwaysEmitIntoClient
internal var _SF_NOUNLINK: CInterop.FileFlags { UInt32(bitPattern: SF_NOUNLINK) }
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _SF_SNAPSHOT: CInterop.FileFlags { UInt32(bitPattern: SF_SNAPSHOT) }
#endif
@_alwaysEmitIntoClient
internal var _SF_FIRMLINK: CInterop.FileFlags { UInt32(bitPattern: SF_FIRMLINK) }
@_alwaysEmitIntoClient
internal var _SF_DATALESS: CInterop.FileFlags { UInt32(bitPattern: SF_DATALESS) }
#endif
// MARK: - Time Specification
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _UTIME_NOW: Int { Int(UTIME_NOW) }
@_alwaysEmitIntoClient
internal var _UTIME_OMIT: Int { Int(UTIME_OMIT) }
#endif
-296
View File
@@ -1,296 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
internal func system_stat(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ buf: UnsafeMutablePointer<stat>
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, buf) }
#endif
return stat(path, buf)
}
internal func system_lstat(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ buf: UnsafeMutablePointer<stat>
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, buf) }
#endif
return lstat(path, buf)
}
internal func system_fstat(
_ fd: Int32,
_ buf: UnsafeMutablePointer<stat>
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, buf) }
#endif
return fstat(fd, buf)
}
internal func system_fstatat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ buf: UnsafeMutablePointer<stat>,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, buf, flag) }
#endif
return fstatat(fd, path, buf, flag)
}
internal func system_chmod(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return chmod(path, mode)
}
internal func system_lchmod(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return lchmod(path, mode)
}
internal func system_fchmod(
_ fd: Int32,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, mode) }
#endif
return fchmod(fd, mode)
}
internal func system_fchmodat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, mode, flag) }
#endif
return fchmodat(fd, path, mode, flag)
}
internal func system_chown(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, userID, groupID) }
#endif
return chown(path, userID, groupID)
}
internal func system_lchown(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, userID, groupID) }
#endif
return lchown(path, userID, groupID)
}
internal func system_fchown(
_ fd: Int32,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, userID, groupID) }
#endif
return fchown(fd, userID, groupID)
}
internal func system_fchownat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, userID, groupID, flag) }
#endif
return fchownat(fd, path, userID, groupID, flag)
}
internal func system_chflags(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ flag: UInt32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, flag) }
#endif
return chflags(path, flag)
}
internal func system_lchflags(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ flag: UInt32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, flag) }
#endif
return lchflags(path, flag)
}
internal func system_fchflags(
_ fd: Int32,
_ flag: UInt32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, flag) }
#endif
return fchflags(fd, flag)
}
internal func system_umask(
_ cmask: CInterop.Mode
) -> CInterop.Mode {
#if ENABLE_MOCKING
if mockingEnabled { return _mockModeT(cmask) }
#endif
return umask(cmask)
}
internal func system_mkfifo(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return mkfifo(path, mode)
}
@available(macOS 13.0, *)
internal func system_mkfifoat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return mkfifoat(fd, path, mode)
}
internal func system_mknod(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode,
_ deviceID: CInterop.DeviceID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode, deviceID) }
#endif
return mknod(path, mode, deviceID)
}
@available(macOS 13.0, *)
internal func system_mknodat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode,
_ deviceID: CInterop.DeviceID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode, deviceID) }
#endif
return mknodat(fd, path, mode, deviceID)
}
internal func system_mkdir(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return mkdir(path, mode)
}
internal func system_mkdirat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, mode) }
#endif
return mkdirat(fd, path, mode)
}
#if os(FreeBSD)
internal func system_utimens(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ times: UnsafePointer<timespec>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, times) }
#endif
return utimens(path, times)
}
#endif
#if os(FreeBSD)
internal func system_lutimens(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ times: UnsafePointer<timespec>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, times) }
#endif
return lutimens(path, times)
}
#endif
internal func system_utimensat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ times: UnsafePointer<timespec>?,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, times, flag) }
#endif
return utimensat(fd, path, times, flag)
}
internal func system_futimens(
_ fd: Int32,
_ times: UnsafePointer<timespec>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, times) }
#endif
return futimens(fd, times)
}
#endif
-96
View File
@@ -1,96 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// MARK: - stat
// int stat(const char *, struct stat *)
// int lstat(const char *, struct stat *)
// FilePath.getFileStatus(followSymlinks:) throws Errno -> FileStatus
// int fstatat(int, const char *, struct stat *, int)
// FilePath.getFileStatus(relativeTo:controlFlags:) throws Errno -> FileStatus
// int fstat(int, struct stat *)
// FileDescriptor.getFileStatus() throws Errno -> FileStatus
// MARK: - chmod
// int chmod(const char *, mode_t)
// int lchmod(const char *, mode_t)
// FilePath.changeFileMode(to:followSymlinks) throws Errno -> Void
// int fchmodat(int, const char *, mode_t, int)
// FilePath.changeFileMode(to:relativeTo:controlFlags:) throws Errno -> Void
// int fchmod(int, mode_t)
// FileDescriptor.changeFileMode(to:) throws Errno -> Void
// MARK: - chown
// int chown(const char *, uid_t, gid_t)
// int lchown(const char *, uid_t, gid_t)
// FilePath.changeFileOwner(to:followSymlinks:) throws Errno -> Void
// int fchownat(int, const char *, uid_t, gid_t, int)
// FilePath.changeFileOwner(to:relativeTo:controlFlags:) throws Errno -> Void
// int fchown(int, uid_t, gid_t)
// FileDescriptor.changeFileOwner(to:) throws Errno -> Void
// MARK: - chflags
// int chflags(const char *, uint32_t)
// int lchflags(const char *, uint32_t)
// FilePath.changeFileFlags(to:followSymlinks:) throws Errno -> Void
// int chflagsat(int, const char *, uint32_t, int) (FreeBSD)
// FilePath.changeFileFlags(to:relativeTo:controlFlags:) throws Errno -> Void
// int fchflags(int, uint32_t)
// FileDescriptor.changeFileFlags(to:) throws Errno -> Void
// MARK: - umask
// mode_t umask(mode_t)
// FileMode.updateProcessMask() -> FileMode
// MARK: - mkfifo
// int mkfifo(const char *, mode_t)
// FilePath.makeFIFO(withMode:) throws Errno -> Void
// int mkfifoat(int, const char *, mode_t)
// FilePath.makeFIFO(withMode:relativeTo:) throws Errno -> Void
// MARK: - mknod
// int mknod(const char *, mode_t, dev_t)
// FilePath.makeNode(withMode:andDeviceID:) throws Errno -> Void
// int mknodat(int, const char *, mode_t, dev_t)
// FilePath.makeNode(withMode:andDeviceID:relativeTo:) throws Errno -> Void
// MARK: - mkdir
// int mkdir(const char *, mode_t)
// FilePath.makeDirectory(withMode:) throws Errno -> Void
// int mkdirat(int, const char *, mode_t)
// FilePath.makeDirectory(withMode:relativeTo:) throws Errno -> Void
// MARK: - utimens
// int utimens(const char *, const struct timespec[2])
// int lutimens(const char *, const struct timespec[2])
// FilePath.changeFileTimes(to:followSymlinks:) throws Errno -> Void
// int utimensat(int, const char *, const struct timespec[2], int)
// FilePath.changeFileTimes(to:relativeTo:controlFlags:) throws Errno -> Void
// int futimens(int, const struct timespec[2])
// FileDescriptor.changeFileTimes(to:) throws Errno -> Void
+62 -29
View File
@@ -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
}
@@ -95,10 +96,18 @@ extension SystemString {
}
extension SystemString {
fileprivate func _invariantsSatisfied() -> Bool {
guard !nullTerminatedStorage.isEmpty else { return false }
guard nullTerminatedStorage.last! == .null else { return false }
guard nullTerminatedStorage.firstIndex(of: .null) == length else {
return false
}
return true
}
fileprivate func _invariantCheck() {
#if DEBUG
precondition(nullTerminatedStorage.last! == .null)
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
precondition(_invariantsSatisfied())
#endif // DEBUG
}
}
@@ -141,44 +150,67 @@ extension SystemString: RangeReplaceableCollection {
nullTerminatedStorage.reserveCapacity(1 + n)
}
// TODO: Below include null terminator, is this desired?
internal func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
try nullTerminatedStorage.withContiguousStorageIfAvailable(body)
// Do not include the null terminator, it is outside the Collection
try nullTerminatedStorage.withContiguousStorageIfAvailable {
try body(.init(start: $0.baseAddress, count: $0.count-1))
}
}
internal mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
defer { _invariantCheck() }
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
// Do not include the null terminator, it is outside the Collection
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable {
var buffer = UnsafeMutableBufferPointer<SystemChar>(
start: $0.baseAddress, count: $0.count-1
)
return try body(&buffer)
}
}
}
extension SystemString: Hashable, Codable {}
extension SystemString: Hashable, 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 {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.nullTerminatedStorage = try container.decode(
Storage.self, forKey: .nullTerminatedStorage
)
guard _invariantsSatisfied() else {
throw DecodingError.dataCorruptedError(
forKey: .nullTerminatedStorage,
in: container,
debugDescription:
"Encoding does not satisfy the invariants of SystemString"
)
}
}
}
extension SystemString {
// TODO: Below include null terminator, is this desired?
internal func withSystemChars<T>(
internal func withNullTerminatedSystemChars<T>(
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
) rethrows -> T {
try 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))
}
}
}
@@ -194,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>(
@@ -236,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 }
@@ -275,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,
@@ -288,11 +326,6 @@ extension SystemString {
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension SystemChar: Sendable {}
extension SystemString: Sendable {}
#endif
// TODO: SystemString should use a COW-interchangable storage form rather
// than array, so you could "borrow" the storage from a non-bridged String
// or Data or whatever
-140
View File
@@ -1,140 +0,0 @@
/*
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
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// sys/time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// A system provided timer which can be configured to run after an initial
/// delay and subsequent interval.
///
/// The corresponding C type is `int`.
@frozen
public struct IntervalTimer: RawRepresentable {
public typealias RawValue = CInterop.IntervalTimer
/// The raw C ITIMER value.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed interval timer from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension IntervalTimer {
/// A timer which decrements in real time.
///
/// A `SIGALRM` signal is delivered when this timer expires.
///
/// The corresponding C timer is `ITIMER_REAL`.
@_alwaysEmitIntoClient
public static var real: Self { Self(rawValue: _ITIMER_REAL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "real")
public static var ITIMER_REAL: Self { real }
/// A timer which decrements in process virtual time.
///
/// The timer runs only while the process is executing. A `SIGVTALRM` signal
/// is delivered when this timer expires.
///
/// The corresponding C timer is `ITIMER_VIRTUAL`.
@_alwaysEmitIntoClient
public static var virtual: Self { Self(rawValue: _ITIMER_VIRTUAL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "virtual")
public static var ITIMER_VIRTUAL: Self { virtual }
/// A timer which decrements both in process virtual time and when the system
/// is running on behalf of the process.
///
/// This timer is designed to be used by interpreters when statistically
/// profiling the execution of interpreted programs. A `SIGPROF` signal
/// is delivered when this timer expires. Because this signal may interrupt
/// in-progress system calls, programs using this timer must be prepared to
/// restart interrupted system calls.
///
/// The corresponding C timer is `ITIMER_PROF`.
@_alwaysEmitIntoClient
public static var profile: Self { Self(rawValue: _ITIMER_PROF) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "profile")
public static var ITIMER_PROF: Self { profile }
}
extension IntervalTimer {
/// Returns the current value for the timer.
///
/// - Returns: The current value of the timer.
///
/// The corresponding C function is `getitimer`.
@_alwaysEmitIntoClient
public func get() throws -> IntervalTimerValue {
try _get().get()
}
@usableFromInline
internal func _get() -> Result<IntervalTimerValue, Errno> {
var currentValue = itimerval()
return nothingOrErrno(retryOnInterrupt: false) {
system_getitimer(self.rawValue, &currentValue)
}
.map {
IntervalTimerValue(rawValue: currentValue)
}
}
/// Sets a timer to run on specified value.
///
/// If the initial delay is non-zero, it indicates the time to the next timer
/// expiration. If the interval is non-zero, it specifies a value to be used
/// in reloading initial delay when the timer expires.
///
/// Setting the initial delay to `0` disables the timer.
/// Setting the interval to `0` causes a timer to be disabled after its next
/// expiration, assuming initial delay is non-zero.
///
/// - Parameters:
/// - newValue: The new interval to run the timer.
/// - Returns: The previous value of the timer.
///
/// The corresponding C function is `setitimer`.
@_alwaysEmitIntoClient
@discardableResult
public func set(newValue: IntervalTimerValue) throws -> IntervalTimerValue {
try _set(newValue: newValue).get()
}
@usableFromInline
internal func _set(
newValue: IntervalTimerValue
) -> Result<IntervalTimerValue, Errno> {
var newValue = newValue.rawValue
var oldValue = itimerval()
return nothingOrErrno(retryOnInterrupt: false) {
system_setitimer(self.rawValue, &newValue, &oldValue)
}
.map {
IntervalTimerValue(rawValue: oldValue)
}
}
}
#endif
@@ -1,70 +0,0 @@
/*
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
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// sys/time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The value an interval timer is configured to run on.
///
/// The corresponding C type is `itimerval`.
@frozen
public struct IntervalTimerValue: RawRepresentable {
public typealias RawValue = CInterop.IntervalTimerValue
/// The raw C itimerval type.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed internal timer value from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension IntervalTimerValue {
/// The initial delay before running the timer.
///
/// Setting the initial delay to `0` disables the timer.
///
/// The corresponding C property is `it_value`.
@_alwaysEmitIntoClient
public var initialDelay: TimeValue {
get { TimeValue(rawValue: rawValue.it_value) }
set { rawValue.it_value = newValue.rawValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "initialDelay")
public var it_value: TimeValue { initialDelay }
/// The subsequent delay after the initial delay before running the timer.
///
/// Setting the interval to `0` causes a timer to be disabled after its next
/// expiration, assuming initial delay is non-zero.
///
/// The corresponding C property is `it_interval`.
@_alwaysEmitIntoClient
public var interval: TimeValue {
get { TimeValue(rawValue: rawValue.it_interval) }
set { rawValue.it_interval = newValue.rawValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "interval")
public var it_interval: TimeValue { interval }
}
#endif
-31
View File
@@ -1,31 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
extension CInterop {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The C `time_t` type
public typealias Time = time_t
/// The C `suseconds_t` type
public typealias Microseconds = suseconds_t
/// The C `long` type
public typealias Nanoseconds = CLong
/// The C `timeval` type
public typealias TimeValue = timeval
/// The C `timespec` type
public typealias TimeSpecification = timespec
/// The C `itimerval` type
public typealias IntervalTimerValue = itimerval
/// The C type of `ITIMER` values
public typealias IntervalTimer = CInt
#endif
}
-21
View File
@@ -1,21 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _ITIMER_REAL: CInterop.IntervalTimer { ITIMER_REAL }
@_alwaysEmitIntoClient
internal var _ITIMER_VIRTUAL: CInterop.IntervalTimer { ITIMER_VIRTUAL }
@_alwaysEmitIntoClient
internal var _ITIMER_PROF: CInterop.IntervalTimer { ITIMER_PROF }
#endif
-37
View File
@@ -1,37 +0,0 @@
/*
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
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// getitimer
internal func system_getitimer(
_ timer: CInt,
_ currentValue: UnsafeMutablePointer<itimerval>
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(timer, currentValue) }
#endif
return getitimer(timer, currentValue)
}
// setitimer
internal func system_setitimer(
_ timer: CInt,
_ newValue: UnsafePointer<itimerval>,
_ oldValue: UnsafeMutablePointer<itimerval>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(timer, newValue, oldValue) }
#endif
return setitimer(timer, newValue, oldValue)
}
#endif
-164
View File
@@ -1,164 +0,0 @@
/*
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
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Represents an elapsed time since a reference point.
///
/// The corresponding C type is `timeval`.
@frozen
public struct TimeSpecification: RawRepresentable {
public typealias RawValue = CInterop.TimeSpecification
/// The raw C timeval type.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed time value from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension TimeSpecification {
/// The elapsed time in seconds.
///
/// The corresponding C property is `tv_sec`.
@_alwaysEmitIntoClient
public var seconds: CInterop.Time {
get { rawValue.tv_sec }
set { rawValue.tv_sec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "seconds")
public var tv_sec: CInterop.Time { seconds }
/// The remaining elapsed time in nanoseconds.
///
/// This value must always be in the range [0, 999999999].
///
/// The corresponding C property is `tv_nsec`.
@_alwaysEmitIntoClient
public var nanoseconds: CInterop.Nanoseconds {
get { rawValue.tv_nsec }
set { rawValue.tv_nsec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "nanoseconds")
public var tv_nsec: CInterop.Nanoseconds { nanoseconds }
}
extension TimeSpecification {
@_alwaysEmitIntoClient
@inline(__always)
private static let attosecondsPerNanoseconds: Int64 = 1_000_000_000
/// Creates a new value, rounded to the closest possible representation.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init(_ duration: Duration) {
let (seconds, attoseconds) = duration.components
let nanoseconds = attoseconds / Self.attosecondsPerNanoseconds
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_nsec: CInterop.Nanoseconds(nanoseconds))
}
/// Creates a new value, if the given duration can be represented exactly.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init?(exactly duration: Duration) {
let (seconds, attoseconds) = duration.components
guard
let seconds = CInterop.Time(exactly: seconds),
attoseconds.isMultiple(of: Self.attosecondsPerNanoseconds)
else {
return nil
}
let nanoseconds = attoseconds / Self.attosecondsPerNanoseconds
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_nsec: CInterop.Nanoseconds(nanoseconds))
}
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public var duration: Duration {
let seconds = Int64(self.seconds)
let attoseconds = Int64(self.nanoseconds) *
Self.attosecondsPerNanoseconds
return .init(
secondsComponent: seconds,
attosecondsComponent: attoseconds)
}
}
extension TimeSpecification: AdditiveArithmetic {
@_alwaysEmitIntoClient
@inline(__always)
private static let nanosecondsPerSecond: CInterop.Nanoseconds = 1_000_000_000
@_alwaysEmitIntoClient
public static var zero: Self {
Self(rawValue: .init(tv_sec: 0, tv_nsec: 0))
}
@_alwaysEmitIntoClient
public static func + (lhs: Self, rhs: Self) -> Self {
var newValue = TimeSpecification.zero
newValue.seconds = lhs.seconds + rhs.seconds
newValue.nanoseconds = lhs.nanoseconds + rhs.nanoseconds
if (newValue.nanoseconds >= Self.nanosecondsPerSecond) {
newValue.seconds += 1
newValue.nanoseconds -= Self.nanosecondsPerSecond
}
return newValue
}
@_alwaysEmitIntoClient
public static func - (lhs: Self, rhs: Self) -> Self {
var newValue = TimeSpecification.zero
newValue.seconds = lhs.seconds - rhs.seconds;
newValue.nanoseconds = lhs.nanoseconds - rhs.nanoseconds
if (newValue.nanoseconds < 0) {
newValue.seconds -= 1
newValue.nanoseconds += Self.nanosecondsPerSecond
}
return newValue
}
}
extension TimeSpecification: Comparable {
@_alwaysEmitIntoClient
public static func < (lhs: Self, rhs: Self) -> Bool {
guard lhs.seconds == rhs.seconds else {
return lhs.seconds < rhs.seconds
}
return lhs.nanoseconds < rhs.nanoseconds
}
}
extension TimeSpecification: Equatable {
@_alwaysEmitIntoClient
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.seconds == rhs.seconds && lhs.nanoseconds == rhs.nanoseconds
}
}
#endif
-164
View File
@@ -1,164 +0,0 @@
/*
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
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// sys/time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Represents an elapsed time since a reference point.
///
/// The corresponding C type is `timeval`.
@frozen
public struct TimeValue: RawRepresentable {
public typealias RawValue = CInterop.TimeValue
/// The raw C timeval type.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed time value from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension TimeValue {
/// The elapsed time in seconds.
///
/// The corresponding C property is `tv_sec`.
@_alwaysEmitIntoClient
public var seconds: CInterop.Time {
get { rawValue.tv_sec }
set { rawValue.tv_sec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "seconds")
public var tv_sec: CInterop.Time { seconds }
/// The remaining elapsed time in microseconds.
///
/// This value must always be in the range [0, 999999].
///
/// The corresponding C property is `tv_usec`.
@_alwaysEmitIntoClient
public var microseconds: CInterop.Microseconds {
get { rawValue.tv_usec }
set { rawValue.tv_usec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "microseconds")
public var tv_usec: CInterop.Microseconds { microseconds }
}
extension TimeValue {
@_alwaysEmitIntoClient
@inline(__always)
private static let attosecondsPerMicrosecond: Int64 = 1_000_000_000_000
/// Creates a new value, rounded to the closest possible representation.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init(_ duration: Duration) {
let (seconds, attoseconds) = duration.components
let microseconds = attoseconds / Self.attosecondsPerMicrosecond
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_usec: CInterop.Microseconds(microseconds))
}
/// Creates a new value, if the given duration can be represented exactly.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init?(exactly duration: Duration) {
let (seconds, attoseconds) = duration.components
guard
let seconds = CInterop.Time(exactly: seconds),
attoseconds.isMultiple(of: Self.attosecondsPerMicrosecond)
else {
return nil
}
let microseconds = attoseconds / Self.attosecondsPerMicrosecond
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_usec: CInterop.Microseconds(microseconds))
}
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public var duration: Duration {
let seconds = Int64(self.seconds)
let attoseconds = Int64(self.microseconds) *
Self.attosecondsPerMicrosecond
return .init(
secondsComponent: seconds,
attosecondsComponent: attoseconds)
}
}
extension TimeValue: AdditiveArithmetic {
@_alwaysEmitIntoClient
@inline(__always)
private static let microsecondsPerSecond: CInterop.Microseconds = 1_000_000
@_alwaysEmitIntoClient
public static var zero: TimeValue {
Self(rawValue: .init(tv_sec: 0, tv_usec: 0))
}
@_alwaysEmitIntoClient
public static func + (lhs: Self, rhs: Self) -> Self {
var newValue = TimeValue.zero
newValue.seconds = lhs.seconds + rhs.seconds
newValue.microseconds = lhs.microseconds + rhs.microseconds
if (newValue.microseconds >= Self.microsecondsPerSecond) {
newValue.seconds += 1
newValue.microseconds -= Self.microsecondsPerSecond
}
return newValue
}
@_alwaysEmitIntoClient
public static func - (lhs: Self, rhs: Self) -> Self {
var newValue = TimeValue.zero
newValue.seconds = lhs.seconds - rhs.seconds;
newValue.microseconds = lhs.microseconds - rhs.microseconds
if (newValue.microseconds < 0) {
newValue.seconds -= 1
newValue.microseconds += Self.microsecondsPerSecond
}
return newValue
}
}
extension TimeValue: Comparable {
@_alwaysEmitIntoClient
public static func < (lhs: Self, rhs: Self) -> Bool {
guard lhs.seconds == rhs.seconds else {
return lhs.seconds < rhs.seconds
}
return lhs.microseconds < rhs.microseconds
}
}
extension TimeValue: Equatable {
@_alwaysEmitIntoClient
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.seconds == rhs.seconds && lhs.microseconds == rhs.microseconds
}
}
#endif
+4 -4
View File
@@ -8,21 +8,21 @@
*/
// Results in errno if i == -1
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@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: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
private func nothingOrErrno<I: FixedWidthInteger>(
_ i: I
) -> Result<(), Errno> {
valueOrErrno(i).map { _ in () }
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@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
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
internal func nothingOrErrno<I: FixedWidthInteger>(
retryOnInterrupt: Bool, _ f: () -> I
) -> Result<(), Errno> {
+2 -2
View File
@@ -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)
+29
View File
@@ -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)
}
+22
View File
@@ -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)
}
}
}
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more