Compare commits

..
343 Commits
Author SHA1 Message Date
Guillaume Lessard 666fba77fc Merge pull request #319 from kkebo/fix-freebsd-closeOnFork
Fix missing `O_CLOFORK` on older FreeBSD
2026-06-12 09:26:30 -07:00
Kenta Kubo 360e6f70f0 Fix missing O_CLOFORK on older FreeBSD 2026-06-12 22:31:04 +09:00
Guillaume Lessard e402d5fa38 Merge pull request #314 from apple/dev/typecast-1.7.x
System: remove unnecessary type casting
2026-06-11 13:50:16 -07:00
Guillaume Lessard 1bd796b6b9 Merge pull request #312 from glessard/pipe2-windows
Add `pipe(options:)` for Windows
2026-06-11 13:39:28 -07:00
Saleem Abdulrasool 7e888c0cb4 System: remove unnecessary type casting
The compiler now imports these as their canonical type, allowing us to
directly use without the explicit type cast. Due to the floor of Swift
6.3, we must preserve the type cast values. Introduce an overlay to
explicitly cast the values in the older compilers.
2026-06-11 13:37:29 -07:00
Guillaume Lessard d937d15735 Add clarifications to the doc-comments of the new overloads. 2026-06-11 13:22:29 -07:00
Guillaume Lessard e60d362ada fix typo 2026-06-10 10:44:38 -07:00
Guillaume Lessard b7b66845da Update proposal with Windows change 2026-06-10 10:27:45 -07:00
Guillaume Lessard 4fdc665a0f Compile out testAdHocDuplicate2 on Windows 2026-06-09 16:39:56 -07:00
Guillaume Lessard 3e0b318176 Add a test for pipe2 2026-06-09 16:27:18 -07:00
Guillaume Lessard a2bc5f0625 Add tests specific to dup2 and dup3 2026-06-09 16:27:18 -07:00
Guillaume Lessard 2cc89c12b3 Defer pipe buffering decision to the OS on Windows 2026-06-09 16:27:18 -07:00
Guillaume Lessard e59002fa14 Add option-taking pipe() implementation for Windows 2026-06-09 16:27:18 -07:00
Guillaume Lessard ebbbc31709 Merge pull request #310 from apple/release/1.6.0 2026-06-05 17:37:50 -07:00
David Smith 669763cfd5 Merge pull request #309 from apple/david/ioring-crash-fix
Fix a crash when work is interleaved between prepare and submit in IORing
2026-06-04 16:38:10 -07:00
David Smith 6fa5c8a6c1 Explain why this is a class 2026-06-04 16:05:44 -07:00
David Smith 2cae953181 Fix a crash when work is interleaved between prepare and submit in IORing 2026-06-04 16:05:28 -07:00
Guillaume Lessard 03453849a2 Merge pull request #274 from glessard/dup3-pipe2-proposal
Proposal to add wrappers for `dup3` and `pipe2`
2026-06-02 09:26:20 -07:00
Guillaume Lessard 0d7feaa50c Merge pull request #303 from apple/dup3-pipe2
[SYS-0007] Add overloads to cover dup3 and pipe2 POSIX APIs
2026-06-01 16:02:18 -07:00
Jonathan Flat 34f4970c1c Build CSystem as a static library in CMake so shims.c is compiled 2026-05-29 12:48:43 -06:00
Guillaume Lessard 56dad9d66e [ci] update workflows library to latest version 2026-05-26 17:16:41 -07:00
Guillaume Lessard 929b835515 Merge pull request #304 from apple/dev/github-actions-refresh
[ci] update workflows library to a recent version
2026-05-26 17:10:03 -07:00
Guillaume Lessard 26f8c4f195 [ci] update workflows library to latest version 2026-05-26 16:53:38 -07:00
Guillaume Lessard de8779fb3d Update copyright headers 2026-05-26 16:21:28 -07:00
Guillaume Lessard 491b97c7c0 Complete implementation of SYS-0007 2026-05-20 10:01:11 -07:00
Guillaume Lessard 814d09c7ea Improve doc-comments 2026-05-20 09:58:46 -07:00
Guillaume Lessard 61280ab365 Fix declaration inconsistencies 2026-05-20 09:58:46 -07:00
Guillaume Lessard cc4afd1a71 Fix types of new static members of option sets 2026-05-20 09:58:46 -07:00
Jake Petroules 348b497836 Add overloads to cover dup3 and pipe2 POSIX APIs
This follows the existing pattern of wrapping dup/dup2 and pipe with FileDescriptor.duplicate and FileDescriptor.pipe, with additional overloads for passing the O_CLOEXEC and similar flags.
2026-05-20 09:58:46 -07:00
Guillaume Lessard 0323dff7db Rephrase using active voice 2026-05-19 18:40:04 -07:00
Guillaume Lessard 4d2c21f6b3 fix a few more inconsistencies 2026-05-19 18:39:02 -07:00
Guillaume Lessard 45e26e7cc1 Merge pull request #278 from glessard/dev/require-swift-6.1
Require Swift 6.1 for the upcoming 1.7.0 tag
2026-03-23 13:41:34 -07:00
Guillaume Lessard 9554473133 Merge pull request #301 from glessard/dev/typo-fix
Fix typo: remove extra space after comma
2026-03-10 15:40:02 -07:00
Guillaume Lessard c0fa05b225 fix typo in Stat proposal
Cherry-picked from commit 9ddcf9a051
Co-authored-by: Layla <0x04cb@gmail.com>
2026-03-03 10:54:26 -08:00
Jonathan Flat 51d396093d [Implementation] Back-deploy CInterop.stat for Migration Compatibility (#299) 2026-03-02 18:17:36 -07:00
Jonathan Flat 6d25d11066 [Proposal] Back-deploy CInterop.stat for Migration Compatibility (#298)
* [Proposal] Back-deploy CInterop.stat for Migration Compatibility

* Update implementation and pitch links

* v2/3: Clarify that CInterop.stat(_:_:) is a new function and why this proposal should not set a precedence for future System APIs

* Rename to SYS-0008
2026-03-02 18:15:49 -07:00
Guillaume Lessard cb63c9a073 Merge pull request #297 from finagolfin/droid
[CI] Use latest workflows tag and properly enable Android with emulator testing
2026-02-20 14:13:45 -08:00
Finagolfin 4471eaa313 [CI] Remove Android SDK exclusions that didn't work, and enable new emulator testing 2026-02-18 03:54:21 +05:30
Finagolfin f86edc7020 [CI] Use latest tag of official workflows, now that they've settled 2026-02-18 03:52:52 +05:30
Guillaume Lessard 71db29e931 Merge pull request #293 from kkebo/fix-freebsd
Fix FreeBSD build
2026-02-06 15:04:21 -08:00
Kenta Kubo 043bda4234 Remove unclear helper function 2026-02-04 02:18:24 +09:00
Kenta Kubo 4278ed8d97 Unify assertions of sizeAllocated on all POSIX platforms 2026-02-04 01:55:12 +09:00
Kenta Kubo cf6956a19a Reduce the use of compile-time branching 2026-01-28 21:33:06 +09:00
Kenta Kubo 91bd99f29a Fix Darwin tests 2026-01-28 21:24:57 +09:00
Kenta Kubo 7c0af0ded6 Fix FreeBSD build 2026-01-28 00:02:14 +09:00
Guillaume Lessard 7e474cb4bd Merge pull request #289 from glessard/issue288-resilient-machport
MachPort inlinability fixes
2026-01-21 12:39:55 -08:00
Guillaume Lessard b0e5ec8932 MachPort inlinability fixes
When compiled with library resilience, `consuming` functions which `discard self` cannot also be `@inlinable`.
2026-01-21 09:10:29 -08:00
Guillaume Lessard 538ae25062 Merge pull request #287 from apple/dev/merge-back-1.6.x
Merge back changes from the 1.6.x branch
2026-01-14 08:44:19 -08:00
Guillaume Lessard fb3c3abebf Merge branch 'release/1.6.0' 2026-01-13 19:20:33 -08:00
Guillaume Lessard f6b96c3ba7 Merge pull request #279 from mairinkdev/main
Fix silent buffer size truncation in Windows pread/pwrite
2026-01-13 14:35:02 -08:00
Guillaume Lessard 7c6ad0fc39 Merge pull request #286 from apple/dev/fix-pread-truncation-windows-1.6.0
[Windows] fix pread/pwrite truncation
2026-01-13 13:53:28 -08:00
lee 13851a3421 Fix silent buffer size truncation in Windows pread/pwrite 2026-01-13 13:37:44 -08:00
Guillaume Lessard 8f8d80a4fe Merge pull request #285 from glessard/fix-HRESULT_FACILITY-1.6.0
[Windows] Fix HRESULT_FACILITY
2026-01-13 13:33:25 -08:00
Guillaume Lessard 608a75b962 Merge pull request #284 from glessard/workflow-edits-1.6.0-again
[ci] re-allow 5.9 and 5.10 for 1.6.x
2026-01-13 12:49:27 -08:00
AZero13 0dbbab4aa1 Fix HRESULT_FACILITY
HRESULT_FACILITY is >> 16 & 0x1fff, not <<
2026-01-13 12:41:47 -08:00
Guillaume Lessard 2eb655e0b7 [ci] re-allow 5.9 and 5.10
- they were excluded in error.
2026-01-13 12:38:57 -08:00
Guillaume Lessard 53afbde6ab Merge pull request #275 from AZero13/patch-1 2026-01-13 12:07:29 -08:00
Guillaume Lessard 07a3f090d7 Merge pull request #280 from glessard/workflow-edits-1.6.0
[ci] adjust the pull-request action
2026-01-08 17:06:26 -08:00
Guillaume Lessard dda2b535b7 [ci] adjust the pull-request action 2026-01-08 16:46:01 -08:00
AZero13 0ed3416369 Merge branch 'main' into patch-1 2026-01-08 14:10:19 -05:00
lee 766415499c Fix silent buffer size truncation in Windows pread/pwrite 2026-01-07 11:37:16 -03:00
Guillaume Lessard 097805e869 require Swift 6.1
- and exclude 6.0 toolchains from executing in CI
2026-01-06 17:10:56 -08:00
Guillaume Lessard e65f5a6cad dup3 wrapper proposal
Improve a sentence.
2026-01-06 17:08:56 -08: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
AZero13 0dcedcb7bb Fix HRESULT_FACILITY
HRESULT_FACILITY is >> 16 & 0x1fff, not <<
2025-12-28 14:33:38 -05: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 7a18b4bf34 Merge pull request #193 from glbrntt/mac-catalyst
Add support for macCatalyst
2024-10-16 13:57:03 -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
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
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 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
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
Karoy Lorentey aac7f54e89 Merge pull request #174 from lorentey/codeowners
Add CODEOWNERS
2024-05-10 17:17:48 -07:00
Karoy Lorentey a6fd8ba9ba Add CODEOWNERS 2024-05-10 17:06:59 -07:00
Mishal Shah 3433699e6e [CI] Remove support for Swift 5.7 2024-05-10 16:32:21 -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
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 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
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 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
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
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
77 changed files with 7318 additions and 466 deletions

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
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@0.0.10
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"},
{"swift_version": "6.0"},
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_macos_checks: true
macos_exclude_xcode_versions: '[]'
enable_windows_checks: true
windows_exclude_swift_versions: |
[
{"swift_version": "5.9"},
{"swift_version": "5.10"},
{"swift_version": "6.0"},
]
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
enable_android_sdk_checks: true
build-abi-stable:
name: Build ABI Stable
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
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@0.0.10
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
+2 -1
View File
@@ -2,7 +2,8 @@
/.swiftpm
/.build
/Packages
swift-system.xcodeproj
/*.xcodeproj
xcuserdata/
.*.sw?
/.swiftpm
.docc-build
+1 -1
View File
@@ -1,5 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.10-jammy"
repo = "swift-system"
branch = "release/1.4.0"
branch = "main"
}
+1 -1
View File
@@ -1,5 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.9-jammy"
repo = "swift-system"
branch = "release/1.4.0"
branch = "main"
}
+1 -1
View File
@@ -1,5 +1,5 @@
macOSSwiftPackageJob {
swift_version = "6.0"
repo = "swift-system"
branch = "release/1.4.0"
branch = "main"
}
+1 -1
View File
@@ -1,5 +1,5 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-6.0-jammy"
repo = "swift-system"
branch = "release/1.4.0"
branch = "main"
}
+1 -1
View File
@@ -1,5 +1,5 @@
macOSSwiftPackageJob {
swift_version = "main"
repo = "swift-system"
branch = "release/1.4.0"
branch = "main"
}
+1 -1
View File
@@ -1,5 +1,5 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-jammy"
repo = "swift-system"
branch = "release/1.4.0"
branch = "main"
}
+1 -1
View File
@@ -1,7 +1,7 @@
WindowsSwiftPackageWithDockerImageJob {
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
repo = "swift-system"
branch = "release/1.4.0"
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)
+101 -6
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.9
// swift-tools-version:6.1
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
@@ -12,20 +12,112 @@
import PackageDescription
let cSettings: [CSetting] = [
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])),
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 swiftSettings: [SwiftSetting] = [
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",
platforms: platforms,
products: [
.library(name: "SystemPackage", targets: ["SystemPackage"]),
],
@@ -40,12 +132,15 @@ let package = Package(
name: "SystemPackage",
dependencies: ["CSystem"],
path: "Sources/System",
exclude: ["CMakeLists.txt"],
exclude: filesToExclude,
cSettings: cSettings,
swiftSettings: swiftSettings),
.testTarget(
name: "SystemTests",
dependencies: ["SystemPackage"],
exclude: testsToExclude,
cSettings: cSettings,
swiftSettings: swiftSettings),
])
],
swiftLanguageModes: [.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 |
+182
View File
@@ -0,0 +1,182 @@
# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor`
* Proposal: SYS-0007
- Author(s): Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
* Other Reviews: [Swift Forums Pitch](https://forums.swift.org/t/82486)
##### Revision history
* **v1** Initial version
- **v2** Add Windows version of `pipe(options:)`
## Introduction
Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively.
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD and Android.
## Motivation
It is considered best practice to set the `O_CLOEXEC` (close-on-exec) bit on newly created file descriptors to prevent them from being inherited by subprocesses.
Some POSIX functions such as `open` provide a "flags" parameter allowing this the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`.
POSIX 2024 corrects this deficiency for `dup2` and `pipe` by introducing `dup3` and `pipe2` variants that allow the close-on-exec bit to be set atomically.
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defence in depth with respect to opened file descriptors.
## Proposed solution
This proposal adds new overloads to `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` that will wrap the functionality of the `dup3` and `pipe2` functions.
## Example usage
```swift
import System
let fd0 = try FileDescriptor.open("/tmp/test.txt", .readOnly)
let fd1 = FileDescriptor(rawValue: 731)
let fd2 = fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec])
```
## Detailed design
`FileDescriptor` will add the following overloads and types:
```swift
struct FileDescriptor {
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
///
/// - Parameters:
/// - options: The behavior for creating the pipe.
///
/// - Returns: The pair of file descriptors.
///
/// The corresponding C function is `pipe2`.
public static func pipe(
options: PipeOptions
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor)
/// Duplicate this file descriptor and return the newly created copy.
///
/// - Parameters:
/// - target: The desired target file descriptor.
/// - options: The behavior for creating the target file descriptor.
/// - retryOnInterrupt: Whether to retry the operation
/// if it throws ``Errno/interrupted``. The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The new file descriptor.
///
/// If the `target` descriptor is already in use, then it is first
/// deallocated as if a close(2) call had been done first.
///
/// File descriptors are merely references to some underlying system resource.
/// The system does not distinguish between the original and the new file
/// descriptor in any way. For example, read, write and seek operations on
/// one of them also affect the logical file position in the other, and
/// append mode, non-blocking I/O and asynchronous I/O options are shared
/// between the references. If a separate pointer into the file is desired,
/// a different object reference to the file must be obtained by issuing an
/// additional call to `open`.
///
/// However, each file descriptor maintains its own close-on-exec and
/// close-on-fork flags.
///
/// The corresponding C function is `dup3`.
@discardableResult
public func duplicate(
as target: FileDescriptor,
options: DuplicateOptions,
retryOnInterrupt: Bool = true
) throws(Errno) -> FileDescriptor
/// Options that specify behavior for a newly-created pipe.
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
public init(rawValue: CInt)
/// Indicates that all subsequent input and output operations
/// on the pipe's file descriptors will be nonblocking.
///
/// The corresponding C constant is `O_NONBLOCK`.
public static var nonBlocking: PipeOptions
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `exec(2)`
/// family of functions. If you specify this option, the system closes the
/// file descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
public static var closeOnExec: PipeOptions
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `fork(2)`
/// function. If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
public static var closeOnFork: PipeOptions
}
/// Options that specify behavior for a duplicated file descriptor.
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
public init(rawValue: CInt)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `exec(2)`
/// family of functions. If you specify this option, the system closes the
/// file descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
public static var closeOnExec: DuplicateOptions
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `fork(2)`
/// function. If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
public static var closeOnFork: DuplicateOptions
}
}
```
These API additions are unavailable on Darwin, as the underlying `dup3` and `pipe2` APIs do not exist.
`pipe(options:)` is added for Windows with the option `.closeOnExec`, but `duplicate(as:options:)` is not added because the underlying API does not match `dup3`.
`closeOnFork` is unavailable on Linux and Android, as the underlying `O_CLOFORK` constant does not exist.
## Impact on existing code
This change will have no impact on existing code, as it is purely additive.
## Alternatives considered
None. The underlying POSIX API are additions that help C developers follow best practices, and these overloads provide the same value to Swift developers.
+262
View File
@@ -0,0 +1,262 @@
# Back-Deploy CInterop.stat for Migration Compatibility
* Proposal: SYS-0008
* Author: [Jonathan Flat](https://github.com/jrflat)
* Status: **Awaiting review**
* Implementation: [apple/swift-system#299](https://github.com/apple/swift-system/pull/299)
* Review: ([pitch](https://forums.swift.org/t/pitch-back-deploy-system-cinterop-stat-for-migration-compatibility/84930))
#### Revision history
* **v1** Initial version
* **v2** Clarify that `CInterop.stat(_:_:)` is a new function
* **v3** Explain why this proposal should not set a precedence for future System APIs
## Introduction
This proposal introduces `CInterop.stat(_:_:)` and back-deploys the `CInterop.Stat` typealias from System to make them available on older OS versions, enabling a migration path for clients who may encounter naming conflicts with `FilePath.stat()` or `FileDescriptor.stat()` when System's new `Stat` API ships.
## Motivation
The introduction of `FilePath.stat()` and `FileDescriptor.stat()` in [SYS-0006](0006-system-stat.md) creates a potential source compatibility issue for a small number of clients. While we estimate this affects an exceedingly rare set of developers (1 case found in public GitHub repositories), we want to provide a clear migration path.
### Compatibility scenario
Some clients may have extended `FilePath` or `FileDescriptor` with custom functions that use `Darwin.stat()` and `Darwin.stat(_:_:)` **without** the `Darwin.` (or other libc) module qualification inside the function body:
```swift
extension FilePath {
func isRegularFile() -> Bool {
var s = stat() // Calls Darwin.stat(_:_:) - unqualified!
guard stat(self.string, &s) == 0 else { // Calls Darwin.stat(_:_:) - unqualified!
return false
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
When the new `FilePath.stat()` API from SYS-0006 ships, these unqualified calls to `stat()` and `stat(_:_:)` will refer to the new instance method, causing build errors:
```
error: Call can throw, but it is not marked with 'try' and the error is not handled
error: Use of 'stat' refers to instance method rather than global function 'stat' in module 'Darwin'
```
### Why not just use `Darwin.stat`?
Clients could resolve the ambiguity by qualifying their calls with `Darwin.`, `Glibc.`, etc. However, this approach has several limitations:
1. **Cross-platform code**: Clients writing code for multiple platforms would need platform-specific `#if` blocks with code for each platform's libc module.
2. **Awkward syntax**: Due to the overload between the `stat` type and `stat(_:_:)` function, clients must use the verbose `Darwin.stat(_:_:)(path, &s)` syntax to call the function, which is unintuitive.
3. **Older deployment targets**: Clients supporting older deployment targets can't use the new `System.Stat` API on older OS versions but still need to avoid build breakage when compiled with an SDK that includes the new `FilePath.stat()`
By back-deploying `CInterop.stat(_:_:)` to `System 0.0.2 (macOS 12.0, iOS 15.0)`, we provide a cross-platform, ergonomic solution: clients can replace `stat(_:_:)` with `CInterop.stat(_:_:)` for older deployment targets, and use the new `Stat` API moving forward.
## Proposed solution
Back-deploy `CInterop.Stat` and `CInterop.stat(_:_:)` to `@available(System 0.0.2, *)`, making them available on `macOS 12.0, iOS 15.0` and aligned. Note that `System 0.0.2` already maps to earliest source availability when System is used as a package, so the back-deployment is only relevant for System as an OS framework.
### API Overview
```swift
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
public typealias Stat = stat
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32
}
#endif
```
The implementation uses `@_alwaysEmitIntoClient` to make the function available on older OS versions by embedding the implementation in client code. This makes sense for a widely-available and standardized C function like `stat()`.
### Migration guidance
If you have `FilePath` or `FileDescriptor` extensions that use unqualified `stat()` calls and need to support older deployment targets, migrate to `CInterop.Stat` (type) and `CInterop.stat(_:_:)` (function):
#### Before:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
var s = stat()
guard stat(self.string, &s) == 0 else {
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
#### After:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
var s = CInterop.Stat() // stat() --> CInterop.Stat()
guard CInterop.stat(self.string, &s) == 0 else { // stat(_:_:) --> CInterop.stat(_:_:)
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
#### Migrate to the new `Stat` API:
Migrate to the more ergonomic interface on newer OS versions using `if #available`:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
if #available(macOS X, iOS Y, *) {
return try stat().type == .regular // Calls FilePath.stat()
}
var s = CInterop.Stat()
guard CInterop.stat(self.string, &s) == 0 else {
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
Alternatively, you may use just the new API if your deployment target supports it.
#### Who should use `CInterop.stat(_:_:)`?
This scenario is rare and only occurs when a project meets **all** of the following conditions:
1. Has a custom extension on `FilePath` or `FileDescriptor`, that
2. Uses **unqualified** `stat()` or `stat(_:_:)` calls inside that method, and
3. Needs to support deployment targets older than the new `Stat` API availability
If your code uses qualified calls, e.g. `Darwin.stat()`, or uses a wrapper around `stat()` already, it is **not** affected by this issue and no migration is needed.
## Detailed design
### CInterop extension
```swift
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
/// The C `stat` struct.
public typealias Stat = stat
/// Calls the C `stat()` function.
///
/// This is a direct wrapper around the C `stat()` system call.
/// For a more ergonomic Swift API, use `Stat` instead.
///
/// - Warning: This API is primarily intended for migration purposes when
/// supporting older deployment targets. If your deployment target supports
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
/// type-safe, ergonomic access to file metadata in Swift.
///
/// - Parameters:
/// - path: A null-terminated C string representing the file path.
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
system_stat(path, &s)
}
}
#endif
```
### Internal wrapper
The `system_stat` wrapper is also marked `@_alwaysEmitIntoClient` so it can be inlined. `system_stat` calls the global `stat` function for the current platform.
```swift
#if !os(Windows)
@_alwaysEmitIntoClient
internal func system_stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
stat(path, &s)
}
#endif
```
## Source compatibility
This proposal is additive and source-compatible.
## ABI compatibility
This proposal is ABI-compatible. The use of `@_alwaysEmitIntoClient` ensures that the implementation is embedded in client code.
## Implications on adoption
Clients can adopt `CInterop.Stat` and `CInterop.stat(_:_:)` to support older deployment targets when building with the new SDK.
## Future directions
Once clients can raise their deployment targets to support the new `Stat` API introduced in SYS-0006, they should migrate to it, which provides:
- Type-safe, ergonomic Swift interfaces
- Strongly-typed wrappers (`FileType`, `FileMode`, `FilePermissions`, etc.)
- Proper error handling with typed throws
## Why this should not set a precedent for CInterop functions
We should not expose `CInterop` functions for most, if not all, other methods that shadow a global function. `stat` is a special case for a few reasons:
- Many other syscalls gain a more Swift-y API name, e.g. `dup/dup2` → `duplicate(as:)`, `ftruncate` → `resize(to:)`, `umask` → `FilePermissions.creationMask` if that becomes API, etc. Those renames mean user extensions are unlikely to collide with future System API. `stat` is one of the few syscalls whose C name is already clear and idiomatic enough to use directly as the Swift API name.
- Many syscalls that do keep their C name (e.g. `open`, `close`, `read`, `write`) have been in System since the beginning, so there was never a window where someone would have needed to create their own extension for that functionality.
- `stat` is both widely used and was missing from System for some time, which creates a better chance for migration friction.
- Other syscalls that could be added to System naturally disambiguate through parameter labels. Names like `rename`, `link`, and `unlink` would require non-optional arguments (e.g. `rename(to:)`, `link(to:)`), so their Swift signatures wouldn't collide with the bare C functions. `stat` is unusual in that it works as a zero-argument call on `FilePath`/`FileDescriptor` and has the same shape as the global C `stat()` struct initializer.
## Alternatives considered
### Do nothing
We could choose not to provide a migration path and let affected clients handle the ambiguity by:
1. Qualifying their calls with platform-specific modules (e.g. `Darwin.stat`)
2. Wrapping `stat()` in another function
3. Raising their deployment target to use the new `Stat` API
However, this creates an unnecessary burden for the (admittedly rare) affected clients, especially those who need to maintain backward compatibility with older OS versions.
### Use a different name for `FilePath.stat()`
We could use a different name such as `FilePath.statInfo()`, `FilePath.status()`, `FilePath.Stat()`, or `FilePath.fileInfo()`. However, considering the rarity of the issue, changing to a less concise, discoverable, and expressive function name is not preferrable when we can offer a migration solution.
### Create `stat()` overloads directly on `FilePath`
We could create `stat()` extensions on `FilePath` within System that guide a developer to use the new instance method via `try stat()`, e.g:
```swift
extension FilePath {
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
public func stat() -> CInterop.Stat {
CInterop.Stat()
}
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
public func stat(
_ path: UnsafePointer<CChar>,
_ s: inout CInterop.Stat
) -> Int32 {
system_stat(path, &s)
}
}
```
This is beneficial because it prevents any SDK breakage with only a System change. However, this is not a great long-term solution to have as public API because:
- It makes choosing the right `stat()` more confusing with 5 total overloads.
- It hurts discoverability for the new `Stat` API.
### Expose the internal `system_stat` wrapper directly
This would achieve the same effect as exposing `CInterop.stat(_:_:)`, but goes against the API naming/organization patterns in System. `CInterop` seems like a clear place for the direct C `stat` wrapper to belong.
### Back-deploy the full `Stat` API
Unlike functions and typealiases, types such as `Stat`, `FileType`, `FileMode`, etc. would require significant coordination and effort to back-deploy, making this alternative less desirable, especially considering it's not required to address the issue.
+9 -7
View File
@@ -24,7 +24,7 @@ try fd.closeAfter {
}
```
[API documentation](https://swiftpackageindex.com/apple/swift-system/main/documentation/SystemPackage)
[API documentation](https://swiftpackageindex.com/apple/swift-system/documentation/SystemPackage)
## Adding `SystemPackage` as a Dependency
@@ -32,7 +32,7 @@ To use the `SystemPackage` library in a SwiftPM project,
add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
```
Finally, include `"SystemPackage"` as a dependency for your executable target:
@@ -41,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
let package = Package(
// name, platforms, products, etc.
dependencies: [
.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
// other dependencies
],
targets: [
@@ -87,7 +87,7 @@ The following table maps existing package releases to their minimum required Swi
| Package version | Swift version | Xcode release |
| ----------------------- | --------------- | ------------- |
| swift-system 1.3.x | >= Swift 5.8 | >= Xcode 14.3 |
| swift-system 1.4.x | >= Swift 5.9 | >= Xcode 15.0 |
| 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.
@@ -105,11 +105,13 @@ Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
We maintain separate branches for each active minor version of the package:
| Package version | Branch |
| Package version | Branch |
| ----------------------- | ----------- |
| swift-system 1.3.x | release/1.3 |
| swift-system 1.4.x (unreleased) | release/1.4 |
| swift-system 1.5.x (unreleased) | main |
| 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:
+7 -5
View File
@@ -1,20 +1,22 @@
#[[
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
add_library(CSystem INTERFACE)
target_include_directories(CSystem INTERFACE
include)
add_library(CSystem STATIC shims.c)
target_include_directories(CSystem PUBLIC
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
$<INSTALL_INTERFACE:include/CSystem>)
install(FILES
include/CSystemLinux.h
include/CSystemShared.h
include/CSystemWindows.h
include/CSystemFreeBSD.h
include/module.modulemap
DESTINATION include/CSystem)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
+21
View File
@@ -0,0 +1,21 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if defined(__FreeBSD__)
#include <fcntl.h>
#ifdef O_CLOFORK
#define FREEBSD_O_CLOFORK O_CLOFORK
#else
#define FREEBSD_O_CLOFORK 0
#endif
#endif
+1
View File
@@ -21,5 +21,6 @@
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include "io_uring.h"
#endif
+14
View File
@@ -0,0 +1,14 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if !defined(_WIN32)
extern int csystem_posix_pipe2(int fildes[2], int flag);
#endif
extern int csystem_posix_dup3(int fildes, int fildes2, int flag);
+36 -1
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2024 Apple Inc. and the Swift System project authors
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
@@ -11,8 +11,10 @@
#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.
@@ -28,4 +30,37 @@ 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
+2
View File
@@ -1,6 +1,8 @@
module CSystem {
header "CSystemShared.h"
header "CSystemLinux.h"
header "CSystemWASI.h"
header "CSystemWindows.h"
header "CSystemFreeBSD.h"
export *
}
+39 -3
View File
@@ -1,18 +1,54 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if defined(__FreeBSD__) || defined(__OpenBSD__)
#define __BSD_VISIBLE
#include <unistd.h>
#endif
#if defined(__FreeBSD__)
#include <CSystemFreeBSD.h>
#endif
#ifdef __linux__
#define _GNU_SOURCE
#include <CSystemLinux.h>
#endif
#if defined(_WIN32)
#include <CSystemWindows.h>
#endif
#include <errno.h>
#if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__)
#define HAVE_PIPE2_DUP3
#endif
// Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h
#if !defined(_WIN32)
extern int csystem_posix_pipe2(int fildes[2], int flag) {
#ifdef HAVE_PIPE2_DUP3
return pipe2(fildes, flag);
#else
errno = ENOSYS;
return -1;
#endif
}
#endif // !defined(_WIN32)
extern int csystem_posix_dup3(int fildes, int fildes2, int flag) {
#ifdef HAVE_PIPE2_DUP3
return dup3(fildes, fildes2, flag);
#else
errno = ENOSYS;
return -1;
#endif
}
+48 -14
View File
@@ -10,7 +10,7 @@
/// An error number used by system calls to communicate what kind of error
/// occurred.
@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 Errno: RawRepresentable, Error, Hashable, Codable {
/// The raw C error number.
@_alwaysEmitIntoClient
@@ -160,7 +160,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
/// No child processes.
///
/// A `wait(2)` or `waitpid(2)` function was executed
/// by a process that dosn't have any existing child processes
/// by a process that doesn't have any existing child processes
/// or whose child processes are all already being waited for.
///
/// The corresponding C error is `ECHILD`.
@@ -961,7 +961,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
/// Stale NFS file handle.
///
/// You attempted access an open file on an NFS filesystem,
/// You attempted access an open file on an NFS file system,
/// which is now unavailable as referenced by the given file descriptor.
/// This may indicate that the file was deleted on the NFS server
/// or that some other catastrophic event occurred.
@@ -1067,7 +1067,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var ENOSYS: Errno { noFunction }
// BSD
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Inappropriate file type or format.
///
/// The file was the wrong type for the operation,
@@ -1082,7 +1082,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var EFTYPE: Errno { badFileTypeOrFormat }
#endif
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Authentication error.
///
/// The authentication ticket used to mount an NFS file system was invalid.
@@ -1253,7 +1253,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@available(*, unavailable, renamed: "illegalByteSequence")
public static var EILSEQ: Errno { illegalByteSequence }
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Attribute not found.
///
/// The specified extended attribute doesn't exist.
@@ -1294,7 +1294,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@available(*, unavailable, renamed: "multiHop")
public static var EMULTIHOP: Errno { multiHop }
#if !os(WASI)
#if !os(WASI) && !os(FreeBSD)
/// No message available.
///
/// No message was available to be received by the requested operation.
@@ -1320,7 +1320,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@available(*, unavailable, renamed: "noLink")
public static var ENOLINK: Errno { noLink }
#if !os(WASI)
#if !os(WASI) && !os(FreeBSD)
/// Reserved.
///
/// This error is reserved for future use.
@@ -1361,7 +1361,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@available(*, unavailable, renamed: "protocolError")
public static var EPROTO: Errno { protocolError }
#if !os(OpenBSD) && !os(WASI)
#if !os(OpenBSD) && !os(WASI) && !os(FreeBSD)
/// Reserved.
///
/// This error is reserved for future use.
@@ -1391,7 +1391,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
}
// Constants defined in header but not man page
@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 Errno {
/// Operation would block.
///
@@ -1459,6 +1459,38 @@ extension Errno {
public static var EOWNERDEAD: Errno { previousOwnerDied }
#endif
#if os(FreeBSD)
/// Capabilities insufficient.
///
/// The corresponding C error is `ENOTCAPABLE`.
@_alwaysEmitIntoClient
public static var notCapable: Errno { .init(rawValue: _ENOTCAPABLE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "notCapable")
public static var ENOTCAPABLE: Errno { notCapable }
/// Not permitted in capability mode.
///
/// The corresponding C error is `ECAPMODE`.
@_alwaysEmitIntoClient
public static var capabilityMode: Errno { .init(rawValue: _ECAPMODE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "capabilityMode")
public static var ECAPMODE: Errno { capabilityMode }
/// Integrity check failed.
///
/// The corresponding C error is `EINTEGRITY`.
@_alwaysEmitIntoClient
public static var integrityCheckFailed: Errno { .init(rawValue: _EINTEGRITY) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "integrityCheckFailed")
public static var EINTEGRITY: Errno { integrityCheckFailed }
#endif
#if SYSTEM_PACKAGE_DARWIN
/// Interface output queue is full.
///
@@ -1469,7 +1501,9 @@ extension Errno {
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "outputQueueFull")
public static var EQFULL: Errno { outputQueueFull }
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// The largest valid error.
///
/// This value is the largest valid value
@@ -1486,7 +1520,7 @@ extension Errno {
#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 Errno {
// TODO: We want to provide safe access to `errno`, but we need a
// release-barrier to do so.
@@ -1501,14 +1535,14 @@ extension Errno {
}
// Use "hidden" entry points for `NSError` bridging
@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 Errno {
public var _code: Int { Int(rawValue) }
public var _domain: String { "NSPOSIXErrorDomain" }
}
@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 Errno: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the most recent error
/// returned by a system call.
@@ -1528,7 +1562,7 @@ extension Errno: CustomStringConvertible, CustomDebugStringConvertible {
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 Errno {
@_alwaysEmitIntoClient
public static func ~=(_ lhs: Errno, _ rhs: Error) -> Bool {
+176 -17
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -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,11 @@ 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
@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 AccessMode: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C access mode.
@_alwaysEmitIntoClient
@@ -88,7 +88,7 @@ extension FileDescriptor {
/// Options that specify behavior for a newly-opened file.
@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 OpenOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
@@ -182,7 +182,7 @@ extension FileDescriptor {
@available(*, unavailable, renamed: "exclusiveCreate")
public static var O_EXCL: OpenOptions { exclusiveCreate }
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Indicates that opening the file
/// atomically obtains a shared lock on the file.
///
@@ -250,6 +250,22 @@ extension FileDescriptor {
public static var O_DIRECTORY: OpenOptions { directory }
#endif
#if os(FreeBSD)
/// Indicates that each write operation is synchronous.
///
/// If this option is specified,
/// each time you write to the file,
/// the new data is written immediately and synchronously to the disk.
///
/// The corresponding C constant is `O_SYNC`.
@_alwaysEmitIntoClient
public static var sync: OpenOptions { .init(rawValue: _O_SYNC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "sync")
public static var O_SYNC: OpenOptions { sync }
#endif
#if SYSTEM_PACKAGE_DARWIN
/// Indicates that opening the file
/// opens symbolic links instead of following them.
@@ -290,12 +306,10 @@ extension FileDescriptor {
///
/// Normally, file descriptors remain open
/// across calls to the `exec(2)` family of functions.
/// If you specify this option,
/// the file descriptor is closed when replacing this process
/// with another process.
/// If you specify this option, the system closes the file
/// descriptor when replacing this process with another process.
///
/// The state of the file
/// descriptor flags can be inspected using `F_GETFD`,
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
@@ -308,9 +322,141 @@ extension FileDescriptor {
#endif
}
/// Options that specify behavior for a newly-created pipe.
@frozen
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
#if !os(Windows)
/// Indicates that all subsequent input and output operations
/// on the pipe's file descriptors will be nonblocking.
///
/// The corresponding C constant is `O_NONBLOCK`.
@_alwaysEmitIntoClient
public static var nonBlocking: PipeOptions { .init(rawValue: _O_NONBLOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "nonBlocking")
public static var O_NONBLOCK: PipeOptions { nonBlocking }
#endif // !os(Windows)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `exec(2)` family of functions.
/// If you specify this option, the system closes the file
/// descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
@_alwaysEmitIntoClient
public static var closeOnExec: PipeOptions { .init(rawValue: _O_CLOEXEC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_CLOEXEC: PipeOptions { closeOnExec }
#if os(Windows)
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_NOINHERIT: PipeOptions { closeOnExec }
#endif
#if !os(Windows) && !os(WASI) && !os(Linux) && !os(Android)
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `fork(2)` function.
/// If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
@_alwaysEmitIntoClient
public static var closeOnFork: PipeOptions { .init(rawValue: _O_CLOFORK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnFork")
public static var O_CLOFORK: PipeOptions { closeOnFork }
#endif
}
/// Options that specify behavior for a duplicated file descriptor.
@frozen
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
#if !os(Windows)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `exec(2)` family of functions.
/// If you specify this option, the system closes the file
/// descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
@_alwaysEmitIntoClient
public static var closeOnExec: DuplicateOptions { .init(rawValue: _O_CLOEXEC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_CLOEXEC: DuplicateOptions { closeOnExec }
#if !os(WASI) && !os(Linux) && !os(Android)
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `fork(2)` function.
/// If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
@_alwaysEmitIntoClient
public static var closeOnFork: DuplicateOptions { .init(rawValue: _O_CLOFORK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnFork")
public static var O_CLOFORK: DuplicateOptions { closeOnFork }
#endif
#endif
}
/// Options for specifying what a file descriptor's offset is relative to.
@frozen
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
public struct SeekOrigin: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C value.
@_alwaysEmitIntoClient
@@ -354,7 +500,7 @@ extension FileDescriptor {
// TODO: These are available on some versions of Linux with appropriate
// macro defines.
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// Indicates that the offset should be set
/// to the next hole after the specified number of bytes.
///
@@ -386,7 +532,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 +551,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
{
@@ -428,7 +574,7 @@ 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
{
@@ -456,6 +602,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"),
+1 -1
View File
@@ -7,7 +7,7 @@
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 {
/// Runs a closure and then closes the file descriptor, even if an error occurs.
///
+145 -19
View File
@@ -1,13 +1,13 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
@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.
///
@@ -368,7 +368,7 @@ extension FileDescriptor {
}
#if !os(WASI)
@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 FileDescriptor {
/// Duplicates this file descriptor and return the newly created copy.
///
@@ -395,10 +395,9 @@ extension FileDescriptor {
///
/// However, each file descriptor maintains its own close-on-exec flag.
///
///
/// The corresponding C functions are `dup` and `dup2`.
@_alwaysEmitIntoClient
@available(/*System 0.0.2: 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
@@ -406,17 +405,82 @@ 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, *)
/// Duplicate this file descriptor and return the newly created copy.
///
/// - Parameters:
/// - target: The desired target file descriptor.
/// - options: The behavior for creating the target file descriptor.
/// - retryOnInterrupt: Whether to retry the operation
/// if it throws ``Errno/interrupted``. The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The new file descriptor.
///
/// If the `target` descriptor the same as `self`, then EINVAL is thrown.
/// If the `target` descriptor is already in use, then it is first
/// deallocated as if a close(2) call had been done first.
///
/// NOTE: This overload called with an empty option set is not necessarily
/// equivalent to calling the overload with no options, because `dup3` with
/// no set options is not required to behave identically to `dup2`.
///
/// File descriptors are merely references to some underlying system resource.
/// The system does not distinguish between the original and the new file
/// descriptor in any way. For example, read, write and seek operations on
/// one of them also affect the logical file position in the other, and
/// append mode, non-blocking I/O and asynchronous I/O options are shared
/// between the references. If a separate pointer into the file is desired,
/// a different object reference to the file must be obtained by issuing an
/// additional call to `open`.
///
/// However, each file descriptor maintains its own close-on-exec and
/// close-on-fork flags.
///
/// The corresponding C function is `dup3`.
@discardableResult
@_alwaysEmitIntoClient
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public func duplicate(
as target: FileDescriptor,
options: DuplicateOptions,
retryOnInterrupt: Bool = true
) throws(Errno) -> FileDescriptor {
try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get()
}
@available(System 0.0.2, *)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor?,
retryOnInterrupt: Bool
) throws -> Result<FileDescriptor, Errno> {
) -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
if let target = target {
return system_dup2(self.rawValue, target.rawValue)
if let target {
system_dup2(self.rawValue, target.rawValue)
} else {
system_dup(self.rawValue)
}
return system_dup(self.rawValue)
}.map(FileDescriptor.init(rawValue:))
}
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor,
options: Int32,
retryOnInterrupt: Bool
) -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_dup3(self.rawValue, target.rawValue, options)
}.map(FileDescriptor.init(rawValue:))
}
@@ -431,26 +495,61 @@ extension FileDescriptor {
public func dup2() throws -> FileDescriptor {
fatalError("Not implemented")
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "duplicate")
public func dup3() throws -> FileDescriptor {
fatalError("Not implemented")
}
}
#endif
#if !os(WASI)
@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *)
@available(System 1.1.0, *)
extension FileDescriptor {
/// Creates a unidirectional data channel, which can be used for interprocess communication.
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
///
/// - Returns: The pair of file descriptors.
///
/// The corresponding C function is `pipe`.
@_alwaysEmitIntoClient
@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *)
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
@available(System 1.1.0, *)
public static func pipe(
) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe().get()
}
@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *)
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
///
/// NOTE: This overload called with an empty option set is not necessarily
/// equivalent to calling the overload with no options. On Windows, this
/// overload with empty options disables the `closeOnExec` behaviour,
/// which is enabled by the overload without options.
///
/// - Parameters:
/// - options: The behavior for creating the pipe.
///
/// - Returns: The pair of file descriptors.
///
/// The corresponding C function is `pipe2`.
@_alwaysEmitIntoClient
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public static func pipe(
options: PipeOptions
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe(options: options.rawValue).get()
}
@available(System 1.1.0, *)
@usableFromInline
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
internal static func _pipe(
) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
var fds: (Int32, Int32) = (-1, -1)
return withUnsafeMutablePointer(to: &fds) { pointer in
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
@@ -460,10 +559,35 @@ extension FileDescriptor {
}
}
}
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@usableFromInline
internal static func _pipe(
options: Int32,
) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
var fds: (Int32, Int32) = (-1, -1)
return withUnsafeMutablePointer(to: &fds) { pointer in
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
valueOrErrno(retryOnInterrupt: false) {
system_pipe2(fds, options)
}.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) }
}
}
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "pipe")
public static func pipe2() throws -> FileDescriptor {
fatalError("Not implemented")
}
}
#endif
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.2.0, *)
extension FileDescriptor {
/// Truncates or extends the file referenced by this file descriptor.
///
@@ -485,7 +609,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,
@@ -497,7 +621,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,6 +633,7 @@ extension FileDescriptor {
}
}
#if !os(WASI) // WASI has no umask
extension FilePermissions {
/// The file creation permission mask (aka "umask").
///
@@ -549,3 +674,4 @@ extension FilePermissions {
return system_umask(mode)
}
}
#endif
+4 -4
View File
@@ -37,7 +37,7 @@
/// 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, *)
@available(System 0.0.1, *)
public struct FilePath: Sendable {
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
// components, etc.
@@ -59,16 +59,16 @@ public struct FilePath: Sendable {
}
}
@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, *)
@available(System 0.0.1, *)
extension FilePath: Hashable {}
@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: Codable {
// Encoder is synthesized; it probably should have been explicit and used
// a single-value container, but making that change now is somewhat risky.
@@ -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,7 @@ extension FilePath {
///
/// path.components.removeAll { $0.kind == .currentDirectory }
/// // path is "/home/username/bin/scripts/tree"
@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 struct ComponentView: Sendable {
internal var _path: FilePath
internal var _start: SystemString.Index
@@ -64,11 +64,11 @@ 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: BidirectionalCollection {
public typealias Element = 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, *)
public struct Index: Sendable, Comparable, Hashable {
internal typealias Storage = SystemString.Index
@@ -100,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())
@@ -150,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>(
@@ -179,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
@@ -192,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
@@ -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,7 @@ extension FilePath {
/// * `\\server\share\`
/// * `\\?\UNC\server\share\`
/// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\`
@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 struct Root: Sendable {
internal var _path: FilePath
internal var _rootEnd: SystemString.Index
@@ -55,7 +55,7 @@ extension FilePath {
/// file.kind == .regular // true
/// file.extension // "txt"
/// path.append(file) // path is "/tmp/foo.txt"
@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 struct Component: Sendable {
internal var _path: FilePath
internal var _range: Range<SystemString.Index>
@@ -74,13 +74,13 @@ 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
@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 Kind: Sendable {
/// The special directory `.`, representing the current directory.
case currentDirectory
@@ -100,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
}
@@ -186,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)
@@ -208,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? {
@@ -237,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?
@@ -250,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?
@@ -265,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() {
@@ -278,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
@@ -116,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()
@@ -197,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
@@ -209,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
@@ -273,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 {
@@ -298,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.
@@ -323,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 }
@@ -345,7 +345,7 @@ internal var _windowsPaths: Bool {
#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 {
@@ -373,7 +373,7 @@ 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 _invariantsSatisfied() -> Bool {
var normal = self
+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() }
@@ -17,7 +17,7 @@ internal func _getTemporaryDirectory() throws -> FilePath {
capacity: Int(MAX_PATH) + 1) {
buffer in
guard GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) != 0 else {
guard GetTempPathW(DWORD(buffer.count), buffer.baseAddress) != 0 else {
throw Errno(windowsError: GetLastError())
}
@@ -40,7 +40,7 @@ fileprivate func forEachFile(
try searchPath.withPlatformString { szPath in
var findData = WIN32_FIND_DATAW()
let hFind = FindFirstFileW(szPath, &findData)
let hFind = try szPath.withCanonicalPathRepresentation({ szPath in FindFirstFileW(szPath, &findData) })
if hFind == INVALID_HANDLE_VALUE {
throw Errno(windowsError: GetLastError())
}
@@ -73,7 +73,7 @@ internal func _recursiveRemove(
) throws {
// First, deal with subdirectories
try forEachFile(at: path) { findData in
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 {
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 {
let name = withUnsafeBytes(of: findData.cFileName) {
return SystemString(platformString: $0.assumingMemoryBound(
to: CInterop.PlatformChar.self).baseAddress!)
@@ -94,9 +94,9 @@ internal func _recursiveRemove(
let component = FilePath.Component(name)!
let subpath = path.appending(component)
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 {
try subpath.withPlatformString {
if !DeleteFileW($0) {
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 {
try subpath.withPlatformString { subpath in
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
throw Errno(windowsError: GetLastError())
}
}
@@ -105,7 +105,7 @@ internal func _recursiveRemove(
// Finally, delete the parent
try path.withPlatformString {
if !RemoveDirectoryW($0) {
if try !$0.withCanonicalPathRepresentation({ RemoveDirectoryW($0) }) {
throw Errno(windowsError: GetLastError())
}
}
@@ -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 ERROR_SUCCESS }
if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
return HRESULT_CODE(hr)
}
return DWORD(hr)
}
#endif
+2 -2
View File
@@ -17,7 +17,7 @@
/// 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, *)
@available(System 0.0.1, *)
public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
/// The raw C file permissions.
@_alwaysEmitIntoClient
@@ -132,7 +132,7 @@ public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
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
{
+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
+486
View File
@@ -0,0 +1,486 @@
#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(
pathBuffers: PendingPathBuffers
) -> 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: pathBuffers.pin(path)))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0
request.rawValue.file_index = UInt32(fileSlot.index + 1)
request.rawValue.user_data = context
case .openat(
let atDirectory, let path, let mode, let options, let permissions, let context):
request.operation = .openAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(bitPattern: pathBuffers.pin(path)))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0
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: pathBuffers.pin(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
+952
View File
@@ -0,0 +1,952 @@
#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)
}
}
/// Owns the FilePaths whose interior pointers have been written into pending
/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to
/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap
/// This is a class purely to avoid making methods calling `pin` mutating, which would be an API break
@usableFromInline
internal final class PendingPathBuffers {
@usableFromInline
var paths: [FilePath] = []
init(reservedCapacity: Int) {
paths.reserveCapacity(reservedCapacity)
}
@usableFromInline
func pin(_ path: FilePath) -> UnsafePointer<CInterop.PlatformChar> {
paths.append(path)
// Safe to escape: `paths` keeps the FilePath (and its underlying
// [SystemChar] buffer) alive until clear() or class deinit.
return paths.last!.withPlatformString { $0 }
}
@usableFromInline
func clear() {
paths.removeAll(keepingCapacity: true)
}
}
// all pointers in this struct reference kernel-visible memory
@usableFromInline struct SQRing: ~Copyable {
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
@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
}
// We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced
// pathnames (and other inline data) out of userspace before io_uring_enter
// returns; the path-buffer side store on IORing relies on this to free
// path buffers as soon as a submission completes.
let requiredFeatures =
IORing.Features.nonDroppingCompletions.rawValue
| IORing.Features.stableSubmissions.rawValue
if params.features & requiredFeatures != requiredFeatures
{
close(ringDescriptor)
throw Errno.invalidArgument
}
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]
@usableFromInline let _pendingPathBuffers: PendingPathBuffers
var features = Features(rawValue: 0)
/// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them.
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._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries))
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)
// IORING_FEAT_SUBMIT_STABLE guarantees the kernel has copied any
// SQE-referenced data (e.g. openat/unlinkAt pathnames) before
// io_uring_enter returns; safe to release path storage now.
_pendingPathBuffers.clear()
}
/// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available.
@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 {
guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else {
return false
}
var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers)
let ok = _tryWriteRequest(
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(ok)
return ok
}
/// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order.
@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!
var allAdded = true
for req in linkedRequests.dropLast() {
var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers)
raw.linkToNextRequest()
let successfullyAdded = _tryWriteRequest(
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
allAdded = allAdded && successfullyAdded
}
let successfullyAdded = _tryWriteRequest(
last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing,
submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
return allAdded && successfullyAdded
}
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
@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
+204
View File
@@ -0,0 +1,204 @@
#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
@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
+42 -4
View File
@@ -5,7 +5,7 @@
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
@@ -21,7 +21,7 @@ import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Bionic)
@_implementationOnly import CSystem
import CSystem
import Bionic
#else
#error("Unsupported Platform")
@@ -37,12 +37,12 @@ import Bionic
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
@@ -79,3 +79,41 @@ public enum CInterop {
public typealias PlatformUnicodeEncoding = UTF8
#endif
}
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
/// The C `stat` struct.
public typealias Stat = stat
/// Calls the C `stat()` function.
///
/// This is a direct wrapper around the C `stat()` system call.
/// For a more ergonomic Swift API, use `Stat` instead.
///
/// - Warning: This API is primarily intended for migration purposes when
/// supporting older deployment targets. If your deployment target supports
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
/// type-safe, ergonomic access to file metadata in Swift.
///
/// - Parameters:
/// - path: A null-terminated C string representing the file path.
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
system_stat(path, &s)
}
}
@available(System 99, *)
extension CInterop {
public typealias 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
+195 -11
View File
@@ -1,11 +1,11 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
*/
// For platform constants redefined in Swift. We define them here so that
// they can be used anywhere without imports and without confusion to
@@ -17,6 +17,7 @@ import Darwin
import CSystem
import ucrt
#elseif canImport(Glibc)
import CSystem
import Glibc
#elseif canImport(Musl)
import CSystem
@@ -359,7 +360,7 @@ internal var _ENOLCK: CInt { ENOLCK }
@_alwaysEmitIntoClient
internal var _ENOSYS: CInt { ENOSYS }
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _EFTYPE: CInt { EFTYPE }
@@ -368,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 }
@@ -409,7 +412,7 @@ internal var _ENOMSG: CInt { ENOMSG }
@_alwaysEmitIntoClient
internal var _EILSEQ: CInt { EILSEQ }
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENOATTR: CInt { ENOATTR }
#endif
@@ -422,7 +425,7 @@ internal var _EBADMSG: CInt { EBADMSG }
@_alwaysEmitIntoClient
internal var _EMULTIHOP: CInt { EMULTIHOP }
#if !os(WASI)
#if !os(WASI) && !os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENODATA: CInt { ENODATA }
#endif
@@ -430,19 +433,19 @@ internal var _ENODATA: CInt { ENODATA }
@_alwaysEmitIntoClient
internal var _ENOLINK: CInt { ENOLINK }
#if !os(WASI)
#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) && !os(WASI)
#if !os(OpenBSD) && !os(WASI) && !os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ETIME: CInt { ETIME }
#endif
@@ -471,10 +474,23 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
#endif
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENOTCAPABLE: CInt { ENOTCAPABLE }
@_alwaysEmitIntoClient
internal var _ECAPMODE: CInt { ECAPMODE }
@_alwaysEmitIntoClient
internal var _EINTEGRITY: CInt { EINTEGRITY }
#endif
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EQFULL: CInt { EQFULL }
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ELAST: CInt { ELAST }
#endif
@@ -524,7 +540,7 @@ internal var _O_APPEND: CInt {
#endif
}
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _O_SHLOCK: CInt { O_SHLOCK }
@@ -543,6 +559,14 @@ internal var _O_ASYNC: CInt { O_ASYNC }
internal var _O_NOFOLLOW: CInt { O_NOFOLLOW }
#endif
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _O_FSYNC: CInt { O_FSYNC }
@_alwaysEmitIntoClient
internal var _O_SYNC: CInt { O_SYNC }
#endif
@_alwaysEmitIntoClient
internal var _O_CREAT: CInt {
#if os(WASI)
@@ -595,9 +619,26 @@ internal var _O_DIRECTORY: CInt {
internal var _O_SYMLINK: CInt { O_SYMLINK }
#endif
@_alwaysEmitIntoClient
internal var _O_CLOEXEC: CInt {
#if os(Windows)
O_NOINHERIT
#else
O_CLOEXEC
#endif
}
#if !os(Windows)
@_alwaysEmitIntoClient
internal var _O_CLOEXEC: CInt { O_CLOEXEC }
internal var _O_CLOFORK: CInt {
#if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD)
O_CLOFORK
#elseif os(FreeBSD)
FREEBSD_O_CLOFORK
#else
0
#endif
}
#endif
@_alwaysEmitIntoClient
@@ -609,10 +650,153 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
@_alwaysEmitIntoClient
internal var _SEEK_END: CInt { SEEK_END }
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
@_alwaysEmitIntoClient
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)
// `S_IFWHT` is `Int32` on FreeBSD.
@_alwaysEmitIntoClient
internal var _S_IFWHT: mode_t { .init(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)
+27 -7
View File
@@ -5,7 +5,7 @@
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.
@@ -90,6 +90,26 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
strlen(s)
}
#if !os(Windows)
@available(System 0.0.2, *)
@_alwaysEmitIntoClient
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.
@@ -140,7 +160,7 @@ extension String {
return
#else
self.init(validatingUTF8: platformString)
self.init(validatingCString: platformString)
#endif
}
@@ -167,20 +187,20 @@ 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() {}
fileprivate init() {}
}
private final class TLSStorage: @unchecked Sendable {
var storage = [ObjectIdentifier: UnsafeMutableRawPointer]()
var storage = [ObjectIdentifier: UnsafeMutableRawPointer]()
}
private let sharedTLSStorage = TLSStorage()
func pthread_setspecific(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) -> Int {
sharedTLSStorage.storage[ObjectIdentifier(key)] = p
return 0
sharedTLSStorage.storage[ObjectIdentifier(key)] = p
return 0
}
func pthread_getspecific(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
sharedTLSStorage.storage[ObjectIdentifier(key)]
sharedTLSStorage.storage[ObjectIdentifier(key)]
}
#else
internal typealias _PlatformTLSKey = pthread_key_t
+1 -1
View File
@@ -130,7 +130,7 @@ internal var mockingEnabled: Bool {
@inline(__always)
internal var forceWindowsPaths: Bool? {
#if !ENABLE_MOCKING
return false
return nil
#else
return MockingDriver.forceWindowsPaths
#endif
+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
}
}
+30 -3
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -23,6 +23,8 @@ import Android
#error("Unsupported Platform")
#endif
import CSystem
// Interacting with the mocking system, tracing, etc., is a potentially significant
// amount of code size, so we hand outline that code for every syscall
@@ -138,6 +140,13 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
#endif
return dup2(fd, fd2)
}
internal func system_dup3(_ fd: Int32, _ fd2: Int32, _ oflag: Int32) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, fd2, oflag) }
#endif
return csystem_posix_dup3(fd, fd2, oflag)
}
#endif
#if !os(WASI)
@@ -147,6 +156,13 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#endif
return pipe(fds)
}
internal func system_pipe2(_ fds: UnsafeMutablePointer<Int32>, _ oflag: Int32) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fds, oflag) }
#endif
return csystem_posix_pipe2(fds, oflag)
}
#endif
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
@@ -189,9 +205,14 @@ internal func system_confstr(
#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
#if os(Linux) || os(Android)
#endif
#if os(Linux) || os(Android) || os(FreeBSD) || os(OpenBSD) || os(WASI)
internal typealias system_DIRPtr = OpaquePointer
#else
internal typealias system_DIRPtr = UnsafeMutablePointer<DIR>
@@ -216,8 +237,12 @@ internal func system_fdopendir(
internal func system_readdir(
_ dir: system_DIRPtr
) -> UnsafeMutablePointer<dirent>? {
) -> UnsafeMutablePointer<system_dirent>? {
#if os(WASI)
return _system_dirent_from_wasi_dirent(readdir(dir))
#else
return readdir(dir)
#endif
}
internal func system_rewinddir(
@@ -246,11 +271,13 @@ internal func system_openat(
}
#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>
@@ -35,17 +35,17 @@ internal func open(
bInheritHandle: decodedFlags.bInheritHandle
)
let hFile = CreateFileW(path,
decodedFlags.dwDesiredAccess,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
nil)
if hFile == INVALID_HANDLE_VALUE {
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
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
}
@@ -77,17 +77,17 @@ internal func open(
bInheritHandle: decodedFlags.bInheritHandle
)
let hFile = CreateFileW(path,
decodedFlags.dwDesiredAccess,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
nil)
if hFile == INVALID_HANDLE_VALUE {
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
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
}
@@ -135,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)
@@ -145,6 +149,12 @@ internal func pread(
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows ReadFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -167,6 +177,12 @@ internal func pwrite(
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows WriteFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -185,9 +201,16 @@ internal func pwrite(
@inline(__always)
internal func pipe(
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 4096
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0
) -> CInt {
  return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
}
@inline(__always)
internal func csystem_posix_pipe2(
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0, _ oflag: Int32
) -> CInt {
return _pipe(fds, bytesReserved, _O_BINARY | oflag)
}
@inline(__always)
@@ -202,16 +225,16 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
// Save the current position and restore it when we're done
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
DWORD(FILE_CURRENT)) {
FILE_CURRENT) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
defer {
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN));
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN);
}
// Truncate (or extend) the file
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN))
if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN)
|| !SetEndOfFile(hFile) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
@@ -242,7 +265,7 @@ internal func mkdir(
bInheritHandle: false
)
if !CreateDirectoryW(path, &saAttrs) {
guard (try? path.withCanonicalPathRepresentation({ path in CreateDirectoryW(path, &saAttrs) })) == true else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
@@ -254,7 +277,7 @@ internal func mkdir(
internal func rmdir(
_ path: UnsafePointer<CInterop.PlatformChar>
) -> CInt {
if !RemoveDirectoryW(path) {
guard (try? path.withCanonicalPathRepresentation({ path in RemoveDirectoryW(path) })) == true else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
@@ -263,7 +286,7 @@ internal func rmdir(
}
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
switch Int32(errorCode) {
switch errorCode {
case ERROR_SUCCESS:
return 0
case ERROR_INVALID_FUNCTION,
@@ -342,28 +365,28 @@ fileprivate func rightsFromModeBits(
var rights: DWORD = 0
if (bits & 0o4) != 0 {
rights |= DWORD(FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
rights |= (FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
}
if (bits & 0o2) != 0 {
rights |= DWORD(FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
rights |= (FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
if fileOrDirectory == .directory && !sticky {
rights |= DWORD(FILE_DELETE_CHILD)
rights |= FILE_DELETE_CHILD
}
}
if (bits & 0o1) != 0 {
rights |= DWORD(FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
rights |= (FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
}
return rights
@@ -431,7 +454,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var everyone: PSID? = nil
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
DWORD(SECURITY_WORLD_RID),
SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&everyone) else {
return nil
@@ -472,7 +495,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -485,7 +508,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -498,7 +521,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: otherRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -515,7 +538,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -533,7 +556,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -562,13 +585,13 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var descriptor = SECURITY_DESCRIPTOR()
guard InitializeSecurityDescriptor(&descriptor,
DWORD(SECURITY_DESCRIPTOR_REVISION)) else {
SECURITY_DESCRIPTOR_REVISION) else {
return nil
}
guard SetSecurityDescriptorControl(&descriptor,
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED),
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED))
SE_DACL_PROTECTED,
SE_DACL_PROTECTED)
&& SetSecurityDescriptorOwner(&descriptor, user, false)
&& SetSecurityDescriptorGroup(&descriptor, group, false)
&& SetSecurityDescriptorDacl(&descriptor,
@@ -608,15 +631,15 @@ fileprivate struct DecodedOpenFlags {
init(_ oflag: Int32) {
switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) {
case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC:
dwCreationDisposition = DWORD(CREATE_NEW)
dwCreationDisposition = CREATE_NEW
case _O_CREAT:
dwCreationDisposition = DWORD(OPEN_ALWAYS)
dwCreationDisposition = OPEN_ALWAYS
case _O_CREAT | _O_TRUNC:
dwCreationDisposition = DWORD(CREATE_ALWAYS)
dwCreationDisposition = CREATE_ALWAYS
case _O_TRUNC:
dwCreationDisposition = DWORD(TRUNCATE_EXISTING)
dwCreationDisposition = TRUNCATE_EXISTING
default:
dwCreationDisposition = DWORD(OPEN_EXISTING)
dwCreationDisposition = OPEN_EXISTING
}
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
@@ -625,11 +648,11 @@ fileprivate struct DecodedOpenFlags {
dwDesiredAccess = 0
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
case _O_RDONLY:
dwDesiredAccess |= DWORD(GENERIC_READ)
dwDesiredAccess |= GENERIC_READ
case _O_WRONLY:
dwDesiredAccess |= DWORD(GENERIC_WRITE)
dwDesiredAccess |= GENERIC_WRITE
case _O_RDWR:
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE)
dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE
default:
break
}
@@ -638,19 +661,19 @@ fileprivate struct DecodedOpenFlags {
dwFlagsAndAttributes = 0
if (oflag & _O_SEQUENTIAL) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN)
dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN
}
if (oflag & _O_RANDOM) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS)
dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS
}
if (oflag & _O_TEMPORARY) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE)
dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE
}
if (oflag & _O_SHORT_LIVED) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY)
dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY
} else {
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL)
dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL
}
}
}
+20 -21
View File
@@ -1,20 +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 swift(>=5.9) && SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN
import Darwin.Mach
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public protocol MachPortRight {}
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
@inlinable
internal func _machPrecondition(
file: StaticString = #file,
@@ -26,10 +26,10 @@ internal func _machPrecondition(
precondition(kr == expected, file: file, line: line)
}
@available(/*System 1.4.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: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public struct Port<RightType: MachPortRight>: ~Copyable {
@usableFromInline
internal var _name: mach_port_name_t
@@ -133,7 +133,7 @@ public enum Mach {
public struct SendOnceRight: MachPortRight {}
}
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@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.
@@ -145,6 +145,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// The underlying port right will be automatically deallocated when
/// the Mach.Port object is destroyed.
@available(System 1.4.0, *)
public init(name: mach_port_name_t, context: mach_port_context_t) {
precondition(name != mach_port_name_t(MACH_PORT_NULL),
"Mach.Port cannot be initialized with MACH_PORT_NULL")
@@ -158,7 +159,7 @@ 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: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public init() {
var storage: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
_machPrecondition(
@@ -180,8 +181,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public consuming func relinquish(
) -> (name: mach_port_name_t, context: mach_port_context_t) {
let destructured = (name: _name, context: _context)
@@ -204,7 +204,7 @@ 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
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@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))
@@ -221,7 +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: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public func withBorrowedName<ReturnType>(
body: (mach_port_name_t, mach_port_context_t) -> ReturnType
) -> ReturnType {
@@ -235,7 +235,7 @@ 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: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@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)
@@ -264,7 +264,7 @@ 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: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public func makeSendRight() -> Mach.Port<Mach.SendRight> {
let how = MACH_MSG_TYPE_MAKE_SEND
@@ -282,7 +282,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// Each get/set of this property makes a syscall.
@inlinable
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public var makeSendCount: mach_port_mscount_t {
get {
var status: mach_port_status = mach_port_status()
@@ -311,7 +311,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
}
}
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.SendRight {
/// Transfer ownership of the underlying port right to the caller.
///
@@ -322,7 +322,7 @@ extension Mach.Port where RightType == Mach.SendRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(System 1.4.0, *)
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
@@ -337,7 +337,7 @@ 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: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public func copySendRight() throws -> Mach.Port<Mach.SendRight> {
let how = MACH_MSG_TYPE_COPY_SEND
@@ -354,7 +354,7 @@ extension Mach.Port where RightType == Mach.SendRight {
}
}
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.SendOnceRight {
/// Transfer ownership of the underlying port right to the caller.
///
@@ -365,8 +365,7 @@ extension Mach.Port where RightType == Mach.SendOnceRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
+3 -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.
@@ -165,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)
@@ -176,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)
+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)
+439
View File
@@ -0,0 +1,439 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2024 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(Windows)
import WinSDK
@_transparent
internal var CREATE_ALWAYS: DWORD {
DWORD(WinSDK.CREATE_ALWAYS)
}
@_transparent
internal var CREATE_NEW: DWORD {
DWORD(WinSDK.CREATE_NEW)
}
@_transparent
internal var ERROR_ACCESS_DENIED: DWORD {
DWORD(WinSDK.ERROR_ACCESS_DENIED)
}
@_transparent
internal var ERROR_ALREADY_EXISTS: DWORD {
DWORD(WinSDK.ERROR_ALREADY_EXISTS)
}
@_transparent
internal var ERROR_ARENA_TRASHED: DWORD {
DWORD(WinSDK.ERROR_ARENA_TRASHED)
}
@_transparent
internal var ERROR_BAD_ENVIRONMENT: DWORD {
DWORD(WinSDK.ERROR_BAD_ENVIRONMENT)
}
@_transparent
internal var ERROR_BAD_FORMAT: DWORD {
DWORD(WinSDK.ERROR_BAD_FORMAT)
}
@_transparent
internal var ERROR_BAD_NET_NAME: DWORD {
DWORD(WinSDK.ERROR_BAD_NET_NAME)
}
@_transparent
internal var ERROR_BAD_NETPATH: DWORD {
DWORD(WinSDK.ERROR_BAD_NETPATH)
}
@_transparent
internal var ERROR_BAD_PATHNAME: DWORD {
DWORD(WinSDK.ERROR_BAD_PATHNAME)
}
@_transparent
internal var ERROR_BROKEN_PIPE: DWORD {
DWORD(WinSDK.ERROR_BROKEN_PIPE)
}
@_transparent
internal var ERROR_CANNOT_MAKE: DWORD {
DWORD(WinSDK.ERROR_CANNOT_MAKE)
}
@_transparent
internal var ERROR_CHILD_NOT_COMPLETE: DWORD {
DWORD(WinSDK.ERROR_CHILD_NOT_COMPLETE)
}
@_transparent
internal var ERROR_CURRENT_DIRECTORY: DWORD {
DWORD(WinSDK.ERROR_CURRENT_DIRECTORY)
}
@_transparent
internal var ERROR_DIR_NOT_EMPTY: DWORD {
DWORD(WinSDK.ERROR_DIR_NOT_EMPTY)
}
@_transparent
internal var ERROR_DISK_FULL: DWORD {
DWORD(WinSDK.ERROR_DISK_FULL)
}
@_transparent
internal var ERROR_DRIVE_LOCKED: DWORD {
DWORD(WinSDK.ERROR_DRIVE_LOCKED)
}
@_transparent
internal var ERROR_DIRECT_ACCESS_HANDLE: DWORD {
DWORD(WinSDK.ERROR_DIRECT_ACCESS_HANDLE)
}
@_transparent
internal var ERROR_FILE_EXISTS: DWORD {
DWORD(WinSDK.ERROR_FILE_EXISTS)
}
@_transparent
internal var ERROR_FILE_NOT_FOUND: DWORD {
DWORD(WinSDK.ERROR_FILE_NOT_FOUND)
}
@_transparent
internal var ERROR_FAIL_I24: DWORD {
DWORD(WinSDK.ERROR_FAIL_I24)
}
@_transparent
internal var ERROR_FILENAME_EXCED_RANGE: DWORD {
DWORD(WinSDK.ERROR_FILENAME_EXCED_RANGE)
}
@_transparent
internal var ERROR_NEGATIVE_SEEK: DWORD {
DWORD(WinSDK.ERROR_NEGATIVE_SEEK)
}
@_transparent
internal var ERROR_NO_MORE_FILES: DWORD {
DWORD(WinSDK.ERROR_NO_MORE_FILES)
}
@_transparent
internal var ERROR_NO_UNICODE_TRANSLATION: DWORD {
DWORD(WinSDK.ERROR_NO_UNICODE_TRANSLATION)
}
@_transparent
internal var ERROR_NOT_ENOUGH_MEMORY: DWORD {
DWORD(WinSDK.ERROR_NOT_ENOUGH_MEMORY)
}
@_transparent
internal var ERROR_INVALID_ACCESS: DWORD {
DWORD(WinSDK.ERROR_INVALID_ACCESS)
}
@_transparent
internal var ERROR_INVALID_BLOCK: DWORD {
DWORD(WinSDK.ERROR_INVALID_BLOCK)
}
@_transparent
internal var ERROR_INVALID_DATA: DWORD {
DWORD(WinSDK.ERROR_INVALID_DATA)
}
@_transparent
internal var ERROR_INVALID_DRIVE: DWORD {
DWORD(WinSDK.ERROR_INVALID_DRIVE)
}
@_transparent
internal var ERROR_INVALID_FUNCTION: DWORD {
DWORD(WinSDK.ERROR_INVALID_FUNCTION)
}
@_transparent
internal var ERROR_INVALID_HANDLE: DWORD {
DWORD(WinSDK.ERROR_INVALID_HANDLE)
}
@_transparent
internal var ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD {
DWORD(WinSDK.ERROR_INFLOOP_IN_RELOC_CHAIN)
}
@_transparent
internal var ERROR_INVALID_PARAMETER: DWORD {
DWORD(WinSDK.ERROR_INVALID_PARAMETER)
}
@_transparent
internal var ERROR_INVALID_STARTING_CODESEG: DWORD {
DWORD(WinSDK.ERROR_INVALID_STARTING_CODESEG)
}
@_transparent
internal var ERROR_INVALID_TARGET_HANDLE: DWORD {
DWORD(WinSDK.ERROR_INVALID_TARGET_HANDLE)
}
@_transparent
internal var ERROR_LOCK_FAILED: DWORD {
DWORD(WinSDK.ERROR_LOCK_FAILED)
}
@_transparent
internal var ERROR_LOCK_VIOLATION: DWORD {
DWORD(WinSDK.ERROR_LOCK_VIOLATION)
}
@_transparent
internal var ERROR_MAX_THRDS_REACHED: DWORD {
DWORD(WinSDK.ERROR_MAX_THRDS_REACHED)
}
@_transparent
internal var ERROR_NESTING_NOT_ALLOWED: DWORD {
DWORD(WinSDK.ERROR_NESTING_NOT_ALLOWED)
}
@_transparent
internal var ERROR_NETWORK_ACCESS_DENIED: DWORD {
DWORD(WinSDK.ERROR_NETWORK_ACCESS_DENIED)
}
@_transparent
internal var ERROR_NO_PROC_SLOTS: DWORD {
DWORD(WinSDK.ERROR_NO_PROC_SLOTS)
}
@_transparent
internal var ERROR_NOT_ENOUGH_QUOTA: DWORD {
DWORD(WinSDK.ERROR_NOT_ENOUGH_QUOTA)
}
@_transparent
internal var ERROR_NOT_LOCKED: DWORD {
DWORD(WinSDK.ERROR_NOT_LOCKED)
}
@_transparent
internal var ERROR_NOT_SAME_DEVICE: DWORD {
DWORD(WinSDK.ERROR_NOT_SAME_DEVICE)
}
@_transparent
internal var ERROR_PATH_NOT_FOUND: DWORD {
DWORD(WinSDK.ERROR_PATH_NOT_FOUND)
}
@_transparent
internal var ERROR_SEEK_ON_DEVICE: DWORD {
DWORD(WinSDK.ERROR_SEEK_ON_DEVICE)
}
@_transparent
internal var ERROR_SHARING_BUFFER_EXCEEDED: DWORD {
DWORD(WinSDK.ERROR_SHARING_BUFFER_EXCEEDED)
}
@_transparent
internal var ERROR_SUCCESS: DWORD {
DWORD(WinSDK.ERROR_SUCCESS)
}
@_transparent
internal var ERROR_WAIT_NO_CHILDREN: DWORD {
DWORD(WinSDK.ERROR_WAIT_NO_CHILDREN)
}
@_transparent
internal var ERROR_WRITE_PROTECT: DWORD {
DWORD(WinSDK.ERROR_WRITE_PROTECT)
}
@_transparent
internal var ERROR_TOO_MANY_OPEN_FILES: DWORD {
DWORD(WinSDK.ERROR_TOO_MANY_OPEN_FILES)
}
@_transparent
internal var FILE_APPEND_DATA: DWORD {
DWORD(WinSDK.FILE_APPEND_DATA)
}
@_transparent
internal var FILE_ATTRIBUTE_DIRECTORY: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_DIRECTORY)
}
@_transparent
internal var FILE_ATTRIBUTE_NORMAL: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_NORMAL)
}
@_transparent
internal var FILE_ATTRIBUTE_TEMPORARY: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_TEMPORARY)
}
@_transparent
internal var FILE_BEGIN: DWORD {
DWORD(WinSDK.FILE_BEGIN)
}
@_transparent
internal var FILE_CURRENT: DWORD {
DWORD(WinSDK.FILE_CURRENT)
}
@_transparent
internal var FILE_DELETE_CHILD: DWORD {
DWORD(WinSDK.FILE_DELETE_CHILD)
}
@_transparent
package var FILE_EXECUTE: DWORD {
DWORD(WinSDK.FILE_EXECUTE)
}
@_transparent
internal var FILE_FLAG_DELETE_ON_CLOSE: DWORD {
DWORD(WinSDK.FILE_FLAG_DELETE_ON_CLOSE)
}
@_transparent
internal var FILE_FLAG_RANDOM_ACCESS: DWORD {
DWORD(WinSDK.FILE_FLAG_RANDOM_ACCESS)
}
@_transparent
internal var FILE_FLAG_SEQUENTIAL_SCAN: DWORD {
DWORD(WinSDK.FILE_FLAG_SEQUENTIAL_SCAN)
}
@_transparent
package var FILE_READ_ATTRIBUTES: DWORD {
DWORD(WinSDK.FILE_READ_ATTRIBUTES)
}
@_transparent
internal var FILE_READ_DATA: DWORD {
DWORD(WinSDK.FILE_READ_DATA)
}
@_transparent
internal var FILE_READ_EA: DWORD {
DWORD(WinSDK.FILE_READ_EA)
}
@_transparent
internal var FILE_SHARE_DELETE: DWORD {
DWORD(WinSDK.FILE_SHARE_DELETE)
}
@_transparent
internal var FILE_SHARE_READ: DWORD {
DWORD(WinSDK.FILE_SHARE_READ)
}
@_transparent
internal var FILE_SHARE_WRITE: DWORD {
DWORD(WinSDK.FILE_SHARE_WRITE)
}
@_transparent
package var FILE_WRITE_ATTRIBUTES: DWORD {
DWORD(WinSDK.FILE_WRITE_ATTRIBUTES)
}
@_transparent
internal var FILE_WRITE_DATA: DWORD {
DWORD(WinSDK.FILE_WRITE_DATA)
}
@_transparent
internal var FILE_WRITE_EA: DWORD {
DWORD(WinSDK.FILE_WRITE_EA)
}
@_transparent
internal var GENERIC_READ: DWORD {
DWORD(WinSDK.GENERIC_READ)
}
@_transparent
internal var GENERIC_WRITE: DWORD {
DWORD(WinSDK.GENERIC_WRITE)
}
@_transparent
internal var NO_INHERITANCE: DWORD {
DWORD(WinSDK.NO_INHERITANCE)
}
@_transparent
internal var OPEN_ALWAYS: DWORD {
DWORD(WinSDK.OPEN_ALWAYS)
}
@_transparent
internal var OPEN_EXISTING: DWORD {
DWORD(WinSDK.OPEN_EXISTING)
}
@_transparent
internal var SE_DACL_PROTECTED: SECURITY_DESCRIPTOR_CONTROL {
SECURITY_DESCRIPTOR_CONTROL(WinSDK.SE_DACL_PROTECTED)
}
@_transparent
internal var SECURITY_DESCRIPTOR_REVISION: DWORD {
DWORD(WinSDK.SECURITY_DESCRIPTOR_REVISION)
}
@_transparent
internal var SECURITY_WORLD_RID: DWORD {
DWORD(WinSDK.SECURITY_WORLD_RID)
}
@_transparent
internal var STANDARD_RIGHTS_READ: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_READ)
}
@_transparent
internal var STANDARD_RIGHTS_EXECUTE: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE)
}
@_transparent
internal var STANDARD_RIGHTS_WRITE: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_WRITE)
}
@_transparent
internal var SYNCHRONIZE: DWORD {
DWORD(WinSDK.SYNCHRONIZE)
}
@_transparent
internal var TRUNCATE_EXISTING: DWORD {
DWORD(WinSDK.TRUNCATE_EXISTING)
}
#endif
+29 -10
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -19,7 +19,7 @@ import System
import WinSDK
#endif
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
final class ErrnoTest: XCTestCase {
func testConstants() {
XCTAssert(EPERM == Errno.notPermitted.rawValue)
@@ -36,7 +36,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOMEM == Errno.noMemory.rawValue)
XCTAssert(EACCES == Errno.permissionDenied.rawValue)
XCTAssert(EFAULT == Errno.badAddress.rawValue)
#if !os(Windows)
#if !os(Windows) && !os(WASI)
XCTAssert(ENOTBLK == Errno.notBlockDevice.rawValue)
#endif
XCTAssert(EBUSY == Errno.resourceBusy.rawValue)
@@ -74,9 +74,11 @@ final class ErrnoTest: XCTestCase {
XCTAssert(WSAEOPNOTSUPP == Errno.notSupported.rawValue)
XCTAssert(WSAEPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
#else
XCTAssert(ESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
XCTAssert(ENOTSUP == Errno.notSupported.rawValue)
#if !os(WASI)
XCTAssert(ESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
XCTAssert(EPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
#endif
#endif
XCTAssert(EAFNOSUPPORT == Errno.addressFamilyNotSupported.rawValue)
XCTAssert(EADDRINUSE == Errno.addressInUse.rawValue)
@@ -91,7 +93,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOTCONN == Errno.socketNotConnected.rawValue)
#if os(Windows)
XCTAssert(WSAESHUTDOWN == Errno.socketShutdown.rawValue)
#else
#elseif !os(WASI)
XCTAssert(ESHUTDOWN == Errno.socketShutdown.rawValue)
#endif
XCTAssert(ETIMEDOUT == Errno.timedOut.rawValue)
@@ -100,7 +102,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENAMETOOLONG == Errno.fileNameTooLong.rawValue)
#if os(Windows)
XCTAssert(WSAEHOSTDOWN == Errno.hostIsDown.rawValue)
#else
#elseif !os(WASI)
XCTAssert(EHOSTDOWN == Errno.hostIsDown.rawValue)
#endif
XCTAssert(EHOSTUNREACH == Errno.noRouteToHost.rawValue)
@@ -115,7 +117,9 @@ final class ErrnoTest: XCTestCase {
XCTAssert(WSAEDQUOT == Errno.diskQuotaExceeded.rawValue)
XCTAssert(WSAESTALE == Errno.staleNFSFileHandle.rawValue)
#else
#if !os(WASI)
XCTAssert(EUSERS == Errno.tooManyUsers.rawValue)
#endif
XCTAssert(EDQUOT == Errno.diskQuotaExceeded.rawValue)
XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue)
#endif
@@ -131,10 +135,13 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOLCK == Errno.noLocks.rawValue)
XCTAssert(ENOSYS == Errno.noFunction.rawValue)
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
XCTAssert(EFTYPE == Errno.badFileTypeOrFormat.rawValue)
XCTAssert(EAUTH == Errno.authenticationError.rawValue)
XCTAssert(ENEEDAUTH == Errno.needAuthenticator.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EPWROFF == Errno.devicePowerIsOff.rawValue)
XCTAssert(EDEVERR == Errno.deviceError.rawValue)
#endif
@@ -164,21 +171,27 @@ final class ErrnoTest: XCTestCase {
#if !os(Windows)
XCTAssert(EBADMSG == Errno.badMessage.rawValue)
XCTAssert(EMULTIHOP == Errno.multiHop.rawValue)
XCTAssert(ENODATA == Errno.noData.rawValue)
XCTAssert(ENOLINK == Errno.noLink.rawValue)
XCTAssert(EPROTO == Errno.protocolError.rawValue)
#endif
#if !os(Windows) && !os(FreeBSD) && !os(WASI)
XCTAssert(ENODATA == Errno.noData.rawValue)
XCTAssert(ENOSR == Errno.noStreamResources.rawValue)
XCTAssert(ENOSTR == Errno.notStream.rawValue)
XCTAssert(EPROTO == Errno.protocolError.rawValue)
XCTAssert(ETIME == Errno.timeout.rawValue)
#endif
XCTAssert(EOPNOTSUPP == Errno.notSupportedOnSocket.rawValue)
// From headers but not man page
#if !os(WASI) // Would need to use _getConst func from CSystem
XCTAssert(EWOULDBLOCK == Errno.wouldBlock.rawValue)
#endif
#if os(Windows)
XCTAssert(WSAETOOMANYREFS == Errno.tooManyReferences.rawValue)
XCTAssert(WSAEREMOTE == Errno.tooManyRemoteLevels.rawValue)
#else
#elseif !os(WASI)
XCTAssert(ETOOMANYREFS == Errno.tooManyReferences.rawValue)
XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue)
#endif
@@ -192,6 +205,12 @@ final class ErrnoTest: XCTestCase {
XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue)
#endif
#if os(FreeBSD)
XCTAssert(ENOTCAPABLE == Errno.notCapable.rawValue)
XCTAssert(ECAPMODE == Errno.capabilityMode.rawValue)
XCTAssert(EINTEGRITY == Errno.integrityCheckFailed.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EQFULL == Errno.outputQueueFull.rawValue)
XCTAssert(ELAST == Errno.lastErrnoValue.rawValue)
+136
View File
@@ -0,0 +1,136 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if !os(Windows)
import Testing
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
@Suite("FileMode")
private struct FileModeTests {
@available(System 99, *)
@Test func basics() async throws {
var mode = FileMode(rawValue: S_IFREG | 0o644) // Regular file, rw-r--r--
#expect(mode.type == .regular)
#expect(mode.permissions == [.ownerReadWrite, .groupRead, .otherRead])
mode.type = .directory // Directory, rw-r--r--
#expect(mode.type == .directory)
#expect(mode.permissions == [.ownerReadWrite, .groupRead, .otherRead])
mode.permissions.insert([.ownerExecute, .groupExecute, .otherExecute]) // Directory, rwxr-xr-x
#expect(mode.type == .directory)
#expect(mode.permissions == [.ownerReadWriteExecute, .groupReadExecute, .otherReadExecute])
mode.type = .symbolicLink // Symbolic link, rwxr-xr-x
#expect(mode.type == .symbolicLink)
#expect(mode.permissions == [.ownerReadWriteExecute, .groupReadExecute, .otherReadExecute])
let mode1 = FileMode(rawValue: S_IFLNK | 0o755) // Symbolic link, rwxr-xr-x
let mode2 = FileMode(type: .symbolicLink, permissions: [.ownerReadWriteExecute, .groupReadExecute, .otherReadExecute])
#expect(mode == mode1)
#expect(mode1 == mode2)
mode.permissions.remove([.otherReadExecute]) // Symbolic link, rwxr-x---
#expect(mode.permissions == [.ownerReadWriteExecute, .groupReadExecute])
#expect(mode != mode1)
#expect(mode != mode2)
#expect(mode.type == mode1.type)
#expect(mode.type == mode2.type)
}
@available(System 99, *)
@Test func invalidInput() async throws {
// No permissions, all other bits set
var invalidMode = FileMode(rawValue: ~0o7777)
#expect(invalidMode.permissions.isEmpty)
#expect(invalidMode.type != .directory)
#expect(invalidMode.type != .characterSpecial)
#expect(invalidMode.type != .blockSpecial)
#expect(invalidMode.type != .regular)
#expect(invalidMode.type != .fifo)
#expect(invalidMode.type != .symbolicLink)
#expect(invalidMode.type != .socket)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(invalidMode.type != .whiteout)
#endif
// All file-type bits set
invalidMode = FileMode(rawValue: S_IFMT)
#expect(invalidMode.type != .directory)
#expect(invalidMode.type != .characterSpecial)
#expect(invalidMode.type != .blockSpecial)
#expect(invalidMode.type != .regular)
#expect(invalidMode.type != .fifo)
#expect(invalidMode.type != .symbolicLink)
#expect(invalidMode.type != .socket)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(invalidMode.type != .whiteout)
#endif
// FileMode(type:permissions:) masks its inputs so
// they don't accidentally modify the other bits.
let emptyPermissions = FileMode(type: FileType(rawValue: ~0), permissions: [])
#expect(emptyPermissions.permissions.isEmpty)
#expect(emptyPermissions.type == FileType(rawValue: S_IFMT))
#expect(emptyPermissions == invalidMode)
let regularFile = FileMode(type: .regular, permissions: FilePermissions(rawValue: ~0))
#expect(regularFile.type == .regular)
#expect(regularFile.permissions == FilePermissions(rawValue: 0o7777))
#expect(regularFile.permissions == [
.ownerReadWriteExecute,
.groupReadWriteExecute,
.otherReadWriteExecute,
.setUserID, .setGroupID, .saveText
])
// Setting properties should not modify the other bits, either.
var mode = FileMode(rawValue: 0)
mode.type = FileType(rawValue: ~0)
#expect(mode.type == FileType(rawValue: S_IFMT))
#expect(mode.permissions.isEmpty)
mode.type.rawValue = 0
#expect(mode.type == FileType(rawValue: 0))
#expect(mode.permissions.isEmpty)
mode.permissions = FilePermissions(rawValue: ~0)
#expect(mode.permissions == FilePermissions(rawValue: 0o7777))
#expect(mode.type == FileType(rawValue: 0))
mode.permissions = []
#expect(mode.permissions.isEmpty)
#expect(mode.type == FileType(rawValue: 0))
}
}
#endif
+117 -4
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -14,9 +14,15 @@ import XCTest
#else
@testable import System
#endif
#if canImport(Android)
import Android
#elseif os(WASI)
import CSystem
#endif
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
final class FileOperationsTest: XCTestCase {
#if ENABLE_MOCKING && !os(WASI) // Would need to use _getConst funcs from CSystem
func testSyscalls() {
let fd = FileDescriptor(rawValue: 1)
@@ -85,6 +91,7 @@ final class FileOperationsTest: XCTestCase {
for test in syscallTestCases { test.runAllTests() }
}
#endif // ENABLE_MOCKING && !os(WASI)
func testWriteFromEmptyBuffer() throws {
#if os(Windows)
@@ -150,6 +157,7 @@ final class FileOperationsTest: XCTestCase {
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
}
#if !os(WASI) // WASI has no pipe
func testAdHocPipe() throws {
// Ad-hoc test testing `Pipe` functionality.
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
@@ -169,6 +177,105 @@ final class FileOperationsTest: XCTestCase {
}
}
#if !SYSTEM_PACKAGE_DARWIN
func testAdHocPipeWithOptions() throws {
// Ad-hoc test testing `Pipe` functionality.
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
let options: FileDescriptor.PipeOptions = [.closeOnExec]
let pipe: (readEnd: FileDescriptor, writeEnd: FileDescriptor)
pipe = try FileDescriptor.pipe(options: options)
try pipe.readEnd.closeAfter {
try pipe.writeEnd.closeAfter {
var abc = "abc"
try abc.withUTF8 {
_ = try pipe.writeEnd.write(UnsafeRawBufferPointer($0))
}
let readLen = 3
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { buf, count in
count = try pipe.readEnd.read(into: UnsafeMutableRawBufferPointer(buf))
}
XCTAssertEqual(readBytes, Array(abc.utf8))
}
}
}
#endif // !SYSTEM_PACKAGE_DARWIN
#endif // !os(WASI)
#if !os(Windows)
func testAdHocDuplicate2() throws {
try withTemporaryFilePath(basename: "test") {
let path = $0.appending("foo2.txt")
let fd1 = try FileDescriptor.open(path, .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite)
let fd2 = FileDescriptor(rawValue: 731)
let fd3 = try fd1.duplicate(as: fd2)
XCTAssertEqual(fd2, fd3)
try fd2.close()
do {
try fd3.close()
XCTFail("Should be unreachable")
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .badFileDescriptor)
}
}
// dup2() accepts two equal parameters.
let fd4 = try fd1.duplicate(as: fd1)
XCTAssertEqual(fd4, fd1)
try fd1.close()
do {
try fd4.close()
XCTFail("Should be unreachable")
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .badFileDescriptor)
}
}
}
}
#endif // !os(Windows)
#if !SYSTEM_PACKAGE_DARWIN && !os(Windows)
func testAdHocDuplicate3() throws {
try withTemporaryFilePath(basename: "test") {
let path = $0.appending("foo3.txt")
let fd1 = try FileDescriptor.open(path, .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite)
let fd2 = FileDescriptor(rawValue: 731)
let fd3 = try fd1.duplicate(as: fd2, options: [.closeOnExec])
XCTAssertEqual(fd2, fd3)
try fd2.close()
do {
try fd3.close()
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .badFileDescriptor)
}
}
// dup3() does not accept two equal parameters.
do {
_ = try fd1.duplicate(as: fd1, options: [])
XCTFail("Should be unreachable")
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .invalidArgument)
}
}
}
}
#endif // !SYSTEM_PACKAGE_DARWIN && !os(Windows)
func testAdHocOpen() {
// Ad-hoc test touching a file system.
do {
@@ -206,10 +313,16 @@ final class FileOperationsTest: XCTestCase {
}
}
#if ENABLE_MOCKING
func testGithubIssues() {
// https://github.com/apple/swift-system/issues/26
#if os(WASI)
let openOptions = _getConst_O_WRONLY() | _getConst_O_CREAT()
#else
let openOptions = O_WRONLY | O_CREAT
#endif
let issue26 = MockTestCase(
name: "open", .interruptable, "a path", O_WRONLY | O_CREAT, 0o020
name: "open", .interruptable, "a path", openOptions, 0o020
) {
retryOnInterrupt in
_ = try FileDescriptor.open(
@@ -218,8 +331,8 @@ final class FileOperationsTest: XCTestCase {
retryOnInterrupt: retryOnInterrupt)
}
issue26.runAllTests()
}
#endif // ENABLE_MOCKING
func testResizeFile() throws {
try withTemporaryFilePath(basename: "testResizeFile") { path in
@@ -19,6 +19,10 @@ import XCTest
import WinSDK
private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA)
private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE)
private let FILE_READ_ATTRIBUTES = DWORD(WinSDK.FILE_READ_ATTRIBUTES)
@available(iOS 8, *)
final class FileOperationsTestWindows: XCTestCase {
private let r = ACCESS_MASK(
@@ -43,6 +47,8 @@ final class FileOperationsTestWindows: XCTestCase {
| SYNCHRONIZE
)
private let none = ACCESS_MASK(0)
private struct Test {
var permissions: CModeT
var ownerAccess: ACCESS_MASK
@@ -72,7 +78,7 @@ final class FileOperationsTestWindows: XCTestCase {
var psidEveryone: PSID? = nil
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
DWORD(SECURITY_WORLD_RID),
SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&psidEveryone))
defer {
@@ -106,7 +112,7 @@ final class FileOperationsTestWindows: XCTestCase {
&psidGroup,
&pDacl,
nil,
&pSD), DWORD(ERROR_SUCCESS))
&pSD), ERROR_SUCCESS)
defer {
LocalFree(pSD)
}
@@ -135,15 +141,15 @@ final class FileOperationsTestWindows: XCTestCase {
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&owner,
&ownerAccess), DWORD(ERROR_SUCCESS))
&ownerAccess), ERROR_SUCCESS)
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&group,
&groupAccess), DWORD(ERROR_SUCCESS))
&groupAccess), ERROR_SUCCESS)
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&everyone,
&otherAccess), DWORD(ERROR_SUCCESS))
&otherAccess), ERROR_SUCCESS)
return (ownerAccess, groupAccess, otherAccess)
}
@@ -174,14 +180,17 @@ final class FileOperationsTestWindows: XCTestCase {
/// Test that the umask works properly
func testUmask() throws {
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
// Default mask should be 0o022
XCTAssertEqual(FilePermissions.creationMask, [.groupWrite, .otherWrite])
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|x, 0),
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|x, none),
Test(0o777, r|w|x, r|x, r|x)
]
@@ -192,9 +201,9 @@ final class FileOperationsTestWindows: XCTestCase {
.otherWrite, .otherExecute]) {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r, 0),
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r, none),
Test(0o777, r|w|x, r, r)
]
@@ -205,37 +214,87 @@ final class FileOperationsTestWindows: XCTestCase {
/// Test that setting permissions on a file works as expected
func testPermissions() throws {
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
try FilePermissions.withCreationMask([]) {
try withTemporaryFilePath(basename: "testPermissions") { path in
let tests = [
Test(0o000, 0, 0, 0),
Test(0o000, none, none, none),
Test(0o400, r, 0, 0),
Test(0o200, w, 0, 0),
Test(0o100, x, 0, 0),
Test(0o040, 0, r, 0),
Test(0o020, 0, w, 0),
Test(0o010, 0, x, 0),
Test(0o004, 0, 0, r),
Test(0o002, 0, 0, w),
Test(0o001, 0, 0, x),
Test(0o400, r, none, none),
Test(0o200, w, none, none),
Test(0o100, x, none, none),
Test(0o040, none, r, none),
Test(0o020, none, w, none),
Test(0o010, none, x, none),
Test(0o004, none, none, r),
Test(0o002, none, none, w),
Test(0o001, none, none, x),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|w|x, 0),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|w|x, none),
Test(0o777, r|w|x, r|w|x, r|w|x),
Test(0o755, r|w|x, r|x, r|x),
Test(0o644, r|w, r, r),
Test(0o007, 0, 0, r|w|x),
Test(0o070, 0, r|w|x, 0),
Test(0o077, 0, r|w|x, r|w|x),
Test(0o007, none, none, r|w|x),
Test(0o070, none, r|w|x, none),
Test(0o077, none, r|w|x, r|w|x),
]
try runTests(tests, at: path)
}
}
}
/// Test that buffer sizes exceeding DWORD.max (4GB) are properly rejected
func testBufferSizeLimit() throws {
try withTemporaryFilePath(basename: "testBufferSizeLimit") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"),
.readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
defer { try? fd.close() }
// Write some data first
try fd.writeAll("test data".utf8)
// Allocate a small buffer for testing
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 1)
defer { buffer.deallocate() }
// Test that a count exceeding DWORD.max (UInt32.max = 4,294,967,295) returns EINVAL
// We use a buffer pointer but pass a count > DWORD.max
let oversizedCount = Int(DWORD.max) + 1
let oversizedBuffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress,
count: oversizedCount
)
// pread should fail with EINVAL
do {
_ = try fd.read(fromAbsoluteOffset: 0, into: oversizedBuffer)
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// pwrite should also fail with EINVAL
do {
_ = try fd.write(toAbsoluteOffset: 0, UnsafeRawBufferPointer(oversizedBuffer))
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// Verify that exactly DWORD.max works (if we had a buffer that large)
// We can't easily test this without allocating 4GB, but the boundary is correct
}
}
}
#endif // os(Windows)
@@ -15,7 +15,7 @@ import XCTest
@testable import System
#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, *)
struct TestPathComponents: TestCase {
var path: FilePath
var expectedRoot: FilePath.Root?
@@ -100,14 +100,14 @@ struct TestPathComponents: TestCase {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
final class FilePathComponentsTest: XCTestCase {
func testAdHocRRC() {
var path: FilePath = "/usr/local/bin"
func expect(
_ s: String,
_ file: StaticString = #file,
_ file: StaticString = #filePath,
_ line: UInt = #line
) {
if path == FilePath(s) { return }
@@ -15,7 +15,7 @@ import XCTest
@testable import System
#endif
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
final class FilePathDecodableTest: XCTestCase {
func testInvalidFilePath() {
// _storage is a valid SystemString, but the invariants of FilePath are
@@ -6,7 +6,7 @@
#endif
// Why can't I write this extension on `FilePath.ComponentView.SubSequence`?
@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 Slice where Base == FilePath.ComponentView {
internal var _storageSlice: SystemString.SubSequence {
base._path._storage[self.startIndex._storage ..< self.endIndex._storage]
@@ -15,7 +15,7 @@ extension Slice where Base == FilePath.ComponentView {
// Proposed API that didn't make the cut, but we stil want to keep our testing for
@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 `self` relative to `base`.
/// This does not cosult the file system or resolve symlinks.
@@ -7,6 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
#if ENABLE_MOCKING
import XCTest
#if SYSTEM_PACKAGE
@@ -68,7 +69,7 @@ extension ParsingTestCase {
@testable import System
#endif
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
final class FilePathParsingTest: XCTestCase {
func testNormalization() {
let unixPaths: Array<ParsingTestCase> = [
@@ -105,3 +106,4 @@ final class FilePathParsingTest: XCTestCase {
}
}
}
#endif // ENABLE_MOCKING
@@ -7,6 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
#if ENABLE_MOCKING
import XCTest
#if SYSTEM_PACKAGE
@@ -146,7 +147,7 @@ extension SyntaxTestCase {
}
}
@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 SyntaxTestCase {
func testComponents(_ path: FilePath, expected: [String]) {
let expectedComponents = expected.map { FilePath.Component($0)! }
@@ -342,7 +343,7 @@ private struct WindowsRootTestCase: TestCase {
var line: UInt
}
@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 WindowsRootTestCase {
func runAllTests() {
withWindowsPaths(enabled: true) {
@@ -357,7 +358,7 @@ extension WindowsRootTestCase {
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
final class FilePathSyntaxTest: XCTestCase {
func testPathSyntax() {
let unixPaths: Array<SyntaxTestCase> = [
@@ -849,7 +850,7 @@ final class FilePathSyntaxTest: XCTestCase {
func expect(
_ s: String,
_ file: StaticString = #file,
_ file: StaticString = #filePath,
_ line: UInt = #line
) {
if path == FilePath(s) { return }
@@ -1238,3 +1239,4 @@ final class FilePathSyntaxTest: XCTestCase {
}
}
#endif // ENABLE_MOCKING
@@ -15,7 +15,7 @@ import SystemPackage
import System
#endif
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
func filePathFromInvalidCodePointSequence<S: Sequence>(_ bytes: S) -> FilePath where S.Element == CInterop.PlatformUnicodeEncoding.CodeUnit {
var array = Array(bytes)
assert(array.last != 0, "already null terminated")
@@ -28,7 +28,7 @@ func filePathFromInvalidCodePointSequence<S: Sequence>(_ bytes: S) -> FilePath w
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@available(System 0.0.2, *)
final class FilePathTest: XCTestCase {
struct TestPath {
let filePath: FilePath
+17 -5
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -14,8 +14,11 @@ import SystemPackage
#else
import System
#endif
#if canImport(Android)
import Android
#endif
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
final class FileDescriptorTest: XCTestCase {
func testStandardDescriptors() {
XCTAssertEqual(FileDescriptor.standardInput.rawValue, 0)
@@ -29,6 +32,7 @@ final class FileDescriptorTest: XCTestCase {
XCTAssertEqual(O_WRONLY, FileDescriptor.AccessMode.writeOnly.rawValue)
XCTAssertEqual(O_RDWR, FileDescriptor.AccessMode.readWrite.rawValue)
#if !os(WASI) // Would need to use _getConst funcs from CSystem
#if !os(Windows)
XCTAssertEqual(O_NONBLOCK, FileDescriptor.OpenOptions.nonBlocking.rawValue)
#endif
@@ -36,24 +40,32 @@ final class FileDescriptorTest: XCTestCase {
XCTAssertEqual(O_CREAT, FileDescriptor.OpenOptions.create.rawValue)
XCTAssertEqual(O_TRUNC, FileDescriptor.OpenOptions.truncate.rawValue)
XCTAssertEqual(O_EXCL, FileDescriptor.OpenOptions.exclusiveCreate.rawValue)
#endif // !os(WASI
#if !os(Windows)
XCTAssertEqual(O_NOFOLLOW, FileDescriptor.OpenOptions.noFollow.rawValue)
XCTAssertEqual(O_CLOEXEC, FileDescriptor.OpenOptions.closeOnExec.rawValue)
#endif
// BSD only
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue)
XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue)
XCTAssertEqual(O_EVTONLY, FileDescriptor.OpenOptions.eventOnly.rawValue)
#endif
#if os(FreeBSD)
XCTAssertEqual(O_SYNC, FileDescriptor.OpenOptions.sync.rawValue)
#endif
XCTAssertEqual(SEEK_SET, FileDescriptor.SeekOrigin.start.rawValue)
XCTAssertEqual(SEEK_CUR, FileDescriptor.SeekOrigin.current.rawValue)
XCTAssertEqual(SEEK_END, FileDescriptor.SeekOrigin.end.rawValue)
#if SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
XCTAssertEqual(SEEK_HOLE, FileDescriptor.SeekOrigin.nextHole.rawValue)
XCTAssertEqual(SEEK_DATA, FileDescriptor.SeekOrigin.nextData.rawValue)
#endif
@@ -64,7 +76,7 @@ final class FileDescriptorTest: XCTestCase {
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
@available(System 0.0.1, *)
final class FilePermissionsTest: XCTestCase {
func testPermissions() {
+35
View File
@@ -0,0 +1,35 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import XCTest
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
import System
#endif
func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
return withUnsafePointer(to: request.rawValue) {
let requestBuf = UnsafeBufferPointer(start: $0, count: 1)
let rawBytes = UnsafeRawBufferPointer(requestBuf)
return .init(rawBytes)
}
}
// This test suite compares various IORequests bit-for-bit to IORequests
// that were generated with liburing or manually written out,
// which are known to work correctly.
final class IORequestTests: XCTestCase {
func testNop() {
let req = IORing.Request.nop().makeRawRequest(
pathBuffers: PendingPathBuffers(reservedCapacity: 0))
let sourceBytes = requestBytes(req)
// convenient property of nop: it's all zeros!
// for some unknown reason, liburing sets the fd field to -1.
// we're not trying to be bug-compatible with it, so 0 *should* work.
XCTAssertEqual(sourceBytes, .init(repeating: 0, count: 64))
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+207
View File
@@ -0,0 +1,207 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import XCTest
import CSystem //for eventfd
#if SYSTEM_PACKAGE
import SystemPackage
#else
import System
#endif
func uringEnabled() throws -> Bool {
do {
let procPath = FilePath("/proc/sys/kernel/io_uring_disabled")
let fd = try FileDescriptor.open(procPath, .readOnly)
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0)
_ = try fd.read(into: buffer)
if buffer.load(fromByteOffset: 0, as: Int.self) == 0 {
return true
}
} catch (_) {
return false
}
return false
}
final class IORingTests: XCTestCase {
func testInit() throws {
guard try uringEnabled() else { return }
_ = try IORing(queueDepth: 32, flags: [])
}
func testNop() throws {
guard try uringEnabled() else { return }
var ring = try IORing(queueDepth: 32, flags: [])
_ = try ring.submit(linkedRequests: .nop())
let completion = try ring.blockingConsumeCompletion()
XCTAssertEqual(completion.result, 0)
}
func makeHelloWorldFile() throws -> (dir: FileDescriptor, file: FilePath) {
mkdir("/tmp/IORingTests/", 0o777)
let path: FilePath = "/tmp/IORingTests/test.txt"
let fd = try FileDescriptor.open(
path,
.readWrite,
options: .create,
permissions: .ownerReadWrite
)
try fd.writeAll("Hello, World!".utf8)
try fd.close()
let parent = try FileDescriptor.open("/tmp/IORingTests/", .readOnly)
return (parent, path)
}
func cleanUpHelloWorldFile(_ parent: FileDescriptor) throws {
try parent.close()
rmdir("/tmp/IORingTests/")
}
func setupTestRing(depth: Int, fileSlots: Int, buffers: [UnsafeMutableRawBufferPointer]) throws -> IORing {
var ring: IORing = try IORing(queueDepth: UInt32(depth))
_ = try ring.registerFileSlots(count: 1)
_ = try ring.registerBuffers(buffers)
return ring
}
func testUndersizedSubmissionQueue() throws {
guard try uringEnabled() else { return }
var ring: IORing = try IORing(queueDepth: 1)
let enqueued = ring.prepare(linkedRequests: .nop(), .nop())
XCTAssertFalse(enqueued)
}
// Exercises opening, reading, closing, registered files, registered buffers, and eventfd
func testOpenReadAndWriteFixedFile() throws {
guard try uringEnabled() else { return }
let (parent, path) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
let eventFD = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE)))
try ring.registerEventFD(eventFD)
//Part 1: read the file we just created, and make sure the eventfd fires
let enqueued = try ring.submit(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly),
.read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]),
.close(ring.registeredFileSlots[0]))
XCTAssert(enqueued)
let efdBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 0)
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //open
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //read
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //close
let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result, "Hello, World!")
//Part 2: delete that file, then use the ring to write out a new one
let rmResult = path.withPlatformString {
remove($0)
}
XCTAssertEqual(rmResult, 0)
let enqueued2 = try ring.submit(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readWrite, options: .create, permissions: .ownerReadWrite),
.write(ring.registeredBuffers[0], into: ring.registeredFileSlots[0]),
.close(ring.registeredFileSlots[0]))
XCTAssert(enqueued2)
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //open
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //write
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //close
memset(rawBuffer.baseAddress!, 0, rawBuffer.count)
//Verify using a non-ring IO method that what we wrote matches our expectations
print("about to open")
let nonRingFD = try FileDescriptor.open(path, .readOnly)
let bytesRead = try nonRingFD.read(into: rawBuffer)
XCTAssert(bytesRead == 13)
let result2 = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result2, "Hello, World!")
try cleanUpHelloWorldFile(parent)
efdBuf.deallocate()
rawBuffer.deallocate()
}
// Prior to the fix this is testing, prepare() escaped a pointer obtained
// inside `path.withPlatformString { ... }` into the SQE and dropped the
// owning FilePath before submit, so io_uring_enter handed the kernel a
// dangling pointer. Here we deliberately let the FilePath go out of scope
// between prepare and submit, then churn the heap to make UAFs observable.
func testPathBufferLifetimeAcrossPrepareSubmit() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
var ring = try IORing(queueDepth: 6)
func enqueueOpen() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly))
XCTAssertTrue(ok)
}
enqueueOpen()
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
}
for buf in churn { buf.deallocate() }
churn.removeAll()
try ring.submitPreparedRequests()
let completion = try ring.blockingConsumeCompletion()
XCTAssertGreaterThanOrEqual(
completion.result, 0,
"open should succeed; got \(completion.result)")
if completion.result >= 0 {
let fd = FileDescriptor(rawValue: Int32(completion.result))
try fd.close()
}
try cleanUpHelloWorldFile(parent)
}
func testPathBufferLifetimeAcrossLinkedRequests() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
func enqueueLinkedReadback() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly),
.read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]),
.close(ring.registeredFileSlots[0]))
XCTAssertTrue(ok)
}
enqueueLinkedReadback()
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
}
for buf in churn { buf.deallocate() }
try ring.submitPreparedRequests()
_ = try ring.blockingConsumeCompletion() // open
_ = try ring.blockingConsumeCompletion() // read
_ = try ring.blockingConsumeCompletion() // close
let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result, "Hello, World!")
try cleanUpHelloWorldFile(parent)
rawBuffer.deallocate()
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+3 -3
View File
@@ -1,13 +1,13 @@
/*
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 swift(>=5.9) && SYSTEM_PACKAGE_DARWIN
#if SYSTEM_PACKAGE_DARWIN
import XCTest
import Darwin.Mach
@@ -18,7 +18,7 @@ import SystemPackage
import System
#endif
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@available(System 1.4.0, *)
final class MachPortTests: XCTestCase {
func refCountForMachPortName(name:mach_port_name_t, kind:mach_port_right_t) -> mach_port_urefs_t {
var refCount:mach_port_urefs_t = .max
+3 -1
View File
@@ -7,6 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
#if ENABLE_MOCKING
import XCTest
#if SYSTEM_PACKAGE
@@ -15,7 +16,7 @@ import XCTest
@testable import System
#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, *)
final class MockingTest: XCTestCase {
func testMocking() {
XCTAssertFalse(mockingEnabled)
@@ -48,3 +49,4 @@ final class MockingTest: XCTestCase {
XCTAssertFalse(mockingEnabled)
}
}
#endif // ENABLE_MOCKING
+419
View File
@@ -0,0 +1,419 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if !os(Windows)
import Testing
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import 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
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
@Suite("Stat")
private struct StatTests {
@available(System 99, *)
@Test func basics() async throws {
try withTemporaryFilePath(basename: "Stat_basics") { tempDir in
let dirStatFromFilePath = try tempDir.stat()
#expect(dirStatFromFilePath.type == .directory)
let dirFD = try FileDescriptor.open(tempDir, .readOnly)
defer {
try? dirFD.close()
}
let dirStatFromFD = try dirFD.stat()
#expect(dirStatFromFD.type == .directory)
let dirStatFromCString = try tempDir.withPlatformString { try Stat($0) }
#expect(dirStatFromCString.type == .directory)
#expect(dirStatFromFilePath == dirStatFromFD)
#expect(dirStatFromFD == dirStatFromCString)
let tempFile = tempDir.appending("test.txt")
let fileFD = try FileDescriptor.open(tempFile, .readWrite, options: .create, permissions: [.ownerReadWrite, .groupRead, .otherRead])
defer {
try? fileFD.close()
}
try fileFD.writeAll("Hello, world!".utf8)
let fileStatFromFD = try fileFD.stat()
#expect(fileStatFromFD.type == .regular)
#expect(fileStatFromFD.permissions == [.ownerReadWrite, .groupRead, .otherRead])
#expect(fileStatFromFD.size == "Hello, world!".utf8.count)
let fileStatFromFilePath = try tempFile.stat()
#expect(fileStatFromFilePath.type == .regular)
let fileStatFromCString = try tempFile.withPlatformString { try Stat($0) }
#expect(fileStatFromCString.type == .regular)
#expect(fileStatFromFD == fileStatFromFilePath)
#expect(fileStatFromFilePath == fileStatFromCString)
}
}
@available(System 99, *)
@Test func followSymlinkInits() async throws {
try withTemporaryFilePath(basename: "Stat_followSymlinkInits") { tempDir in
let targetFilePath = tempDir.appending("target.txt")
let symlinkPath = tempDir.appending("symlink")
let targetFD = try FileDescriptor.open(targetFilePath, .readWrite, options: .create, permissions: .ownerReadWrite)
defer {
try? targetFD.close()
}
try targetFD.writeAll(Array(repeating: UInt8(ascii: "A"), count: 1025))
try targetFilePath.withPlatformString { targetPtr in
try symlinkPath.withPlatformString { symlinkPtr in
try #require(symlink(targetPtr, symlinkPtr) == 0, "\(Errno.current)")
}
}
// Can't open an fd to a symlink on WASI (no O_PATH)
// On non-Darwin, we need O_PATH | O_NOFOLLOW to open the symlink
// directly, but O_PATH requires _GNU_SOURCE be defined (TODO).
#if SYSTEM_PACKAGE_DARWIN
let symlinkFD = try FileDescriptor.open(symlinkPath, .readOnly, options: .symlink)
defer {
try? symlinkFD.close()
}
#endif
let targetStat = try targetFilePath.stat()
let originalTargetAccessTime = targetStat.st_atim
let symlinkStat = try symlinkPath.stat(followTargetSymlink: false)
let originalSymlinkAccessTime = symlinkStat.st_atim
#expect(targetStat != symlinkStat)
#expect(targetStat.type == .regular)
#expect(symlinkStat.type == .symbolicLink)
#expect(symlinkStat.size < targetStat.size)
#expect(symlinkStat.sizeAllocated <= targetStat.sizeAllocated)
// Set each .st_atim back to its original value for comparison
// FileDescriptor Extensions
var stat = try targetFD.stat()
stat.st_atim = originalTargetAccessTime
#expect(stat == targetStat)
#if SYSTEM_PACKAGE_DARWIN
stat = try symlinkFD.stat()
stat.st_atim = originalSymlinkAccessTime
#expect(stat == symlinkStat)
#endif
// Initializing Stat with FileDescriptor
stat = try Stat(targetFD)
stat.st_atim = originalTargetAccessTime
#expect(stat == targetStat)
#if SYSTEM_PACKAGE_DARWIN
stat = try Stat(symlinkFD)
stat.st_atim = originalSymlinkAccessTime
#expect(stat == symlinkStat)
#endif
// FilePath Extensions
stat = try symlinkPath.stat(followTargetSymlink: true)
stat.st_atim = originalTargetAccessTime
#expect(stat == targetStat)
stat = try symlinkPath.stat(followTargetSymlink: false)
stat.st_atim = originalSymlinkAccessTime
#expect(stat == symlinkStat)
// Initializing Stat with UnsafePointer<CChar>
try symlinkPath.withPlatformString { pathPtr in
stat = try Stat(pathPtr, followTargetSymlink: true)
stat.st_atim = originalTargetAccessTime
#expect(stat == targetStat)
stat = try Stat(pathPtr, followTargetSymlink: false)
stat.st_atim = originalSymlinkAccessTime
#expect(stat == symlinkStat)
}
// Initializing Stat with FilePath
stat = try Stat(symlinkPath, followTargetSymlink: true)
stat.st_atim = originalTargetAccessTime
#expect(stat == targetStat)
stat = try Stat(symlinkPath, followTargetSymlink: false)
stat.st_atim = originalSymlinkAccessTime
#expect(stat == symlinkStat)
// Initializing Stat with String
stat = try Stat(symlinkPath.string, followTargetSymlink: true)
stat.st_atim = originalTargetAccessTime
#expect(stat == targetStat)
stat = try Stat(symlinkPath.string, followTargetSymlink: false)
stat.st_atim = originalSymlinkAccessTime
#expect(stat == symlinkStat)
}
}
@available(System 99, *)
@Test func permissions() async throws {
try withTemporaryFilePath(basename: "Stat_permissions") { tempDir in
let testFile = tempDir.appending("test.txt")
let fd = try FileDescriptor.open(testFile, .writeOnly, options: .create, permissions: [.ownerReadWrite, .groupRead, .otherRead])
try fd.close()
let stat = try testFile.stat()
#expect(stat.type == .regular)
#expect(stat.permissions == [.ownerReadWrite, .groupRead, .otherRead])
var newMode = stat.mode
newMode.permissions.insert(.ownerExecute)
try testFile.withPlatformString { pathPtr in
try #require(chmod(pathPtr, newMode.permissions.rawValue) == 0, "\(Errno.current)")
}
let updatedStat = try testFile.stat()
#expect(updatedStat.permissions == newMode.permissions)
newMode.permissions.remove(.ownerWriteExecute)
try testFile.withPlatformString { pathPtr in
try #require(chmod(pathPtr, newMode.permissions.rawValue) == 0, "\(Errno.current)")
}
let readOnlyStat = try testFile.stat()
#expect(readOnlyStat.permissions == newMode.permissions)
}
}
@available(System 99, *)
@Test func times() async throws {
var start = timespec()
try #require(clock_gettime(CLOCK_REALTIME, &start) == 0, "\(Errno.current)")
start.tv_sec -= 1 // A little wiggle room
try withTemporaryFilePath(basename: "Stat_times") { tempDir in
var dirStat = try tempDir.stat()
let dirAccessTime0 = dirStat.st_atim
let dirModificationTime0 = dirStat.st_mtim
let dirChangeTime0 = dirStat.st_ctim
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
let dirCreationTime0 = dirStat.st_birthtim
#endif
var startUpperBound = start
startUpperBound.tv_sec += 5
#expect(dirAccessTime0 >= start)
#expect(dirAccessTime0 < startUpperBound)
#expect(dirModificationTime0 >= start)
#expect(dirModificationTime0 < startUpperBound)
#expect(dirChangeTime0 >= start)
#expect(dirChangeTime0 < startUpperBound)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(dirCreationTime0 >= start)
#expect(dirCreationTime0 < startUpperBound)
#endif
// Fails intermittently if less than 5ms
usleep(10000)
let file1 = tempDir.appending("test1.txt")
let fd1 = try FileDescriptor.open(file1, .writeOnly, options: .create, permissions: .ownerReadWrite)
defer {
try? fd1.close()
}
dirStat = try tempDir.stat()
let dirAccessTime1 = dirStat.st_atim
let dirModificationTime1 = dirStat.st_mtim
let dirChangeTime1 = dirStat.st_ctim
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
let dirCreationTime1 = dirStat.st_birthtim
#endif
// Creating a file updates directory modification and change time.
// Access time may not be updated depending on mount options like NOATIME.
#expect(dirModificationTime1 > dirModificationTime0)
#expect(dirChangeTime1 > dirChangeTime0)
#expect(dirAccessTime1 >= dirAccessTime0)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(dirCreationTime1 == dirCreationTime0)
#endif
usleep(10000)
// Changing permissions only updates directory change time
try tempDir.withPlatformString { pathPtr in
var newMode = dirStat.mode
// tempDir only starts with .ownerReadWriteExecute
newMode.permissions.insert(.groupReadWriteExecute)
try #require(chmod(pathPtr, newMode.rawValue) == 0, "\(Errno.current)")
}
dirStat = try tempDir.stat()
let dirChangeTime2 = dirStat.st_ctim
#expect(dirChangeTime2 > dirChangeTime1)
#expect(dirStat.st_atim == dirAccessTime1)
#expect(dirStat.st_mtim == dirModificationTime1)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(dirStat.st_birthtim == dirCreationTime1)
#endif
var stat1 = try file1.stat()
let file1AccessTime1 = stat1.st_atim
let file1ModificationTime1 = stat1.st_mtim
let file1ChangeTime1 = stat1.st_ctim
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
let file1CreationTime1 = stat1.st_birthtim
#endif
usleep(10000)
try fd1.writeAll("Hello, world!".utf8)
stat1 = try file1.stat()
let file1AccessTime2 = stat1.st_atim
let file1ModificationTime2 = stat1.st_mtim
let file1ChangeTime2 = stat1.st_ctim
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
let file1CreationTime2 = stat1.st_birthtim
#endif
#expect(file1AccessTime2 >= file1AccessTime1)
#expect(file1ModificationTime2 > file1ModificationTime1)
#expect(file1ChangeTime2 > file1ChangeTime1)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(file1CreationTime2 == file1CreationTime1)
#endif
// Changing file metadata or content does not update directory times
dirStat = try tempDir.stat()
#expect(dirStat.st_ctim == dirChangeTime2)
#expect(dirStat.st_atim == dirAccessTime1)
#expect(dirStat.st_mtim == dirModificationTime1)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(dirStat.st_birthtim == dirCreationTime1)
#endif
usleep(10000)
let file2 = tempDir.appending("test2.txt")
let fd2 = try FileDescriptor.open(file2, .writeOnly, options: .create, permissions: .ownerReadWrite)
defer {
try? fd2.close()
}
let stat2 = try file2.stat()
#expect(stat2.st_atim > file1AccessTime2)
#expect(stat2.st_mtim > file1ModificationTime2)
#expect(stat2.st_ctim > file1ChangeTime2)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(stat2.st_birthtim > file1CreationTime2)
#endif
}
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 99, *)
@Test func flags() async throws {
try withTemporaryFilePath(basename: "Stat_flags") { tempDir in
let filePath = tempDir.appending("test.txt")
let fd = try FileDescriptor.open(filePath, .writeOnly, options: .create, permissions: .ownerReadWrite)
defer {
try? fd.close()
}
var stat = try fd.stat()
var flags = stat.flags
#if SYSTEM_PACKAGE_DARWIN
let userSettableFlags: FileFlags = [
.noDump, .userImmutable, .userAppend,
.opaque, .tracked, .hidden,
/* .dataVault (throws EPERM when testing) */
]
#elseif os(FreeBSD)
let userSettableFlags: FileFlags = [
.noDump, .hidden, .offline,
.readOnly, .sparse, .system
// The following flags throw EPERM on ZFS.
// .userImmutable, .userAppend, .opaque,
// .userNoUnlink, .reparse,
]
#else // os(OpenBSD)
let userSettableFlags: FileFlags = [
.noDump, .userImmutable, .userAppend
]
#endif
flags.insert(userSettableFlags)
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
stat = try fd.stat()
#expect(stat.flags == flags)
flags.remove(userSettableFlags)
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
stat = try fd.stat()
#expect(stat.flags == flags)
}
}
#endif
}
// Comparison operators for timespec until UTCClock.Instant properties are available
private func >= (lhs: timespec, rhs: timespec) -> Bool {
(lhs.tv_sec, lhs.tv_nsec) >= (rhs.tv_sec, rhs.tv_nsec)
}
private func < (lhs: timespec, rhs: timespec) -> Bool {
(lhs.tv_sec, lhs.tv_nsec) < (rhs.tv_sec, rhs.tv_nsec)
}
private func > (lhs: timespec, rhs: timespec) -> Bool {
(lhs.tv_sec, lhs.tv_nsec) > (rhs.tv_sec, rhs.tv_nsec)
}
private func == (lhs: timespec, rhs: timespec) -> Bool {
lhs.tv_sec == rhs.tv_sec && lhs.tv_nsec == rhs.tv_nsec
}
#endif
@@ -17,6 +17,7 @@ import XCTest
internal struct Wildcard: Hashable {}
#if ENABLE_MOCKING
extension Trace.Entry {
/// This implements `==` with wildcard matching.
/// (`Entry` cannot conform to `Equatable`/`Hashable` this way because
@@ -33,9 +34,10 @@ extension Trace.Entry {
return true
}
}
#endif // ENABLE_MOCKING
// To aid debugging, force failures to fatal error
internal var forceFatalFailures = false
internal let forceFatalFailures = false
internal protocol TestCase {
// TODO: want a source location stack, more fidelity, kinds of stack entries, etc
@@ -81,6 +83,7 @@ extension TestCase {
fail(message)
}
}
#if ENABLE_MOCKING
func expectMatch(
_ expected: Trace.Entry?, _ actual: Trace.Entry?,
_ message: String? = nil
@@ -102,6 +105,7 @@ extension TestCase {
fail(message)
}
}
#endif // ENABLE_MOCKING
func expectNil<T>(
_ actual: T?,
_ message: String? = nil
@@ -142,6 +146,7 @@ extension TestCase {
}
#if ENABLE_MOCKING
internal struct MockTestCase: TestCase {
var file: StaticString
var line: UInt
@@ -241,6 +246,7 @@ internal struct MockTestCase: TestCase {
}
}
}
#endif // ENABLE_MOCKING
internal func withWindowsPaths(enabled: Bool, _ body: () -> ()) {
_withWindowsPaths(enabled: enabled, body)
+1 -1
View File
@@ -34,7 +34,7 @@ class UtilTests: XCTestCase {
func testCStringArray() {
func check(
_ array: [String],
file: StaticString = #file,
file: StaticString = #filePath,
line: UInt = #line
) {
array._withCStringArray { carray in
-117
View File
@@ -1,117 +0,0 @@
#!/usr/bin/env python3
# This script can be used to automatically add/remove `@available` attributes to
# declarations in Swift sources in this package.
#
# In order for this to work, ABI-impacting declarations need to be annotated
# with special comments in the following format:
#
# @available(/*System 0.0.2*/iOS 8, *)
# public func greeting() -> String {
# "Hello"
# }
#
# (The iOS 8 availability is a dummy no-op declaration -- it only has to be
# there because `@available(*)` isn't valid syntax, and commenting out the
# entire `@available` attribute would interfere with parser tools for doc
# comments. `iOS 8` is the shortest version string that matches the minimum
# possible deployment target for Swift code, so we use that as our dummy
# availability version. `@available(iOS 8, *)` is functionally equivalent to not
# having an `@available` attribute at all.)
#
# The script adds full availability incantations to these comments. It can run
# in one of two modes:
#
# By default, `expand-availability.py` expands availability macros within the
# comments. This is useful during package development to cross-reference
# availability across `SystemPackage` and the ABI-stable `System` module that
# ships in Apple's OS releases:
#
# @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
# public func greeting() -> String {
# "Hello"
# }
#
# `expand-availability.py --attributes` adds actual availability declarations.
# This is used by maintainers to build ABI stable releases of System on Apple's
# platforms:
#
# @available(/*System 0.0.2: */macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
# public func greeting() -> String {
# "Hello"
# }
#
# The script recognizes all three forms of these annotations and updates them on
# every run, so we can run the script to enable/disable attributes as needed.
import os
import os.path
import fileinput
import re
import sys
import argparse
versions = {
"System 0.0.1": "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0",
"System 0.0.2": "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0",
"System 1.1.0": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4",
"System 1.2.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
"System 1.3.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
"System 1.4.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
}
parser = argparse.ArgumentParser(description="Expand availability macros.")
parser.add_argument("--attributes", help="Add @available attributes",
action="store_true")
args = parser.parse_args()
def swift_sources_in(path):
result = []
for (dir, _, files) in os.walk(path):
for file in files:
extension = os.path.splitext(file)[1]
if extension == ".swift":
result.append(os.path.join(dir, file))
return result
# Old-style syntax:
# /*System 0.0.2*/
# /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
# /*System 0.0.2*/@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
old_macro_pattern = re.compile(
r"/\*(System [^ *]+)(, @available\([^)]*\))?\*/(@available\([^)]*\))?")
# New-style comments:
# @available(/*SwiftSystem 0.0.2*/macOS 10, *)
# @available(/*SwiftSystem 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
# @available(/*SwiftSystem 0.0.2*/macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
#
# These do not interfere with our tools' ability to find doc comments.
macro_pattern = re.compile(
r"@available\(/\*(System [^ *:]+)[^*/)]*\*/([^)]*)\*\)")
def available_attribute(filename, lineno, symbolic_version):
expansion = versions[symbolic_version]
if expansion is None:
raise ValueError("{0}:{1}: error: Unknown System version '{0}'"
.format(fileinput.filename(), fileinput.lineno(), symbolic_version))
if args.attributes:
attribute = "@available(/*{0}*/{1}, *)".format(symbolic_version, expansion)
else:
# Sadly `@available(*)` is not valid syntax, so we have to mention at
# least one actual platform here.
attribute = "@available(/*{0}: {1}*/iOS 8, *)".format(symbolic_version, expansion)
return attribute
sources = swift_sources_in("Sources") + swift_sources_in("Tests")
for line in fileinput.input(files=sources, inplace=True):
match = re.search(macro_pattern, line)
if match is None:
match = re.search(old_macro_pattern, line)
if match:
symbolic_version = match.group(1)
replacement = available_attribute(
fileinput.filename(), fileinput.lineno(), symbolic_version)
line = line[:match.start()] + replacement + line[match.end():]
print(line, end="")
+30 -10
View File
@@ -36,7 +36,7 @@ function(get_swift_host_arch result_var_name)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
set("${result_var_name}" "armv7" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "amd64")
set("${result_var_name}" "amd64" PARENT_SCOPE)
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
@@ -45,6 +45,8 @@ function(get_swift_host_arch result_var_name)
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "riscv64")
set("${result_var_name}" "riscv64" PARENT_SCOPE)
else()
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
endif()
@@ -67,6 +69,28 @@ function(get_swift_host_os result_var_name)
endif()
endfunction()
if(NOT Swift_MODULE_TRIPLE)
# Attempt to get the module triple from the Swift compiler.
set(module_triple_command "${CMAKE_Swift_COMPILER}" -print-target-info)
if(CMAKE_Swift_COMPILER_TARGET)
list(APPEND module_triple_command -target ${CMAKE_Swift_COMPILER_TARGET})
endif()
execute_process(COMMAND ${module_triple_command}
OUTPUT_VARIABLE target_info_json)
string(JSON module_triple GET "${target_info_json}" "target" "moduleTriple")
# Exit now if we failed to infer the triple.
if(NOT module_triple)
message(FATAL_ERROR
"Failed to get module triple from Swift compiler. "
"Compiler output: ${target_info_json}")
endif()
# Cache the module triple for future use.
set(Swift_MODULE_TRIPLE "${module_triple}" CACHE STRING "swift module triple used for installed swiftmodule and swiftinterface files")
mark_as_advanced(Swift_MODULE_TRIPLE)
endif()
function(_install_target module)
get_swift_host_os(swift_os)
get_target_property(type ${module} TYPE)
@@ -77,24 +101,20 @@ function(_install_target module)
set(swift swift)
endif()
install(TARGETS ${module}
ARCHIVE DESTINATION lib/${swift}/${swift_os}
LIBRARY DESTINATION lib/${swift}/${swift_os}
RUNTIME DESTINATION bin)
install(TARGETS ${module})
if(type STREQUAL EXECUTABLE)
return()
endif()
get_swift_host_arch(swift_arch)
get_target_property(module_name ${module} Swift_MODULE_NAME)
if(NOT module_name)
set(module_name ${module})
endif()
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftdoc
DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${swift_arch}.swiftdoc)
DESTINATION ${CMAKE_INSTALL_LIBDIR}/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${Swift_MODULE_TRIPLE}.swiftdoc)
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftmodule
DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${swift_arch}.swiftmodule)
DESTINATION ${CMAKE_INSTALL_LIBDIR}/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${Swift_MODULE_TRIPLE}.swiftmodule)
endfunction()