Compare commits

...
177 Commits
Author SHA1 Message Date
Guillaume Lessard 640e5755b5 Merge pull request #421 from 100lalitahegde-eng/fix-156-thread-safe-strerror
Use a thread-safe strerror in Errno.description
2026-11-12 10:22:43 -08:00
Lalita Hegade 1c44ed678c Copy strerror message directly into the String buffer
Use String(unsafeUninitializedCapacity:initializingUTF8With:), through
the existing backwards-compatible helper, so the message is written
straight into the string's storage instead of a stack buffer that is
then copied. Also update the copyright year range of Errno.swift.

musl's message for an unknown error number doesn't include the number,
so skip that check when building against Musl, as on WASI.
2026-11-12 08:13:35 +01:00
Lalita Hegade 6c5077b2d2 Report truncated strerror messages as ERANGE on every platform
strerror_s on Windows and bionic's strerror_r truncate without
returning an error, so detect a full buffer in the shim instead.
Also avoid the deprecated String(cString:) array overload in the test.
2026-11-11 22:12:05 +01:00
Lalita Hegade 013178c00e Use a thread-safe strerror in Errno.description
strerror(3) isn't guaranteed to be thread-safe: for an unknown error
number, it may format the message into a static buffer shared by all
threads, so concurrent calls to Errno.description could return each
other's text.

Add a csystem_strerror_r shim to CSystem that writes into a
caller-provided buffer. It hides the difference between the XSI
strerror_r (Darwin, BSDs, musl, WASI) and the GNU variant that glibc
and bionic provide under _GNU_SOURCE, and uses strerror_s on Windows.
Errno.description now formats into a stack buffer through this shim.

Also add tests for Errno.description, which were a TODO.

Fixes #156
2026-11-11 17:46:01 +01:00
Jonathan Flat 70505cf6fc Merge pull request #419 from jrflat/windows-test-typed-winsdk-constants 2026-11-10 16:25:19 -07:00
Jonathan Flat d1b4ed40f2 Merge pull request #418 from apple/automerge/merge-main-2026-11-05_09-07
Merge `release/1.9.x` into `main`
2026-11-05 10:16:45 -07:00
Jonathan Flat 20dddc22ed Fix Windows test build with typed WinSDK constants 2026-11-05 10:10:29 -07:00
Guillaume Lessard f6105a8be1 Remove trapping operations from test 2026-11-04 16:35:26 -08:00
Guillaume Lessard 65df702254 Implement FilePathComponentsTest’s testRRC() 2026-11-04 16:35:26 -08:00
Ugur Toprakdeviren 77882a1fc8 fix(FilePath.ComponentView): prevent trailing separator when replacing suffix 2026-11-04 15:21:12 -08:00
Jonathan Flat 402eb4b586 Merge pull request #414 from jrflat/statfs-availability
Update StatFS availability to 1.9.0
2026-11-04 15:38:26 -07:00
Guillaume Lessard 7f6a009cc4 Merge pull request #413 from apple/require-swift-6.2
Require Swift 6.2
2026-11-04 14:30:51 -08:00
Jonathan Flat 8f2745da9a Merge pull request #415 from jrflat/automerger-1.9.x
Update automergers to run from 1.8.x to 1.9.x to main
2026-11-04 15:28:58 -07:00
Guillaume Lessard 74c1ef0581 Require Swift 6.2 2026-11-04 14:00:17 -08:00
Jonathan Flat 6dbc60a373 Update automergers to run from 1.8.x to 1.9.x to main 2026-11-04 14:39:33 -07:00
Jonathan Flat 443e03c16f Update StatFS availability to 1.9.0 2026-11-04 14:25:26 -07:00
Guillaume Lessard 1e6e65ede7 Merge pull request #409 from finagolfin/ci
Spruce up CI config
2026-11-04 13:12:53 -08:00
Jonathan Flat 90a005db2f Merge pull request #361 from jrflat/statfs-implementation
[Implementation] StatFS and supporting types
2026-11-04 12:54:26 -07:00
Jonathan Flat 98517ef93b Merge pull request #362 from jrflat/statfs-proposal
[Proposal] StatFS and supporting types
2026-11-04 12:53:58 -07:00
Jonathan Flat f28e22fbc1 Clarify we'll use the modern @export(implementation) spelling once possible 2026-11-04 12:41:08 -07:00
Finagolfin e16b3f1066 Spruce up CI config 2026-10-28 16:51:05 +05:30
Jonathan Flat a3e9687c91 Merge pull request #402 from rksharma-owg/codex/system-400-immutable-writes
[IO_URING] Accept immutable buffers for unregistered writes
2026-10-21 17:58:55 -06:00
Jonathan Flat b1f3496e31 Move table to doc comment, other comment updates 2026-10-21 13:49:53 -06:00
Jonathan Flat 15479b53b9 Merge branch 'main' into statfs-implementation 2026-10-21 13:07:09 -06:00
RKS 688716f8a2 Merge remote-tracking branch 'upstream/main' into codex/system402-refresh-20261020 2026-10-20 21:42:47 -04:00
Guillaume Lessard 6374a4ab3a Merge pull request #407 from apple/automerge/merge-main-2026-10-17_09-08 2026-10-18 17:22:18 -07:00
Jonathan Flat feb66db229 Merge remote-tracking branch 'origin/main' into automerge/merge-main-2026-10-17_09-08 2026-10-17 13:38:14 -06:00
RKS a51425f6d8 Disfavor deprecated mutable write overloads 2026-10-16 22:42:35 -04:00
RKS da235b4503 Test inferred rebased write buffers on current main 2026-10-16 22:36:43 -04:00
Jonathan Flat 86fdc1dd1d Merge pull request #406 from jrflat/automerger
Add automerger workflow from release/1.8.x to main
2026-10-16 17:26:22 -06:00
Jonathan Flat d0f7d75929 Add automerger workflow from release/1.8.x to main 2026-10-16 17:12:07 -06:00
Jonathan Flat f325ebf78f Merge pull request #391 from jrflat/improve-csystem-import-handling-v2
Improve CSystem import handling
2026-10-16 15:24:40 -06:00
Jonathan Flat 4179b2cce5 Remove CSystemFreeBSD.h, too 2026-10-12 19:39:54 -06:00
Jonathan Flat f5fe750a57 Improve CSystem import handling 2026-10-12 19:39:51 -06:00
Jonathan Flat 9bf5df3d10 v4: Add FileSystemTypeName wrapper 2026-10-12 16:59:19 -06:00
Jonathan Flat d27cb52754 v3: Rename MountFlags constants for consistency, remove type on Darwin and FreeBSD, and remove the statfs() methods on FilePath and FileDescriptor, eliminating the need for CInterop back-deployment 2026-10-12 16:58:24 -06:00
Jonathan Flat faae10c4ec v4: Add FileSystemTypeName wrapper 2026-10-12 16:53:39 -06:00
Jonathan Flat a85b97fc62 v3: Rename MountFlags constants for consistency, remove type on Darwin and FreeBSD, and remove the statfs() methods on FilePath and FileDescriptor, eliminating the need for CInterop back-deployment 2026-10-12 16:52:50 -06:00
RKS 92481cc056 [IO_URING] Document immutable write requests 2026-10-06 12:39:41 -04:00
RKS f0d63f4282 Merge remote-tracking branch 'origin/main' into codex/system-400-immutable-writes 2026-10-06 12:38:53 -04:00
Franz Busch 486d48c80f Merge pull request #401 from apple/fb-iouring-completion-error
[IO_URING] Keep the completion of failed IORing operations
2026-10-06 10:53:11 +02:00
Franz Busch 95ed6aa2a4 Address review comments 2026-10-06 10:21:52 +02:00
RKS b832f4134a [IO_URING] Keep test ring cleanup within buffer lifetime 2026-10-05 22:48:56 -04:00
RKS 0eab740450 [IO_URING] Accept immutable buffers for unregistered writes 2026-10-05 22:39:32 -04:00
Franz Busch cbf57d4575 [IO_URING] Keep the completion of failed IORing operations
When an operation failed, the blocking consume methods dropped its completion and only reported the `Errno`. The caller could not tell which request failed, since the `context` was lost. This breaks any user that matches completions to requests.

This PR makes `blockingConsumeCompletions` pass the completion of a failed operation together with its error. Errors of the ring itself, such as `.timeout`, are still passed without a completion. Additionally, `blockingConsumeCompletion(timeout:)` now returns the completion of a failed operation instead of throwing. It only throws errors of the ring itself.

I also added `Completion.error`, which is `nil` on success and the decoded `Errno` otherwise to make it easy to get to the error of a completion.

Fixes #364
Fixes #395
2026-10-05 20:59:39 +02:00
Jonathan Flat c3b7f2a48e Merge pull request #393 from jrflat/ioring-consume-completions-undone
Fix missing `done` in `IORing.blockingConsumeCompletions`
2026-10-02 10:36:45 -06:00
Jonathan Flat cf36a2fe7b v2: Use statfs on Linux and Android, make StatFS unavailable on WASI, omit Linux flags the kernel never reports, add descriptions for MountFlags and FileSystemID, and back-deploy CInterop.StatFS with CInterop.statfs(_:_:) for migration 2026-10-01 10:30:50 -06:00
Jonathan Flat 74a7b6f618 Fix missing done in IORing.blockingConsumeCompletions 2026-09-30 15:59:05 -06:00
Jonathan Flat 9a9b78e4e9 Include statvfs.h in CSystemWASI 2026-09-30 15:30:38 -06:00
Jonathan Flat 292eb44442 Add missing CSystem import on Android 2026-09-30 15:30:38 -06:00
Jonathan Flat b2237390d8 Define ST_NOSYMFOLLOW for older Linux versions 2026-09-30 15:30:37 -06:00
Jonathan Flat 671a219316 StatFS implementation 2026-09-30 15:30:36 -06:00
Jonathan Flat 5cf1e06016 v2: Use statfs on Linux and Android, make StatFS unavailable on WASI, omit Linux flags the kernel never reports, add descriptions for MountFlags and FileSystemID, and back-deploy CInterop.StatFS with CInterop.statfs(_:_:) for migration 2026-09-30 13:25:22 -06:00
Jonathan Flat 411318ca34 StatFS proposal 2026-09-29 20:48:35 -06:00
Guillaume Lessard e6796eb47d Merge branch 'release/1.8.x' into main 2026-09-25 15:03:14 -07:00
Guillaume Lessard b0d4217c8c [ci] update github actions (#389)
* [ci] update version of workflows dependencies
2026-09-25 14:58:42 -07:00
Paris 85e911cd30 Merge pull request #388 from apple/ospobot/code-of-conduct
Housekeeping: replace repo-level CODE_OF_CONDUCT
2026-09-25 12:22:16 -07:00
apple-ospo[bot] 65f43f5d57 Replace repo-level CODE_OF_CONDUCT file with the inherited org-wide Code of Conduct in .github repo. 2026-09-25 17:42:48 +00:00
Franz Busch b62bce1bc4 Merge pull request #273 from apple/fb-io-uring-poll-add
[IO_URING] Add support for `pollAdd` operation
2026-09-25 10:52:31 +02:00
Jonathan Flat 6843adad5a Add missing @inlinable 2026-09-24 19:38:24 -06:00
Jonathan Flat 4699556133 Add unavailable/renamed hints for C names 2026-09-24 19:37:41 -06:00
Jonathan Flat 1c80f27aef Remove PollEvents.allEvents and use internal Event enum for testing 2026-09-24 19:37:41 -06:00
Jonathan Flat 59b5659a1e Make internal isMultiShot default match public API 2026-09-24 19:37:38 -06:00
Jonathan Flat dc65a924d9 Doc comment updates 2026-09-24 19:36:21 -06:00
Franz Busch 3b8124e350 Smaller touch ups 2026-09-22 10:18:47 +02:00
Franz Busch 241fedcbbd Address review feedback 2026-09-22 10:07:05 +02:00
Guillaume Lessard 1b452c2996 Merge pull request #375 from apple/dev/enable-member-import-visibility 2026-08-17 11:27:16 -07:00
Aryan Singh K.andGuillaume Lessard 869129b7bf fix(MachPort): silence concurrency check for mach_task_self_ (#379)
Darwin.Mach's mach_task_self_ is a shared global; Swift 6.3
reports it as not concurrency-safe when imported. Use a
preconcurrency import for older Darwin SDKs.

Fixes #373

Co-authored-by: Guillaume Lessard <guillaume.lessard@apple.com>
2026-08-13 12:54:10 -07:00
Aryan Singh K. 5c2854d7bd fix(wasi): use mock TLS for all non-threaded WASI targets (#378)
The gate os(WASI) && (swift(<6.1) || !_runtime) incorrectly falls
through to pthread APIs on Swift 6.1+ non-threaded WASI, where
pthread_* is not in scope. Guard solely on !_runtime.

Fixes #370
2026-08-12 11:08:01 -07:00
Guillaume Lessard 6dc13544bb Merge branch 'release/1.8.x' into ‘main’ 2026-08-11 13:49:06 -07:00
Guillaume Lessard d0ef8d091d [readme] update for 1.8.x branch 2026-08-11 13:46:15 -07:00
Guillaume Lessard 79b7490ae9 Hoist “import CSystem” above the platform-specific imports 2026-08-07 15:43:00 -07:00
Guillaume Lessard c5c1a835d6 Explicitly import CSystem for wasi 2026-08-07 15:42:10 -07:00
Guillaume Lessard 27bc5e7e8d Enable “MemberImportVisibility” 2026-08-07 14:40:11 -07:00
Guillaume Lessard c49268ed91 Merge branch 'release/1.8.x' into dev/forward-merge-1.8.x 2026-08-06 09:52:52 -07:00
Guillaume Lessard 704705c5c5 Merge pull request #369 from apple/dev/swift6-language-mode
Enable Swift 6 language mode
2026-08-04 09:13:02 -07:00
Guillaume Lessard 16cfbd4f8b Enable Swift 6 language mode 2026-07-30 07:33:23 -07:00
Guillaume Lessard 755a5b4b3d Merge pull request #367 from apple/dev/linux-import-issue
Prepare for Swift 6 language mode
2026-07-30 07:18:05 -07:00
Guillaume Lessard 6485260369 [Windows] use Atomic to protect the backing store of umask() 2026-07-29 19:41:17 -07:00
Guillaume Lessard d4e86324e9 Add availability macro support to CMake build
For now this heplfully silences warnings.
2026-07-29 19:41:17 -07:00
Guillaume Lessard 29b14a3025 Concurrency tweak for single-thread wasm 2026-07-29 19:41:17 -07:00
Guillaume Lessard 6a63f086f6 Merge branch 'release/1.7.0' into main
# Conflicts:
#	Tests/SystemTests/FileOperationsTest.swift
2026-07-29 18:12:22 -07:00
Guillaume Lessard b9e0ecaa60 [linux] remove @_implementationOnly import qualifiers 2026-07-29 09:28:38 -07:00
Guillaume Lessard 6e3259aec3 Better explain a skip condition 2026-07-28 16:51:19 -07:00
Guillaume Lessard d4373e36f6 Clarify .pollNval and add test reading from an invalid descriptor 2026-07-28 16:46:33 -07:00
Guillaume Lessard a6d4c153b7 Add test to demonstrate a POLLERR result 2026-07-28 16:46:33 -07:00
Guillaume Lessard 4df226b098 Fix copyright notices 2026-07-28 16:46:33 -07:00
Guillaume Lessard a2ca84e281 Round out PollEvents 2026-07-28 16:46:33 -07:00
Guillaume Lessard 980a71f20c Add test to show that PollEvents has too few values 2026-07-28 16:46:33 -07:00
Guillaume Lessard bd49600d62 Prevent tests from hanging in the wrong conditions 2026-07-28 16:46:32 -07:00
Guillaume Lessard 0ecb080d5c Test ready events in a better way 2026-07-28 16:46:32 -07:00
Guillaume Lessard bed8e28860 Clean up permissively 2026-07-28 16:46:32 -07:00
Guillaume Lessard 2e81d94142 Add a test similar to the example in the pollAdd doc-comment 2026-07-28 16:46:32 -07:00
Guillaume Lessard 75c85d47e7 Account for big-endian architectures for poll event encoding 2026-07-28 16:46:32 -07:00
Guillaume Lessard 5b7e24a6b1 Define a constant in Swift rather than in C 2026-07-28 16:46:31 -07:00
Guillaume Lessard 6baba54adb Reflow or improve some doc-comments 2026-07-28 16:46:31 -07:00
Guillaume Lessard 27b4a4a03a Use XCTSkipIf to guard IORing tests 2026-07-28 16:46:31 -07:00
Guillaume Lessard 8ac955bde7 Merge pull request #365 from apple/dev/fix-imports 2026-07-28 12:47:38 -07:00
Guillaume Lessard 617edb8398 Move an import
In all other cases, the `import CSystem` happens before the platform-specific import. This makes this detail consistent.
2026-07-28 10:28:06 -07:00
Guillaume Lessard 5db65c3086 Add an explicit import
Necessary to use `timespec` in Swift 6 mode.
2026-07-28 10:27:25 -07:00
Guillaume Lessard 2159235ef0 Merge pull request #363 from apple/dev/tweaks-just-gardening
[gardening] some corrections
2026-07-27 17:08:17 -07:00
Guillaume Lessard dd5313284d [cmake] add new file to configuration 2026-07-27 16:26:22 -07:00
Franz Busch 2a069e401b Update Sources/System/IORing/IORequest.swift 2026-07-27 16:26:21 -07:00
Franz BuschandMartin e775d1bf59 Apply suggestion from @MarSe32m
Co-authored-by: Martin <sebastian.toivonen@gmail.com>
2026-07-27 16:26:21 -07:00
Guillaume Lessard e4b352c650 [test] fix spelling error 2026-07-27 16:26:21 -07:00
Franz Busch ab11b74b39 [IO_URING] Add support for pollAdd operation
To observe events on file descriptors IO_URING supports the `pollAdd` operation. This is useful when you want to observe a file descriptor becoming ready to read or write

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

We can now use IO_URING to poll for events on file descriptors.
2026-07-27 16:26:21 -07:00
Guillaume Lessard 353a48d98d Correct a doc-comment 2026-07-27 12:43:15 -07:00
Guillaume Lessard aa7ed87b5f Correct a copyright notice 2026-07-27 12:43:15 -07:00
Guillaume Lessard 73067f8221 Availability annotation tweaks 2026-07-27 11:57:38 -07:00
Guillaume Lessard a352b4c224 Improve test timing for Android targets 2026-07-22 11:22:27 -07:00
Guillaume Lessard cd18a372c0 Implement dup3/pipe2 wrappers and types for Darwin 2026-07-22 11:10:19 -07:00
Guillaume Lessard 0d9e29baa0 Fix some doc-comments 2026-07-22 11:01:56 -07:00
Guillaume Lessard 4966bcbf8b Further clarifications 2026-07-22 11:01:56 -07:00
Guillaume Lessard 71be76265f Proposal typo fixes 2026-07-22 11:01:56 -07:00
Guillaume Lessard 90a174256e Revise 0007-FileDescriptor-dup3-pipe2.md 2026-07-22 11:01:56 -07:00
Guillaume Lessard a9597cc068 Merge branch 'release/1.7.0' into main 2026-07-21 10:25:33 -07:00
Jonathan Flat 50688cacbd Update Stat.generationNumber to UInt64 2026-07-21 10:07:16 -07:00
Jonathan Flat bd155c104f Enable FreeBSD checks 2026-07-21 10:06:51 -07:00
Jonathan Flat 52930bf6be Merge pull request #355 from jrflat/stat-equality
Don't compare padding/reserved fields for `Stat` equality
2026-07-20 16:55:53 -06:00
Jonathan Flat 7c072c0d97 Hash the same fields compared by ==
From the `hash(into:)` docs: "The components used for hashing must be the same as the components compared in your type’s == operator implementation."
2026-07-20 13:30:27 -06:00
Jonathan Flat 5d61ccdc7e Remove @_alwaysEmitIntoClient from == and hash(into:)
The implementations of these functions are non-trivial, so remove the annotation to reduce client code size.
2026-07-20 11:48:41 -06:00
Jonathan Flat 2b266acf85 Don't compare padding/reserved fields for Stat equality 2026-07-17 15:15:09 -06:00
Guillaume Lessard 101cc809ba Merge branch 'release/1.6.0' into ‘release/1.7.0’ 2026-07-16 13:19:29 -07:00
Guillaume Lessard 0b30161977 Merge branch 'release/1.5.0' into ‘release/1.6.0’ 2026-07-16 13:02:41 -07:00
Guillaume Lessard b349ff8c05 Update pull request workflow 2026-07-16 12:41:01 -07:00
Guillaume Lessard 7cb32eb7a4 Cherry-pick: 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.

Cherry-pick of #308
2026-07-16 10:21:23 -07:00
Guillaume Lessard a6515006f5 Adjust availability macro 2026-07-13 10:56:30 -07:00
Guillaume Lessard 7edc09a749 Remove an accidental throw annotation 2026-07-13 10:56:05 -07:00
Guillaume Lessard 03604ffcd9 Use typed error instead of rethrows 2026-07-13 10:40:41 -07:00
Guillaume Lessard 2d0912acba Specify some omitted error types 2026-07-13 10:40:41 -07:00
Owen Voorhees 16cdb0d008 Set -package-name in CMake build 2026-07-10 17:03:44 -07:00
Guillaume Lessard e2ae946862 Merge branch 'release/1.7.0' 2026-07-09 12:55:43 -07:00
Guillaume LessardandJonathan Flat f05c1d815d [ci] improve cmake-checking script
Co-authored-by: Jonathan Flat <jflat@apple.com>
2026-07-09 12:54:49 -07:00
Guillaume Lessard 0601f0edec [ci] validate cmake build on Linux 2026-07-09 12:54:49 -07:00
Guillaume Lessard a10991ab88 Fix a test flakiness issue
These timestamps are frequently equal on Android, causing spurious failures.
2026-07-09 09:03:39 -07:00
Guillaume Lessard b5544ba79a Merge pull request #338 from apple/dev/cmake-again
Fix cmake configuration
2026-07-07 16:40:41 -07:00
Guillaume Lessard dda389ed2b Fix cmake configuration 2026-07-07 16:23:09 -07:00
Guillaume Lessard d3c632e868 Merge branch 'release/1.7.0' 2026-07-07 11:26:07 -07:00
Guillaume Lessard 326260ee3b Merge pull request #332 from finagolfin/patch-1
Update CI to latest version of official workflows
2026-07-07 11:24:24 -07:00
Guillaume Lessard d5f004e6f1 Merge pull request #328 from 3405691582/invisible
Don't define __BSD_VISIBLE on OpenBSD.
2026-07-07 11:18:28 -07:00
Guillaume Lessard 38cd4aaf65 Merge pull request #336 from glessard/ioring-syscall-wrappers
Improve syscall wrappers for IORing
2026-07-07 10:11:37 -07:00
Minh Vu 41de235573 Add missing System CMake sources (#325) 2026-07-07 10:34:42 -06:00
Guillaume Lessard efc401eb32 Add testing of throwing behaviour 2026-07-06 14:11:32 -07:00
Guillaume Lessard 73da907161 improve Errno handling for io_uring_register 2026-07-06 14:11:32 -07:00
Guillaume Lessard 124e17164c improve Errno handling for io_uring_enter 2026-07-06 14:11:32 -07:00
Guillaume Lessard d7ca4a9e4c improve Errno handling for io_uring_enter2 2026-07-06 14:11:32 -07:00
Guillaume Lessard 4a55025558 Merge pull request #335 from apple/dev/windows-closeOnExec-1.7.x 2026-07-06 13:17:19 -07:00
Guillaume Lessard 8771bb6199 Add test of OpenOptions.closeOnExec for Windows 2026-07-06 13:15:48 -07:00
Jake Petroules e927959165 Enable .closeOnExec for FileDescriptor.open on Windows
Make OpenOptions.closeOnExec available on Windows, where it maps to
_O_CLOEXEC (O_NOINHERIT). The Windows open adapter already decodes
O_NOINHERIT into a non-inheritable handle, so this produces the
expected close-on-exec semantics. Also add the deprecated O_NOINHERIT
alias, matching the PipeOptions treatment from #312.
2026-07-06 13:15:48 -07:00
Guillaume Lessard f52438c1b8 Merge pull request #334 from apple/dev/workflows-update
[1.7.x] Update CI to latest version of official workflows
2026-07-06 12:37:04 -07:00
finagolfin 636e14a3d2 Update CI to latest version of official workflows 2026-07-06 12:11:05 -07:00
Guillaume Lessard 7c504cabbf Exclude unavailable combinations 2026-07-06 12:07:58 -07:00
Guillaume Lessard 0b7fc03c76 Add test of OpenOptions.closeOnExec for Windows 2026-07-06 11:44:36 -07:00
Jake Petroules a7e7c56fec Enable .closeOnExec for FileDescriptor.open on Windows
Make OpenOptions.closeOnExec available on Windows, where it maps to
_O_CLOEXEC (O_NOINHERIT). The Windows open adapter already decodes
O_NOINHERIT into a non-inheritable handle, so this produces the
expected close-on-exec semantics. Also add the deprecated O_NOINHERIT
alias, matching the PipeOptions treatment from #312.
2026-07-06 11:02:51 -07:00
finagolfin c124911240 Update CI to latest version of official workflows 2026-07-03 11:45:09 +05:30
Guillaume Lessard a17caca7af Merge pull request #329 from glessard/fix-ioring-blockingConsumeCompletion
Test ioring's blocking consume completion with timeout
2026-07-01 16:47:17 -07:00
Guillaume Lessard 1cfd5105b2 [gardening] remove a forgotten print statement 2026-06-27 11:24:37 -07:00
Guillaume Lessard 76a2dc6162 Improve _blockingConsumeCompletionGuts 2026-06-27 11:24:37 -07:00
Guillaume Lessard e0aa78a944 Test for an implementation bug 2026-06-27 11:24:36 -07:00
Guillaume Lessard 1494bb89fc Change the io_uring existence macros to integer values
`true` and `false` import differently with C23 than before, so the swift-side test `(__SWIFT_IORING_SUPPORTED != 0)` became dependent on the toolchain. Integer constants are more reliable for this.
2026-06-26 17:10:10 -07:00
Guillaume Lessard e358151f96 Improve existence/enablement test for io_uring 2026-06-26 17:10:10 -07:00
Guillaume Lessard e7723528a1 Apply suggestions from code review
Refactor conditional compilation blocks

Co-authored-by: Guillaume Lessard <glessard@tffenterprises.com>
2026-06-26 16:15:53 -07:00
Minh Vu 58bce128ce Forward io_uring_enter2 size argument (#326) 2026-06-25 19:54:56 -07:00
3405691582 5b670937e3 Don't define __BSD_VISIBLE on OpenBSD.
This causes a compilation error because OpenBSD headers that refer to
this aren't `#ifdef` but `#if`, so the define must have a value.

This doesn't actually seem to be necessary on OpenBSD, so let's just
remove it on OpenBSD.
2026-06-25 20:44:48 -04:00
Jonathan Flat 74bc402c95 Add Android to MemberImportVisibility test probe (#327) 2026-06-16 10:00:21 -06:00
Guillaume Lessard 96c5f3b852 Merge branch 'release/1.7.0' into dev/mergeback-1.7.x 2026-06-13 09:18:51 -07:00
Minh Vu 776989a955 Install missing CSystem headers (#323) 2026-06-13 09:09:41 -07:00
Aditya Singh 671bd1a573 Replace precondition with fatalError for missing permissions on .create (#307)
FileDescriptor.open traps when options contains .create but permissions
is nil. The previous precondition could elide its message in optimized
builds, leaving users to hunt through source to diagnose the crash.
Use fatalError with a descriptive message so the reason is always
present in the crash dump, and document the trapping behavior.

Fixes #78
2026-06-12 17:12:22 -07:00
Guillaume Lessard 69ba2cd76e Merge pull request #315 from apple/dev/mergeback-1.7.x
Merge forward from release/1.7.0
2026-06-12 17:08:34 -07:00
Sarunas ede51c41cb fix: build with MemberImportVisibility 2026-06-12 16:35:26 -07:00
Guillaume Lessard 64545cfc87 Merge branch 'release/1.7.0' into mergeback-1.7.x 2026-06-12 15:30:38 -07:00
Saleem Abdulrasool 8af20f00ab Merge pull request #308 from compnerd/typecast
System: remove unnecessary type casting
2026-06-11 13:16:39 -07:00
Saleem Abdulrasool 9a8bef12be 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 09:29:01 -07:00
Guillaume Lessard c6cc06d24d Merge pull request #306 from kkebo/enable-freebsd-ci
[CI] Enable FreeBSD testing
2026-06-05 15:06:13 -07:00
Kenta Kubo 2986958695 [CI] Enable FreeBSD testing 2026-05-28 15:04:49 +09:00
Guillaume Lessard 30d09ac188 Merge pull request #305 from glessard/github-actions-refresh
[ci] update workflows library to a recent version
2026-05-27 19:32:52 -07:00
Guillaume Lessard 686feb3a39 [ci] update workflows library to latest version 2026-05-26 17:30:12 -07:00
58 changed files with 5599 additions and 567 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
name: Create PR to merge release branch into the main branch
# Changes should land on the earliest release branch they will need to ship on and then be automatically forwarded to main
permissions:
contents: read
on:
schedule:
- cron: '0 9 * * *'
workflow_dispatch:
jobs:
create_merge_pr:
name: Create PR to merge release branch into main branch
uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.17
with:
base_branch: main
head_branch: release/1.9.x
pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on main. If yes, merge the PR. Otherwise revert changes that should not be included on this branch.
permissions:
contents: write
pull-requests: write
if: (github.event_name == 'schedule' && github.repository == 'apple/swift-system') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork
@@ -0,0 +1,21 @@
name: Create PR to merge the previous release branch into the current release branch
# Changes should land on the earliest release branch they will need to ship on and then be automatically forwarded to later release branches and main
permissions:
contents: read
on:
schedule:
# An hour before automerge_to_main.yml. Runs at the same time would collide due to <HH-MM> branch naming.
- cron: '0 8 * * *'
workflow_dispatch:
jobs:
create_merge_pr:
name: Create PR to merge previous release branch into current release branch
uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.17
with:
base_branch: release/1.9.x
head_branch: release/1.8.x
pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on this release branch. If yes, merge the PR. Otherwise revert changes that should not be included on this branch.
permissions:
contents: write
pull-requests: write
if: (github.event_name == 'schedule' && github.repository == 'apple/swift-system') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork
+55 -24
View File
@@ -5,73 +5,104 @@ permissions:
on:
pull_request:
types: [opened, reopened, synchronize]
types: [opened, reopened, synchronize, ready_for_review]
jobs:
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.17
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"},
{"swift_version": "6.1"},
{"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": "6.4"},
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_macos_checks: true
macos_exclude_xcode_versions: '[]'
enable_windows_checks: true
macos_exclude_xcode_versions: |
[
{"xcode_version": "swift_6.1"},
]
windows_exclude_swift_versions: |
[
{"swift_version": "5.9"},
{"swift_version": "5.10"},
{"swift_version": "6.0"},
{"swift_version": "6.1"},
]
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-6.4.x"},
{"os_version": "focal", "swift_version": "6.4"},
{"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-6.4.x"},
{"os_version": "focal", "swift_version": "6.4"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_android_sdk_build: true
enable_android_sdk_checks: true
enable_freebsd_checks: true
build-abi-stable:
name: Build ABI Stable
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.17
with:
enable_linux_checks: false
enable_macos_checks: true
macos_exclude_xcode_versions: |
[
{"xcode_version": "swift_6.1"},
]
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"
cmake_build:
name: CMake Validation
runs-on: ubuntu-latest
container: swiftlang/swift:nightly-main-noble
steps:
- name: Copy Sources
uses: actions/checkout@v6
- name: Install Dependencies
shell: bash
run: apt update && apt install -y cmake ninja-build jq
- name: Configure Project
shell: bash
run: |
mkdir -p build/.cmake/api/v1/query
touch build/.cmake/api/v1/query/codemodel-v2
cmake -G 'Ninja' -B build -S . -DCMAKE_C_COMPILER=clang -DCMAKE_Swift_COMPILER=swiftc -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=YES
- name: Validate CMake File Lists
shell: bash
run: |
swift package describe --type json > /tmp/swiftpm.json
cat build/.cmake/api/v1/reply/target-SystemPackage-*.json > /tmp/cmake.json
jq '.targets[] | select(.name == "SystemPackage") | .sources[]' /tmp/swiftpm.json | sort > /tmp/swiftpm-list.txt
jq '.sources[].path[15:]' /tmp/cmake.json | sort > /tmp/cmake-list.txt
comm -23 /tmp/swiftpm-list.txt /tmp/cmake-list.txt > /tmp/missing.txt
if [ -s /tmp/missing.txt ]; then
echo "::error::SystemPackage CMakeLists.txt does not match SwiftPM. Missing sources:"
cat /tmp/missing.txt
exit 1
fi
echo "::notice::SystemPackage CMakeLists.txt matches SwiftPM"
- name: Build Project with CMake
shell: bash
run: cmake --build build
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.17
with:
license_header_check_project_name: "Swift.org"
# https://github.com/apple/swift-system/issues/224
+2
View File
@@ -13,6 +13,8 @@ project(SwiftSystem
include(GNUInstallDirs)
set(CMAKE_Swift_LANGUAGE_VERSION 6)
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
-38
View File
@@ -1,38 +0,0 @@
# Code of Conduct
To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.
To give clarity of what is expected of our members, this code of conduct is based on [contributor-covenant.org](http://contributor-covenant.org). This document is used across many open source communities, and we think it articulates our values well.
### Contributor Code of Conduct v1.4
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language (e.g., prefer non-gendered words like “folks” to “guys”, non-ableist words like “soundness check” to “sanity check”, etc.)
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others’ private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
This Code of Conduct applies within all project spaces managed by Swift.org, including (but not limited to) source code repositories, bug trackers, web sites, documentation, and online forums. It also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a member of the [Swift Core Team](https://swift.org/community/#community-structure) or by flagging the behavior for moderation (e.g., in the Forums), whether you are the target of that behavior or not. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. The site of the disputed behavior is usually not an acceptable place to discuss moderation decisions, and moderators may move or remove any such discussion.
Project maintainers are held to a higher standard, and project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
If you disagree with a moderation action, you can appeal to the Core Team (or individual Core Team members) privately.
This policy is adapted from the Contributor Code of Conduct [version 1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/).
+14 -9
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.1
// swift-tools-version:6.2
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
@@ -59,13 +59,11 @@ let availability: [Available] = [
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("1.7.0", "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0"),
Available("99", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.9.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("199", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
]
let swiftSettingsAvailability = availability.map(\.swiftSetting)
@@ -85,6 +83,7 @@ let swiftSettings = swiftSettingsAvailability + swiftSettingsCI + [
.define("SYSTEM_PACKAGE"),
.define("ENABLE_MOCKING", .when(configuration: .debug)),
.enableExperimentalFeature("Lifetimes"),
.enableUpcomingFeature("MemberImportVisibility"),
]
let cSettings: [CSetting] = [
@@ -128,9 +127,15 @@ let package = Package(
dependencies: [],
exclude: ["CMakeLists.txt"],
cSettings: cSettings),
.systemLibrary(
name: "CSystemStatFS",
path: "Sources/CSystemStatFS"),
.target(
name: "SystemPackage",
dependencies: ["CSystem"],
dependencies: [
"CSystem",
.target(name: "CSystemStatFS", condition: .when(platforms: [.linux])),
],
path: "Sources/System",
exclude: filesToExclude,
cSettings: cSettings,
@@ -148,5 +153,5 @@ let package = Package(
dependencies: ["SystemPackage"],
swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]),
],
swiftLanguageModes: [.v5]
swiftLanguageModes: [.v6]
)
+10 -7
View File
@@ -79,7 +79,7 @@ These initializers use a typed `throws(Errno)` and require Swift 6.0 or later.
See the **Appendix** section at the end of this proposal for a table view of Swift API to C mappings.
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability.
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability, except `Stat`'s `==` and `hash(into:)`, which are ordinary `public` API.
### FileType
@@ -693,24 +693,27 @@ public struct Stat: RawRepresentable, Sendable {
/// File generation number
///
/// The file generation number is used to distinguish between different files
/// that have used the same inode over time.
/// The file generation number may be used to distinguish between different
/// files that have used the same inode over time.
///
/// The corresponding C property is `st_gen`.
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
public var generationNumber: Int { get set }
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
public var generationNumber: UInt64 { get set }
#endif
}
// MARK: - Equatable and Hashable
extension Stat: Equatable {
/// Compares the raw bytes of two `Stat` structs for equality.
/// Compares the meaningful file-metadata fields of two `Stat` values.
///
/// Alignment padding and platform reserved/"spare" fields are not compared.
public static func == (lhs: Self, rhs: Self) -> Bool
}
extension Stat: Hashable {
/// Hashes the raw bytes of this `Stat` struct.
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
public func hash(into hasher: inout Hasher)
}
```
+18 -10
View File
@@ -1,31 +1,31 @@
# 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>
* Authors: Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
* Other Reviews: [Swift Forums Pitch](https://forums.swift.org/t/82486)
##### Revision history
#### Revision history
* **v1** Initial version
- **v2** Add Windows version of `pipe(options:)`
* **v2** Add Windows version of `pipe(options:)`
* **v3** Add Darwin versions of `dup3` and `pipe2` wrappers
## Introduction
Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively.
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD and Android.
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD, Android, and the Apple operating systems based on Darwin 27.0 or newer; `pipe(options:)` will also be available on Windows.
## Motivation
It is considered best practice to set the `O_CLOEXEC` (close-on-exec) bit on newly created file descriptors to prevent them from being inherited by subprocesses.
Some POSIX functions such as `open` provide a "flags" parameter allowing 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`.
Some POSIX functions such as `open` provide a "flags" parameter allowing the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`.
POSIX 2024 corrects this deficiency for `dup2` and `pipe` by introducing `dup3` and `pipe2` variants that allow the close-on-exec bit to be set atomically.
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defence in depth with respect to opened file descriptors.
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defense in depth with respect to opened file descriptors.
## Proposed solution
@@ -38,7 +38,7 @@ 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])
let fd2 = try fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec])
```
## Detailed design
@@ -50,6 +50,11 @@ struct FileDescriptor {
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
///
/// NOTE: This overload called with an empty option set is not necessarily
/// equivalent to calling the overload with no options. On Windows, the
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
/// but this overload disables it when called with an empty option set.
///
/// - Parameters:
/// - options: The behavior for creating the pipe.
///
@@ -70,9 +75,14 @@ struct FileDescriptor {
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The new file descriptor.
///
/// If the `target` descriptor is the same as `self`, then EINVAL is thrown.
/// If the `target` descriptor is already in use, then it is first
/// deallocated as if a close(2) call had been done first.
///
/// NOTE: This overload called with an empty option set is not necessarily
/// equivalent to calling the overload with no options, because `dup3` with
/// no set options is not required to behave identically to `dup2`.
///
/// File descriptors are merely references to some underlying system resource.
/// The system does not distinguish between the original and the new file
/// descriptor in any way. For example, read, write and seek operations on
@@ -167,8 +177,6 @@ struct FileDescriptor {
}
```
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.
+972
View File
@@ -0,0 +1,972 @@
# StatFS for Swift System
* Proposal: [SYS-0009](0009-system-statfs.md)
* Authors: [Jonathan Flat](https://github.com/jrflat)
* Review Manager: TBD
* Status: **Implemented**
* Implementation: [apple/swift-system#361](https://github.com/apple/swift-system/pull/361)
* Review: ([pitch](https://forums.swift.org/t/pitch-statfs-and-supporting-types/88151))
#### Revision history
* **v1** Initial version
* **v2** Use `statfs` on Linux and Android, make `StatFS` unavailable on WASI, omit Linux flags the kernel never reports, add descriptions for `MountFlags` and `FileSystemID`, and back-deploy `CInterop.StatFS` with `CInterop.statfs(_:_:)` for migration
* **v3** Rename `MountFlags` constants for consistency, remove `type` on Darwin and FreeBSD, and remove the `statfs()` methods on `FilePath` and `FileDescriptor`, eliminating the need for `CInterop` back-deployment
* **v4** Add `FileSystemTypeName` wrapper
## Introduction
This proposal introduces a Swift-native `StatFS` type to the System library, providing comprehensive access to file system metadata on Unix-like platforms through type-safe, platform-aware APIs that wrap the underlying C `statfs` 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 C `statfs` interfaces add a few problems of their own:
- On Linux, Swift's Glibc module doesn't export `statfs`, so calling it requires a C shim.
- Block counts are in units of `f_bsize` on Darwin and BSD, but `f_frsize` on Linux and Android, so computing space in bytes requires platform-specific code.
- Field widths and signedness vary by platform and C library. For example, `f_bavail` is signed on FreeBSD and OpenBSD.
The goal of the `StatFS` 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 StatFS` that is available on Unix-like platforms. On Windows and WASI, the struct is declared but marked unavailable (see **Availability on Windows and WASI**). Windows-specific file system APIs and WASI support are discussed in **Future directions**.
`StatFS` is a Swift wrapper around the C `statfs` struct, which provides information about file systems. This type uses `statfs` rather than the POSIX `statvfs` for the additional information it provides, such as the file system type. Computed properties like `.totalSpace` and `.availableSpace` are supplied for convenience.
```swift
// Get file system information from a path
let statfs = try StatFS("/")
// From FileDescriptor
let fdStatFS = try StatFS(fd)
// From FilePath
let pathStatFS = try StatFS(filePath)
print("File system ID: \(statfs.fileSystemID)")
print("Total space: \(statfs.totalSpace) bytes")
print("Available space: \(statfs.availableSpace) bytes")
// Check mount flags
if statfs.mountFlags.contains(.readOnly) {
print("File system is read-only")
}
// Platform-specific information when available
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
print("File system is mounted at \(statfs.mountPoint)")
print("File system is mounted from \(statfs.mountSource)")
#endif
#if os(anyAppleOS)
if statfs.typeName == .apfs {
print("File system is APFS")
}
#endif
```
### Error handling
The throwing initializers use a typed `throws(Errno)` and require Swift 6.0 or later:
```swift
do {
let statfs = try StatFS("/nonexistent/file")
} catch Errno.noSuchFileOrDirectory {
print("File not found")
} catch {
print("Other error: \(error)")
}
```
## Detailed design
See the **Appendix** section at the end of this proposal for a table view of Swift API to C mappings.
All APIs will be marked `@export(implementation)` for performance, except `StatFS`'s `==` and `hash(into:)`, and descriptions, which are ordinary `public` APIs. Until the package requires Swift 6.4, the implementation will use the equivalent `@_alwaysEmitIntoClient` instead.
### `MountFlags`
This proposal introduces a `MountFlags` type representing flags that could be present in a `statfs` struct. On Darwin and BSD, many of these flags could also be passed to a future implementation of `mount`, though some, like `local` and `rootFileSystem`, only describe state the kernel reports. (Linux `mount(2)` instead takes a separate `MS_*` set, distinct from the `ST_*` flags `statfs` reports.) Mount-specific flags are outside the scope of this proposal (see **Future directions**).
`MountFlags` uses a `CInterop` typealias for its `rawValue` to support different widths of integers used on different operating systems. On Linux and Android, `CInterop.MountFlags` is `CUnsignedLong` rather than the type of `f_flags`, which varies by C library (glibc's is a signed `long`).
Glibc and musl also define `ST_WRITE`, `ST_APPEND`, and `ST_IMMUTABLE`, but Linux never reports them in `f_flags`, so `MountFlags` omits them. For space, doc comments are omitted for flags that aren't available on Darwin.
```swift
/// Flags describing a mounted file system.
///
/// These are the flags reported in the `f_flags` field of a `statfs` struct.
/// Some reflect options employed when mounting the file system, while others,
/// like `local` and `rootFileSystem`, describe state the kernel reports.
///
/// - Note: Not available on Windows or WASI.
@frozen
public struct MountFlags: OptionSet, Sendable, Hashable, Codable {
/// The raw C flags.
public let rawValue: CInterop.MountFlags
/// Creates a strongly-typed `MountFlags` from the raw C value.
public init(rawValue: CInterop.MountFlags)
// Flags available on all platforms
/// The file system is mounted read-only, even for the super-user.
///
/// The corresponding C constant is `MNT_RDONLY` on Darwin and BSD,
/// or `ST_RDONLY` otherwise.
public static var readOnly: MountFlags { get }
/// The file system is written to synchronously.
///
/// The corresponding C constant is `MNT_SYNCHRONOUS` on Darwin and BSD,
/// or `ST_SYNCHRONOUS` otherwise.
public static var synchronous: MountFlags { get }
/// Programs may not be executed from the file system.
///
/// The corresponding C constant is `MNT_NOEXEC` on Darwin and BSD,
/// or `ST_NOEXEC` otherwise.
public static var noExecution: MountFlags { get }
/// Set-user-ID and set-group-ID (setuid and setgid) bits are not honored on
/// the file system.
///
/// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD,
/// or `ST_NOSUID` otherwise.
public static var noSetUserID: MountFlags { get }
/// Access times are not updated on the file system.
///
/// - Note: On OpenBSD, access time may still be updated when the
/// modification or status-change time is also being updated.
///
/// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD,
/// or `ST_NOATIME` otherwise.
public static var noAccessTime: MountFlags { get }
// Flags available on all platforms except FreeBSD
#if !os(FreeBSD)
/// Special files may not be interpreted on the file system.
///
/// - Note: Not available on FreeBSD.
///
/// The corresponding C constant is `MNT_NODEV` on Darwin and OpenBSD,
/// or `ST_NODEV` otherwise.
public static var noDevices: MountFlags { get }
#endif
// Flags available on Linux and Android
#if os(Linux) || os(Android)
public static var mandatoryLocking: MountFlags { get }
public static var noDirectoryAccessTime: MountFlags { get }
public static var relativeAccessTime: MountFlags { get }
#endif
// Flags available on Linux, Android, and FreeBSD
#if os(Linux) || os(Android) || os(FreeBSD)
public static var noSymlinkFollowing: MountFlags { get }
#endif
// Flags available on Darwin, FreeBSD, and OpenBSD
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
/// The file system is written to asynchronously.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_ASYNC`.
public static var asynchronous: MountFlags { get }
/// The file system is exported for use over the network via NFS.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_EXPORTED`.
public static var exported: MountFlags { get }
/// The file system is stored locally, rather than being accessed over a network.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_LOCAL`.
public static var local: MountFlags { get }
/// Quotas are enabled on the file system.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_QUOTA`.
public static var quotasEnabled: MountFlags { get }
/// The file system is the root file system.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_ROOTFS`.
public static var rootFileSystem: MountFlags { get }
#endif
// Flags available on Darwin and FreeBSD
#if os(anyAppleOS) || os(FreeBSD)
/// The file system is unioned with the underlying file system, rather than
/// obscuring it.
///
/// - Note: Only available on Darwin and FreeBSD.
///
/// The corresponding C constant is `MNT_UNION`.
public static var union: MountFlags { get }
/// The file system was mounted by the automounter.
///
/// - Note: Only available on Darwin and FreeBSD. See `automount(8)`.
///
/// The corresponding C constant is `MNT_AUTOMOUNTED`.
public static var automounted: MountFlags { get }
/// The file system maintains Mandatory Access Control (MAC) labels for
/// individual objects.
///
/// - Note: Only available on Darwin and FreeBSD.
///
/// The corresponding C constant is `MNT_MULTILABEL`.
public static var multiLabel: MountFlags { get }
#endif
// Flags available on FreeBSD and OpenBSD
#if os(FreeBSD) || os(OpenBSD)
public static var exportedReadOnly: MountFlags { get }
public static var exportedByDefault: MountFlags { get }
public static var exportedAnonymously: MountFlags { get }
public static var softUpdates: MountFlags { get }
#endif
// Flags available on Darwin only
#if os(anyAppleOS)
/// Per-file encrypted data protection is enabled on the file system.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_CPROTECT`.
public static var contentProtection: MountFlags { get }
/// The file system resides on removable media.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_REMOVABLE`.
public static var removable: MountFlags { get }
/// The file system is quarantined.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_QUARANTINE`.
public static var quarantined: MountFlags { get }
/// The file system supports volfs.
///
/// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5.
///
/// The corresponding C constant is `MNT_DOVOLFS`.
public static var supportsVolfs: MountFlags { get }
/// The file system should not be presented to the user for browsing
/// (e.g. hidden in Finder).
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_DONTBROWSE`.
public static var noBrowsing: MountFlags { get }
/// The file system ignores ownership information.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`.
public static var ignoresOwnership: MountFlags { get }
/// The file system is journaled.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_JOURNALED`.
public static var journaled: MountFlags { get }
/// User extended attributes are not allowed on the file system.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_NOUSERXATTR`.
public static var noUserExtendedAttributes: MountFlags { get }
/// The file system defers writes.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_DEFWRITE`.
public static var defersWrites: MountFlags { get }
/// Symbolic links are not followed when resolving the mount point.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_NOFOLLOW`.
public static var noSymlinkFollowingAtMountPoint: MountFlags { get }
/// The file system is a snapshot.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_SNAPSHOT`.
public static var snapshot: MountFlags { get }
/// Access times are always updated when files are read. Without this flag,
/// the file system may skip some access time updates for performance.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_STRICTATIME`.
public static var strictAccessTime: MountFlags { get }
#endif
// Flags available on FreeBSD only
#if os(FreeBSD)
public static var exportedWithKerberos: MountFlags { get }
public static var exportedPublicly: MountFlags { get }
public static var posixACLs: MountFlags { get }
public static var geomJournaled: MountFlags { get }
public static var excludedFromDiskFreeReports: MountFlags { get }
public static var nfs4ACLs: MountFlags { get }
public static var noClusteredReads: MountFlags { get }
public static var noClusteredWrites: MountFlags { get }
public static var setUserIDDirectories: MountFlags { get }
public static var softUpdatesJournaling: MountFlags { get }
public static var untrusted: MountFlags { get }
public static var userMounted: MountFlags { get }
public static var verified: MountFlags { get }
#endif
// Flags available on OpenBSD only
#if os(OpenBSD)
public static var noPermissionChecks: MountFlags { get }
public static var writeExecuteAllowed: MountFlags { get }
#endif
}
extension MountFlags: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the mount flags.
public var description: String { get }
/// A textual representation of the mount flags, suitable for debugging.
public var debugDescription: String { get }
}
```
Like `FilePermissions`, `MountFlags` describes itself by listing its flags, such as `[.readOnly, .local]`.
### `FileSystemID`, `FileSystemType`, `FileSystemSubtype`, and `FileSystemTypeName`
```swift
/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs`
/// struct.
///
/// - Note: Not available on Windows or WASI.
@frozen
public struct FileSystemID: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system ID.
public var rawValue: CInterop.FileSystemID
/// Creates a strongly-typed `FileSystemID` from the raw C value.
public init(rawValue: CInterop.FileSystemID)
/// Creates a strongly-typed `FileSystemID` from the raw C value.
public init(_ rawValue: CInterop.FileSystemID)
}
extension FileSystemID: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the file system ID.
public var description: String { get }
/// A textual representation of the file system ID, suitable for debugging.
public var debugDescription: String { get }
}
// `FileSystemType` is available on Linux and Android, where `f_type` is the
// file system's magic number. Darwin and FreeBSD report a kernel-assigned
// index in `f_type`, so `typeName` identifies the file system there instead.
// `FileSystemSubtype` is Darwin-only. Both fit in a `UInt32` on every platform
// that provides them, so no `CInterop` typealias is needed.
#if os(Linux) || os(Android)
/// A Swift wrapper of the C `f_type` file system type found in a `statfs`
/// struct.
///
/// - Note: Only available on Linux and Android.
@frozen
public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system type.
public var rawValue: UInt32
/// Creates a strongly-typed `FileSystemType` from the raw C value.
public init(rawValue: UInt32)
/// Creates a strongly-typed `FileSystemType` from the raw C value.
public init(_ rawValue: UInt32)
}
#endif
#if os(anyAppleOS)
/// A Swift wrapper of the C `f_fssubtype` file system subtype found in a
/// `statfs` struct on Darwin.
///
/// - Note: Only available on Darwin.
@frozen
public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system subtype.
public var rawValue: UInt32
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
public init(rawValue: UInt32)
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
public init(_ rawValue: UInt32)
}
#endif
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
/// A Swift wrapper of the C `f_fstypename` file system type name found in a
/// `statfs` struct.
///
/// - Note: Only available on Darwin and BSD.
@frozen
public struct FileSystemTypeName: RawRepresentable, Sendable, Hashable, Codable, ExpressibleByStringLiteral {
/// The raw file system type name.
public var rawValue: String
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
public init(rawValue: String)
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
public init(_ rawValue: String)
/// Creates a `FileSystemTypeName` from a string literal, such as `"apfs"`.
public init(stringLiteral value: String)
// Type names available on Darwin only
#if os(anyAppleOS)
/// The Apple File System (APFS).
///
/// - Note: Only available on Darwin.
///
/// The corresponding `f_fstypename` value is `"apfs"`.
public static var apfs: FileSystemTypeName { get }
/// The Mac OS Extended file system (HFS Plus).
///
/// - Note: Only available on Darwin.
///
/// The corresponding `f_fstypename` value is `"hfs"`.
public static var hfs: FileSystemTypeName { get }
#endif
}
extension FileSystemTypeName: CustomStringConvertible, CustomDebugStringConvertible {
/// The file system type name, such as `apfs`.
public var description: String { get }
/// The file system type name as a quoted string, such as `"apfs"`.
public var debugDescription: String { get }
}
#endif
```
`CInterop.FileSystemID` is the C `fsid_t` struct (a fixed two-element `int32_t` array), which provides no synthesized conformances. `FileSystemID` implements `Equatable`, `Hashable`, and `Codable` manually in terms of its elements, named `val` on Darwin and BSD and `__val` on Linux and Android. It encodes them as an unkeyed container of two `Int32` values and describes itself by listing them, such as `FileSystemID(16777239, 26)`.
`FileSystemTypeName` wraps `f_fstypename` so that well-known type names can be offered as constants, such as `.apfs`. It conforms to `ExpressibleByStringLiteral` so comparisons against names without a constant like `statfs.typeName == "nfs"` still read naturally. This proposal only provides constants for `"apfs"` and `"hfs"`. Other names can be added in the future when their stability is confirmed.
### `StatFS`
`StatFS` offers initializers that accept a `FilePath`, null-terminated `UnsafePointer<CChar>`, or `FileDescriptor`.
The underlying C fields for each numeric property vary in signedness and width across platforms. Rather than create a platform-dependent type for each, we choose one fixed integer type per property — `Int` or `UInt64` — and clamp when getting or setting the value.
Block sizes and lengths (`blockSize`, `preferredIOBlockSize`, `fragmentSize`, and `maximumNameLength`) are exposed as `Int`. Most modern file systems report 4KiB block sizes by default, and in practice, the highest value seen on specialized (often network) file systems is on the order of 1MiB. The preferred I/O size could similarly reach values around 16MiB. These are still orders of magnitude smaller than `Int.max`, even for 32-bit platforms.
Block and inode counts, and the space values computed from them, are exposed as `UInt64` to preserve their full unsigned range on every platform. Real-world values can exceed `Int64.max`, and space computations can overflow and saturate to `UInt64.max`. Clamping lets us report `0` for the signed "available to non-superuser" counts that some BSDs allow to go negative.
```swift
/// A Swift wrapper of the C `statfs` struct.
///
/// - Note: Not available on Windows or WASI.
/// - Note: The numeric properties clamp when converting to or from the
/// underlying C field. Use `rawValue` for exact, unclamped access.
@frozen
public struct StatFS: RawRepresentable, Sendable, Hashable {
/// The raw C `statfs` struct.
public var rawValue: CInterop.StatFS
/// Creates a Swift `StatFS` from the raw C struct.
public init(rawValue: CInterop.StatFS)
/// Creates a `StatFS` from a `FilePath`.
///
/// The corresponding C function is `statfs()`.
public init(
_ path: FilePath,
retryOnInterrupt: Bool = true
) throws(Errno)
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
///
/// The corresponding C function is `statfs()`.
public init(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool = true
) throws(Errno)
/// Creates a `StatFS` from a `FileDescriptor`.
///
/// The corresponding C function is `fstatfs()`.
public init(
_ fd: FileDescriptor,
retryOnInterrupt: Bool = true
) throws(Errno)
/// File system block size, in bytes.
///
/// - Note: On Darwin and BSD, this is the fundamental size for block counts.
/// Other platforms use `fragmentSize` (`f_frsize`) instead.
///
/// The corresponding C property is `f_bsize`.
public var blockSize: Int { get set }
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
/// Block size for optimal data transfer, in bytes.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_iosize`.
public var preferredIOBlockSize: Int { get set }
#else
/// File system fragment size, in bytes.
///
/// - Note: On Linux and Android, this is the fundamental size for block
/// counts. Not present on Darwin or BSD, which use `blockSize` instead.
///
/// The corresponding C property is `f_frsize`.
public var fragmentSize: Int { get set }
#endif
/// Total number of blocks in the file system.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise.
///
/// The corresponding C property is `f_blocks`.
public var totalBlocks: UInt64 { get set }
/// Total size of the file system, in bytes.
///
/// - Note: Computed for convenience as `totalBlocks` times the fundamental
/// block size (see `totalBlocks`). Saturates to `UInt64.max` on overflow.
public var totalSpace: UInt64 { get }
/// Number of free blocks in the file system.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise.
///
/// The corresponding C property is `f_bfree`.
public var freeBlocks: UInt64 { get set }
/// Free space in the file system, in bytes.
///
/// - Note: Computed for convenience as `freeBlocks` times the fundamental
/// block size (see `freeBlocks`). Saturates to `UInt64.max` on overflow.
public var freeSpace: UInt64 { get }
/// Number of free blocks available to non-superuser.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise. On FreeBSD and OpenBSD, the underlying C property is
/// signed; negative values are clamped to 0.
///
/// The corresponding C property is `f_bavail`.
public var availableBlocks: UInt64 { get set }
/// Available space in the file system for non-superuser, in bytes.
///
/// - Note: Computed for convenience as `availableBlocks` times the fundamental
/// block size (see `availableBlocks`). Saturates to `UInt64.max` on overflow.
public var availableSpace: UInt64 { get }
/// Total number of inodes in the file system.
///
/// The corresponding C property is `f_files`.
public var totalInodes: UInt64 { get set }
/// Number of free inodes in the file system.
///
/// - Note: On FreeBSD, this reports the inodes available to a non-superuser
/// rather than the total free count, and the underlying C field is signed
/// (negative values are clamped to 0); on other platforms, it is the total
/// number of free inodes.
///
/// The corresponding C property is `f_ffree`.
public var freeInodes: UInt64 { get set }
#if os(OpenBSD)
/// Number of free inodes available to non-superuser.
///
/// - Note: Darwin, FreeBSD, Linux, and Android `statfs` do not report it.
/// On OpenBSD, the underlying C property is signed; negative values are
/// clamped to 0.
///
/// The corresponding C property is `f_favail`.
public var availableInodes: UInt64 { get set }
#endif
#if !os(anyAppleOS)
/// Maximum length of a file name on the file system, in bytes.
///
/// - Note: Darwin's `statfs` does not report it.
///
/// The corresponding C property is `f_namelen` on Linux and Android, or
/// `f_namemax` otherwise.
public var maximumNameLength: Int { get set }
#endif
/// File system ID.
///
/// The corresponding C property is `f_fsid`.
public var fileSystemID: FileSystemID { get set }
/// Flags describing how the file system is mounted.
///
/// - Note: On Linux, the kernel also sets an `ST_VALID` bit in `f_flags`
/// to mark the field as filled in. It isn't a mount flag, so this
/// property omits it like glibc's `statvfs` and Bionic's `statfs` do.
/// The setter preserves it.
///
/// The corresponding C property is `f_flags`.
public var mountFlags: MountFlags { get set }
#if os(Linux) || os(Android)
/// File system type.
///
/// - Note: This is the file system's magic number, such as `0xEF53` for
/// ext4. Only available on Linux and Android. On Darwin and BSD, use
/// `typeName` to identify the file system.
///
/// The corresponding C property is `f_type`.
public var type: FileSystemType { get set }
#endif
#if os(anyAppleOS)
/// File system subtype.
///
/// - Note: This is a numeric value whose meaning depends on `typeName`,
/// with no stable, public constants. Only available on Darwin.
///
/// The corresponding C property is `f_fssubtype`.
public var subtype: FileSystemSubtype { get set }
#endif
#if os(anyAppleOS) || os(FreeBSD) || os(OpenBSD)
/// User that mounted the file system.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_owner`.
public var owner: UserID { get set }
/// File system type name, such as "apfs".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_fstypename`.
public var typeName: FileSystemTypeName { get }
/// Directory where the file system is mounted, such as "/System/Volumes/Data".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_mntonname`.
public var mountPoint: FilePath { get }
/// The source of the mounted file system, such as "/dev/disk3s7".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_mntfromname`.
public var mountSource: FilePath { get }
#endif
/// Compares the file system metadata fields of two `StatFS` values,
/// including fields not exposed as properties, such as `f_flags_ext` on
/// Darwin.
///
/// Fields are compared by their raw C values. Reserved/"spare" fields and
/// OpenBSD's `mount_info` union are not compared. Name buffers are compared
/// only up to their NUL terminators.
public static func == (lhs: Self, rhs: Self) -> Bool
/// Hashes the file system metadata fields of a `StatFS` struct.
///
/// These are the same fields compared by `==`. Reserved/"spare" fields are
/// not hashed, and name buffers are hashed only up to their NUL terminators.
public func hash(into hasher: inout Hasher)
}
```
`typeName`, `mountPoint`, and `mountSource` are get-only because they are backed by fixed-size C character buffers, which a non-throwing setter could not safely fill without risking silent truncation. Callers that need to write these fields can do so through `rawValue` directly.
`StatFS` conforms to `Hashable` (and therefore `Equatable`) by comparing and hashing the raw values of its C fields, as `Stat` does, so two `StatFS` values are equal when their `rawValue`s match in every meaningful field. Comparing the clamped properties instead would treat different raw values like two negative `f_bavail` counts as equal, and would ignore fields without a property. A byte-wise comparison would be unreliable because the bytes following each name buffer's NUL terminator are unspecified, and the struct may carry reserved/spare padding.
### CInterop extensions
This proposal extends the existing `CInterop` namespace with platform-appropriate typealiases for the underlying C types. Each is used as the `rawValue` for a corresponding strongly-typed representation.
```swift
extension CInterop {
/// The C `statfs` struct.
public typealias StatFS = statfs
public typealias FileSystemID = fsid_t
#if os(anyAppleOS) || os(OpenBSD)
public typealias MountFlags = UInt32
#elseif os(FreeBSD)
public typealias MountFlags = UInt64
#else
public typealias MountFlags = CUnsignedLong
#endif
}
```
All three have the same availability as the rest of this proposal.
### Vending `struct statfs` on glibc platforms
Unlike the Musl and Android modules, Swift's Glibc module doesn't export `<sys/vfs.h>`, which declares `struct statfs`. On glibc platforms, System therefore vends `struct statfs` from a new module, `CSystemStatFS`, that contains only this header, and re-exports it so clients can access `rawValue`'s fields under `MemberImportVisibility`. As a result, importing System on glibc platforms also brings C's `statfs()` and `fstatfs()` into scope. The Glibc module does export `fsid_t`, so accessing the `__val` field of a `CInterop.FileSystemID` under `MemberImportVisibility` requires importing Glibc.
### Availability on Windows and WASI
Windows has no `statfs`/`statvfs`. Rather than omit the type there, where usage would fail with an unhelpful `cannot find 'StatFS' in scope`, we declare an unavailable stub with a message suggesting the relevant Win32 APIs. In the future, the message could suggest dedicated System APIs instead.
`wasi-libc` has no `statfs`, and in the current `wasi-libc`, `statvfs` and `fstatvfs` are unconditional stubs (in `libc-bottom-half/sources/posix.c`) that set `errno` to `ENOSYS` and return `-1`:
```c
int statvfs(const char *__restrict path, struct statvfs *__restrict buf) {
// TODO: We plan to support this eventually in WASI, but not yet.
errno = ENOSYS;
return -1;
}
```
As a result, `StatFS` initializers would always fail at runtime on WASI and throw `Errno.noFunction`, so WASI gets an unavailable stub as well.
```swift
#if os(Windows)
@available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.")
public struct StatFS {
public init(_ path: FilePath, retryOnInterrupt: Bool = true) throws(Errno)
public init(_ path: UnsafePointer<CChar>, retryOnInterrupt: Bool = true) throws(Errno)
public init(_ fd: FileDescriptor, retryOnInterrupt: Bool = true) throws(Errno)
}
#elseif os(WASI)
@available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.")
public struct StatFS {
// The same three initializers
}
#else
// ...
#endif
```
Marking the type covers the three throwing initializers each stub declares. The other types and `CInterop` additions in this proposal aren't declared on either platform.
## Source compatibility
This proposal is additive, but on glibc platforms, clients that already vend `struct statfs` from their own module (since Swift's Glibc module doesn't export it) may need to import both that module and System in each file that accesses `statfs` fields. When two modules declare the same C struct, `MemberImportVisibility` attributes its fields to the module the compiler reaches the struct through first, which can differ between debug and release builds. In testing, a client that used `StatFS.rawValue` in one file and its own module's `statfs` in another built in debug but failed in release, reporting a missing import of `CSystemStatFS`.
## 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 `StatFS`. However, the types introduced in this proposal could serve as the foundation of broader file system APIs in Swift.
For instance, on Darwin and BSD, `MountFlags` could be useful for a future `mount()` implementation, and a future Swift wrapper of `getfsstat()` could return an array of `StatFS` structs.
A Linux `mount(2)` wrapper would look different. There, the flags `statfs` reports (`ST_*`) are a distinct set from the flags `mount(2)` accepts (`MS_*`), so a mount wrapper would need its own input type rather than reusing `MountFlags`. The `MS_*` set also mixes per-mount options with operation selectors like bind, move, remount, and propagation changes, so an idiomatic wrapper would likely split these into separate functions. A new implementation might also prefer the newer `fsopen` / `fsmount` / `move_mount` family over classic `mount(2)`. Because Linux's `mount` signature differs from Darwin's and BSD's, any such wrapper would be platform-specific.
Once `wasi-libc` implements `statvfs`, a future proposal could make `StatFS` available on WASI by wrapping `statvfs` and `fstatvfs`.
On Darwin, `f_flags_ext` reports extended flags such as `MNT_EXT_ROOT_DATA_VOL` and `MNT_EXT_FSKIT`. They're reachable through `rawValue` today, and a future proposal could expose them as their own option set.
If Swift's Glibc module exports `<sys/vfs.h>` in the future, `CSystemStatFS` would become redundant. System could keep re-exporting it, but accessing `rawValue`'s fields under `MemberImportVisibility` would then require importing Glibc, as with `CInterop.Stat`.
While this proposal does not include `StatFS` on Windows, SYS-0017 proposes `volumeInformation()` on `Win32.FileHandle`, a Swift-native wrapper of `GetVolumeInformationByHandleW`. Other volume APIs, such as `GetDiskFreeSpaceExW` and `DeviceIoControl`, could follow with their associated types.
A more general `FileSystemInfo` API could then build on these OS-specific types to provide an ergonomic, cross-platform abstraction for file system metadata. These future cross-platform APIs might be better implemented outside of System, such as in Foundation or another dedicated package.
## Alternatives considered
### `FileSystemInfo` as the lowest-level type
An alternative approach could be to have a more general `FileSystemInfo` type be the lowest level of abstraction provided by the System library. This type would then handle all the `statfs` 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 `statfs` 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` ([SYS-0006](https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md)) and `StatFS` 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.
### Separate `StatFS` and `StatVFS` types
Having separate types for `statfs` and `statvfs` would increase cognitive overhead and confusion for developers deciding which to choose. It would require additional documentation explaining differences that are transparently handled by platform availability, and would require duplicate code. On operating systems where `statfs` exposes additional information, such as Darwin, FreeBSD, and Linux, `statvfs` is just a wrapper around `statfs`, so there's little upside to providing a `StatVFS` type here. One upside might be that all properties of `StatVFS` would be available where the struct itself is available, but this likely doesn't outweigh the cost of having two types.
### Use `statvfs` on Linux and Android
`statvfs` is the POSIX interface, and the Glibc, Musl, and Android modules all export it, so System wouldn't need a `CSystemStatFS` module, which can conflict with clients' own `statfs` modules (see **Source compatibility**). However, on Linux, `statvfs` is also a wrapper around `statfs`, and it drops useful information: 1) with Bionic or glibc before 2.39, `f_type`, the file system magic number (such as `0xEF53` for ext4) that Linux code conventionally uses to identify a file system is absent; and 2) with musl or 32-bit platforms, half of the 2-word `fsid_t` is omitted. `statvfs`'s only extra field, `f_favail`, is a copy of `f_ffree` in glibc, musl, and Bionic.
### Add `statfs()` methods to `FilePath` and `FileDescriptor`
Like `FilePath.stat()` and `FileDescriptor.stat()` in [SYS-0006](https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md), `StatFS` could offer `statfs()` methods alongside its initializers. However, `statfs` describes the file system containing a file rather than the file itself, so it's not as closely tied to the individual `FilePath` or `FileDescriptor`. The proposed initializers can still chain, as in `try StatFS(path).availableSpace`.
The methods would also shadow the C `statfs` struct initializer and function inside extensions of those types, so existing code that calls them unqualified there would no longer compile. [SYS-0008](0008-backdeploy-cinterop-stat.md) back-deployed `CInterop.stat(_:_:)` as a migration path for the same issue with `stat()`. Leaving out the methods avoids the break and the need for new `CInterop` APIs. They could always be added later, along with a migration path, if desired.
### Expose `type` and `subtype` as raw integers
`FileSystemType` and `FileSystemSubtype` wrap `UInt32` values that, except for Linux magic numbers, have no stable, public constants, so exposing `type` and `subtype` as bare `UInt32` was considered. We keep the wrapper types for fidelity to the underlying struct and for consistency with `FileSystemID`, which is similarly opaque. The wrappers also give these fields distinct types, avoiding accidental cross-comparisons and granting flexibility to add members later, if desired.
### Expose `typeName` as a `String`
`typeName` could be a `String` like Foundation's `volumeTypeName` resource value. Unlike Linux magic numbers, type names are already readable, so `typeName == "apfs"` works about as well as a constant would. However, a wrapper allows us to provide constants like `.apfs`, which help with discoverability and avoid mistakes like comparing against `"APFS"`. And `ExpressibleByStringLiteral` allows us to still keep the ergonomics of literal comparison.
### Make `StatFS` available on WASI
`StatFS` could wrap `statvfs` and `fstatvfs` on WASI, as v1 of this proposal did. This would let developers write code that is otherwise portable across Unix-like platforms, and since clients calling `try StatFS(...)` are expected to handle a potential `Errno`, the always-failing calls wouldn't degrade ergonomics. It would also keep the availability coupled: once `wasi-libc` gains real `statvfs` support, System would pick it up automatically without needing to track it.
However, the portability would only be at compile time, since every call would throw `Errno.noFunction`. The WASI mappings, such as reading `mountFlags` from `f_flag` and an integer `FileSystemID` that other platforms can't decode, would also be designed against `wasi-libc`'s stubs. Leaving WASI out also lets `StatFS` wrap `statfs` on every platform where it's available, instead of `statvfs` on WASI alone. Making `StatFS` available later is additive, while reshaping it after it ships would be source-breaking.
## Acknowledgments
Thank you to Michael Ilseman for discussions on the shape and future directions of this API.
## Appendix
### Swift API to C mapping
The following tables show the mapping between Swift APIs and their underlying C system calls across different operating systems:
#### `StatFS` function mappings
The `retryOnInterrupt: Bool = true` parameter is omitted for clarity.
| Swift API | Darwin / BSD / Linux / Android |
|-----------|--------------------------------|
| `StatFS(_ path: UnsafePointer<CChar>)` | `statfs()` |
| `StatFS(_ path: FilePath)` | `statfs()` |
| | |
| `StatFS(_ fd: FileDescriptor)` | `fstatfs()` |
#### `StatFS` property mappings
`"` denotes the same property name across all operating systems.
| Swift Property | Darwin | FreeBSD | OpenBSD | Linux | Android |
|----------------|--------|---------|---------|-------|---------|
| `blockSize` | `f_bsize` | " | " | " | " |
| `preferredIOBlockSize` | `f_iosize` | `f_iosize` | `f_iosize` | N/A | N/A |
| `fragmentSize` | N/A | N/A | N/A | `f_frsize` | `f_frsize` |
| `totalBlocks` | `f_blocks` | " | " | " | " |
| `freeBlocks` | `f_bfree` | " | " | " | " |
| `availableBlocks` | `f_bavail` | " | " | " | " |
| `totalInodes` | `f_files` | " | " | " | " |
| `freeInodes` | `f_ffree` | " | " | " | " |
| `availableInodes` | N/A | N/A | `f_favail` | N/A | N/A |
| `maximumNameLength` | N/A | `f_namemax` | `f_namemax` | `f_namelen` | `f_namelen` |
| `fileSystemID` | `f_fsid` | " | " | " | " |
| `mountFlags` | `f_flags` | " | " | " | " |
| `type` | N/A | N/A | N/A | `f_type` | `f_type` |
| `subtype` | `f_fssubtype` | N/A | N/A | N/A | N/A |
| `owner` | `f_owner` | `f_owner` | `f_owner` | N/A | N/A |
| `typeName` | `f_fstypename` | `f_fstypename` | `f_fstypename` | N/A | N/A |
| `mountPoint` | `f_mntonname` | `f_mntonname` | `f_mntonname` | N/A | N/A |
| `mountSource` | `f_mntfromname` | `f_mntfromname` | `f_mntfromname` | N/A | N/A |
#### `MountFlags` mappings
| Swift Flag | Darwin | FreeBSD | OpenBSD | Linux | Android |
|------------|--------|---------|---------|-------|---------|
| `readOnly` | `MNT_RDONLY` | `MNT_RDONLY` | `MNT_RDONLY` | `ST_RDONLY` | `ST_RDONLY` |
| `synchronous` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `ST_SYNCHRONOUS` | `ST_SYNCHRONOUS` |
| `noExecution` | `MNT_NOEXEC` | `MNT_NOEXEC` | `MNT_NOEXEC` | `ST_NOEXEC` | `ST_NOEXEC` |
| `noSetUserID` | `MNT_NOSUID` | `MNT_NOSUID` | `MNT_NOSUID` | `ST_NOSUID` | `ST_NOSUID` |
| `noAccessTime` | `MNT_NOATIME` | `MNT_NOATIME` | `MNT_NOATIME` | `ST_NOATIME` | `ST_NOATIME` |
| `noDevices` | `MNT_NODEV` | N/A | `MNT_NODEV` | `ST_NODEV` | `ST_NODEV` |
| `mandatoryLocking` | N/A | N/A | N/A | `ST_MANDLOCK` | `ST_MANDLOCK` |
| `noDirectoryAccessTime` | N/A | N/A | N/A | `ST_NODIRATIME` | `ST_NODIRATIME` |
| `relativeAccessTime` | N/A | N/A | N/A | `ST_RELATIME` | `ST_RELATIME` |
| `noSymlinkFollowing` | N/A | `MNT_NOSYMFOLLOW` | N/A | `ST_NOSYMFOLLOW` | `ST_NOSYMFOLLOW` |
| `asynchronous` | `MNT_ASYNC` | `MNT_ASYNC` | `MNT_ASYNC` | N/A | N/A |
| `exported` | `MNT_EXPORTED` | `MNT_EXPORTED` | `MNT_EXPORTED` | N/A | N/A |
| `local` | `MNT_LOCAL` | `MNT_LOCAL` | `MNT_LOCAL` | N/A | N/A |
| `quotasEnabled` | `MNT_QUOTA` | `MNT_QUOTA` | `MNT_QUOTA` | N/A | N/A |
| `rootFileSystem` | `MNT_ROOTFS` | `MNT_ROOTFS` | `MNT_ROOTFS` | N/A | N/A |
| `union` | `MNT_UNION` | `MNT_UNION` | N/A | N/A | N/A |
| `automounted` | `MNT_AUTOMOUNTED` | `MNT_AUTOMOUNTED` | N/A | N/A | N/A |
| `multiLabel` | `MNT_MULTILABEL` | `MNT_MULTILABEL` | N/A | N/A | N/A |
| `exportedReadOnly` | N/A | `MNT_EXRDONLY` | `MNT_EXRDONLY` | N/A | N/A |
| `exportedByDefault` | N/A | `MNT_DEFEXPORTED` | `MNT_DEFEXPORTED` | N/A | N/A |
| `exportedAnonymously` | N/A | `MNT_EXPORTANON` | `MNT_EXPORTANON` | N/A | N/A |
| `softUpdates` | N/A | `MNT_SOFTDEP` | `MNT_SOFTDEP` | N/A | N/A |
| `contentProtection` | `MNT_CPROTECT` | N/A | N/A | N/A | N/A |
| `removable` | `MNT_REMOVABLE` | N/A | N/A | N/A | N/A |
| `quarantined` | `MNT_QUARANTINE` | N/A | N/A | N/A | N/A |
| `supportsVolfs` | `MNT_DOVOLFS` | N/A | N/A | N/A | N/A |
| `noBrowsing` | `MNT_DONTBROWSE` | N/A | N/A | N/A | N/A |
| `ignoresOwnership` | `MNT_IGNORE_OWNERSHIP` | N/A | N/A | N/A | N/A |
| `journaled` | `MNT_JOURNALED` | N/A | N/A | N/A | N/A |
| `noUserExtendedAttributes` | `MNT_NOUSERXATTR` | N/A | N/A | N/A | N/A |
| `defersWrites` | `MNT_DEFWRITE` | N/A | N/A | N/A | N/A |
| `noSymlinkFollowingAtMountPoint` | `MNT_NOFOLLOW` | N/A | N/A | N/A | N/A |
| `snapshot` | `MNT_SNAPSHOT` | N/A | N/A | N/A | N/A |
| `strictAccessTime` | `MNT_STRICTATIME` | N/A | N/A | N/A | N/A |
| `exportedWithKerberos` | N/A | `MNT_EXKERB` | N/A | N/A | N/A |
| `exportedPublicly` | N/A | `MNT_EXPUBLIC` | N/A | N/A | N/A |
| `posixACLs` | N/A | `MNT_ACLS` | N/A | N/A | N/A |
| `geomJournaled` | N/A | `MNT_GJOURNAL` | N/A | N/A | N/A |
| `excludedFromDiskFreeReports` | N/A | `MNT_IGNORE` | N/A | N/A | N/A |
| `nfs4ACLs` | N/A | `MNT_NFS4ACLS` | N/A | N/A | N/A |
| `noClusteredReads` | N/A | `MNT_NOCLUSTERR` | N/A | N/A | N/A |
| `noClusteredWrites` | N/A | `MNT_NOCLUSTERW` | N/A | N/A | N/A |
| `setUserIDDirectories` | N/A | `MNT_SUIDDIR` | N/A | N/A | N/A |
| `softUpdatesJournaling` | N/A | `MNT_SUJ` | N/A | N/A | N/A |
| `untrusted` | N/A | `MNT_UNTRUSTED` | N/A | N/A | N/A |
| `userMounted` | N/A | `MNT_USER` | N/A | N/A | N/A |
| `verified` | N/A | `MNT_VERIFIED` | N/A | N/A | N/A |
| `noPermissionChecks` | N/A | N/A | `MNT_NOPERM` | N/A | N/A |
| `writeExecuteAllowed` | N/A | N/A | `MNT_WXALLOWED` | N/A | N/A |
+9 -8
View File
@@ -32,7 +32,7 @@ To use the `SystemPackage` library in a SwiftPM project,
add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-system", from: "1.7.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.8.0"),
```
Finally, include `"SystemPackage"` as a dependency for your executable target:
@@ -41,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
let package = Package(
// name, platforms, products, etc.
dependencies: [
.package(url: "https://github.com/apple/swift-system", from: "1.7.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.8.0"),
// other dependencies
],
targets: [
@@ -87,8 +87,8 @@ The following table maps existing package releases to their minimum required Swi
| Package version | Swift version | Xcode release |
| ----------------------- | --------------- | ------------- |
| swift-system 1.3.x | >= Swift 5.8 | >= Xcode 14.3 |
| swift-system 1.4.x through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 |
| swift-system 1.7.x | >= Swift 6.1 | >= Xcode 16.3 |
| swift-system 1.4.0 through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 |
| swift-system 1.7.0 through 1.8.x | >= Swift 6.1 | >= Xcode 16.3 |
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so.
@@ -113,16 +113,17 @@ We maintain separate branches for each active minor version of the package:
| swift-system 1.5.x | release/1.5.0 |
| swift-system 1.6.x | release/1.6.0 |
| swift-system 1.7.x | release/1.7.0 |
| swift-system 1.8.x (unreleased) | main |
| swift-system 1.8.x | release/1.8.x |
| swift-system 1.9.x (unreleased) | release/1.9.x |
Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction:
`release/1.6.0` → `release/1.7.0` → `main`
`release/1.8.x` → `release/1.9.x` → `main`
For example, anything landing on `release/1.3` will eventually appear on `release/1.4` and then `main` too; there is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.)
For example, anything landing on `release/1.8.x` will eventually appear on `release/1.9.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Merges into `release/1.9.x` and `main` are performed by the [release](.github/workflows/automerge_to_release.yml) and [main](.github/workflows/automerge_to_main.yml) automergers; propagation from older release branches is performed by project maintainers.)
### Code of Conduct
Like all Swift.org projects, we would like the Swift System project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc].
[coc]: CODE_OF_CONDUCT.md
[coc]: https://github.com/apple/.github/blob/main/CODE_OF_CONDUCT.md
+3
View File
@@ -8,4 +8,7 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_subdirectory(CSystem)
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
add_subdirectory(CSystemStatFS)
endif()
add_subdirectory(System)
+2 -2
View File
@@ -15,8 +15,8 @@ target_include_directories(CSystem PUBLIC
install(FILES
include/CSystemLinux.h
include/CSystemShared.h
include/CSystemWindows.h
include/CSystemFreeBSD.h
include/CSystemWASI.h
include/io_uring.h
include/module.modulemap
DESTINATION include/CSystem)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
-21
View File
@@ -1,21 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if defined(__FreeBSD__)
#include <fcntl.h>
#ifdef O_CLOFORK
#define FREEBSD_O_CLOFORK O_CLOFORK
#else
#define FREEBSD_O_CLOFORK 0
#endif
#endif
+32 -12
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 - 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
@@ -9,16 +9,36 @@
#ifdef __linux__
#include <sys/epoll.h>
// Glibc doesn't export eventfd, which the tests use.
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <sys/sysinfo.h>
#include <sys/timerfd.h>
#include <sys/types.h>
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include "io_uring.h"
#endif
// Test-only getters for constants that require _GNU_SOURCE.
unsigned long long _system_get_ST_RDONLY(void);
unsigned long long _system_get_ST_NOSUID(void);
unsigned long long _system_get_ST_NODEV(void);
unsigned long long _system_get_ST_NOEXEC(void);
unsigned long long _system_get_ST_SYNCHRONOUS(void);
unsigned long long _system_get_ST_MANDLOCK(void);
unsigned long long _system_get_ST_NOATIME(void);
unsigned long long _system_get_ST_NODIRATIME(void);
unsigned long long _system_get_ST_RELATIME(void);
unsigned long long _system_get_ST_NOSYMFOLLOW(void);
#if !defined(__ANDROID__)
#include <stddef.h>
#include "io_uring.h"
// Defined in shims.c, which can include the libc headers they need.
extern int csystem_io_uring_setup(unsigned int entries,
struct io_uring_params *p);
extern int csystem_io_uring_enter(int fd, unsigned int to_submit,
unsigned int min_complete,
unsigned int flags, void *sig);
extern int csystem_io_uring_enter2(int fd, unsigned int to_submit,
unsigned int min_complete,
unsigned int flags, void *args, size_t sz);
extern int csystem_io_uring_register(int fd, unsigned int opcode, void *arg,
unsigned int nr_args);
#endif // !defined(__ANDROID__)
#endif // __linux__
+15
View File
@@ -12,3 +12,18 @@ extern int csystem_posix_pipe2(int fildes[2], int flag);
#endif
extern int csystem_posix_dup3(int fildes, int fildes2, int flag);
#include <stddef.h>
// Thread-safe replacement for strerror(3).
//
// Writes the message for `errnum` into `buf`, which holds `buflen` bytes, and
// always NUL-terminates it if `buflen` is not zero. Returns 0 on success, or an
// error number (e.g. EINVAL for an unknown `errnum`, ERANGE if the message was
// truncated). A message that exactly fills the buffer is also reported as
// ERANGE, because not every C library can tell that apart from truncation.
// Even on failure, `buf` may contain a message such as "Unknown error 1234".
//
// This hides the differences between the XSI and GNU variants of strerror_r,
// and uses strerror_s on Windows.
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen);
-17
View File
@@ -1,17 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if defined(_WIN32)
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRA_LEAN
#include <Windows.h>
#endif
+8 -47
View File
@@ -1,7 +1,6 @@
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <signal.h>
#pragma once
// Types only: the syscall wrappers need libc headers, so they're in shims.c.
#define __SWIFT_IORING_SQE_FALLBACK_STRUCT { \
__u8 opcode; \
@@ -81,7 +80,7 @@
#ifdef IORING_TIMEOUT_BOOTTIME
// Kernel version >= 5.15, io_uring_sqe has file_index
// and all current Swift operations are supported.
#define __SWIFT_IORING_SUPPORTED true
#define __SWIFT_IORING_SUPPORTED 1
typedef struct io_uring_sqe swift_io_uring_sqe;
#else
// io_uring_sqe is missing properties that IORequest expects.
@@ -89,7 +88,7 @@ typedef struct io_uring_sqe swift_io_uring_sqe;
//
// Define a fallback struct to avoid build errors, but IORing
// will throw ENOTSUP on initialization.
#define __SWIFT_IORING_SUPPORTED false
#define __SWIFT_IORING_SUPPORTED 0
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
#endif
@@ -107,13 +106,14 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
// Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK)
#include <stdint.h>
#define __SWIFT_IORING_SUPPORTED false
#define __SWIFT_IORING_SUPPORTED 0
#define IORING_OFF_SQ_RING 0ULL
#define IORING_OFF_CQ_RING 0x8000000ULL
#define IORING_OFF_SQES 0x10000000ULL
#define IORING_ENTER_GETEVENTS (1U << 0)
#define IORING_ENTER_GETEVENTS (1U << 0)
#define IORING_ENTER_EXT_ARG (1U << 3)
#define IORING_FEAT_SINGLE_MMAP (1U << 0)
#define IORING_FEAT_NODROP (1U << 1)
@@ -192,19 +192,6 @@ struct io_uring_params {
};
#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;
@@ -219,29 +206,3 @@ struct swift_io_uring_getevents_arg {
__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
+11 -2
View File
@@ -1,8 +1,17 @@
// System imports CSystem with `internal import`. Don't include a header that
// the platform's C module also includes: CSystem would then co-own its
// declarations, so Swift would limit them to CSystem's import access level and
// could credit their members to CSystem under MemberImportVisibility.
// (CSystemWASI.h still does; see Constants.swift.)
module CSystem {
header "CSystemShared.h"
header "CSystemLinux.h"
header "CSystemWASI.h"
header "CSystemWindows.h"
header "CSystemFreeBSD.h"
export *
}
// IORing's inlinable code stores these types, so System imports this module
// with `public import`. Keep libc headers out of it too.
module CSystemIOUring {
header "io_uring.h"
}
+138 -19
View File
@@ -7,48 +7,167 @@
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>
#define __BSD_VISIBLE
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__)
#include <unistd.h>
#endif
#ifdef __linux__
#define _GNU_SOURCE
#include <signal.h>
#include <sys/statvfs.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <CSystemLinux.h>
#endif
#if defined(_WIN32)
#include <CSystemWindows.h>
unsigned long long _system_get_ST_RDONLY(void) { return ST_RDONLY; }
unsigned long long _system_get_ST_NOSUID(void) { return ST_NOSUID; }
unsigned long long _system_get_ST_NODEV(void) { return ST_NODEV; }
unsigned long long _system_get_ST_NOEXEC(void) { return ST_NOEXEC; }
unsigned long long _system_get_ST_SYNCHRONOUS(void) { return ST_SYNCHRONOUS; }
unsigned long long _system_get_ST_MANDLOCK(void) { return ST_MANDLOCK; }
unsigned long long _system_get_ST_NOATIME(void) { return ST_NOATIME; }
unsigned long long _system_get_ST_NODIRATIME(void) { return ST_NODIRATIME; }
unsigned long long _system_get_ST_RELATIME(void) { return ST_RELATIME; }
// ST_NOSYMFOLLOW wasn't defined until glibc 2.34. 0x2000 is the bit the
// kernel's internal <linux/statfs.h> and newer glibc both use.
#ifndef ST_NOSYMFOLLOW
#define ST_NOSYMFOLLOW 0x2000
#endif
unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; }
#endif
#include <errno.h>
#include <string.h>
#include <CSystemShared.h>
static int csystem_strerror_r_impl(int errnum, char *buf, size_t buflen) {
#if defined(_WIN32)
return strerror_s(buf, buflen, errnum);
#elif defined(_GNU_SOURCE) && \
(defined(__GLIBC__) || (defined(__ANDROID__) && __ANDROID_API__ >= 23))
// With _GNU_SOURCE (defined above on Linux), glibc and bionic provide the
// GNU variant, which returns a pointer to the message. That pointer is
// either `buf` or an immutable static string, so copying from it is safe.
const char *message = strerror_r(errnum, buf, buflen);
if (message == NULL) {
return EINVAL;
}
if (message != buf) {
size_t length = strlen(message);
if (length >= buflen) {
memcpy(buf, message, buflen - 1);
buf[buflen - 1] = '\0';
return ERANGE;
}
memcpy(buf, message, length + 1);
}
return 0;
#else
// XSI variant (Darwin, FreeBSD, OpenBSD, musl, WASI). Some implementations
// return -1 and set errno instead of returning the error number.
int result = strerror_r(errnum, buf, buflen);
if (result == -1) {
result = errno;
}
return result;
#endif
}
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen) {
if (buf == NULL || buflen == 0) {
return ERANGE;
}
buf[0] = '\0';
int result = csystem_strerror_r_impl(errnum, buf, buflen);
buf[buflen - 1] = '\0';
// strerror_s on Windows and bionic's strerror_r silently truncate the
// message and return 0. Report a message that fills the whole buffer as
// ERANGE on every platform, since it may have been truncated.
if (result == 0 && strlen(buf) == buflen - 1) {
result = ERANGE;
}
return result;
}
#if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__)
#define HAVE_PIPE2_DUP3
#endif
#if defined(__APPLE__)
#include <Availability.h>
#if defined(__MAC_27_0)
#include <unistd.h>
#define HAVE_PIPE2_DUP3
#endif
#endif // defined(__APPLE__)
// Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h
#if !defined(_WIN32)
extern int csystem_posix_pipe2(int fildes[2], int flag) {
#ifdef HAVE_PIPE2_DUP3
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
return pipe2(fildes, flag);
#else
errno = ENOSYS;
return -1;
#endif
__builtin_trap();
#elif defined(HAVE_PIPE2_DUP3)
return pipe2(fildes, flag);
#else
errno = ENOSYS;
return -1;
#endif
}
#endif // !defined(_WIN32)
extern int csystem_posix_dup3(int fildes, int fildes2, int flag) {
#ifdef HAVE_PIPE2_DUP3
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
return dup3(fildes, fildes2, flag);
#else
errno = ENOSYS;
return -1;
#endif
__builtin_trap();
#elif defined(HAVE_PIPE2_DUP3)
return dup3(fildes, fildes2, flag);
#else
errno = ENOSYS;
return -1;
#endif
}
#if defined(__linux__) && !defined(__ANDROID__)
# 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
extern int csystem_io_uring_setup(unsigned int entries,
struct io_uring_params *p) {
return syscall(__NR_io_uring_setup, entries, p);
}
extern int csystem_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, sz);
}
extern int csystem_io_uring_enter(int fd, unsigned int to_submit,
unsigned int min_complete,
unsigned int flags, void *sig) {
return csystem_io_uring_enter2(fd, to_submit, min_complete, flags, sig,
_NSIG / 8);
}
extern int csystem_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);
}
#endif // defined(__linux__) && !defined(__ANDROID__)
+19
View File
@@ -0,0 +1,19 @@
#[[
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
#]]
add_library(CSystemStatFS INTERFACE)
target_include_directories(CSystemStatFS INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>"
$<INSTALL_INTERFACE:include/CSystemStatFS>)
install(FILES
CSystemStatFS.h
module.modulemap
DESTINATION include/CSystemStatFS)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystemStatFS)
+18
View File
@@ -0,0 +1,18 @@
/*
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
*/
#pragma once
// Unlike the Musl and Android modules, Glibc doesn't export <sys/vfs.h>,
// which declares `struct statfs` and `statfs()`/`fstatfs()`. SystemPackage
// re-exports this module on glibc platforms so that clients can use the
// raw `CInterop.StatFS` value under MemberImportVisibility.
#if defined(__linux__) && !defined(__ANDROID__)
#include <sys/vfs.h>
#endif
+4
View File
@@ -0,0 +1,4 @@
module CSystemStatFS [system] {
header "CSystemStatFS.h"
export *
}
+50 -2
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 - 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
@@ -9,6 +9,7 @@ See https://swift.org/LICENSE.txt for license information
add_library(SystemPackage
Errno.swift
ErrnoWindows.swift
FileDescriptor.swift
FileHelpers.swift
FileOperations.swift
@@ -18,9 +19,32 @@ add_library(SystemPackage
SystemString.swift
Util.swift
Util+StringArray.swift
UtilConsumers.swift)
UtilConsumers.swift
WinSDK+Overlay.swift)
set_target_properties(SystemPackage PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
# Availability macro definitions.
# Should stay in sync with the `availability` array in Package.swift,
# matching `sourceAvailability`, which is the minimum Swift availability.
# Availability support for Darwin platforms is omitted.
set(SWIFT_SYSTEM_AVAILABILITY_VERSIONS
0.0.1 0.0.2 0.0.3
1.1.0 1.1.1 1.2.0 1.2.1 1.3.0 1.3.1 1.3.2 1.4.0
1.7.0 1.9.0
199)
set(SWIFT_SYSTEM_SOURCE_AVAILABILITY
"macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0")
set(SWIFT_SYSTEM_AVAILABILITY_MACRO)
foreach(version IN LISTS SWIFT_SYSTEM_AVAILABILITY_VERSIONS)
list(APPEND SWIFT_SYSTEM_AVAILABILITY_MACRO
"SHELL:-enable-experimental-feature \"AvailabilityMacro=System ${version}:${SWIFT_SYSTEM_SOURCE_AVAILABILITY}\"")
endforeach()
target_compile_options(SystemPackage PRIVATE
-enable-experimental-feature Lifetimes
${SWIFT_SYSTEM_AVAILABILITY_MACRO}
"SHELL:-package-name swift-system")
target_sources(SystemPackage PRIVATE
FilePath/FilePath.swift
FilePath/FilePathComponents.swift
@@ -28,7 +52,27 @@ target_sources(SystemPackage PRIVATE
FilePath/FilePathParsing.swift
FilePath/FilePathString.swift
FilePath/FilePathSyntax.swift
FilePath/FilePathTemp.swift
FilePath/FilePathTempPosix.swift
FilePath/FilePathTempWindows.swift
FilePath/FilePathWindows.swift)
target_sources(SystemPackage PRIVATE
FileSystem/FileFlags.swift
FileSystem/FileMode.swift
FileSystem/FileType.swift
FileSystem/Identifiers.swift
FileSystem/MountFlags.swift
FileSystem/Stat.swift
FileSystem/StatFS.swift)
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
target_sources(SystemPackage PRIVATE
IORing/IOCompletion.swift
IORing/IORequest.swift
IORing/IORing.swift
IORing/IORing+Util.swift
IORing/PollEvents.swift
IORing/RawIORequest.swift)
endif()
target_sources(SystemPackage PRIVATE
Internals/Backcompat.swift
Internals/CInterop.swift
@@ -40,6 +84,10 @@ target_sources(SystemPackage PRIVATE
Internals/WindowsSyscallAdapters.swift)
target_link_libraries(SystemPackage PUBLIC
CSystem)
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
target_link_libraries(SystemPackage PUBLIC
CSystemStatFS)
endif()
set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS")
if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS)
+18 -4
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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
@@ -1547,11 +1547,25 @@ extension Errno: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the most recent error
/// returned by a system call.
///
/// The corresponding C function is `strerror(3)`.
/// The corresponding C function is `strerror(3)`. This property uses a
/// thread-safe variant of it, so it is safe to use from multiple threads.
@inline(never)
public var description: String {
guard let ptr = system_strerror(self.rawValue) else { return "unknown error" }
return String(cString: ptr)
// Error messages are short, so 256 bytes is plenty. If one is longer,
// csystem_strerror_r truncates it. The message is written directly into
// the new string's storage.
let message = String(_unsafeUninitializedCapacity: 256) { buffer in
let capacity = buffer.count
buffer.withMemoryRebound(to: CChar.self) { buffer in
// Even when strerror_r fails, e.g. with EINVAL for an unknown error
// number, most C libraries still write a message like
// "Unknown error 1234", so use whatever was written. The shim always
// NUL-terminates the buffer.
_ = system_strerror_r(self.rawValue, buffer.baseAddress!, capacity)
}
return UnsafeBufferPointer(buffer).firstIndex(of: 0) ?? 0
}
return message.isEmpty ? "unknown error" : message
}
/// A textual representation,
+7 -12
View File
@@ -301,7 +301,6 @@ extension FileDescriptor {
public static var O_EVTONLY: OpenOptions { eventOnly }
#endif
#if !os(Windows)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open
@@ -319,16 +318,17 @@ extension FileDescriptor {
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_CLOEXEC: OpenOptions { closeOnExec }
#if os(Windows)
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_NOINHERIT: OpenOptions { closeOnExec }
#endif
}
/// Options that specify behavior for a newly-created pipe.
@frozen
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
@@ -399,11 +399,7 @@ extension FileDescriptor {
/// 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)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
@@ -528,7 +524,6 @@ extension FileDescriptor {
@available(*, unavailable, renamed: "nextData")
public static var SEEK_DATA: SeekOrigin { nextData }
#endif
}
}
+30 -35
View File
@@ -16,6 +16,8 @@ extension FileDescriptor {
/// - mode: The read and write access to use.
/// - options: The behavior for opening the file.
/// - permissions: The file permissions to use for created files.
/// This value must not be `nil` when `options` contains `.create`;
/// passing `nil` in that case is a programmer error and traps at runtime.
/// - retryOnInterrupt: Whether to retry the open operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
@@ -55,6 +57,8 @@ extension FileDescriptor {
/// - mode: The read and write access to use.
/// - options: The behavior for opening the file.
/// - permissions: The file permissions to use for created files.
/// This value must not be `nil` when `options` contains `.create`;
/// passing `nil` in that case is a programmer error and traps at runtime.
/// - retryOnInterrupt: Whether to retry the open operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
@@ -88,8 +92,10 @@ extension FileDescriptor {
if let permissions = permissions {
return system_open(path, oFlag, permissions.rawValue)
}
precondition(!options.contains(.create),
"Create must be given permissions")
if options.contains(.create) {
fatalError(
"FileDescriptor.open: 'permissions' must not be nil when 'options' contains '.create'")
}
return system_open(path, oFlag)
}
return descOrError.map { FileDescriptor(rawValue: $0) }
@@ -102,6 +108,8 @@ extension FileDescriptor {
/// - mode: The read and write access to use.
/// - options: The behavior for opening the file.
/// - permissions: The file permissions to use for created files.
/// This value must not be `nil` when `options` contains `.create`;
/// passing `nil` in that case is a programmer error and traps at runtime.
/// - retryOnInterrupt: Whether to retry the open operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
@@ -222,7 +230,7 @@ extension FileDescriptor {
internal func _read(
into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool
) throws -> Result<Int, Errno> {
) -> Result<Int, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_read(self.rawValue, buffer.baseAddress, buffer.count)
}
@@ -370,13 +378,13 @@ extension FileDescriptor {
#if !os(WASI)
@available(System 0.0.2, *)
extension FileDescriptor {
/// Duplicates this file descriptor and return the newly created copy.
/// Duplicates this file descriptor and returns the newly created copy.
///
/// - Parameters:
/// - `target`: The desired target file descriptor, or `nil`, in which case
/// the copy is assigned to the file descriptor with the lowest raw value
/// that is not currently in use by the process.
/// - retryOnInterrupt: Whether to retry the write operation
/// - retryOnInterrupt: Whether to retry the duplicate operation
/// if it throws ``Errno/interrupted``. The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The new file descriptor.
@@ -415,7 +423,7 @@ extension FileDescriptor {
/// 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 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.
///
@@ -436,20 +444,19 @@ extension FileDescriptor {
/// 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)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@_alwaysEmitIntoClient
@discardableResult
public func duplicate(
as target: FileDescriptor,
options: DuplicateOptions,
retryOnInterrupt: Bool = true
) throws(Errno) -> FileDescriptor {
try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get()
let result = _duplicate(
as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt
)
return try result.get()
}
@available(System 0.0.2, *)
@@ -468,11 +475,7 @@ extension FileDescriptor {
}
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor,
@@ -502,7 +505,7 @@ extension FileDescriptor {
fatalError("Not implemented")
}
}
#endif
#endif // !os(WASI)
#if !os(WASI)
@available(System 1.1.0, *)
@@ -524,9 +527,9 @@ extension FileDescriptor {
/// 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.
/// equivalent to calling the overload with no options. On Windows, the
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
/// but this overload disables it when called with an empty option set.
///
/// - Parameters:
/// - options: The behavior for creating the pipe.
@@ -535,11 +538,7 @@ extension FileDescriptor {
///
/// The corresponding C function is `pipe2`.
@_alwaysEmitIntoClient
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public static func pipe(
options: PipeOptions
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
@@ -560,11 +559,7 @@ extension FileDescriptor {
}
}
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@usableFromInline
internal static func _pipe(
options: Int32,
@@ -585,7 +580,7 @@ extension FileDescriptor {
fatalError("Not implemented")
}
}
#endif
#endif // !os(WASI)
@available(System 1.2.0, *)
extension FileDescriptor {
@@ -674,4 +669,4 @@ extension FilePermissions {
return system_umask(mode)
}
}
#endif
#endif // !os(WASI)
@@ -143,7 +143,9 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
str.append(platformSeparator)
}
str.appendComponents(components: newElements)
if !atEnd {
// If we're replacing through the end, we must not leave a trailing
// separator.
if subrange.upperBound != endIndex {
str.append(platformSeparator)
}
_path._storage.replaceSubrange(range, with: str)
@@ -461,7 +461,10 @@ extension String {
public init(decoding path: FilePath) {
self.init(_decoding: path)
}
}
@available(System 0.0.2, *)
extension String {
/// Creates a string from a file path, validating its contents as UTF-8 on
/// Unix and UTF-16 on Windows.
///
@@ -470,6 +473,7 @@ extension String {
///
/// If the contents of the file path isn't a well-formed Unicode string,
/// this initializer returns `nil`.
@available(System 0.0.2, *)
public init?(validating path: FilePath) {
self.init(_validating: path)
}
@@ -12,15 +12,13 @@
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import CSystem
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#elseif canImport(WASILibc)
internal import CSystem // For the members of system_dirent
import WASILibc
#elseif canImport(Android)
import CSystem
import Android
#else
#error("Unsupported Platform")
+2 -2
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -45,7 +45,7 @@
///
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
/// The raw C flags.
+2 -2
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -14,7 +14,7 @@
///
/// - Note: Only available on Unix-like platforms.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C mode.
+2 -2
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -34,7 +34,7 @@
///
/// - Note: Only available on Unix-like platforms.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
/// The raw file-type bits from the C mode.
+5 -5
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -12,7 +12,7 @@
#if !os(Windows)
/// A Swift wrapper of the C `uid_t` type.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C `uid_t`.
@@ -30,7 +30,7 @@ public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
/// A Swift wrapper of the C `gid_t` type.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C `gid_t`.
@@ -48,7 +48,7 @@ public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
/// A Swift wrapper of the C `dev_t` type.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C `dev_t`.
@@ -66,7 +66,7 @@ public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
/// A Swift wrapper of the C `ino_t` type.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C `ino_t`.
+647
View File
@@ -0,0 +1,647 @@
//===----------------------------------------------------------------------===//
//
// 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 !os(Windows) && !os(WASI)
/// Flags describing a mounted file system.
///
/// These are the flags reported in the `f_flags` field of a `statfs` struct.
/// Some reflect options employed when mounting the file system, while others,
/// like `local` and `rootFileSystem`, describe state the kernel reports.
///
/// - Note: Not available on Windows or WASI.
///
/// The corresponding C constants available on each platform:
///
/// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android |
/// |----------------------------------|------------------------|-------------------|-------------------|------------------|------------------|
/// | `readOnly` | `MNT_RDONLY` | `MNT_RDONLY` | `MNT_RDONLY` | `ST_RDONLY` | `ST_RDONLY` |
/// | `synchronous` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `ST_SYNCHRONOUS` | `ST_SYNCHRONOUS` |
/// | `noExecution` | `MNT_NOEXEC` | `MNT_NOEXEC` | `MNT_NOEXEC` | `ST_NOEXEC` | `ST_NOEXEC` |
/// | `noSetUserID` | `MNT_NOSUID` | `MNT_NOSUID` | `MNT_NOSUID` | `ST_NOSUID` | `ST_NOSUID` |
/// | `noAccessTime` | `MNT_NOATIME` | `MNT_NOATIME` | `MNT_NOATIME` | `ST_NOATIME` | `ST_NOATIME` |
/// | `noDevices` | `MNT_NODEV` | N/A | `MNT_NODEV` | `ST_NODEV` | `ST_NODEV` |
/// | `mandatoryLocking` | N/A | N/A | N/A | `ST_MANDLOCK` | `ST_MANDLOCK` |
/// | `noDirectoryAccessTime` | N/A | N/A | N/A | `ST_NODIRATIME` | `ST_NODIRATIME` |
/// | `relativeAccessTime` | N/A | N/A | N/A | `ST_RELATIME` | `ST_RELATIME` |
/// | `noSymlinkFollowing` | N/A | `MNT_NOSYMFOLLOW` | N/A | `ST_NOSYMFOLLOW` | `ST_NOSYMFOLLOW` |
/// | `asynchronous` | `MNT_ASYNC` | `MNT_ASYNC` | `MNT_ASYNC` | N/A | N/A |
/// | `exported` | `MNT_EXPORTED` | `MNT_EXPORTED` | `MNT_EXPORTED` | N/A | N/A |
/// | `local` | `MNT_LOCAL` | `MNT_LOCAL` | `MNT_LOCAL` | N/A | N/A |
/// | `quotasEnabled` | `MNT_QUOTA` | `MNT_QUOTA` | `MNT_QUOTA` | N/A | N/A |
/// | `rootFileSystem` | `MNT_ROOTFS` | `MNT_ROOTFS` | `MNT_ROOTFS` | N/A | N/A |
/// | `union` | `MNT_UNION` | `MNT_UNION` | N/A | N/A | N/A |
/// | `automounted` | `MNT_AUTOMOUNTED` | `MNT_AUTOMOUNTED` | N/A | N/A | N/A |
/// | `multiLabel` | `MNT_MULTILABEL` | `MNT_MULTILABEL` | N/A | N/A | N/A |
/// | `exportedReadOnly` | N/A | `MNT_EXRDONLY` | `MNT_EXRDONLY` | N/A | N/A |
/// | `exportedByDefault` | N/A | `MNT_DEFEXPORTED` | `MNT_DEFEXPORTED` | N/A | N/A |
/// | `exportedAnonymously` | N/A | `MNT_EXPORTANON` | `MNT_EXPORTANON` | N/A | N/A |
/// | `softUpdates` | N/A | `MNT_SOFTDEP` | `MNT_SOFTDEP` | N/A | N/A |
/// | `contentProtection` | `MNT_CPROTECT` | N/A | N/A | N/A | N/A |
/// | `removable` | `MNT_REMOVABLE` | N/A | N/A | N/A | N/A |
/// | `quarantined` | `MNT_QUARANTINE` | N/A | N/A | N/A | N/A |
/// | `supportsVolfs` | `MNT_DOVOLFS` | N/A | N/A | N/A | N/A |
/// | `noBrowsing` | `MNT_DONTBROWSE` | N/A | N/A | N/A | N/A |
/// | `ignoresOwnership` | `MNT_IGNORE_OWNERSHIP` | N/A | N/A | N/A | N/A |
/// | `journaled` | `MNT_JOURNALED` | N/A | N/A | N/A | N/A |
/// | `noUserExtendedAttributes` | `MNT_NOUSERXATTR` | N/A | N/A | N/A | N/A |
/// | `defersWrites` | `MNT_DEFWRITE` | N/A | N/A | N/A | N/A |
/// | `noSymlinkFollowingAtMountPoint` | `MNT_NOFOLLOW` | N/A | N/A | N/A | N/A |
/// | `snapshot` | `MNT_SNAPSHOT` | N/A | N/A | N/A | N/A |
/// | `strictAccessTime` | `MNT_STRICTATIME` | N/A | N/A | N/A | N/A |
/// | `exportedWithKerberos` | N/A | `MNT_EXKERB` | N/A | N/A | N/A |
/// | `exportedPublicly` | N/A | `MNT_EXPUBLIC` | N/A | N/A | N/A |
/// | `posixACLs` | N/A | `MNT_ACLS` | N/A | N/A | N/A |
/// | `geomJournaled` | N/A | `MNT_GJOURNAL` | N/A | N/A | N/A |
/// | `excludedFromDiskFreeReports` | N/A | `MNT_IGNORE` | N/A | N/A | N/A |
/// | `nfs4ACLs` | N/A | `MNT_NFS4ACLS` | N/A | N/A | N/A |
/// | `noClusteredReads` | N/A | `MNT_NOCLUSTERR` | N/A | N/A | N/A |
/// | `noClusteredWrites` | N/A | `MNT_NOCLUSTERW` | N/A | N/A | N/A |
/// | `setUserIDDirectories` | N/A | `MNT_SUIDDIR` | N/A | N/A | N/A |
/// | `softUpdatesJournaling` | N/A | `MNT_SUJ` | N/A | N/A | N/A |
/// | `untrusted` | N/A | `MNT_UNTRUSTED` | N/A | N/A | N/A |
/// | `userMounted` | N/A | `MNT_USER` | N/A | N/A | N/A |
/// | `verified` | N/A | `MNT_VERIFIED` | N/A | N/A | N/A |
/// | `noPermissionChecks` | N/A | N/A | `MNT_NOPERM` | N/A | N/A |
/// | `writeExecuteAllowed` | N/A | N/A | `MNT_WXALLOWED` | N/A | N/A |
@frozen
@available(System 1.9.0, *)
public struct MountFlags: OptionSet, Sendable, Hashable, Codable {
/// The raw C flags.
@_alwaysEmitIntoClient
public let rawValue: CInterop.MountFlags
/// Creates a strongly-typed `MountFlags` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.MountFlags) { self.rawValue = rawValue }
// MARK: Flags Available on All Platforms
/// The file system is mounted read-only, even for the super-user.
///
/// The corresponding C constant is `MNT_RDONLY` on Darwin and BSD,
/// or `ST_RDONLY` otherwise.
@_alwaysEmitIntoClient
public static var readOnly: MountFlags { MountFlags(rawValue: _MOUNT_RDONLY) }
/// The file system is written to synchronously.
///
/// The corresponding C constant is `MNT_SYNCHRONOUS` on Darwin and BSD,
/// or `ST_SYNCHRONOUS` otherwise.
@_alwaysEmitIntoClient
public static var synchronous: MountFlags { MountFlags(rawValue: _MOUNT_SYNCHRONOUS) }
/// Programs may not be executed from the file system.
///
/// The corresponding C constant is `MNT_NOEXEC` on Darwin and BSD,
/// or `ST_NOEXEC` otherwise.
@_alwaysEmitIntoClient
public static var noExecution: MountFlags { MountFlags(rawValue: _MOUNT_NOEXEC) }
/// Set-user-ID and set-group-ID (setuid and setgid) bits are not honored on
/// the file system.
///
/// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD,
/// or `ST_NOSUID` otherwise.
@_alwaysEmitIntoClient
public static var noSetUserID: MountFlags { MountFlags(rawValue: _MOUNT_NOSUID) }
/// Access times are not updated on the file system.
///
/// - Note: On OpenBSD, access time may still be updated when the
/// modification or status-change time is also being updated.
///
/// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD,
/// or `ST_NOATIME` otherwise.
@_alwaysEmitIntoClient
public static var noAccessTime: MountFlags { MountFlags(rawValue: _MOUNT_NOATIME) }
// MARK: Flags Available on All Platforms Except FreeBSD
#if !os(FreeBSD)
/// Special files may not be interpreted on the file system.
///
/// - Note: Not available on FreeBSD.
///
/// The corresponding C constant is `MNT_NODEV` on Darwin and OpenBSD,
/// or `ST_NODEV` otherwise.
@_alwaysEmitIntoClient
public static var noDevices: MountFlags { MountFlags(rawValue: _MOUNT_NODEV) }
#endif
// MARK: Flags Available on Linux and Android
// Glibc and musl also define `ST_WRITE`, `ST_APPEND`, and `ST_IMMUTABLE`, but
// Linux never reports them in `f_flags`, so they have no corresponding flag.
#if os(Linux) || os(Android)
/// Mandatory file locking is enabled on the file system.
///
/// - Note: Only available on Linux and Android.
/// - Note: Mandatory locking was deprecated and removed in Linux 5.15.
///
/// The corresponding C constant is `ST_MANDLOCK`.
@_alwaysEmitIntoClient
public static var mandatoryLocking: MountFlags { MountFlags(rawValue: _ST_MANDLOCK) }
/// Directory access times are not updated on the file system.
///
/// - Note: Only available on Linux and Android.
///
/// The corresponding C constant is `ST_NODIRATIME`.
@_alwaysEmitIntoClient
public static var noDirectoryAccessTime: MountFlags { MountFlags(rawValue: _ST_NODIRATIME) }
/// The access time is only updated if it's earlier than or equal to the file's
/// last modification or status-change time, or if it's more than a day old.
///
/// - Note: Only available on Linux and Android.
///
/// The corresponding C constant is `ST_RELATIME`.
@_alwaysEmitIntoClient
public static var relativeAccessTime: MountFlags { MountFlags(rawValue: _ST_RELATIME) }
#endif
// MARK: Flags Available on Linux, Android, and FreeBSD
#if os(Linux) || os(Android) || os(FreeBSD)
/// Symbolic links are not followed when resolving paths on the file system.
///
/// - Note: Only available on Linux, Android, and FreeBSD.
///
/// The corresponding C constant is `MNT_NOSYMFOLLOW` on FreeBSD,
/// or `ST_NOSYMFOLLOW` on Linux and Android.
@_alwaysEmitIntoClient
public static var noSymlinkFollowing: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) }
#endif
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
/// The file system is written to asynchronously.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_ASYNC`.
@_alwaysEmitIntoClient
public static var asynchronous: MountFlags { MountFlags(rawValue: _MNT_ASYNC) }
/// The file system is exported for use over the network via NFS.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_EXPORTED`.
@_alwaysEmitIntoClient
public static var exported: MountFlags { MountFlags(rawValue: _MNT_EXPORTED) }
/// The file system is stored locally, rather than being accessed over a network.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_LOCAL`.
@_alwaysEmitIntoClient
public static var local: MountFlags { MountFlags(rawValue: _MNT_LOCAL) }
/// Quotas are enabled on the file system.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_QUOTA`.
@_alwaysEmitIntoClient
public static var quotasEnabled: MountFlags { MountFlags(rawValue: _MNT_QUOTA) }
/// The file system is the root file system.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_ROOTFS`.
@_alwaysEmitIntoClient
public static var rootFileSystem: MountFlags { MountFlags(rawValue: _MNT_ROOTFS) }
#endif
// MARK: Flags Available on Darwin and FreeBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// The file system is unioned with the underlying file system.
///
/// - Note: Only available on Darwin and FreeBSD.
///
/// The corresponding C constant is `MNT_UNION`.
@_alwaysEmitIntoClient
public static var union: MountFlags { MountFlags(rawValue: _MNT_UNION) }
/// The file system was mounted by the automounter.
///
/// - Note: Only available on Darwin and FreeBSD. See `automount(8)`.
///
/// The corresponding C constant is `MNT_AUTOMOUNTED`.
@_alwaysEmitIntoClient
public static var automounted: MountFlags { MountFlags(rawValue: _MNT_AUTOMOUNTED) }
/// The file system maintains Mandatory Access Control (MAC) labels for
/// individual objects.
///
/// - Note: Only available on Darwin and FreeBSD.
///
/// The corresponding C constant is `MNT_MULTILABEL`.
@_alwaysEmitIntoClient
public static var multiLabel: MountFlags { MountFlags(rawValue: _MNT_MULTILABEL) }
#endif
// MARK: Flags Available on FreeBSD and OpenBSD
#if os(FreeBSD) || os(OpenBSD)
/// The file system is exported for reading only.
///
/// - Note: Only available on FreeBSD and OpenBSD.
///
/// The corresponding C constant is `MNT_EXRDONLY`.
@_alwaysEmitIntoClient
public static var exportedReadOnly: MountFlags { MountFlags(rawValue: _MNT_EXRDONLY) }
/// The file system is exported to any host by default.
///
/// - Note: Only available on FreeBSD and OpenBSD.
///
/// The corresponding C constant is `MNT_DEFEXPORTED`.
@_alwaysEmitIntoClient
public static var exportedByDefault: MountFlags { MountFlags(rawValue: _MNT_DEFEXPORTED) }
/// The file system is exported with all remote users mapped to the
/// anonymous user account.
///
/// - Note: Only available on FreeBSD and OpenBSD.
///
/// The corresponding C constant is `MNT_EXPORTANON`.
@_alwaysEmitIntoClient
public static var exportedAnonymously: MountFlags { MountFlags(rawValue: _MNT_EXPORTANON) }
/// Soft updates are enabled on the file system.
///
/// - Note: Only available on FreeBSD and OpenBSD. Accepted for compatibility
/// on OpenBSD, but has no effect there.
///
/// The corresponding C constant is `MNT_SOFTDEP`.
@_alwaysEmitIntoClient
public static var softUpdates: MountFlags { MountFlags(rawValue: _MNT_SOFTDEP) }
#endif
// MARK: Flags Available on Darwin Only
#if SYSTEM_PACKAGE_DARWIN
/// Per-file encrypted data protection is enabled on the file system.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_CPROTECT`.
@_alwaysEmitIntoClient
public static var contentProtection: MountFlags { MountFlags(rawValue: _MNT_CPROTECT) }
/// The file system resides on removable media.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_REMOVABLE`.
@_alwaysEmitIntoClient
public static var removable: MountFlags { MountFlags(rawValue: _MNT_REMOVABLE) }
/// The file system is quarantined.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_QUARANTINE`.
@_alwaysEmitIntoClient
public static var quarantined: MountFlags { MountFlags(rawValue: _MNT_QUARANTINE) }
/// The file system supports volfs.
///
/// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5.
///
/// The corresponding C constant is `MNT_DOVOLFS`.
@_alwaysEmitIntoClient
public static var supportsVolfs: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) }
/// The file system should not be presented to the user for browsing
/// (e.g. hidden in Finder).
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_DONTBROWSE`.
@_alwaysEmitIntoClient
public static var noBrowsing: MountFlags { MountFlags(rawValue: _MNT_DONTBROWSE) }
/// The file system ignores ownership information.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`.
@_alwaysEmitIntoClient
public static var ignoresOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) }
/// The file system is journaled.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_JOURNALED`.
@_alwaysEmitIntoClient
public static var journaled: MountFlags { MountFlags(rawValue: _MNT_JOURNALED) }
/// User extended attributes are not allowed on the file system.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_NOUSERXATTR`.
@_alwaysEmitIntoClient
public static var noUserExtendedAttributes: MountFlags { MountFlags(rawValue: _MNT_NOUSERXATTR) }
/// The file system defers writes.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_DEFWRITE`.
@_alwaysEmitIntoClient
public static var defersWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) }
/// Symbolic links are not followed when resolving the mount point.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_NOFOLLOW`.
@_alwaysEmitIntoClient
public static var noSymlinkFollowingAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) }
/// The file system is a snapshot.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_SNAPSHOT`.
@_alwaysEmitIntoClient
public static var snapshot: MountFlags { MountFlags(rawValue: _MNT_SNAPSHOT) }
/// Access times are always updated when files are read. Without this flag,
/// the file system may skip some access time updates for performance.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_STRICTATIME`.
@_alwaysEmitIntoClient
public static var strictAccessTime: MountFlags { MountFlags(rawValue: _MNT_STRICTATIME) }
#endif
// MARK: Flags Available on FreeBSD Only
#if os(FreeBSD)
/// The file system is exported with Kerberos user-ID mapping.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_EXKERB`.
@_alwaysEmitIntoClient
public static var exportedWithKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) }
/// The file system is exported publicly for WebNFS clients.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_EXPUBLIC`.
@_alwaysEmitIntoClient
public static var exportedPublicly: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) }
/// POSIX.1e ACLs are enabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_ACLS`.
@_alwaysEmitIntoClient
public static var posixACLs: MountFlags { MountFlags(rawValue: _MNT_ACLS) }
/// The file system is journaled by `gjournal`.
///
/// - Note: Only available on FreeBSD. See `gjournal(8)`.
///
/// The corresponding C constant is `MNT_GJOURNAL`.
@_alwaysEmitIntoClient
public static var geomJournaled: MountFlags { MountFlags(rawValue: _MNT_GJOURNAL) }
/// The file system is omitted from `df(1)` listings.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_IGNORE`.
@_alwaysEmitIntoClient
public static var excludedFromDiskFreeReports: MountFlags { MountFlags(rawValue: _MNT_IGNORE) }
/// NFSv4 ACLs are enabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_NFS4ACLS`.
@_alwaysEmitIntoClient
public static var nfs4ACLs: MountFlags { MountFlags(rawValue: _MNT_NFS4ACLS) }
/// Clustered reads are disabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_NOCLUSTERR`.
@_alwaysEmitIntoClient
public static var noClusteredReads: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) }
/// Clustered writes are disabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_NOCLUSTERW`.
@_alwaysEmitIntoClient
public static var noClusteredWrites: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) }
/// Newly created files in a directory with the set-user-ID bit set are owned
/// by that directory's owner, rather than by the creating user.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_SUIDDIR`.
@_alwaysEmitIntoClient
public static var setUserIDDirectories: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) }
/// Soft updates journaling is enabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_SUJ`.
@_alwaysEmitIntoClient
public static var softUpdatesJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) }
/// The file system is untrusted, as the integrity of its media is unknown.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_UNTRUSTED`.
@_alwaysEmitIntoClient
public static var untrusted: MountFlags { MountFlags(rawValue: _MNT_UNTRUSTED) }
/// The file system was mounted by a non-root user.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_USER`.
@_alwaysEmitIntoClient
public static var userMounted: MountFlags { MountFlags(rawValue: _MNT_USER) }
/// The file system is marked as verified, so per-file integrity checks are
/// skipped on execution.
///
/// - Note: Only available on FreeBSD. See `mac_veriexec(4)`.
///
/// The corresponding C constant is `MNT_VERIFIED`.
@_alwaysEmitIntoClient
public static var verified: MountFlags { MountFlags(rawValue: _MNT_VERIFIED) }
#endif
// MARK: Flags Available on OpenBSD Only
#if os(OpenBSD)
/// File permissions are not checked on the file system (FFS only).
///
/// - Note: Only available on OpenBSD.
///
/// The corresponding C constant is `MNT_NOPERM`.
@_alwaysEmitIntoClient
public static var noPermissionChecks: MountFlags { MountFlags(rawValue: _MNT_NOPERM) }
/// Programs residing on the file system may create memory mappings that are
/// both writable and executable.
///
/// By default, requesting such a mapping (via `mmap(2)` or `mprotect(2)`)
/// kills the process. This flag lifts that restriction.
///
/// - Note: Only available on OpenBSD.
///
/// The corresponding C constant is `MNT_WXALLOWED`.
@_alwaysEmitIntoClient
public static var writeExecuteAllowed: MountFlags { MountFlags(rawValue: _MNT_WXALLOWED) }
#endif
}
@available(System 1.9.0, *)
extension MountFlags
: CustomStringConvertible, CustomDebugStringConvertible
{
/// A textual representation of the mount flags.
@inline(never)
public var description: String {
#if SYSTEM_PACKAGE_DARWIN
let descriptions: [(Element, StaticString)] = [
(.readOnly, ".readOnly"),
(.synchronous, ".synchronous"),
(.noExecution, ".noExecution"),
(.noSetUserID, ".noSetUserID"),
(.noAccessTime, ".noAccessTime"),
(.noDevices, ".noDevices"),
(.asynchronous, ".asynchronous"),
(.exported, ".exported"),
(.local, ".local"),
(.quotasEnabled, ".quotasEnabled"),
(.rootFileSystem, ".rootFileSystem"),
(.union, ".union"),
(.automounted, ".automounted"),
(.multiLabel, ".multiLabel"),
(.contentProtection, ".contentProtection"),
(.removable, ".removable"),
(.quarantined, ".quarantined"),
(.supportsVolfs, ".supportsVolfs"),
(.noBrowsing, ".noBrowsing"),
(.ignoresOwnership, ".ignoresOwnership"),
(.journaled, ".journaled"),
(.noUserExtendedAttributes, ".noUserExtendedAttributes"),
(.defersWrites, ".defersWrites"),
(.noSymlinkFollowingAtMountPoint, ".noSymlinkFollowingAtMountPoint"),
(.snapshot, ".snapshot"),
(.strictAccessTime, ".strictAccessTime"),
]
#elseif os(FreeBSD)
let descriptions: [(Element, StaticString)] = [
(.readOnly, ".readOnly"),
(.synchronous, ".synchronous"),
(.noExecution, ".noExecution"),
(.noSetUserID, ".noSetUserID"),
(.noAccessTime, ".noAccessTime"),
(.noSymlinkFollowing, ".noSymlinkFollowing"),
(.asynchronous, ".asynchronous"),
(.exported, ".exported"),
(.local, ".local"),
(.quotasEnabled, ".quotasEnabled"),
(.rootFileSystem, ".rootFileSystem"),
(.union, ".union"),
(.automounted, ".automounted"),
(.multiLabel, ".multiLabel"),
(.exportedReadOnly, ".exportedReadOnly"),
(.exportedByDefault, ".exportedByDefault"),
(.exportedAnonymously, ".exportedAnonymously"),
(.softUpdates, ".softUpdates"),
(.exportedWithKerberos, ".exportedWithKerberos"),
(.exportedPublicly, ".exportedPublicly"),
(.posixACLs, ".posixACLs"),
(.geomJournaled, ".geomJournaled"),
(.excludedFromDiskFreeReports, ".excludedFromDiskFreeReports"),
(.nfs4ACLs, ".nfs4ACLs"),
(.noClusteredReads, ".noClusteredReads"),
(.noClusteredWrites, ".noClusteredWrites"),
(.setUserIDDirectories, ".setUserIDDirectories"),
(.softUpdatesJournaling, ".softUpdatesJournaling"),
(.untrusted, ".untrusted"),
(.userMounted, ".userMounted"),
(.verified, ".verified"),
]
#elseif os(OpenBSD)
let descriptions: [(Element, StaticString)] = [
(.readOnly, ".readOnly"),
(.synchronous, ".synchronous"),
(.noExecution, ".noExecution"),
(.noSetUserID, ".noSetUserID"),
(.noAccessTime, ".noAccessTime"),
(.noDevices, ".noDevices"),
(.asynchronous, ".asynchronous"),
(.exported, ".exported"),
(.local, ".local"),
(.quotasEnabled, ".quotasEnabled"),
(.rootFileSystem, ".rootFileSystem"),
(.exportedReadOnly, ".exportedReadOnly"),
(.exportedByDefault, ".exportedByDefault"),
(.exportedAnonymously, ".exportedAnonymously"),
(.softUpdates, ".softUpdates"),
(.noPermissionChecks, ".noPermissionChecks"),
(.writeExecuteAllowed, ".writeExecuteAllowed"),
]
#elseif os(Linux) || os(Android)
let descriptions: [(Element, StaticString)] = [
(.readOnly, ".readOnly"),
(.synchronous, ".synchronous"),
(.noExecution, ".noExecution"),
(.noSetUserID, ".noSetUserID"),
(.noAccessTime, ".noAccessTime"),
(.noDevices, ".noDevices"),
(.mandatoryLocking, ".mandatoryLocking"),
(.noDirectoryAccessTime, ".noDirectoryAccessTime"),
(.relativeAccessTime, ".relativeAccessTime"),
(.noSymlinkFollowing, ".noSymlinkFollowing"),
]
#endif
return _buildDescription(descriptions)
}
/// A textual representation of the mount flags, suitable for debugging.
public var debugDescription: String { self.description }
}
#endif // !os(Windows) && !os(WASI)
+74 -26
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -15,15 +15,12 @@
#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")
@@ -35,7 +32,7 @@ import Android
///
/// - Note: Only available on Unix-like platforms.
@frozen
@available(System 99, *)
@available(System 1.7.0, *)
public struct Stat: RawRepresentable, Sendable {
/// The raw C `stat` struct.
@@ -521,42 +518,93 @@ public struct Stat: RawRepresentable, Sendable {
/// File generation number
///
/// The file generation number is used to distinguish between different files
/// that have used the same inode over time.
/// The file generation number may be used to distinguish between different
/// files that have used the same inode over time.
///
/// The corresponding C property is `st_gen`.
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
@_alwaysEmitIntoClient
public var generationNumber: Int {
get { Int(rawValue.st_gen) }
set { rawValue.st_gen = numericCast(newValue)}
public var generationNumber: UInt64 {
get { UInt64(rawValue.st_gen) }
set { rawValue.st_gen = numericCast(newValue) }
}
#endif
}
// MARK: - Equatable and Hashable
@available(System 99, *)
@available(System 1.7.0, *)
extension Stat: Equatable {
@_alwaysEmitIntoClient
/// Compares the raw bytes of two `Stat` structs for equality.
/// Compares the meaningful file-metadata fields of two `Stat` values.
///
/// Alignment padding and platform reserved/"spare" fields are not compared.
public static func == (lhs: Self, rhs: Self) -> Bool {
return withUnsafeBytes(of: lhs.rawValue) { lhsBytes in
withUnsafeBytes(of: rhs.rawValue) { rhsBytes in
lhsBytes.elementsEqual(rhsBytes)
}
guard lhs.rawValue.st_dev == rhs.rawValue.st_dev,
lhs.rawValue.st_ino == rhs.rawValue.st_ino,
lhs.rawValue.st_mode == rhs.rawValue.st_mode,
lhs.rawValue.st_nlink == rhs.rawValue.st_nlink,
lhs.rawValue.st_uid == rhs.rawValue.st_uid,
lhs.rawValue.st_gid == rhs.rawValue.st_gid,
lhs.rawValue.st_rdev == rhs.rawValue.st_rdev,
lhs.rawValue.st_size == rhs.rawValue.st_size,
lhs.rawValue.st_blksize == rhs.rawValue.st_blksize,
lhs.rawValue.st_blocks == rhs.rawValue.st_blocks,
lhs.st_atim.tv_sec == rhs.st_atim.tv_sec,
lhs.st_atim.tv_nsec == rhs.st_atim.tv_nsec,
lhs.st_mtim.tv_sec == rhs.st_mtim.tv_sec,
lhs.st_mtim.tv_nsec == rhs.st_mtim.tv_nsec,
lhs.st_ctim.tv_sec == rhs.st_ctim.tv_sec,
lhs.st_ctim.tv_nsec == rhs.st_ctim.tv_nsec else {
return false
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
guard lhs.st_birthtim.tv_sec == rhs.st_birthtim.tv_sec,
lhs.st_birthtim.tv_nsec == rhs.st_birthtim.tv_nsec else {
return false
}
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
guard lhs.rawValue.st_flags == rhs.rawValue.st_flags,
lhs.rawValue.st_gen == rhs.rawValue.st_gen else {
return false
}
#endif
return true
}
}
@available(System 99, *)
@available(System 1.7.0, *)
extension Stat: Hashable {
@_alwaysEmitIntoClient
/// Hashes the raw bytes of this `Stat` struct.
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
///
/// These are the same fields compared by `==`, fed in the same order.
/// Alignment padding and platform reserved/"spare" fields are not hashed.
public func hash(into hasher: inout Hasher) {
withUnsafeBytes(of: rawValue) { bytes in
hasher.combine(bytes: bytes)
}
hasher.combine(rawValue.st_dev)
hasher.combine(rawValue.st_ino)
hasher.combine(rawValue.st_mode)
hasher.combine(rawValue.st_nlink)
hasher.combine(rawValue.st_uid)
hasher.combine(rawValue.st_gid)
hasher.combine(rawValue.st_rdev)
hasher.combine(rawValue.st_size)
hasher.combine(rawValue.st_blksize)
hasher.combine(rawValue.st_blocks)
hasher.combine(st_atim.tv_sec)
hasher.combine(st_atim.tv_nsec)
hasher.combine(st_mtim.tv_sec)
hasher.combine(st_mtim.tv_nsec)
hasher.combine(st_ctim.tv_sec)
hasher.combine(st_ctim.tv_nsec)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
hasher.combine(st_birthtim.tv_sec)
hasher.combine(st_birthtim.tv_nsec)
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
hasher.combine(rawValue.st_flags)
hasher.combine(rawValue.st_gen)
#endif
}
}
@@ -564,7 +612,7 @@ extension Stat: Hashable {
// MARK: - FileDescriptor Extensions
@available(System 99, *)
@available(System 1.7.0, *)
extension FileDescriptor {
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
@@ -580,7 +628,7 @@ extension FileDescriptor {
// MARK: - FilePath Extensions
@available(System 99, *)
@available(System 1.7.0, *)
extension FilePath {
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
+866
View File
@@ -0,0 +1,866 @@
//===----------------------------------------------------------------------===//
//
// 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 os(Windows)
/// A Swift wrapper of the C `statfs` struct.
///
/// - Note: Not available on Windows or WASI.
@available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.")
public struct StatFS {
/// Creates a `StatFS` from a `FilePath`.
public init(
_ path: FilePath,
retryOnInterrupt: Bool = true
) throws(Errno) {
fatalError("StatFS is unavailable on Windows")
}
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
public init(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool = true
) throws(Errno) {
fatalError("StatFS is unavailable on Windows")
}
/// Creates a `StatFS` from a `FileDescriptor`.
public init(
_ fd: FileDescriptor,
retryOnInterrupt: Bool = true
) throws(Errno) {
fatalError("StatFS is unavailable on Windows")
}
}
#elseif os(WASI)
/// A Swift wrapper of the C `statfs` struct.
///
/// - Note: Not available on Windows or WASI.
@available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.")
public struct StatFS {
/// Creates a `StatFS` from a `FilePath`.
public init(
_ path: FilePath,
retryOnInterrupt: Bool = true
) throws(Errno) {
fatalError("StatFS is unavailable on WASI")
}
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
public init(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool = true
) throws(Errno) {
fatalError("StatFS is unavailable on WASI")
}
/// Creates a `StatFS` from a `FileDescriptor`.
public init(
_ fd: FileDescriptor,
retryOnInterrupt: Bool = true
) throws(Errno) {
fatalError("StatFS is unavailable on WASI")
}
}
#else
// Must import here to use C statfs properties in @_alwaysEmitIntoClient APIs.
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
#if os(Linux)
import CSystemStatFS
#endif
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: - FileSystemID
/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs`
/// struct.
///
/// - Note: Not available on Windows or WASI.
@frozen
@available(System 1.9.0, *)
public struct FileSystemID: RawRepresentable, Sendable {
/// The raw C file system ID.
@_alwaysEmitIntoClient
public var rawValue: CInterop.FileSystemID
/// Creates a strongly-typed `FileSystemID` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.FileSystemID) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemID` from the raw C value.
@_alwaysEmitIntoClient
public init(_ rawValue: CInterop.FileSystemID) { self.rawValue = rawValue }
}
// `CInterop.FileSystemID` is the C `fsid_t` struct (a fixed two-element
// `int32_t` array), which provides no synthesized conformances.
@available(System 1.9.0, *)
extension FileSystemID {
@_alwaysEmitIntoClient
internal var _words: (Int32, Int32) {
#if os(Linux) || os(Android)
rawValue.__val
#else
rawValue.val
#endif
}
@_alwaysEmitIntoClient
internal init(_words words: (Int32, Int32)) {
#if os(Linux) || os(Android)
self.init(rawValue: CInterop.FileSystemID(__val: words))
#else
self.init(rawValue: CInterop.FileSystemID(val: words))
#endif
}
}
@available(System 1.9.0, *)
extension FileSystemID: Equatable {
@_alwaysEmitIntoClient
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs._words.0 == rhs._words.0 && lhs._words.1 == rhs._words.1
}
}
@available(System 1.9.0, *)
extension FileSystemID: Hashable {
@_alwaysEmitIntoClient
public func hash(into hasher: inout Hasher) {
hasher.combine(_words.0)
hasher.combine(_words.1)
}
}
@available(System 1.9.0, *)
extension FileSystemID: Codable {
@_alwaysEmitIntoClient
public func encode(to encoder: any Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(_words.0)
try container.encode(_words.1)
}
@_alwaysEmitIntoClient
public init(from decoder: any Decoder) throws {
var container = try decoder.unkeyedContainer()
let val0 = try container.decode(Int32.self)
let val1 = try container.decode(Int32.self)
self.init(_words: (val0, val1))
}
}
@available(System 1.9.0, *)
extension FileSystemID: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the file system ID.
@inline(never)
public var description: String {
"FileSystemID(\(_words.0), \(_words.1))"
}
/// A textual representation of the file system ID, suitable for debugging.
public var debugDescription: String { self.description }
}
#if os(Linux) || os(Android)
// MARK: - FileSystemType
/// A Swift wrapper of the C `f_type` file system type found in a `statfs`
/// struct.
///
/// - Note: Only available on Linux and Android.
@frozen
@available(System 1.9.0, *)
public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system type.
@_alwaysEmitIntoClient
public var rawValue: UInt32
/// Creates a strongly-typed `FileSystemType` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: UInt32) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemType` from the raw C value.
@_alwaysEmitIntoClient
public init(_ rawValue: UInt32) { self.rawValue = rawValue }
}
#endif // os(Linux) || os(Android)
#if SYSTEM_PACKAGE_DARWIN
// MARK: - FileSystemSubtype
/// A Swift wrapper of the C `f_fssubtype` file system subtype found in a
/// `statfs` struct on Darwin.
///
/// - Note: Only available on Darwin.
@frozen
@available(System 1.9.0, *)
public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system subtype.
@_alwaysEmitIntoClient
public var rawValue: UInt32
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: UInt32) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
@_alwaysEmitIntoClient
public init(_ rawValue: UInt32) { self.rawValue = rawValue }
}
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// MARK: - FileSystemTypeName
/// A Swift wrapper of the C `f_fstypename` file system type name found in a
/// `statfs` struct.
///
/// - Note: Only available on Darwin and BSD.
@frozen
@available(System 1.9.0, *)
public struct FileSystemTypeName
: RawRepresentable, Sendable, Hashable, Codable, ExpressibleByStringLiteral
{
/// The raw file system type name.
@_alwaysEmitIntoClient
public var rawValue: String
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
@_alwaysEmitIntoClient
public init(rawValue: String) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
@_alwaysEmitIntoClient
public init(_ rawValue: String) { self.rawValue = rawValue }
/// Creates a `FileSystemTypeName` from a string literal, such as `"apfs"`.
@_alwaysEmitIntoClient
public init(stringLiteral value: String) { self.rawValue = value }
// MARK: Type Names Available on Darwin Only
#if SYSTEM_PACKAGE_DARWIN
/// The Apple File System (APFS).
///
/// - Note: Only available on Darwin.
///
/// The corresponding `f_fstypename` value is `"apfs"`.
@_alwaysEmitIntoClient
public static var apfs: FileSystemTypeName { FileSystemTypeName(rawValue: "apfs") }
/// The Mac OS Extended file system (HFS Plus).
///
/// - Note: Only available on Darwin.
///
/// The corresponding `f_fstypename` value is `"hfs"`.
@_alwaysEmitIntoClient
public static var hfs: FileSystemTypeName { FileSystemTypeName(rawValue: "hfs") }
#endif
}
@available(System 1.9.0, *)
extension FileSystemTypeName: CustomStringConvertible, CustomDebugStringConvertible {
/// The file system type name, such as `apfs`.
@inline(never)
public var description: String { rawValue }
/// The file system type name as a quoted string, such as `"apfs"`.
public var debugDescription: String { description.debugDescription }
}
#endif // SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// MARK: - StatFS
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// Helpers for reading the fixed-size, NUL-terminated C character buffers
// (`f_fstypename`, `f_mntonname`, `f_mntfromname`) in Darwin/BSD `statfs`.
// If the buffer has no NUL (malformed), the entire buffer is used.
@available(System 1.9.0, *)
extension String {
@usableFromInline
internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) {
let bytes = buffer.prefix { $0 != 0 }
self = String(decoding: bytes, as: CInterop.PlatformUnicodeEncoding.self)
}
}
@available(System 1.9.0, *)
extension FilePath {
@usableFromInline
internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) {
let chars = buffer.bindMemory(to: CInterop.PlatformChar.self)
guard let base = chars.baseAddress else {
self = FilePath()
return
}
self = if chars.firstIndex(of: 0) != nil {
FilePath(platformString: base)
} else {
withUnsafeTemporaryAllocation(
of: CInterop.PlatformChar.self,
capacity: chars.count + 1
) { terminatedBuffer in
terminatedBuffer.baseAddress!.initialize(from: base, count: chars.count)
terminatedBuffer[chars.count] = 0
return FilePath(platformString: terminatedBuffer.baseAddress!)
}
}
}
}
#endif
/// A Swift wrapper of the C `statfs` struct.
///
/// - Note: Not available on Windows or WASI.
/// - Note: The numeric properties clamp when converting to or from the
/// underlying C field. Use `rawValue` for exact, unclamped access.
@frozen
@available(System 1.9.0, *)
public struct StatFS: RawRepresentable, Sendable, Hashable {
/// The raw C `statfs` struct.
@_alwaysEmitIntoClient
public var rawValue: CInterop.StatFS
/// Creates a Swift `StatFS` from the raw C struct.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.StatFS) { self.rawValue = rawValue }
// MARK: Initializers
/// Creates a `StatFS` from a `FilePath`.
///
/// The corresponding C function is `statfs()`.
@_alwaysEmitIntoClient
public init(
_ path: FilePath,
retryOnInterrupt: Bool = true
) throws(Errno) {
self.rawValue = try path.withPlatformString {
Self._statfs($0, retryOnInterrupt: retryOnInterrupt)
}.get()
}
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
///
/// The corresponding C function is `statfs()`.
@_alwaysEmitIntoClient
public init(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool = true
) throws(Errno) {
self.rawValue = try Self._statfs(
path, retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal static func _statfs(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool
) -> Result<CInterop.StatFS, Errno> {
var result = CInterop.StatFS()
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_statfs(path, &result)
}.map { result }
}
/// Creates a `StatFS` from a `FileDescriptor`.
///
/// The corresponding C function is `fstatfs()`.
@_alwaysEmitIntoClient
public init(
_ fd: FileDescriptor,
retryOnInterrupt: Bool = true
) throws(Errno) {
self.rawValue = try Self._fstatfs(
fd, retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal static func _fstatfs(
_ fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<CInterop.StatFS, Errno> {
var result = CInterop.StatFS()
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fstatfs(fd.rawValue, &result)
}.map { result }
}
// MARK: Properties
/// File system block size, in bytes.
///
/// - Note: On Darwin and BSD, this is the fundamental size for block counts.
/// Other platforms use `fragmentSize` (`f_frsize`) instead.
///
/// The corresponding C property is `f_bsize`.
@_alwaysEmitIntoClient
public var blockSize: Int {
get { Int(clamping: rawValue.f_bsize) }
set { rawValue.f_bsize = .init(clamping: newValue) }
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
/// Block size for optimal data transfer, in bytes.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_iosize`.
@_alwaysEmitIntoClient
public var preferredIOBlockSize: Int {
get { Int(clamping: rawValue.f_iosize) }
set { rawValue.f_iosize = .init(clamping: newValue) }
}
#else
/// File system fragment size, in bytes.
///
/// - Note: On Linux and Android, this is the fundamental size for block
/// counts. Not present on Darwin or BSD, which use `blockSize` instead.
///
/// The corresponding C property is `f_frsize`.
@_alwaysEmitIntoClient
public var fragmentSize: Int {
get { Int(clamping: rawValue.f_frsize) }
set { rawValue.f_frsize = .init(clamping: newValue) }
}
#endif
/// The fundamental block size used for space calculations, in bytes.
///
/// This is `blockSize` on Darwin and BSD, or `fragmentSize` otherwise.
@_alwaysEmitIntoClient
internal var _fundamentalBlockSize: UInt64 {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
UInt64(clamping: rawValue.f_bsize)
#else
UInt64(clamping: rawValue.f_frsize)
#endif
}
@_alwaysEmitIntoClient
internal func _saturatingSpace(_ blocks: UInt64) -> UInt64 {
let (result, overflow) = blocks.multipliedReportingOverflow(by: _fundamentalBlockSize)
return overflow ? .max : result
}
/// Total number of blocks in the file system.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise.
///
/// The corresponding C property is `f_blocks`.
@_alwaysEmitIntoClient
public var totalBlocks: UInt64 {
get { UInt64(clamping: rawValue.f_blocks) }
set { rawValue.f_blocks = .init(clamping: newValue) }
}
/// Total size of the file system, in bytes.
///
/// - Note: Computed for convenience as `totalBlocks` times the fundamental
/// block size (see `totalBlocks`). Saturates to `UInt64.max` on overflow.
@_alwaysEmitIntoClient
public var totalSpace: UInt64 { _saturatingSpace(totalBlocks) }
/// Number of free blocks in the file system.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise.
///
/// The corresponding C property is `f_bfree`.
@_alwaysEmitIntoClient
public var freeBlocks: UInt64 {
get { UInt64(clamping: rawValue.f_bfree) }
set { rawValue.f_bfree = .init(clamping: newValue) }
}
/// Free space in the file system, in bytes.
///
/// - Note: Computed for convenience as `freeBlocks` times the fundamental
/// block size (see `freeBlocks`). Saturates to `UInt64.max` on overflow.
@_alwaysEmitIntoClient
public var freeSpace: UInt64 { _saturatingSpace(freeBlocks) }
/// Number of free blocks available to non-superuser.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise. On FreeBSD and OpenBSD, the underlying C property is
/// signed; negative values are clamped to 0.
///
/// The corresponding C property is `f_bavail`.
@_alwaysEmitIntoClient
public var availableBlocks: UInt64 {
get { UInt64(clamping: rawValue.f_bavail) }
set { rawValue.f_bavail = .init(clamping: newValue) }
}
/// Available space in the file system for non-superuser, in bytes.
///
/// - Note: Computed for convenience as `availableBlocks` times the fundamental
/// block size (see `availableBlocks`). Saturates to `UInt64.max` on overflow.
@_alwaysEmitIntoClient
public var availableSpace: UInt64 { _saturatingSpace(availableBlocks) }
/// Total number of inodes in the file system.
///
/// The corresponding C property is `f_files`.
@_alwaysEmitIntoClient
public var totalInodes: UInt64 {
get { UInt64(clamping: rawValue.f_files) }
set { rawValue.f_files = .init(clamping: newValue) }
}
/// Number of free inodes in the file system.
///
/// - Note: On FreeBSD, this reports the inodes available to a non-superuser
/// rather than the total free count, and the underlying C field is signed
/// (negative values are clamped to 0); on other platforms, it is the total
/// number of free inodes.
///
/// The corresponding C property is `f_ffree`.
@_alwaysEmitIntoClient
public var freeInodes: UInt64 {
get { UInt64(clamping: rawValue.f_ffree) }
set { rawValue.f_ffree = .init(clamping: newValue) }
}
#if os(OpenBSD)
/// Number of free inodes available to non-superuser.
///
/// - Note: Darwin, FreeBSD, Linux, and Android `statfs` do not report it.
/// On OpenBSD, the underlying C property is signed; negative values are
/// clamped to 0.
///
/// The corresponding C property is `f_favail`.
@_alwaysEmitIntoClient
public var availableInodes: UInt64 {
get { UInt64(clamping: rawValue.f_favail) }
set { rawValue.f_favail = .init(clamping: newValue) }
}
#endif
#if !SYSTEM_PACKAGE_DARWIN
/// Maximum length of a file name on the file system, in bytes.
///
/// - Note: Darwin's `statfs` does not report it.
///
/// The corresponding C property is `f_namelen` on Linux and Android, or
/// `f_namemax` otherwise.
@_alwaysEmitIntoClient
public var maximumNameLength: Int {
get {
#if os(Linux) || os(Android)
Int(clamping: rawValue.f_namelen)
#else
Int(clamping: rawValue.f_namemax)
#endif
}
set {
#if os(Linux) || os(Android)
rawValue.f_namelen = .init(clamping: newValue)
#else
rawValue.f_namemax = .init(clamping: newValue)
#endif
}
}
#endif
/// File system ID.
///
/// The corresponding C property is `f_fsid`.
@_alwaysEmitIntoClient
public var fileSystemID: FileSystemID {
get { FileSystemID(rawValue: rawValue.f_fsid) }
set { rawValue.f_fsid = newValue.rawValue }
}
/// Flags describing how the file system is mounted.
///
/// - Note: On Linux, the kernel also sets an `ST_VALID` bit in `f_flags`
/// to mark the field as filled in. It isn't a mount flag, so this
/// property omits it like glibc's `statvfs` and Bionic's `statfs` do.
/// The setter preserves it.
///
/// The corresponding C property is `f_flags`.
@_alwaysEmitIntoClient
public var mountFlags: MountFlags {
get {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
MountFlags(rawValue: rawValue.f_flags)
#elseif os(Linux) || os(Android)
MountFlags(rawValue: CInterop.MountFlags(truncatingIfNeeded: rawValue.f_flags) & ~_ST_VALID_BIT)
#endif
}
set {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
rawValue.f_flags = newValue.rawValue
#elseif os(Linux) || os(Android)
let valid = CInterop.MountFlags(truncatingIfNeeded: rawValue.f_flags) & _ST_VALID_BIT
rawValue.f_flags = .init(truncatingIfNeeded: newValue.rawValue | valid)
#endif
}
}
#if os(Linux) || os(Android)
/// File system type.
///
/// - Note: This is the file system's magic number, such as `0xEF53` for
/// ext4. Only available on Linux and Android. On Darwin and BSD, use
/// `typeName` to identify the file system.
///
/// The corresponding C property is `f_type`.
@_alwaysEmitIntoClient
public var type: FileSystemType {
get {
// glibc's `f_type` is a signed `long` and can be negative.
FileSystemType(rawValue: UInt32(truncatingIfNeeded: rawValue.f_type))
}
set {
rawValue.f_type = .init(truncatingIfNeeded: newValue.rawValue)
}
}
#endif
#if SYSTEM_PACKAGE_DARWIN
/// File system subtype.
///
/// - Note: This is a numeric value whose meaning depends on `typeName`,
/// with no stable, public constants. Only available on Darwin.
///
/// The corresponding C property is `f_fssubtype`.
@_alwaysEmitIntoClient
public var subtype: FileSystemSubtype {
get { FileSystemSubtype(rawValue: rawValue.f_fssubtype) }
set { rawValue.f_fssubtype = newValue.rawValue }
}
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
/// User that mounted the file system.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_owner`.
@_alwaysEmitIntoClient
public var owner: UserID {
get { UserID(rawValue: rawValue.f_owner) }
set { rawValue.f_owner = newValue.rawValue }
}
/// File system type name, such as "apfs".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_fstypename`.
@_alwaysEmitIntoClient
public var typeName: FileSystemTypeName {
FileSystemTypeName(rawValue: withUnsafeBytes(of: rawValue.f_fstypename) {
String(_nullTerminatedBytes: $0)
})
}
/// Directory where the file system is mounted, such as "/System/Volumes/Data".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_mntonname`.
@_alwaysEmitIntoClient
public var mountPoint: FilePath {
withUnsafeBytes(of: rawValue.f_mntonname) {
FilePath(_nullTerminatedBytes: $0)
}
}
/// The source of the mounted file system, such as "/dev/disk3s7".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_mntfromname`.
@_alwaysEmitIntoClient
public var mountSource: FilePath {
withUnsafeBytes(of: rawValue.f_mntfromname) {
FilePath(_nullTerminatedBytes: $0)
}
}
#endif
}
// MARK: - StatFS Equatable & Hashable
@available(System 1.9.0, *)
extension StatFS {
/// Compares the file system metadata fields of two `StatFS` values,
/// including fields not exposed as properties, such as `f_flags_ext` on
/// Darwin.
///
/// Fields are compared by their raw C values. Reserved/"spare" fields and
/// OpenBSD's `mount_info` union are not compared. Name buffers are compared
/// only up to their NUL terminators.
public static func == (lhs: Self, rhs: Self) -> Bool {
guard lhs.rawValue.f_bsize == rhs.rawValue.f_bsize,
lhs.rawValue.f_blocks == rhs.rawValue.f_blocks,
lhs.rawValue.f_bfree == rhs.rawValue.f_bfree,
lhs.rawValue.f_bavail == rhs.rawValue.f_bavail,
lhs.rawValue.f_files == rhs.rawValue.f_files,
lhs.rawValue.f_ffree == rhs.rawValue.f_ffree,
lhs.fileSystemID == rhs.fileSystemID else {
return false
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
guard lhs.rawValue.f_iosize == rhs.rawValue.f_iosize,
lhs.rawValue.f_flags == rhs.rawValue.f_flags,
lhs.rawValue.f_owner == rhs.rawValue.f_owner,
_nullTerminatedBytesEqual(lhs.rawValue.f_fstypename,
rhs.rawValue.f_fstypename),
_nullTerminatedBytesEqual(lhs.rawValue.f_mntonname,
rhs.rawValue.f_mntonname),
_nullTerminatedBytesEqual(lhs.rawValue.f_mntfromname,
rhs.rawValue.f_mntfromname) else {
return false
}
#elseif os(Linux) || os(Android)
guard lhs.rawValue.f_type == rhs.rawValue.f_type,
lhs.rawValue.f_frsize == rhs.rawValue.f_frsize,
lhs.rawValue.f_flags == rhs.rawValue.f_flags,
lhs.rawValue.f_namelen == rhs.rawValue.f_namelen else {
return false
}
#endif
#if SYSTEM_PACKAGE_DARWIN
guard lhs.rawValue.f_type == rhs.rawValue.f_type,
lhs.rawValue.f_fssubtype == rhs.rawValue.f_fssubtype,
lhs.rawValue.f_flags_ext == rhs.rawValue.f_flags_ext else {
return false
}
#elseif os(FreeBSD)
guard lhs.rawValue.f_version == rhs.rawValue.f_version,
lhs.rawValue.f_type == rhs.rawValue.f_type,
lhs.rawValue.f_namemax == rhs.rawValue.f_namemax,
lhs.rawValue.f_syncwrites == rhs.rawValue.f_syncwrites,
lhs.rawValue.f_asyncwrites == rhs.rawValue.f_asyncwrites,
lhs.rawValue.f_syncreads == rhs.rawValue.f_syncreads,
lhs.rawValue.f_asyncreads == rhs.rawValue.f_asyncreads else {
return false
}
#elseif os(OpenBSD)
guard lhs.rawValue.f_favail == rhs.rawValue.f_favail,
lhs.rawValue.f_namemax == rhs.rawValue.f_namemax,
lhs.rawValue.f_syncwrites == rhs.rawValue.f_syncwrites,
lhs.rawValue.f_syncreads == rhs.rawValue.f_syncreads,
lhs.rawValue.f_asyncwrites == rhs.rawValue.f_asyncwrites,
lhs.rawValue.f_asyncreads == rhs.rawValue.f_asyncreads,
lhs.rawValue.f_ctime == rhs.rawValue.f_ctime,
_nullTerminatedBytesEqual(lhs.rawValue.f_mntfromspec,
rhs.rawValue.f_mntfromspec) else {
return false
}
#endif
return true
}
/// Hashes the file system metadata fields of a `StatFS` struct.
///
/// These are the same fields compared by `==`. Reserved/"spare" fields are
/// not hashed, and name buffers are hashed only up to their NUL terminators.
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue.f_bsize)
hasher.combine(rawValue.f_blocks)
hasher.combine(rawValue.f_bfree)
hasher.combine(rawValue.f_bavail)
hasher.combine(rawValue.f_files)
hasher.combine(rawValue.f_ffree)
hasher.combine(fileSystemID)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
hasher.combine(rawValue.f_iosize)
hasher.combine(rawValue.f_flags)
hasher.combine(rawValue.f_owner)
Self._combineNullTerminatedBytes(rawValue.f_fstypename, into: &hasher)
Self._combineNullTerminatedBytes(rawValue.f_mntonname, into: &hasher)
Self._combineNullTerminatedBytes(rawValue.f_mntfromname, into: &hasher)
#elseif os(Linux) || os(Android)
hasher.combine(rawValue.f_type)
hasher.combine(rawValue.f_frsize)
hasher.combine(rawValue.f_flags)
hasher.combine(rawValue.f_namelen)
#endif
#if SYSTEM_PACKAGE_DARWIN
hasher.combine(rawValue.f_type)
hasher.combine(rawValue.f_fssubtype)
hasher.combine(rawValue.f_flags_ext)
#elseif os(FreeBSD)
hasher.combine(rawValue.f_version)
hasher.combine(rawValue.f_type)
hasher.combine(rawValue.f_namemax)
hasher.combine(rawValue.f_syncwrites)
hasher.combine(rawValue.f_asyncwrites)
hasher.combine(rawValue.f_syncreads)
hasher.combine(rawValue.f_asyncreads)
#elseif os(OpenBSD)
hasher.combine(rawValue.f_favail)
hasher.combine(rawValue.f_namemax)
hasher.combine(rawValue.f_syncwrites)
hasher.combine(rawValue.f_syncreads)
hasher.combine(rawValue.f_asyncwrites)
hasher.combine(rawValue.f_asyncreads)
hasher.combine(rawValue.f_ctime)
Self._combineNullTerminatedBytes(rawValue.f_mntfromspec, into: &hasher)
#endif
}
@inline(__always)
private static func _nullTerminatedBytesEqual<T>(_ lhs: T, _ rhs: T) -> Bool {
withUnsafeBytes(of: lhs) { lhsBytes in
withUnsafeBytes(of: rhs) { rhsBytes in
lhsBytes.prefix { $0 != 0 }.elementsEqual(rhsBytes.prefix { $0 != 0 })
}
}
}
// Feeds the length first so adjacent buffers can't run together.
@inline(__always)
private static func _combineNullTerminatedBytes<T>(
_ value: T, into hasher: inout Hasher
) {
withUnsafeBytes(of: value) { buffer in
let bytes = buffer.prefix { $0 != 0 }
hasher.combine(bytes.count)
hasher.combine(bytes: .init(rebasing: bytes))
}
}
}
#endif // !os(Windows) && !os(WASI)
+25 -1
View File
@@ -1,7 +1,16 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2023 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
public import CSystemIOUring
public extension IORing {
struct Completion: ~Copyable {
@@ -45,12 +54,27 @@ public extension IORing.Completion {
}
}
/// The result of the completed operation.
///
/// A non-negative value is the operation's success result: a byte count
/// for a read or a write, an event mask for a poll, and so on.
///
/// A negative value is an `errno` code multiplied by -1. Recover the error
/// by negating it again: `Errno(rawValue: -completion.result)`, or use
/// ``error``.
@inlinable var result: Int32 {
get {
rawValue.res
}
}
/// The error of the completed operation, or `nil` if the operation succeeded.
@inlinable var error: Errno? {
get {
rawValue.res < 0 ? Errno(rawValue: -rawValue.res) : nil
}
}
@inlinable var flags: IORing.Completion.Flags {
get {
Flags(rawValue: rawValue.flags & 0x0000FFFF)
+233 -18
View File
@@ -1,7 +1,16 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
public import CSystemIOUring
@usableFromInline
internal enum IORequestCore {
@@ -23,6 +32,12 @@ internal enum IORequestCore {
intoSlot: IORing.RegisteredFile,
context: UInt64 = 0
)
case pollAdd(
file: FileDescriptor,
events: IORing.Request.PollEvents,
isMultiShot: Bool = false,
context: UInt64 = 0
)
case read(
file: FileDescriptor,
buffer: IORing.RegisteredBuffer,
@@ -187,6 +202,118 @@ extension IORing.Request {
.init(core: .nop)
}
// Poll
/// Multishot poll: the poll handler continues to report CQEs on behalf
/// of the same SQE, each flagged with
/// ``IORing/Completion/Flags/moreCompletions``.
///
/// Corresponds to `IORING_POLL_ADD_MULTI`. Note that since
/// `sqe->poll_events` is the event space, the command flags for
/// `POLL_ADD` are stored in `sqe->len`.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_POLL_ADD_MULTI: UInt32 { 1 << 0 }
/// Adds a poll operation to monitor a file descriptor for specific I/O
/// events.
///
/// This method creates an `io_uring` poll operation that monitors the
/// specified file descriptor for I/O readiness events. The operation
/// completes when any of the requested events occur on the file
/// descriptor, such as data becoming available for reading or the
/// descriptor becoming ready for writing.
///
/// Poll operations are useful for implementing efficient I/O
/// multiplexing, allowing you to monitor multiple file descriptors
/// concurrently within a single `io_uring` instance. When used with
/// multishot mode, a single poll operation can deliver multiple
/// completion events without needing to be resubmitted.
///
/// Poll requests on a ring created with
/// ``IORing/SetupFlags/pollCompletions`` fail with
/// ``Errno/invalidArgument``.
///
/// ## Multishot Behavior
///
/// When `isMultiShot` is `true`, the poll operation automatically rearms
/// after each completion event, continuing to monitor the file descriptor
/// for subsequent events. This reduces submission overhead for long-lived
/// monitoring operations. The poll stays armed until it's canceled or the
/// kernel ends it; its last completion is the one without
/// ``IORing/Completion/Flags/moreCompletions``. Neither a hangup nor
/// closing the descriptor ends the poll, and the request keeps the file
/// open until the poll ends.
///
/// When `isMultiShot` is `false`, the poll operation completes once after
/// the first matching event occurs, requiring resubmission to continue
/// monitoring.
///
/// ## Example Usage
///
/// ```swift
/// // Monitor a socket for incoming connections
/// var ring = try IORing(queueDepth: 32)
/// let pollRequest = IORing.Request.pollAdd(
/// listenSocket,
/// events: .readable,
/// isMultiShot: true,
/// context: 1
/// )
/// guard try ring.submit(linkedRequests: pollRequest) else {
/// // The submission queue was full; retry or drain completions first.
/// return
/// }
///
/// // Process completions. A multishot poll stays armed while its
/// // completions contain `.moreCompletions`.
/// var armed = true
/// while armed {
/// let completion = try ring.blockingConsumeCompletion()
/// guard completion.context == 1 else {
/// // Handle completions for other requests.
/// continue
/// }
/// armed = completion.flags.contains(.moreCompletions)
/// if let error = completion.error {
/// // The poll ended with an error, such as `.canceled`.
/// throw error
/// }
/// // Handle incoming connection
/// }
/// ```
///
/// If the poll ends with an error, such as ``Errno/canceled``, its last
/// completion carries that error in ``IORing/Completion/error`` and
/// doesn't contain `.moreCompletions`.
///
/// - Parameters:
/// - file: The file descriptor to monitor for I/O events.
/// - events: The I/O events to monitor on the file descriptor.
/// - isMultiShot: If `true`, the poll operation automatically rearms
/// after each event, continuing to monitor the file descriptor. If
/// `false`, the operation completes after the first matching event.
/// Defaults to `false`.
/// - context: An application-specific value passed through to the
/// completion event, allowing you to identify which operation
/// completed. Defaults to `0`.
///
/// - Returns: An I/O ring request that monitors the file descriptor for
/// the specified events.
///
/// ## See Also
///
/// - ``PollEvents``: The events that can be monitored.
/// - ``IORing/Request/cancel(_:matching:)-(_,FileDescriptor)``:
/// Canceling poll operations.
@inlinable public static func pollAdd(
_ file: FileDescriptor,
events: PollEvents,
isMultiShot: Bool = false,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .pollAdd(file: file, events: events, isMultiShot: isMultiShot, context: context))
}
@inlinable public static func read(
_ file: IORing.RegisteredFile,
into buffer: IORing.RegisteredBuffer,
@@ -241,6 +368,8 @@ extension IORing.Request {
.init(core: .write(file: file, buffer: buffer, offset: offset, context: context))
}
@available(*, deprecated, message: "Use the overload accepting UnsafeRawBufferPointer instead.")
@_disfavoredOverload
@inlinable public static func write(
_ buffer: UnsafeMutableRawBufferPointer,
into file: IORing.RegisteredFile,
@@ -251,6 +380,8 @@ extension IORing.Request {
file: file, buffer: buffer, offset: offset, context: context))
}
@available(*, deprecated, message: "Use the overload accepting UnsafeRawBufferPointer instead.")
@_disfavoredOverload
@inlinable public static func write(
_ buffer: UnsafeMutableRawBufferPointer,
into file: FileDescriptor,
@@ -262,6 +393,60 @@ extension IORing.Request {
)
}
/// Creates a request to write an unregistered buffer to a registered file.
///
/// The request does not copy the buffer's contents. Keep its storage alive
/// and unchanged until the operation completes. The write only reads from
/// the buffer; it does not modify its contents.
///
/// - Parameters:
/// - buffer: The bytes to write.
/// - file: The registered file to write to.
/// - offset: The byte offset in the file at which to begin writing.
/// Ignored for non-seekable files. Defaults to `0`.
/// - context: An application-specific value passed through to the
/// completion event. Defaults to `0`.
/// - Returns: An I/O ring write request. A successful completion's result
/// is the number of bytes written, which may be less than the buffer's count.
@inlinable public static func write(
_ buffer: UnsafeRawBufferPointer,
into file: IORing.RegisteredFile,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
// The shared request encoder uses a mutable pointer, but writes only read the buffer.
.init(core: .writeUnregisteredSlot(
file: file, buffer: UnsafeMutableRawBufferPointer(mutating: buffer), offset: offset, context: context
))
}
/// Creates a request to write an unregistered buffer to a file descriptor.
///
/// The request does not copy the buffer's contents. Keep its storage alive
/// and unchanged until the operation completes. The write only reads from
/// the buffer; it does not modify its contents.
///
/// - Parameters:
/// - buffer: The bytes to write.
/// - file: The file descriptor to write to.
/// - offset: The byte offset in the file at which to begin writing.
/// Ignored for non-seekable files. Defaults to `0`.
/// - context: An application-specific value passed through to the
/// completion event. Defaults to `0`.
/// - Returns: An I/O ring write request. A successful completion's result
/// is the number of bytes written, which may be less than the buffer's count.
@inlinable public static func write(
_ buffer: UnsafeRawBufferPointer,
into file: FileDescriptor,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
// The shared request encoder uses a mutable pointer, but writes only read the buffer.
.init(core: .writeUnregistered(
file: file, buffer: UnsafeMutableRawBufferPointer(mutating: buffer), offset: offset, context: context
))
}
@inlinable public static func close(
_ file: FileDescriptor,
context: UInt64 = 0
@@ -316,24 +501,46 @@ extension IORing.Request {
// Cancel
/*
* ASYNC_CANCEL flags.
*
* IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key
* IORING_ASYNC_CANCEL_FD Key off 'fd' for cancellation rather than the
* request 'user_data'
* IORING_ASYNC_CANCEL_ANY Match any request
* IORING_ASYNC_CANCEL_FD_FIXED 'fd' passed in is a fixed descriptor
* IORING_ASYNC_CANCEL_USERDATA Match on user_data, default for no other key
* IORING_ASYNC_CANCEL_OP Match request based on opcode
*/
/// Cancel every request matching the given key.
///
/// Corresponds to `IORING_ASYNC_CANCEL_ALL`.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 }
/// Cancel any request matching the given file descriptor.
///
/// Corresponds to `IORING_ASYNC_CANCEL_FD`. Cannot be combined with
/// ``SWIFT_IORING_ASYNC_CANCEL_ANY``.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 }
/// Cancel any matching request, disregarding every other key.
///
/// Corresponds to `IORING_ASYNC_CANCEL_ANY`. Cannot be combined with
/// ``SWIFT_IORING_ASYNC_CANCEL_FD`` or ``SWIFT_IORING_ASYNC_CANCEL_OP``.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 }
/// Cancel any request matching a registered file.
///
/// Corresponds to `IORING_ASYNC_CANCEL_FD_FIXED`, and accompanies
/// ``SWIFT_IORING_ASYNC_CANCEL_FD``.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 }
/// Cancel requests matching the `user_data`. This is the default when no other
/// key is given.
///
/// Corresponds to `IORING_ASYNC_CANCEL_USERDATA`.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 }
/// Cancel requests matching the operation.
///
/// Corresponds to `IORING_ASYNC_CANCEL_OP`. Cannot be combined with
/// ``SWIFT_IORING_ASYNC_CANCEL_ANY``.
@_alwaysEmitIntoClient
internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 }
public enum CancellationMatch {
case all
@@ -477,6 +684,14 @@ extension IORing.Request {
case .cancel(let flags):
request.operation = .asyncCancel
request.cancel_flags = flags
case .pollAdd(let file, let events, let isMultiShot, let context):
request.operation = .pollAdd
request.fileDescriptor = file
request.rawValue.user_data = context
if isMultiShot {
request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI
}
request.pollEvents = events
}
return request
+80
View File
@@ -0,0 +1,80 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
internal import CSystem
public import CSystemIOUring
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif
/// Throwing wrapper around the `csystem_io_uring_enter2` shim.
///
/// On success returns the syscall's non-negative result (the number of SQEs
/// consumed by the kernel). On failure, reads `errno` and throws the matching
/// `Errno`. `EINTR` is retried automatically.
@usableFromInline
internal func _ioUringEnter2(
ringDescriptor: Int32,
toSubmit: UInt32,
minComplete: UInt32,
flags: UInt32,
args: UnsafeMutablePointer<swift_io_uring_getevents_arg>?,
argsSize: Int
) throws(Errno) -> Int32 {
let result = valueOrErrno(retryOnInterrupt: true) {
csystem_io_uring_enter2(
ringDescriptor, toSubmit, minComplete, flags, args, argsSize
)
}
return try result.get()
}
/// Throwing wrapper around the `csystem_io_uring_enter` shim.
///
/// On success returns the syscall's non-negative result (the number of SQEs
/// consumed by the kernel). On failure, reads `errno` and throws the matching
/// `Errno`. `EINTR` is retried automatically.
@usableFromInline
internal func _ioUringEnter(
ringDescriptor: Int32,
toSubmit: UInt32,
minComplete: UInt32,
flags: UInt32,
sig: UnsafeMutablePointer<sigset_t>?
) throws(Errno) -> Int32 {
let result = valueOrErrno(retryOnInterrupt: true) {
csystem_io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig)
}
return try result.get()
}
/// Throwing wrapper around the `csystem_io_uring_register` shim.
///
/// On success returns the syscall's non-negative result. On failure, reads
/// `errno` and throws the matching `Errno`. `EINTR` is retried automatically.
@usableFromInline
internal func _ioUringRegister(
ringDescriptor: Int32,
opcode: UInt32,
arg: UnsafeMutableRawPointer?,
nrArgs: UInt32
) throws(Errno) -> Int32 {
let result = valueOrErrno(retryOnInterrupt: true) {
csystem_io_uring_register(ringDescriptor, opcode, arg, nrArgs)
}
return try result.get()
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+128 -110
View File
@@ -1,7 +1,17 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
internal import CSystem
public import CSystemIOUring
// needed for mmap
#if canImport(Glibc)
import Glibc
@@ -42,8 +52,8 @@ extension UnsafeMutableRawBufferPointer {
}
/// Owns the FilePaths whose interior pointers have been written into pending
/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to
/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap
/// 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 {
@@ -128,23 +138,30 @@ internal func _enter(
// Ring always needs enter right now;
// TODO: support SQPOLL here
while true {
let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil)
do {
let ret = try _ioUringEnter(
ringDescriptor: ringDescriptor,
toSubmit: numEvents,
minComplete: minCompletions,
flags: flags,
sig: nil
)
if _getSubmissionQueueCount(ring: ring) > 0 {
// See https://github.com/axboe/liburing/issues/309,
// in some cases not all pending requests are submitted
continue
}
return ret
// error handling:
// EAGAIN / EINTR (try again),
// EAGAIN (try again),
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
// (failure in ring lifetime management, fatal),
// EINVAL (bad constant flag?, fatal),
// EFAULT (bad address for argument from library, fatal)
if ret == -EAGAIN || ret == -EINTR {
} catch Errno.resourceTemporarilyUnavailable {
//TODO: should we wait a bit on AGAIN?
//alternatively we could treat EAGAIN the same as EINTR in the wrapper
continue
} else if ret < 0 {
throw(Errno(rawValue: -ret))
} else if _getSubmissionQueueCount(ring: ring) > 0 {
// See https://github.com/axboe/liburing/issues/309, in some cases not all pending requests are submitted
continue
} else {
return ret
}
}
}
@@ -216,7 +233,7 @@ private func setUpRing(
var err: Errno? = nil
let ringDescriptor = withUnsafeMutablePointer(to: &params) {
let result = io_uring_setup(queueDepth, $0)
let result = csystem_io_uring_setup(queueDepth, $0)
if result < 0 {
err = Errno.current
}
@@ -503,11 +520,10 @@ public struct IORing: ~Copyable {
var count = 0
while let completion = _tryConsumeCompletion(ring: completionRing) {
count += 1
if completion.result < 0 {
try consumer(nil, Errno(rawValue: -completion.result), false)
} else {
try consumer(completion, nil, false)
}
// We still return the completion for a failed operation so that the
// caller can tell which request failed through its `context`.
let error = completion.error
try consumer(completion, error, false)
if count == maximumCount {
try consumer(nil, nil, true)
return
@@ -517,49 +533,56 @@ public struct IORing: ~Copyable {
if count < minimumCount {
while count < minimumCount {
var sz = 0
var flags = IORING_ENTER_GETEVENTS
if extraArgs != nil {
sz = MemoryLayout<swift_io_uring_getevents_arg>.size
flags |= IORING_ENTER_EXT_ARG
}
let res = io_uring_enter2(
ringDescriptor,
0,
minimumCount,
IORING_ENTER_GETEVENTS,
extraArgs,
sz
)
do {
_ = try _ioUringEnter2(
ringDescriptor: ringDescriptor,
toSubmit: 0,
minComplete: minimumCount,
flags: flags,
args: extraArgs,
argsSize: sz
)
break
// error handling:
// EAGAIN / EINTR (try again),
// EAGAIN (try again),
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
// (failure in ring lifetime management, fatal),
// EINVAL (bad constant flag?, fatal),
// EFAULT (bad address for argument from library, fatal)
// EBUSY (not enough space for events; implies events filled
// by kernel between kernelTail load and now)
if res >= 0 || res == -EBUSY {
// ETIME (timeout from extraArgs.ts elapsed before
// minimumCount completions arrived)
} catch Errno.resourceBusy {
break
} else if res == -EAGAIN || res == -EINTR {
} catch Errno.resourceTemporarilyUnavailable {
continue
} catch Errno.timeout {
try consumer(nil, .timeout, true)
return
} catch {
fatalError(
"fatal error in receiving requests: "
+ error.debugDescription
)
}
fatalError(
"fatal error in receiving requests: "
+ Errno(rawValue: -res).debugDescription
)
}
var count = 0
while let completion = _tryConsumeCompletion(ring: completionRing) {
count += 1
if completion.result < 0 {
try consumer(nil, Errno(rawValue: -completion.result), false)
} else {
try consumer(completion, nil, false)
}
let error = completion.error
try consumer(completion, error, false)
if count == maximumCount {
break
}
}
try consumer(nil, nil, true)
}
try consumer(nil, nil, true)
}
@inlinable
@@ -569,17 +592,23 @@ public struct IORing: ~Copyable {
var result: Completion? = nil
try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) {
(completion: consuming Completion?, error, done) throws(Errno) in
if let error {
throw error
}
if let completion {
result = consume completion
} else if let error {
throw error
}
}
return result.take()!
}
/// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified)
///
/// The completion is returned even if its operation failed. Check
/// ``IORing/Completion/error`` to find out whether it did, and
/// ``IORing/Completion/context`` to find out which request it belongs to.
///
/// - Throws: An error of the ring itself, such as ``Errno/timeout`` when
/// no operation completed within `timeout`.
@inlinable
public func blockingConsumeCompletion(
timeout: Duration? = nil
@@ -603,7 +632,17 @@ public struct IORing: ~Copyable {
}
}
/// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout` (or forever if not specified). For each completed operation found, `consumer` is called to handle processing it
/// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout`
/// (or forever if not specified). For each completed operation found, `consumer` is called to handle
/// processing it.
///
/// `consumer` receives a completion, an error, and whether consuming is done:
/// - For each completed operation, it receives the completion. If the
/// operation failed, it receives the operation's error alongside the
/// completion.
/// - If the ring itself fails, such as with ``Errno/timeout``, it receives
/// the error without a completion.
/// - Once consuming is done, it is called a final time with `done` set to `true`.
@inlinable
public func blockingConsumeCompletions<Err: Error>(
minimumCount: UInt32 = 1,
@@ -632,10 +671,6 @@ public struct IORing: ~Copyable {
}
}
// public func peekNextCompletion() -> IOCompletion {
// }
/// Takes a completed operation from the ring and returns it, if one is ready. Otherwise, returns nil.
@inlinable
public func tryConsumeCompletion() -> Completion? {
@@ -660,31 +695,22 @@ public struct IORing: ~Copyable {
/// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information.
public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) {
var rawfd = descriptor.rawValue
let result = withUnsafePointer(to: &rawfd) { fdptr in
let result = io_uring_register(
ringDescriptor,
RegistrationOps.registerEventFD.rawValue,
UnsafeMutableRawPointer(mutating: fdptr),
1
)
return result >= 0 ? nil : Errno(rawValue: -result)
}
if let result {
throw result
}
_ = try _ioUringRegister(
ringDescriptor: ringDescriptor,
opcode: RegistrationOps.registerEventFD.rawValue,
arg: &rawfd,
nrArgs: 1
)
}
/// Removes a registered event file descriptor from the ring
public mutating func unregisterEventFD() throws(Errno) {
let result = io_uring_register(
ringDescriptor,
RegistrationOps.unregisterEventFD.rawValue,
nil,
0
_ = try _ioUringRegister(
ringDescriptor: ringDescriptor,
opcode: RegistrationOps.unregisterEventFD.rawValue,
arg: nil,
nrArgs: 0
)
if result < 0 {
throw Errno(rawValue: -result)
}
}
/// Registers `count` files with the ring for later use in IO operations
@@ -693,18 +719,13 @@ public struct IORing: ~Copyable {
precondition(count < UInt32.max)
let files = [UInt32](repeating: UInt32.max, count: count)
let regResult = files.withUnsafeBufferPointer { bPtr in
let result = io_uring_register(
self.ringDescriptor,
RegistrationOps.registerFiles.rawValue,
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
UInt32(truncatingIfNeeded: count)
try files.withUnsafeBufferPointer { bPtr throws(Errno) in
_ = try _ioUringRegister(
ringDescriptor: self.ringDescriptor,
opcode: RegistrationOps.registerFiles.rawValue,
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
nrArgs: UInt32(truncatingIfNeeded: count)
)
return result >= 0 ? nil : Errno(rawValue: -result)
}
if let regResult {
throw regResult
}
_registeredFiles = files
@@ -712,16 +733,13 @@ public struct IORing: ~Copyable {
}
/// Removes registered files from the ring
public func unregisterFiles() throws {
let result = io_uring_register(
ringDescriptor,
RegistrationOps.unregisterFiles.rawValue,
nil,
0
public func unregisterFiles() throws(Errno) {
_ = try _ioUringRegister(
ringDescriptor: ringDescriptor,
opcode: RegistrationOps.unregisterFiles.rawValue,
arg: nil,
nrArgs: 0
)
if result < 0 {
throw Errno(rawValue: -result)
}
}
/// Allows access to registered files by index
@@ -737,18 +755,13 @@ public struct IORing: ~Copyable {
precondition(buffers.count < UInt32.max)
precondition(_registeredBuffers.isEmpty)
let iovecs = buffers.map { $0.to_iovec() }
let regResult = iovecs.withUnsafeBufferPointer { bPtr in
let result = io_uring_register(
self.ringDescriptor,
RegistrationOps.registerBuffers.rawValue,
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
UInt32(truncatingIfNeeded: buffers.count)
try iovecs.withUnsafeBufferPointer { bPtr throws(Errno) in
_ = try _ioUringRegister(
ringDescriptor: self.ringDescriptor,
opcode: RegistrationOps.registerBuffers.rawValue,
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
nrArgs: UInt32(truncatingIfNeeded: buffers.count)
)
return result >= 0 ? nil : Errno(rawValue: -result)
}
if let regResult {
throw regResult
}
_registeredBuffers = iovecs
@@ -786,16 +799,13 @@ public struct IORing: ~Copyable {
RegisteredResources(resources: _registeredBuffers)
}
public func unregisterBuffers() throws {
let result = io_uring_register(
self.ringDescriptor,
RegistrationOps.unregisterBuffers.rawValue,
nil,
0
public func unregisterBuffers() throws(Errno) {
_ = try _ioUringRegister(
ringDescriptor: self.ringDescriptor,
opcode: RegistrationOps.unregisterBuffers.rawValue,
arg: nil,
nrArgs: 0
)
guard result >= 0 else {
throw Errno(rawValue: -result)
}
}
/// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring.
@@ -809,6 +819,14 @@ public struct IORing: ~Copyable {
}
/// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available.
///
/// `consumer` receives a completion, an error, and whether consuming is done:
/// - For each completed operation, it receives the completion. If the
/// operation failed, it receives the operation's error alongside the
/// completion.
/// - If submitting the requests or waiting for completions fails, such as
/// with ``Errno/timeout``, it receives the error without a completion.
/// - Once consuming is done, it is called a final time with `done` set to `true`.
@inlinable
public func submitPreparedRequestsAndConsumeCompletions<Err: Error>(
minimumCount: UInt32 = 1,
@@ -884,7 +902,7 @@ public struct IORing: ~Copyable {
return true
}
/// Describes which io_uring features are supported by the kernel this program is running on
/// Describes which `io_uring` features are supported by the kernel this program is running on
public struct Features: OptionSet, RawRepresentable, Hashable {
public let rawValue: UInt32
@@ -910,7 +928,7 @@ public struct IORing: ~Copyable {
@inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE
}
/// Describes which io_uring features are supported by the kernel this program is running on
/// Describes which `io_uring` features are supported by the kernel this program is running on
public var supportedFeatures: Features {
return features
}
+168
View File
@@ -0,0 +1,168 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
extension IORing.Request {
/// A set of I/O events that can be monitored on a file descriptor.
///
/// `PollEvents` represents the event mask used with `io_uring` poll
/// operations to specify which I/O conditions to monitor on a file
/// descriptor. These events correspond to the standard POSIX poll events
/// defined in the kernel's `poll.h` header.
///
/// Use `PollEvents` with
/// ``IORing/Request/pollAdd(_:events:isMultiShot:context:)`` to
/// register interest in specific I/O events. The poll operation completes
/// when any of the specified events become active on the file descriptor.
///
/// ## Usage
///
/// ```swift
/// // Monitor a socket for incoming data
/// let request = IORing.Request.pollAdd(
/// socketFD,
/// events: .readable,
/// isMultiShot: true
/// )
/// ```
public struct PollEvents: OptionSet, Hashable, Codable {
public let rawValue: UInt32
@inlinable
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
@usableFromInline
init(_ event: Event) {
self.rawValue = event.rawValue
}
@usableFromInline
enum Event: UInt32, RawRepresentable, Hashable, CaseIterable {
case readable = 0x0001
case priorityData = 0x0002
case writable = 0x0004
case error = 0x0008
case hangUp = 0x0010
case invalidDescriptor = 0x0020
case peerClosed = 0x2000
}
/// An event indicating data is available for reading.
///
/// This event becomes active when data arrives on the file descriptor
/// and can be read without blocking. For sockets, this includes when
/// a new connection is available on a listening socket. Corresponds
/// to the POSIX `POLLIN` event flag.
@inlinable
public static var readable: PollEvents { PollEvents(.readable) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "readable")
public static var POLLIN: PollEvents { readable }
/// An event indicating out-of-band data is available for reading.
///
/// For sockets this signals urgent data; it is also used to report
/// exceptional conditions on descriptors that have no other way to
/// signal them, such as a `sysfs` attribute that has changed value.
/// Corresponds to the POSIX `POLLPRI` event flag.
@inlinable
public static var priorityData: PollEvents { PollEvents(.priorityData) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "priorityData")
public static var POLLPRI: PollEvents { priorityData }
/// An event indicating the file descriptor is ready for writing.
///
/// This event becomes active when writing to the file descriptor will
/// not block. For sockets, this indicates that send buffer space is
/// available. Corresponds to the POSIX `POLLOUT` event flag.
@inlinable
public static var writable: PollEvents { PollEvents(.writable) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "writable")
public static var POLLOUT: PollEvents { writable }
/// An event indicating an error condition on the file descriptor.
///
/// The kernel reports this event whether or not it was requested, so
/// it can appear in a completion's result mask even when the poll
/// asked only for ``readable`` or ``writable``. Requesting it
/// explicitly has no effect. Corresponds to the POSIX `POLLERR` event
/// flag.
@inlinable
public static var error: PollEvents { PollEvents(.error) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "error")
public static var POLLERR: PollEvents { error }
/// An event indicating the peer closed its end of the channel.
///
/// For a pipe this means the writing end was closed; for a socket, that
/// the connection was shut down.
///
/// The kernel reports this event whether or not it was requested, and
/// requesting it explicitly has no effect. Corresponds to the POSIX
/// `POLLHUP` event flag.
@inlinable
public static var hangUp: PollEvents { PollEvents(.hangUp) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "hangUp")
public static var POLLHUP: PollEvents { hangUp }
/// An event indicating that the object a descriptor refers to is no
/// longer valid.
///
/// This arises when the descriptor itself resolves, but the thing it
/// refers to has since become invalid. For example, the disconnection
/// of a sound device could cause this event.
///
/// A descriptor that doesn't resolve at all would make the request
/// fail with ``Errno/badFileDescriptor`` instead.
///
/// The kernel reports this event whether or not it was requested, and
/// requesting it explicitly has no effect. Corresponds to the POSIX
/// `POLLNVAL` event flag.
@inlinable
public static var invalidDescriptor: PollEvents {
PollEvents(.invalidDescriptor)
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "invalidDescriptor")
public static var POLLNVAL: PollEvents { invalidDescriptor }
/// An event indicating the peer closed its writing end of a stream
/// socket, or shut it down for writing.
///
/// Unlike ``hangUp``, this event can arrive while the connection is
/// still half-open: data already in flight can still be read, and the
/// local end can still write. Once both directions are shut down,
/// ``hangUp`` is reported alongside this event.
///
/// Unlike `poll(2)`, `io_uring` reports this event whether or not it
/// was requested, and requesting it explicitly has no effect.
/// Corresponds to the Linux `POLLRDHUP` event flag.
@inlinable
public static var peerClosed: PollEvents { PollEvents(.peerClosed) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "peerClosed")
public static var POLLRDHUP: PollEvents { peerClosed }
}
}
#endif
#endif
+43 -8
View File
@@ -1,8 +1,22 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
public import CSystemIOUring
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif
@usableFromInline
internal struct RawIORequest: ~Copyable {
// swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where
@@ -75,6 +89,27 @@ extension RawIORequest {
set { rawValue.addr = newValue }
}
/// The poll event mask, stored in `sqe->poll32_events`.
///
/// Big-endian kernels swap the halfwords of this field before reading it.
/// Equivalent to liburing's `__io_uring_prep_poll_mask`.
@_alwaysEmitIntoClient var pollEvents: IORing.Request.PollEvents {
get { .init(rawValue: Self._applyPollMask(rawValue.poll32_events)) }
set { rawValue.poll32_events = Self._applyPollMask(newValue.rawValue) }
}
/// Converts a poll event mask between its in-memory and `sqe` encodings.
///
/// This is a halfword rotate (`swahw32` from `<linux/swab.h>`), which keeps
/// the byte order within each half.
@_alwaysEmitIntoClient static func _applyPollMask(_ mask: UInt32) -> UInt32 {
#if _endian(big)
return (mask &<< 16) | (mask &>> 16)
#else
return mask
#endif
}
@inlinable public var flags: Flags {
get { Flags(rawValue: rawValue.flags) }
set { rawValue.flags = newValue.rawValue }
@@ -176,20 +211,20 @@ extension RawIORequest {
}
@inlinable
static func withTimeoutRequest<R>(
static func withTimeoutRequest<R, E: Error>(
linkedTo opEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
in timeoutEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
duration: Duration,
flags: TimeOutFlags,
work: () throws -> R) rethrows -> R {
duration: Duration,
flags: TimeOutFlags,
work: () throws(E) -> R) throws(E) -> R {
opEntry.pointee.flags |= Flags.linkRequest.rawValue
opEntry.pointee.off = 1
var ts = timespec(
tv_sec: Int(duration.components.seconds),
tv_sec: Int(duration.components.seconds),
tv_nsec: Int(duration.components.attoseconds / 1_000_000_000)
)
return try withUnsafePointer(to: &ts) { tsPtr in
return try withUnsafePointer(to: &ts) { tsPtr throws(E) -> R in
var req: RawIORequest = RawIORequest()
req.operation = .link_timeout
req.rawValue.timeout_flags = flags.rawValue
+27 -8
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
@@ -10,19 +10,20 @@
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
#if os(Linux)
// SwiftGlibc doesn't export `struct statfs`, so re-export it for clients who
// need to use the fields of a `CInterop.StatFS`.
@_exported import CSystemStatFS
#endif
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Bionic)
import CSystem
import Bionic
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
@@ -106,7 +107,7 @@ extension CInterop {
}
}
@available(System 99, *)
@available(System 1.7.0, *)
extension CInterop {
public typealias DeviceID = dev_t
public typealias Inode = ino_t
@@ -116,4 +117,22 @@ extension CInterop {
public typealias FileFlags = UInt32
#endif
}
#if !os(WASI)
@available(System 1.9.0, *)
extension CInterop {
/// The C `statfs` struct.
public typealias StatFS = statfs
#if SYSTEM_PACKAGE_DARWIN || os(OpenBSD)
public typealias MountFlags = UInt32
#elseif os(FreeBSD)
public typealias MountFlags = UInt64
#else
public typealias MountFlags = CUnsignedLong
#endif
public typealias FileSystemID = fsid_t
}
#endif
#endif
+345 -7
View File
@@ -14,16 +14,13 @@
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Windows)
import CSystem
import ucrt
import WinSDK
#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
@@ -31,6 +28,11 @@ import Android
#error("Unsupported Platform")
#endif
// Some WASI constants come from CSystem and are inlined into clients.
#if os(WASI)
public import CSystem
#endif
// MARK: errno
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
@@ -631,10 +633,10 @@ internal var _O_CLOEXEC: CInt {
#if !os(Windows)
@_alwaysEmitIntoClient
internal var _O_CLOFORK: CInt {
#if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
0x0800_0000 // O_CLOFORK, which SDKs before macOS 27 and older FreeBSD lack
#elseif !os(WASI) && !os(Linux) && !os(Android)
O_CLOFORK
#elseif os(FreeBSD)
FREEBSD_O_CLOFORK
#else
0
#endif
@@ -799,4 +801,340 @@ internal var _UF_SYSTEM: UInt32 { UInt32(bitPattern: UF_SYSTEM) }
internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) }
#endif
// MARK: - statfs Mount Flags
// `_MOUNT_*` is `MNT_*` on Darwin and BSD, or `ST_*` on Linux and Android.
#if !os(WASI)
// MARK: ST_* bits on Linux and Android
// Literal bits to keep our `@_alwaysEmitIntoClient` semantics. Calling
// CSystem's `_system_get_ST_*` getters would put a CSystem symbol in every
// client, block constant folding, and require a public `import CSystem`.
// `StatFSTests.mountFlagBitsMatchLibc` checks the literals against libc.
#if os(Linux) || os(Android)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_RDONLY_BIT: CInterop.MountFlags { 0x0001 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NOSUID_BIT: CInterop.MountFlags { 0x0002 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NODEV_BIT: CInterop.MountFlags { 0x0004 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NOEXEC_BIT: CInterop.MountFlags { 0x0008 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_SYNCHRONOUS_BIT: CInterop.MountFlags { 0x0010 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_MANDLOCK_BIT: CInterop.MountFlags { 0x0040 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NOATIME_BIT: CInterop.MountFlags { 0x0400 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NODIRATIME_BIT: CInterop.MountFlags { 0x0800 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_RELATIME_BIT: CInterop.MountFlags { 0x1000 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NOSYMFOLLOW_BIT: CInterop.MountFlags { 0x2000 }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_VALID_BIT: CInterop.MountFlags { 0x0020 }
#endif
// MARK: Flags Available on All Platforms
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_RDONLY: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_RDONLY)
#elseif os(Linux) || os(Android)
_ST_RDONLY_BIT
#endif
}
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_SYNCHRONOUS: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_SYNCHRONOUS)
#elseif os(Linux) || os(Android)
_ST_SYNCHRONOUS_BIT
#endif
}
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOEXEC: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOEXEC)
#elseif os(Linux) || os(Android)
_ST_NOEXEC_BIT
#endif
}
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOSUID: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOSUID)
#elseif os(Linux) || os(Android)
_ST_NOSUID_BIT
#endif
}
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOATIME: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOATIME)
#elseif os(Linux) || os(Android)
_ST_NOATIME_BIT
#endif
}
// MARK: Flags Available on All Platforms Except FreeBSD
#if !os(FreeBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NODEV: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NODEV)
#elseif os(Linux) || os(Android)
_ST_NODEV_BIT
#endif
}
#endif
// MARK: Flags Available on Linux and Android
#if os(Linux) || os(Android)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_MANDLOCK: CInterop.MountFlags { _ST_MANDLOCK_BIT }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_NODIRATIME: CInterop.MountFlags { _ST_NODIRATIME_BIT }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _ST_RELATIME: CInterop.MountFlags { _ST_RELATIME_BIT }
#endif
// MARK: Flags Available on Linux, Android, and FreeBSD
#if os(Linux) || os(Android) || os(FreeBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOSYMFOLLOW: CInterop.MountFlags {
#if os(FreeBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOSYMFOLLOW)
#else
_ST_NOSYMFOLLOW_BIT
#endif
}
#endif
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_ASYNC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ASYNC) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_EXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTED) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_LOCAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_LOCAL) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_QUOTA: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUOTA) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_ROOTFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ROOTFS) }
#endif
// MARK: Flags Available on Darwin and FreeBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_UNION: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNION) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_AUTOMOUNTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_AUTOMOUNTED) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_MULTILABEL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_MULTILABEL) }
#endif
// MARK: Flags Available on FreeBSD and OpenBSD
#if os(FreeBSD) || os(OpenBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_EXRDONLY: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXRDONLY) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_DEFEXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFEXPORTED) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_EXPORTANON: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTANON) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_SOFTDEP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SOFTDEP) }
#endif
// MARK: Flags Available on Darwin Only
#if SYSTEM_PACKAGE_DARWIN
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_CPROTECT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_CPROTECT) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_REMOVABLE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_REMOVABLE) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_QUARANTINE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUARANTINE) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_DOVOLFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DOVOLFS) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_DONTBROWSE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DONTBROWSE) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_IGNORE_OWNERSHIP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE_OWNERSHIP) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_JOURNALED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_JOURNALED) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_NOUSERXATTR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOUSERXATTR) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_DEFWRITE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFWRITE) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_NOFOLLOW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOFOLLOW) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_SNAPSHOT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SNAPSHOT) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_STRICTATIME: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_STRICTATIME) }
#endif
// MARK: Flags Available on FreeBSD Only
#if os(FreeBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_EXKERB: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXKERB) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_EXPUBLIC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPUBLIC) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ACLS) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_GJOURNAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_GJOURNAL) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_IGNORE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_NFS4ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NFS4ACLS) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_NOCLUSTERR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERR) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_NOCLUSTERW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERW) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_SUIDDIR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUIDDIR) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_SUJ: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUJ) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_UNTRUSTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNTRUSTED) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_USER: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_USER) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_VERIFIED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_VERIFIED) }
#endif
// MARK: Flags Available on OpenBSD Only
#if os(OpenBSD)
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_NOPERM: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOPERM) }
@available(System 1.9.0, *)
@_alwaysEmitIntoClient
internal var _MNT_WXALLOWED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_WXALLOWED) }
#endif
#endif // !os(WASI)
#endif // !os(Windows)
+24 -18
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
@@ -10,23 +10,21 @@
// Internal wrappers and typedefs which help reduce #if littering in System's
// code base.
// TODO: Should CSystem just include all the header files we need?
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Windows)
import CSystem
import ucrt
import WinSDK
#elseif canImport(Glibc)
@_implementationOnly import CSystem
#if os(Linux)
import CSystemStatFS
#endif
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Android)
@_implementationOnly import CSystem
import Android
#else
#error("Unsupported Platform")
@@ -79,10 +77,6 @@ internal var system_errno: CInt {
// Convention: `system_foo` is system's wrapper for `foo`.
internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
strerror(__errnum)
}
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
strlen(s)
}
@@ -96,18 +90,29 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
stat(p, &s)
}
@available(System 99, *)
@available(System 1.7.0, *)
internal func system_lstat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
lstat(p, &s)
}
@available(System 99, *)
@available(System 1.7.0, *)
internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
fstat(fd, &s)
}
@available(System 99, *)
@available(System 1.7.0, *)
internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 {
fstatat(fd, p, &s, flags)
}
#if !os(WASI)
@available(System 1.9.0, *)
internal func system_statfs(_ p: UnsafePointer<CChar>, _ s: inout CInterop.StatFS) -> Int32 {
statfs(p, &s)
}
@available(System 1.9.0, *)
internal func system_fstatfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 {
fstatfs(fd, &s)
}
#endif
#endif
// Convention: `system_platform_foo` is a
@@ -184,9 +189,10 @@ extension String {
// TLS
#if os(Windows)
internal typealias _PlatformTLSKey = DWORD
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
// Mock TLS storage for single-threaded WASI
internal final class _PlatformTLSKey {
#elseif os(WASI) && !_runtime(_multithreaded)
// Mock TLS storage for single-threaded WASI.
// Carries no state of its own, and only used to index `sharedTLSStorage`.
internal final class _PlatformTLSKey: @unchecked Sendable {
fileprivate init() {}
}
private final class TLSStorage: @unchecked Sendable {
@@ -213,7 +219,7 @@ internal func makeTLSKey() -> _PlatformTLSKey {
fatalError("Unable to create key")
}
return raw
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
#elseif os(WASI) && !_runtime(_multithreaded)
return _PlatformTLSKey()
#else
var raw = pthread_key_t()
+20 -9
View File
@@ -7,6 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
internal import CSystem
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
@@ -23,11 +24,19 @@ 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
// strerror(3) isn't guaranteed to be thread-safe: for an unknown error number,
// it may format the message into a buffer shared by all threads. This wrapper
// uses a caller-provided buffer instead (strerror_r(3), or strerror_s on
// Windows). It isn't a syscall, so it isn't mocked.
internal func system_strerror_r(
_ errnum: CInt, _ buffer: UnsafeMutablePointer<CChar>, _ length: Int
) -> CInt {
csystem_strerror_r(errnum, buffer, length)
}
// open
internal func system_open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
@@ -141,13 +150,14 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
return dup2(fd, fd2)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
internal func system_dup3(_ fd: Int32, _ fd2: Int32, _ oflag: Int32) -> Int32 {
#if ENABLE_MOCKING
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, fd2, oflag) }
#endif
#endif
return csystem_posix_dup3(fd, fd2, oflag)
}
#endif
#endif // !os(WASI)
#if !os(WASI)
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
@@ -157,13 +167,14 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
return pipe(fds)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
internal func system_pipe2(_ fds: UnsafeMutablePointer<Int32>, _ oflag: Int32) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fds, oflag) }
#endif
return csystem_posix_pipe2(fds, oflag)
}
#endif
#endif // !os(WASI)
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
#if ENABLE_MOCKING
@@ -201,7 +212,7 @@ internal func system_confstr(
) -> Int {
return confstr(name, buf, len)
}
#endif
#endif // SYSTEM_PACKAGE_DARWIN
#if !os(Windows)
internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR
@@ -269,7 +280,7 @@ internal func system_openat(
#endif
return openat(fd, path, oflag)
}
#endif
#endif // !os(Windows)
#if !os(WASI) // WASI has no umask
internal func system_umask(
@@ -277,7 +288,7 @@ internal func system_umask(
) -> CInterop.Mode {
return umask(mode)
}
#endif
#endif // !os(WASI)
internal func system_getenv(
_ name: UnsafePointer<CChar>
@@ -11,16 +11,15 @@
import ucrt
import WinSDK
import Synchronization
fileprivate var _umask: CInterop.Mode = 0o22
private let _umask = Atomic<CInterop.Mode>(0o22)
@inline(__always)
func umask(
_ mode: CInterop.Mode
) -> CInterop.Mode {
let oldMask = _umask
_umask = mode
return oldMask
_umask.exchange(mode, ordering: .relaxed)
}
@inline(__always)
@@ -58,7 +57,7 @@ internal func open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
_ mode: CInterop.Mode
) -> CInt {
let actualMode = mode & ~_umask
let actualMode = mode & ~_umask.load(ordering: .relaxed)
guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
@@ -248,7 +247,7 @@ internal func mkdir(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> CInt {
let actualMode = mode & ~_umask
let actualMode = mode & ~_umask.load(ordering: .relaxed)
guard let pSD = _createSecurityDescriptor(from: actualMode,
for: .directory) else {
+4
View File
@@ -9,7 +9,11 @@
#if SYSTEM_PACKAGE_DARWIN
#if canImport(Darwin, _version: 310)
import Darwin.Mach
#else
@preconcurrency import Darwin.Mach
#endif
@available(System 1.4.0, *)
public protocol MachPortRight {}
+31 -4
View File
@@ -12,18 +12,21 @@
// private CSystem module.
//
// For new type wrappers introduced to System, access their C members here:
// - Import the platform overlay (Glibc/Musl), as consumers do.
// - Import the platform overlay (Glibc/Musl/Android), as consumers do.
// - Access raw C members of vended types (e.g. CInterop.Stat) as a downstream
// consumer would. Don't go through the Swift (e.g. Stat) wrapper since its
// accesses happen inside System, where importing CSystem is fine.
// - Touch every direct member the public API exposes. One field is not always
// a safe proxy for the rest.
// - Touch every direct member the public API exposes, and the members of C
// types it exposes through them (e.g. timespec). One field is not always a
// safe proxy for the rest.
#if canImport(Glibc) || canImport(Musl)
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#endif
import SystemPackage
@@ -41,5 +44,29 @@ func _mivProbe(_ s: CInterop.Stat) {
_ = s.st_atim
_ = s.st_mtim
_ = s.st_ctim
_ = s.st_atim.tv_sec
_ = s.st_atim.tv_nsec
}
// These are the Linux and Android field names. FreeBSD's libc module is also
// named Glibc, but its `statfs` and `fsid_t` use the BSD names.
#if os(Linux) || os(Android)
func _mivProbe(_ s: CInterop.StatFS) {
_ = s.f_type
_ = s.f_bsize
_ = s.f_blocks
_ = s.f_bfree
_ = s.f_bavail
_ = s.f_files
_ = s.f_ffree
_ = s.f_fsid
_ = s.f_namelen
_ = s.f_frsize
_ = s.f_flags
}
func _mivProbe(_ id: CInterop.FileSystemID) {
_ = id.__val
}
#endif
#endif
+69 -2
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -19,6 +19,14 @@ import System
import WinSDK
#endif
#if SYSTEM_PACKAGE && canImport(CSystem)
import CSystem // for csystem_strerror_r
#endif
#if canImport(Dispatch)
import Dispatch
#endif
@available(System 0.0.1, *)
final class ErrnoTest: XCTestCase {
func testConstants() {
@@ -235,5 +243,64 @@ final class ErrnoTest: XCTestCase {
// TODO: `_code/_domain` for NSError bridging
// TODO: `description`
func testDescription() {
XCTAssertEqual(Errno.noSuchFileOrDirectory.description, "No such file or directory")
XCTAssertEqual(Errno.notPermitted.debugDescription, Errno.notPermitted.description)
// Unknown error numbers still get a message.
let unknown = Errno(rawValue: 98765).description
XCTAssertFalse(unknown.isEmpty)
#if !os(Windows) && !os(WASI) && !canImport(Musl)
// Windows' message is just "Unknown error", and musl's (also used by
// WASI) is "No error information", without the number.
XCTAssert(unknown.contains("98765"), unknown)
#endif
}
#if canImport(Dispatch)
func testDescriptionIsThreadSafe() {
// For unknown error numbers, strerror(3) may format the message into a
// buffer shared by all threads, so concurrent calls could see each
// other's messages.
let errnos = (0..<64).map { Errno(rawValue: 90000 + CInt($0)) }
let expected = errnos.map(\.description)
let iterations = 200
nonisolated(unsafe) let mismatches =
UnsafeMutableBufferPointer<Int>.allocate(capacity: errnos.count)
mismatches.initialize(repeating: 0)
defer { mismatches.deallocate() }
DispatchQueue.concurrentPerform(iterations: errnos.count) { index in
for _ in 0..<iterations where errnos[index].description != expected[index] {
mismatches[index] += 1
}
}
XCTAssertEqual(mismatches.reduce(0, +), 0)
}
#endif
#if SYSTEM_PACKAGE && canImport(CSystem)
func testStrerrorShim() {
var buffer = [CChar](repeating: 1, count: 256)
XCTAssertEqual(csystem_strerror_r(ENOENT, &buffer, buffer.count), 0)
XCTAssertEqual(
buffer.withUnsafeBufferPointer { String(cString: $0.baseAddress!) },
"No such file or directory")
// A buffer that is too small yields a truncated, NUL-terminated message.
var small = [CChar](repeating: 1, count: 4)
XCTAssertEqual(csystem_strerror_r(ENOENT, &small, small.count), ERANGE)
#if !os(Windows)
XCTAssertEqual(
small.withUnsafeBufferPointer { String(cString: $0.baseAddress!) },
"No ")
#endif
XCTAssertEqual(small[3], 0)
// A zero-length buffer is rejected without writing to it.
var empty = CChar(1)
XCTAssertEqual(csystem_strerror_r(ENOENT, &empty, 0), ERANGE)
XCTAssertEqual(empty, 1)
}
#endif
}
+3 -3
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -36,7 +36,7 @@ import Android
@Suite("FileMode")
private struct FileModeTests {
@available(System 99, *)
@available(System 1.7.0, *)
@Test func basics() async throws {
var mode = FileMode(rawValue: S_IFREG | 0o644) // Regular file, rw-r--r--
#expect(mode.type == .regular)
@@ -67,7 +67,7 @@ private struct FileModeTests {
#expect(mode.type == mode2.type)
}
@available(System 99, *)
@available(System 1.7.0, *)
@Test func invalidInput() async throws {
// No permissions, all other bits set
var invalidMode = FileMode(rawValue: ~0o7777)
+29 -9
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -157,7 +157,8 @@ final class FileOperationsTest: XCTestCase {
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
}
#if !os(WASI) // WASI has no pipe
#if !os(WASI) // WASI has no pipe
@available(System 1.1.0, *)
func testAdHocPipe() throws {
// Ad-hoc test testing `Pipe` functionality.
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
@@ -177,8 +178,10 @@ final class FileOperationsTest: XCTestCase {
}
}
#if !SYSTEM_PACKAGE_DARWIN
func testAdHocPipeWithOptions() throws {
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
throw XCTSkip("pipe2 and PipeOptions require Darwin 27 or newer")
}
// Ad-hoc test testing `Pipe` functionality.
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
let options: FileDescriptor.PipeOptions = [.closeOnExec]
@@ -198,10 +201,25 @@ final class FileOperationsTest: XCTestCase {
}
}
}
#endif // !SYSTEM_PACKAGE_DARWIN
#endif // !os(WASI)
#if !os(Windows)
#if canImport(Darwin, _version: 428) // The macOS 27 SDK defines O_CLOFORK.
func testAdHocPipeCloseOnFork() throws {
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
throw XCTSkip("pipe2 and PipeOptions require anyAppleOS 27 or newer")
}
// System spells O_CLOFORK as a literal on Darwin.
XCTAssertEqual(FileDescriptor.PipeOptions.closeOnFork.rawValue, O_CLOFORK)
let pipe = try FileDescriptor.pipe(options: .closeOnFork)
try pipe.readEnd.closeAfter {
try pipe.writeEnd.closeAfter {
XCTAssertEqual(fcntl(pipe.readEnd.rawValue, F_GETFD) & FD_CLOFORK, FD_CLOFORK)
}
}
}
#endif
#endif // !os(WASI)
#if !os(Windows)
func testAdHocDuplicate2() throws {
try withTemporaryFilePath(basename: "test") {
let path = $0.appending("foo2.txt")
@@ -238,10 +256,11 @@ final class FileOperationsTest: XCTestCase {
}
}
}
#endif // !os(Windows)
#if !SYSTEM_PACKAGE_DARWIN && !os(Windows)
func testAdHocDuplicate3() throws {
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
throw XCTSkip("dup3 and DuplicateOptions require Darwin 27 or newer")
}
try withTemporaryFilePath(basename: "test") {
let path = $0.appending("foo3.txt")
@@ -274,7 +293,7 @@ final class FileOperationsTest: XCTestCase {
}
}
}
#endif // !SYSTEM_PACKAGE_DARWIN && !os(Windows)
#endif // !os(Windows)
func testAdHocOpen() {
// Ad-hoc test touching a file system.
@@ -334,6 +353,7 @@ final class FileOperationsTest: XCTestCase {
}
#endif // ENABLE_MOCKING
@available(System 1.2.0, *)
func testResizeFile() throws {
try withTemporaryFilePath(basename: "testResizeFile") { path in
let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
@@ -18,10 +18,22 @@ import XCTest
#endif
import WinSDK
import ucrt
private let ERROR_SUCCESS = DWORD(WinSDK.ERROR_SUCCESS)
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)
private let FILE_READ_DATA = DWORD(WinSDK.FILE_READ_DATA)
private let FILE_READ_EA = DWORD(WinSDK.FILE_READ_EA)
private let FILE_WRITE_ATTRIBUTES = DWORD(WinSDK.FILE_WRITE_ATTRIBUTES)
private let FILE_WRITE_DATA = DWORD(WinSDK.FILE_WRITE_DATA)
private let FILE_WRITE_EA = DWORD(WinSDK.FILE_WRITE_EA)
private let SECURITY_WORLD_RID = DWORD(WinSDK.SECURITY_WORLD_RID)
private let STANDARD_RIGHTS_EXECUTE = DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE)
private let STANDARD_RIGHTS_READ = DWORD(WinSDK.STANDARD_RIGHTS_READ)
private let STANDARD_RIGHTS_WRITE = DWORD(WinSDK.STANDARD_RIGHTS_WRITE)
private let SYNCHRONIZE = DWORD(WinSDK.SYNCHRONIZE)
@available(iOS 8, *)
final class FileOperationsTestWindows: XCTestCase {
@@ -295,6 +307,38 @@ final class FileOperationsTestWindows: XCTestCase {
// We can't easily test this without allocating 4GB, but the boundary is correct
}
}
func testCloseOnExecOpenOption() throws {
try withTemporaryFilePath(basename: "testCloseOnExec") { path in
func hasInheritFlag(of fd: FileDescriptor) throws -> Bool {
let osfHandle = _get_osfhandle(fd.rawValue)
let handle = try XCTUnwrap(HANDLE(bitPattern: osfHandle))
var flags: DWORD = 0
XCTAssertTrue(GetHandleInformation(handle, &flags))
return flags & DWORD(HANDLE_FLAG_INHERIT) == DWORD(HANDLE_FLAG_INHERIT)
}
var fd: FileDescriptor
fd = try FileDescriptor.open(
path.appending("wontinherit.txt"), .readWrite,
options: [.create, .truncate, .closeOnExec],
permissions: .ownerReadWrite
)
try fd.closeAfter {
XCTAssertEqual(try hasInheritFlag(of: fd), false)
}
fd = try FileDescriptor.open(
path.appending("inheritable.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
XCTAssertEqual(try hasInheritFlag(of: fd), true)
}
}
}
}
#endif // os(Windows)
@@ -70,7 +70,39 @@ struct TestPathComponents: TestCase {
}
func testRRC() {
// TODO: programmatic tests showing parity with Array<Component>
// Show that FilePathComponents's replaceSubrange behaves like Array.
let pool: [FilePath.Component] = ["x", "..", ".", "longer-name"]
let replacements: [[FilePath.Component]] = [[]] + (1 ... 3).flatMap { len in
pool.indices.map { offset in
(0 ..< len).map { pool[(offset + $0) % pool.count] }
}
}
let count = expectedComponents.count
for lower in 0 ... count {
for upper in lower ... count {
for replacement in replacements {
var model = expectedComponents
model.replaceSubrange(lower ..< upper, with: replacement)
var p = path
let indices = Array(p.components.indices) + [p.components.endIndex]
p.components.replaceSubrange(
indices[lower] ..< indices[upper], with: replacement
)
let expected = FilePath(root: path.root, model)
let message = """
replaceSubrange(\(lower)..<\(upper), with: \(replacement)) \
returned \(p), expected \(expected)
"""
expectEqual(expected, p, message + " [path]")
expectEqual(path.root, p.root, message + " [root]")
expectEqualSequence(model, p.components, message + " [components]")
expectEqual(model.last, p.lastComponent, message + " [lastComponent]")
}
}
}
}
func testModify() {
@@ -102,7 +134,7 @@ struct TestPathComponents: TestCase {
@available(System 0.0.2, *)
final class FilePathComponentsTest: XCTestCase {
func testAdHocRRC() {
func testAdHocRRC() throws {
var path: FilePath = "/usr/local/bin"
func expect(
@@ -118,26 +150,26 @@ final class FilePathComponentsTest: XCTestCase {
// Run `body`, restoring `path` afterwards
func restoreAfter(
body: () -> ()
) {
body: () throws -> ()
) rethrows {
let copy = path
defer { path = copy }
body()
try body()
}
// Interior removal keeps path prefix intact, if there is one
restoreAfter {
try restoreAfter {
path = "prefix//middle1/middle2////suffix"
let suffix = path.components.indices.last!
let suffix = try XCTUnwrap(path.components.indices.last)
path.components.removeSubrange(..<suffix)
expect("suffix")
}
restoreAfter {
try restoreAfter {
path = "prefix//middle1/middle2////suffix"
let firstMiddle = path.components.index(
path.components.startIndex, offsetBy: 1)
let suffix = path.components.indices.last!
let suffix = try XCTUnwrap(path.components.indices.last)
path.components.removeSubrange(firstMiddle ..< suffix)
expect("prefix/suffix")
}
@@ -193,14 +225,16 @@ final class FilePathComponentsTest: XCTestCase {
}
// Insertion into the middle adds trailing separator
restoreAfter {
try restoreAfter {
path.components.remove(
at: path.components.index(after: path.components.startIndex))
expect("/usr/bin")
path.components.insert("middle", at: path.components.indices.last!)
path.components.insert(
"middle", at: try XCTUnwrap(path.components.indices.last))
expect("/usr/middle/bin")
path.components.insert(
contentsOf: ["middle2", "middle3"], at: path.components.indices.last!)
contentsOf: ["middle2", "middle3"],
at: try XCTUnwrap(path.components.indices.last))
expect("/usr/middle/middle2/middle3/bin")
let slice = path.components.dropFirst().dropLast()
@@ -210,6 +244,35 @@ final class FilePathComponentsTest: XCTestCase {
expect("/usr/newMiddle/newMiddle2/newMiddle3/newMiddle4/bin")
}
// Replacing components at the end of a path must not append a separator.
try restoreAfter {
let last = try XCTUnwrap(path.components.indices.last)
path.components.replaceSubrange(last..., with: ["sbin"])
expect("/usr/local/sbin")
XCTAssertEqual(path.lastComponent, "sbin")
XCTAssertEqual(path.components.last, "sbin")
path.components.replaceSubrange(
path.components.index(after: path.components.startIndex)...,
with: ["a", "b", "c"])
expect("/usr/a/b/c")
path.components.append("d")
expect("/usr/a/b/c/d")
XCTAssertEqual(path.components.count, 5)
path.components.replaceSubrange(
path.components.startIndex..., with: ["x", "y"])
expect("/x/y")
}
try restoreAfter {
path = "a/b"
path.components.replaceSubrange(
try XCTUnwrap(path.components.indices.last)..., with: ["x"])
expect("a/x")
XCTAssertEqual(path.lastComponent, "x")
}
restoreAfter {
path.components.removeLast(3)
expect("/")
@@ -218,14 +281,15 @@ final class FilePathComponentsTest: XCTestCase {
}
// Empty insertions / removals
restoreAfter {
try restoreAfter {
path.components.replaceSubrange(..<path.components.startIndex, with: [])
expect("/usr/local/bin")
path.components.replaceSubrange(path.components.endIndex..., with: [])
expect("/usr/local/bin")
path.components.insert(contentsOf: [], at: path.components.startIndex)
expect("/usr/local/bin")
path.components.insert(contentsOf: [], at: path.components.indices.last!)
path.components.insert(
contentsOf: [], at: try XCTUnwrap(path.components.indices.last))
expect("/usr/local/bin")
}
}
+71
View File
@@ -2,6 +2,7 @@
#if os(Linux)
import XCTest
import CSystem
#if SYSTEM_PACKAGE
@testable import SystemPackage
@@ -21,6 +22,76 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
// that were generated with liburing or manually written out,
// which are known to work correctly.
final class IORequestTests: XCTestCase {
func testWriteUnregisteredImmutableBuffer() {
let bytes: [UInt8] = [1, 2, 3]
bytes.withUnsafeBytes { buffer in
let request = IORing.Request.write(
buffer, into: FileDescriptor(rawValue: 7), at: 17, context: 42
).makeRawRequest(pathBuffers: PendingPathBuffers(reservedCapacity: 0))
XCTAssertEqual(request.rawValue.opcode, 23)
XCTAssertEqual(request.rawValue.fd, 7)
XCTAssertEqual(request.rawValue.flags, 0)
XCTAssertEqual(request.rawValue.addr, UInt64(UInt(bitPattern: buffer.baseAddress)))
XCTAssertEqual(request.rawValue.len, 3)
XCTAssertEqual(request.rawValue.off, 17)
XCTAssertEqual(request.rawValue.user_data, 42)
}
}
func testWriteUnregisteredImmutableBufferToRegisteredFile() {
let bytes: [UInt8] = [1, 2, 3]
bytes.withUnsafeBytes { buffer in
let file = IORing.RegisteredFile(resource: 7, index: 3)
let request = IORing.Request.write(
buffer, into: file, at: 17, context: 42
).makeRawRequest(pathBuffers: PendingPathBuffers(reservedCapacity: 0))
XCTAssertEqual(request.rawValue.opcode, 23)
XCTAssertEqual(request.rawValue.fd, 3)
XCTAssertEqual(request.rawValue.flags, 1)
XCTAssertEqual(request.rawValue.addr, UInt64(UInt(bitPattern: buffer.baseAddress)))
XCTAssertEqual(request.rawValue.len, 3)
XCTAssertEqual(request.rawValue.off, 17)
XCTAssertEqual(request.rawValue.user_data, 42)
}
}
func testInferredRebasedWriteBuffer() {
var bytes: [UInt8] = [1, 2, 3]
bytes.withUnsafeMutableBytes { buffer in
let written = 1
let file = FileDescriptor(rawValue: 7)
let request = IORing.Request.write(
.init(rebasing: buffer[written...]), into: file, at: UInt64(written)
).makeRawRequest(pathBuffers: PendingPathBuffers(reservedCapacity: 0))
let registered = IORing.Request.write(
.init(rebasing: buffer[written...]),
into: IORing.RegisteredFile(resource: 7, index: 3), at: UInt64(written)
).makeRawRequest(pathBuffers: PendingPathBuffers(reservedCapacity: 0))
XCTAssertEqual(request.rawValue.len, 2)
XCTAssertEqual(request.rawValue.off, 1)
XCTAssertEqual(registered.rawValue.len, 2)
XCTAssertEqual(registered.rawValue.off, 1)
}
}
func testMutableWriteFunctionReferences() {
let write: (UnsafeMutableRawBufferPointer, FileDescriptor, UInt64, UInt64) -> IORing.Request =
IORing.Request.write
let writeRegistered: (UnsafeMutableRawBufferPointer, IORing.RegisteredFile, UInt64, UInt64) -> IORing.Request =
IORing.Request.write
var bytes: [UInt8] = [1, 2, 3]
bytes.withUnsafeMutableBytes { buffer in
let request = write(buffer, FileDescriptor(rawValue: 7), 17, 42)
.makeRawRequest(pathBuffers: PendingPathBuffers(reservedCapacity: 0))
let registered = writeRegistered(buffer, IORing.RegisteredFile(resource: 7, index: 3), 17, 42)
.makeRawRequest(pathBuffers: PendingPathBuffers(reservedCapacity: 0))
XCTAssertEqual(request.rawValue.fd, 7)
XCTAssertEqual(request.rawValue.len, 3)
XCTAssertEqual(registered.rawValue.fd, 3)
XCTAssertEqual(registered.rawValue.flags, 1)
}
}
func testNop() {
let req = IORing.Request.nop().makeRawRequest(
pathBuffers: PendingPathBuffers(reservedCapacity: 0))
+541 -24
View File
@@ -2,37 +2,96 @@
#if os(Linux)
import XCTest
import CSystem //for eventfd
#if SYSTEM_PACKAGE
import SystemPackage
#else
import System
import CSystem // for eventfd and csystem_io_uring_setup
import CSystemIOUring
#if canImport(Glibc)
import Glibc // for errno
#elseif canImport(Musl)
import Musl // for errno
#endif
func uringEnabled() throws -> Bool {
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
// Cache `isUringEnabled()`. The probe is complex and the answer doesn't change
// during a test run.
let uringEnabled: Bool = {
do {
let procPath = FilePath("/proc/sys/kernel/io_uring_disabled")
let fd = try FileDescriptor.open(procPath, .readOnly)
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0)
_ = try fd.read(into: buffer)
if buffer.load(fromByteOffset: 0, as: Int.self) == 0 {
return true
}
} catch (_) {
return try isUringEnabled()
} catch {
return false
}
return false
}()
let failureMessage = "Runtime environment does not support IORing."
func isUringEnabled() throws -> Bool {
// Even if the kernel supports io_uring, the SystemPackage build may have
// been compiled against older kernel headers that lack features it needs
// (gated on IORING_TIMEOUT_BOOTTIME in io_uring.h); in that configuration
// IORing.init throws ENOTSUP. Treat that as disabled so tests skip cleanly
// instead of failing.
do throws(Errno) {
_ = try IORing(queueDepth: 1, flags: [])
} catch {
switch error {
case .notSupported, .noFunction, .invalidArgument,
.notPermitted, .permissionDenied:
return false
default:
throw error
}
}
// The ideal test uses /proc/sys/kernel/io_uring_disabled (Linux >= 6.6).
if let fd = try? FileDescriptor.open(
"/proc/sys/kernel/io_uring_disabled", .readOnly)
{
defer { try? fd.close() }
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1, alignment: 1)
defer { buffer.deallocate() }
let n = try fd.read(into: buffer)
return n == 1 && (buffer.load(as: UInt8.self) == UInt8(ascii: "0"))
}
// Fallback for older kernels: simply attempt io_uring_setup.
// - ENOSYS -> syscall doesn't exist (Linux < 5.1) -> disabled.
// - EPERM or EACCES -> treat as disabled
// - propagate any other error.
var params = io_uring_params()
let raw = csystem_io_uring_setup(1, &params)
if raw < 0 {
let err = Errno(rawValue: errno)
switch err {
case .noFunction, .notPermitted, .permissionDenied:
return false
default:
throw err
}
}
try? FileDescriptor(rawValue: raw).close()
return true
}
final class IORingTests: XCTestCase {
func testIsUringEnabled() throws {
// If `isUringEnabled()` throws, it is incomplete in some way.
let enabled = try isUringEnabled()
if !enabled {
print("IORing tests will be skipped.")
}
}
func testInit() throws {
guard try uringEnabled() else { return }
try XCTSkipIf(!uringEnabled, failureMessage)
_ = try IORing(queueDepth: 32, flags: [])
}
func testNop() throws {
guard try uringEnabled() else { return }
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 32, flags: [])
_ = try ring.submit(linkedRequests: .nop())
let completion = try ring.blockingConsumeCompletion()
@@ -67,8 +126,32 @@ final class IORingTests: XCTestCase {
return ring
}
func testWriteImmutableUnregisteredBuffer() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
let bytes: [UInt8] = [1, 2, 3]
try bytes.withUnsafeBytes { buffer in
var ring = try IORing(queueDepth: 1)
let (readFD, writeFD) = try FileDescriptor.pipe()
defer {
try? readFD.close()
try? writeFD.close()
}
XCTAssertTrue(try ring.submit(linkedRequests: .write(buffer, into: writeFD, context: 42)))
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(1))
XCTAssertEqual(completion.context, 42)
guard completion.result == 3 else {
XCTFail("Expected three bytes written, got \(completion.result)")
return
}
var received = [UInt8](repeating: 0, count: 3)
let count = try received.withUnsafeMutableBytes { try readFD.read(into: $0) }
XCTAssertEqual(count, 3)
XCTAssertEqual(received, bytes)
}
}
func testUndersizedSubmissionQueue() throws {
guard try uringEnabled() else { return }
try XCTSkipIf(!uringEnabled, failureMessage)
var ring: IORing = try IORing(queueDepth: 1)
let enqueued = ring.prepare(linkedRequests: .nop(), .nop())
XCTAssertFalse(enqueued)
@@ -76,7 +159,7 @@ final class IORingTests: XCTestCase {
// Exercises opening, reading, closing, registered files, registered buffers, and eventfd
func testOpenReadAndWriteFixedFile() throws {
guard try uringEnabled() else { return }
try XCTSkipIf(!uringEnabled, failureMessage)
let (parent, path) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
@@ -117,12 +200,11 @@ final class IORingTests: XCTestCase {
_ = try ring.blockingConsumeCompletion() //close
memset(rawBuffer.baseAddress!, 0, rawBuffer.count)
//Verify using a non-ring IO method that what we wrote matches our expectations
print("about to open")
let nonRingFD = try FileDescriptor.open(path, .readOnly)
let bytesRead = try nonRingFD.read(into: rawBuffer)
XCTAssert(bytesRead == 13)
let result2 = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result2, "Hello, World!")
XCTAssertEqual(result2, "Hello, World!")
try cleanUpHelloWorldFile(parent)
efdBuf.deallocate()
rawBuffer.deallocate()
@@ -134,7 +216,7 @@ final class IORingTests: XCTestCase {
// 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 }
try XCTSkipIf(!uringEnabled, failureMessage)
let (parent, _) = try makeHelloWorldFile()
var ring = try IORing(queueDepth: 6)
@@ -168,7 +250,7 @@ final class IORingTests: XCTestCase {
}
func testPathBufferLifetimeAcrossLinkedRequests() throws {
guard try uringEnabled() else { return }
try XCTSkipIf(!uringEnabled, failureMessage)
let (parent, _) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
@@ -202,6 +284,441 @@ final class IORingTests: XCTestCase {
try cleanUpHelloWorldFile(parent)
rawBuffer.deallocate()
}
// Timeout test for `blockingConsumeCompletion(timeout:)`:
func testBlockingConsumeCompletionWithTimeoutOnIdleRing() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
let ring = try IORing(queueDepth: 4, flags: [])
try XCTSkipIf(
!ring.supportedFeatures.contains(.extendedArguments),
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
)
let clock = ContinuousClock()
let start = clock.now
var thrown: Errno? = nil
do throws(Errno) {
_ = try ring.blockingConsumeCompletion(timeout: .milliseconds(100))
XCTFail("expected timeout, got a completion on an idle ring")
} catch {
thrown = error
}
let elapsed = start.duration(to: clock.now)
XCTAssertEqual(thrown, .timeout)
XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(50))
}
func testBlockingConsumeCompletionsSendsDone() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4)
XCTAssertTrue(try ring.submit(linkedRequests: .nop()))
var dones: [Bool] = []
ring.blockingConsumeCompletions { (completion: consuming IORing.Completion?, error, done) in
dones.append(done)
}
XCTAssertEqual(dones, [false, true])
}
func testBlockingConsumeCompletionsKeepsContextOfFailedCompletion() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4)
XCTAssertTrue(try ring.submit(
linkedRequests: .close(FileDescriptor(rawValue: -1), context: 42)
))
var received: [(context: UInt64?, error: Errno?, done: Bool)] = []
ring.blockingConsumeCompletions { (completion: consuming IORing.Completion?, error, done) in
received.append((completion?.context, error, done))
}
XCTAssertEqual(received.count, 2)
XCTAssertEqual(received.first?.context, 42)
XCTAssertEqual(received.first?.error, .badFileDescriptor)
XCTAssertEqual(received.first?.done, false)
XCTAssertEqual(received.last?.context, nil)
XCTAssertEqual(received.last?.error, nil)
XCTAssertEqual(received.last?.done, true)
}
func testBlockingConsumeCompletionReturnsFailedCompletion() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4)
XCTAssertTrue(try ring.submit(
linkedRequests: .close(FileDescriptor(rawValue: -1), context: 43)
))
let completion = try ring.blockingConsumeCompletion()
XCTAssertEqual(completion.context, 43)
XCTAssertEqual(completion.error, .badFileDescriptor)
XCTAssertEqual(completion.result, -Errno.badFileDescriptor.rawValue)
}
func testSubmitAndConsumeCompletionsKeepsContextOfFailedCompletion() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4)
XCTAssertTrue(ring.prepare(request: .close(FileDescriptor(rawValue: -1), context: 44)))
var received: [(context: UInt64?, error: Errno?, done: Bool)] = []
ring.submitPreparedRequestsAndConsumeCompletions {
(completion: consuming IORing.Completion?, error, done) in
received.append((completion?.context, error, done))
}
XCTAssertEqual(received.count, 2)
XCTAssertEqual(received.first?.context, 44)
XCTAssertEqual(received.first?.error, .badFileDescriptor)
XCTAssertEqual(received.first?.done, false)
XCTAssertEqual(received.last?.context, nil)
XCTAssertEqual(received.last?.error, nil)
XCTAssertEqual(received.last?.done, true)
}
func testCompletionOfSuccessfulOperationHasNoError() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4)
XCTAssertTrue(try ring.submit(linkedRequests: .nop()))
let completion = try ring.blockingConsumeCompletion()
XCTAssertEqual(completion.result, 0)
XCTAssertNil(completion.error)
}
func testRegisterEventFDTwiceThrows() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4)
let efd = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE)))
defer { try? efd.close() }
try ring.registerEventFD(efd)
do throws(Errno) {
try ring.registerEventFD(efd) // second registration -> EBUSY
XCTFail("expected second registerEventFD to throw")
} catch {
XCTAssertEqual(error, .resourceBusy)
}
}
func testSubmitOnDisabledRingThrows() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 4, flags: [.startDisabled])
do throws(Errno) {
_ = try ring.submit(linkedRequests: .nop())
XCTFail("expected submit on a disabled ring to throw")
} catch {
XCTAssertEqual(error, Errno(rawValue: EBADFD))
}
}
func testPollAddPollIn() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 32, flags: [])
// This test case requires timeout support
try XCTSkipIf(
!ring.supportedFeatures.contains(.extendedArguments),
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
)
// Test POLLIN: Create an eventfd to monitor for read readiness
let testEventFD = FileDescriptor(rawValue: eventfd(0, 0))
defer {
try? testEventFD.close()
}
let pollInContext: UInt64 = 42
// Submit a pollAdd request to monitor for POLLIN events (data available for reading)
let enqueued = try ring.submit(linkedRequests:
.pollAdd(testEventFD, events: .readable, isMultiShot: false, context: pollInContext))
XCTAssert(enqueued)
// Write to the eventfd to trigger the POLLIN event
var value: UInt64 = 1
withUnsafeBytes(of: &value) { bufferPtr in
_ = try? testEventFD.write(bufferPtr)
}
// Consume the completion from the poll operation
let completion = try ring.blockingConsumeCompletion(
timeout: .seconds(1)
)
XCTAssertEqual(completion.context, pollInContext)
let readable = Int32(IORing.Request.PollEvents.readable.rawValue)
XCTAssertNotEqual(
completion.result & readable, 0, "expected POLLIN in the result mask"
)
}
func testPollAddPollOut() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 32, flags: [])
// This test case requires timeout support
try XCTSkipIf(
!ring.supportedFeatures.contains(.extendedArguments),
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
)
// Test POLLOUT: Create a pipe to monitor for write readiness
var pipeFDs: [Int32] = [0, 0]
let pipeResult = pipe(&pipeFDs)
XCTAssertEqual(pipeResult, 0)
let writeFD = FileDescriptor(rawValue: pipeFDs[1])
let readFD = FileDescriptor(rawValue: pipeFDs[0])
defer {
try? writeFD.close()
try? readFD.close()
}
let pollOutContext: UInt64 = 43
// Submit a pollAdd request to monitor for POLLOUT events (ready for writing)
// Pipes are typically ready for writing when empty
let enqueuedOut = try ring.submit(linkedRequests:
.pollAdd(writeFD, events: .writable, isMultiShot: false, context: pollOutContext))
XCTAssert(enqueuedOut)
// Consume the completion from the poll operation
let completionOut = try ring.blockingConsumeCompletion(
timeout: .seconds(1)
)
XCTAssertEqual(completionOut.context, pollOutContext)
let writable = Int32(IORing.Request.PollEvents.writable.rawValue)
XCTAssertNotEqual(
completionOut.result & writable, 0,
"expected POLLOUT in the result mask"
)
}
// Similar to the multishot example in the documentation for
// `pollAdd(_:events:isMultiShot:context:)`: arm a multishot poll,
// then consume completions for as long as they carry `.moreCompletions`.
func testPollAddMultiShotRearmsAcrossEvents() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 32, flags: [])
// This test case requires timeout support
try XCTSkipIf(
!ring.supportedFeatures.contains(.extendedArguments),
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
)
var pipeFDs: [Int32] = [0, 0]
XCTAssertEqual(pipe(&pipeFDs), 0)
let readFD = FileDescriptor(rawValue: pipeFDs[0])
let writeFD = FileDescriptor(rawValue: pipeFDs[1])
defer {
try? readFD.close()
try? writeFD.close()
}
func writeByte() throws {
var byte: UInt8 = 1
try withUnsafeBytes(of: &byte) {
try XCTAssertEqual(writeFD.write($0), 1)
}
}
func readByte() throws {
var scratch: UInt8 = 0
try withUnsafeMutableBytes(of: &scratch) {
try XCTAssertEqual(readFD.read(into: $0), 1)
}
}
let context: UInt64 = 44
let readable = Int32(IORing.Request.PollEvents.readable.rawValue)
let pollRequest = IORing.Request.pollAdd(
readFD, events: .readable, isMultiShot: true, context: context
)
let enqueued = try ring.submit(linkedRequests: pollRequest)
XCTAssert(enqueued)
try writeByte()
let first = try ring.blockingConsumeCompletion(timeout: .seconds(1))
// Kernels before 5.13 reject IORING_POLL_ADD_MULTI
try XCTSkipIf(
first.result == -EINVAL,
"Kernel < 5.13: multishot poll is unsupported."
)
XCTAssertEqual(first.context, context)
XCTAssertNotEqual(
first.result & readable, 0, "expected POLLIN in the result mask"
)
XCTAssert(first.flags.contains(.moreCompletions))
// Drain the pipe, then any extra completions.
try readByte()
while ring.tryConsumeCompletion() != nil {}
try writeByte()
// This written byte will only be reported by a re-armed poll.
let second = try ring.blockingConsumeCompletion(timeout: .seconds(1))
XCTAssertEqual(second.context, context)
XCTAssertNotEqual(
second.result & readable, 0, "expected POLLIN in the result mask"
)
// Drain again
try readByte()
while ring.tryConsumeCompletion() != nil {}
// Cancel to end the multishot poll.
try XCTAssert(
ring.submit(linkedRequests: .cancel(.all, matchingContext: context))
)
var terminal: (result: Int32, flags: IORing.Completion.Flags)? = nil
var observed: [(context: UInt64, result: Int32, flags: UInt32)] = []
// The cancel posts a completion of its own under a different context,
// and the two may land a moment apart, so retry briefly rather than
// draining exactly once.
for _ in 0..<100 where terminal == nil {
while let completion = ring.tryConsumeCompletion() {
observed.append(
(
completion.context,
completion.result,
completion.flags.rawValue
)
)
if completion.context == context {
terminal = (completion.result, completion.flags)
}
}
if terminal == nil { usleep(1000) }
}
XCTAssertNotNil(
terminal,
"no terminal completion for the cancelled poll; "
+ "completions seen: \(observed)"
)
if let terminal {
XCTAssertEqual(terminal.result, -ECANCELED)
XCTAssertFalse(
terminal.flags.contains(.moreCompletions),
"poll kept its armed state after being cancelled"
)
}
}
func testPollHangup() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 8)
let (readFD, writeFD) = try FileDescriptor.pipe()
// The hangup is produced by closing the write end mid-test, so the
// cleanup below must not close it a second time: the descriptor number
// may already have been reused elsewhere in the test process.
var writeEndClosed = false
defer {
try? readFD.close()
if !writeEndClosed { try? writeFD.close() }
}
// This test case requires timeout support
try XCTSkipIf(
!ring.supportedFeatures.contains(.extendedArguments),
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
)
let request = IORing.Request.pollAdd(
readFD, events: .readable, isMultiShot: false, context: 97
)
let success = try ring.submit(linkedRequests: request)
XCTAssertEqual(success, true)
try writeFD.close()
writeEndClosed = true
let dt = Duration.seconds(1)
let completion = try ring.blockingConsumeCompletion(timeout: dt)
for event in IORing.Request.PollEvents.Event.allCases {
if completion.result & Int32(event.rawValue) != 0 {
XCTAssertEqual(event, .hangUp)
return
}
}
let unexpected = completion.result
XCTFail("Unexpected poll event: 0x\(String(unexpected, radix: 16))")
}
func testPollError() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 8)
let (readFD, writeFD) = try FileDescriptor.pipe(options: .nonBlocking)
// POLLERR is produced by closing the read end mid-test; see the note in
// `testPollHangup` for why cleanup must not close it twice.
var readEndClosed = false
defer {
if !readEndClosed { try? readFD.close() }
try? writeFD.close()
}
// This test case requires timeout support
try XCTSkipIf(
!ring.supportedFeatures.contains(.extendedArguments),
"Kernel < 5.11: timeouts in io_uring_enter aren't supported."
)
let chunk = [UInt8](repeating: 0, count: 4096)
chunk.withUnsafeBytes {
// Fill the pipe by writing until an operation fails
while let written = try? writeFD.write($0), written > 0 {}
}
let request = IORing.Request.pollAdd(
writeFD, events: .writable, isMultiShot: false, context: 98
)
let success = try ring.submit(linkedRequests: request)
XCTAssertEqual(success, true)
try readFD.close()
readEndClosed = true
let dt = Duration.seconds(1)
let completion = try ring.blockingConsumeCompletion(timeout: dt)
XCTAssertEqual(completion.context, 98)
let pollError = IORing.Request.PollEvents.error.rawValue
let result = completion.result & Int32(pollError)
if result != pollError {
XCTFail("expected POLLERR, got 0x\(String(result, radix: 16))")
}
}
// A completion's `result` is two things in one field: a non-negative
// value is an event mask, and a negative value is a negated errno. The
// sign is the only thing distinguishing them, so it has to be checked
// before the value is treated as anything else.
func testPollAddOnInvalidDescriptor() throws {
try XCTSkipIf(!uringEnabled, failureMessage)
var ring = try IORing(queueDepth: 8)
let request = IORing.Request.pollAdd(
FileDescriptor(rawValue: -1), events: .readable,
isMultiShot: false, context: 99
)
let success = try ring.submit(linkedRequests: request)
XCTAssertEqual(success, true)
guard let completion = ring.tryConsumeCompletion() else {
XCTFail("expected a completion for the failed poll")
return
}
XCTAssertEqual(completion.context, 99)
// A negative value for `result` marks the completion a a failure.
XCTAssertLessThan(completion.result, 0, "expected a failure")
// The negative value is the error code multiplied by -1.
XCTAssertEqual(Errno(rawValue: -completion.result), .badFileDescriptor)
// A negative result may look like another result code.
// Checking for the error must happen first.
let invalidDescriptor = Int32(IORing.Request.PollEvents.invalidDescriptor.rawValue)
XCTAssertNotEqual(completion.result & invalidDescriptor, 0)
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+499
View File
@@ -0,0 +1,499 @@
//===----------------------------------------------------------------------===//
//
// 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 !os(Windows) && !os(WASI)
import Testing
#if canImport(Foundation)
import Foundation
#endif
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import CSystem
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#elseif canImport(Android)
import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
@Suite("StatFS")
private struct StatFSTests {
@available(System 1.9.0, *)
@Test func initializersAgree() async throws {
try withTemporaryFilePath(basename: "StatFS_initializersAgree") { tempDir in
let fromFilePath = try StatFS(tempDir)
let fromCString = try tempDir.withPlatformString { try StatFS($0) }
let dirFD = try FileDescriptor.open(tempDir, .readOnly)
defer { try? dirFD.close() }
let fromFD = try StatFS(dirFD)
#expect(fromFilePath.fileSystemID == fromCString.fileSystemID)
#expect(fromFilePath.fileSystemID == fromFD.fileSystemID)
#expect(fromFilePath.blockSize == fromFD.blockSize)
#expect(fromFilePath.totalBlocks == fromFD.totalBlocks)
#expect(fromFilePath.mountFlags == fromFD.mountFlags)
}
}
@available(System 1.9.0, *)
@Test func spaceAndBlocks() async throws {
try withTemporaryFilePath(basename: "StatFS_spaceAndBlocks") { tempDir in
let statfs = try StatFS(tempDir)
#expect(statfs.blockSize > 0)
#expect(statfs.totalBlocks > 0)
#expect(statfs.freeBlocks <= statfs.totalBlocks)
#expect(statfs.availableBlocks <= statfs.freeBlocks)
}
}
@available(System 1.9.0, *)
@Test func readOnlyFlagReflectsWritableFileSystem() async throws {
try withTemporaryFilePath(basename: "StatFS_readOnly") { tempDir in
let statfs = try StatFS(tempDir)
#expect(!statfs.mountFlags.contains(.readOnly))
}
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 1.9.0, *)
@Test func darwinAndBSDFields() async throws {
try withTemporaryFilePath(basename: "StatFS_darwinBSD") { tempDir in
let statfs = try StatFS(tempDir)
#expect(statfs.preferredIOBlockSize > 0)
#expect(!statfs.typeName.rawValue.isEmpty)
#expect(statfs.mountPoint.isAbsolute)
#expect(!statfs.mountSource.string.isEmpty)
let mountStatFS = try StatFS(statfs.mountPoint)
#expect(mountStatFS.mountPoint == statfs.mountPoint)
#expect(mountStatFS.typeName == statfs.typeName)
}
}
#endif
@available(System 1.9.0, *)
@Test func nonexistentPathThrows() async throws {
#expect(throws: Errno.noSuchFileOrDirectory) {
_ = try StatFS("/var/empty/definitely/does/not/exist")
}
#expect(throws: Errno.noSuchFileOrDirectory) {
_ = try StatFS(FilePath("/var/empty/definitely/does/not/exist"))
}
}
@available(System 1.9.0, *)
@Test func badFileDescriptorThrows() async throws {
let badFD = FileDescriptor(rawValue: -1)
#expect(throws: Errno.badFileDescriptor) {
_ = try StatFS(badFD)
}
}
@available(System 1.9.0, *)
@Test func propertiesMatchRawFields() async throws {
try withTemporaryFilePath(basename: "StatFS_diff") { tempDir in
var raw = CInterop.StatFS()
try tempDir.withPlatformString {
try #require(statfs($0, &raw) == 0, "\(Errno.current)")
}
let s = StatFS(rawValue: raw)
#expect(s.blockSize == Int(raw.f_bsize))
#expect(s.totalBlocks == UInt64(clamping: raw.f_blocks))
#expect(s.freeBlocks == UInt64(clamping: raw.f_bfree))
#expect(s.availableBlocks == UInt64(clamping: raw.f_bavail))
#expect(s.totalInodes == UInt64(clamping: raw.f_files))
#expect(s.freeInodes == UInt64(clamping: raw.f_ffree))
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
#expect(s.preferredIOBlockSize == Int(raw.f_iosize))
#expect(s.owner.rawValue == raw.f_owner)
#expect(s.mountFlags.rawValue == raw.f_flags)
#expect(s.typeName.rawValue == withUnsafeBytes(of: raw.f_fstypename) {
$0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
})
#expect(s.mountPoint.string == withUnsafeBytes(of: raw.f_mntonname) {
$0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
})
#expect(s.mountSource.string == withUnsafeBytes(of: raw.f_mntfromname) {
$0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
})
#if SYSTEM_PACKAGE_DARWIN
#expect(s.subtype.rawValue == raw.f_fssubtype)
#elseif os(FreeBSD)
#expect(s.maximumNameLength == Int(raw.f_namemax))
#else // os(OpenBSD)
#expect(s.maximumNameLength == Int(raw.f_namemax))
#expect(s.availableInodes == UInt64(clamping: raw.f_favail))
#endif
#else
#expect(s.fragmentSize == Int(raw.f_frsize))
#expect(s.maximumNameLength == Int(raw.f_namelen))
#expect(s.type.rawValue == UInt32(truncatingIfNeeded: raw.f_type))
// `mountFlags` omits the kernel's ST_VALID (0x20) bookkeeping bit.
#expect(s.mountFlags.rawValue == CInterop.MountFlags(truncatingIfNeeded: raw.f_flags) & ~0x20)
#endif
}
}
// Each setter writes its own field, and clamps instead of trapping.
@available(System 1.9.0, *)
@Test func settersWriteRawFields() throws {
var s = StatFS(rawValue: CInterop.StatFS())
s.blockSize = 1
s.totalBlocks = 2
s.freeBlocks = 3
s.availableBlocks = 4
s.totalInodes = 5
s.freeInodes = 6
#expect(s.rawValue.f_bsize == 1)
#expect(s.rawValue.f_blocks == 2)
#expect(s.rawValue.f_bfree == 3)
#expect(s.rawValue.f_bavail == 4)
#expect(s.rawValue.f_files == 5)
#expect(s.rawValue.f_ffree == 6)
#if SYSTEM_PACKAGE_DARWIN
s.subtype = FileSystemSubtype(8)
#expect(s.rawValue.f_fssubtype == 8)
#endif
s.mountFlags.insert(.readOnly)
#expect(s.mountFlags.contains(.readOnly))
s.blockSize = .max
#expect(s.blockSize == Int(clamping: type(of: s.rawValue.f_bsize).max))
}
@available(System 1.9.0, *)
@Test func craftedStructComputesSpace() throws {
var raw = CInterop.StatFS()
// The block-count unit is f_bsize on Darwin/BSD, f_frsize elsewhere.
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
raw.f_bsize = 512
#else
raw.f_bsize = 4096 // Should not be used in calculations
raw.f_frsize = 512
#endif
raw.f_blocks = 1000
raw.f_bfree = 400
raw.f_bavail = 100
let s = StatFS(rawValue: raw)
#expect(s.totalSpace == 1000 * 512)
#expect(s.freeSpace == 400 * 512)
#expect(s.availableSpace == 100 * 512)
}
@available(System 1.9.0, *)
@Test func spaceSaturatesOnOverflow() throws {
var raw = CInterop.StatFS()
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
raw.f_bsize = 512
#else
raw.f_frsize = 512
#endif
raw.f_blocks = .max
let s = StatFS(rawValue: raw)
if MemoryLayout.size(ofValue: raw.f_blocks) == MemoryLayout<UInt64>.size {
#expect(s.totalSpace == .max)
} else {
#expect(s.totalSpace == UInt64(raw.f_blocks) * 512)
}
}
#if os(FreeBSD) || os(OpenBSD)
@available(System 1.9.0, *)
@Test func negativeCountsClampToZero() throws {
var raw = CInterop.StatFS()
raw.f_bsize = 512
raw.f_bavail = -1
#if os(FreeBSD)
raw.f_ffree = -1
#else
raw.f_favail = -1
#endif
let s = StatFS(rawValue: raw)
#expect(s.availableBlocks == 0)
#expect(s.availableSpace == 0)
#if os(FreeBSD)
#expect(s.freeInodes == 0)
#else
#expect(s.availableInodes == 0)
#endif
// Distinct negative counts read the same through the clamped property,
// but they're still different values.
var other = raw
other.f_bavail = -2
#expect(StatFS(rawValue: other).availableBlocks == s.availableBlocks)
#expect(StatFS(rawValue: other) != s)
}
#endif
#if os(Linux)
// /proc files report size 0 via stat, so read until EOF instead of getting
// the size up front.
private func _readEntireFile(_ path: String) throws -> String {
let fd = try FileDescriptor.open(FilePath(path), .readOnly)
defer { try? fd.close() }
var result = [UInt8]()
var chunk = [UInt8](repeating: 0, count: 64 * 1024)
while true {
let n = try chunk.withUnsafeMutableBytes { try fd.read(into: $0) }
if n == 0 { break }
result.append(contentsOf: chunk[..<n])
}
return String(decoding: result, as: UTF8.self)
}
@available(System 1.9.0, *)
@Test func mountFlagsMatchProcMounts() throws {
let contents = try _readEntireFile("/proc/self/mounts")
// Fields: device, mountPoint, fsType, options, dump, pass.
var mounts: [String: Set<String>] = [:]
for line in contents.split(separator: "\n") {
let fields = line.split(separator: " ")
guard fields.count >= 4 else { continue }
let mountPoint = String(fields[1])
// Skip octal-escaped paths (spaces, tabs, etc.).
if mountPoint.contains(where: { $0 == "\\" }) { continue }
mounts[mountPoint] = Set(fields[3].split(separator: ",").map(String.init))
}
let checks: [(option: String, flag: MountFlags)] = [
("ro", .readOnly),
("noexec", .noExecution),
("nosuid", .noSetUserID),
("nodev", .noDevices),
("noatime", .noAccessTime),
]
// Only probe well-known local mounts. statfs on an arbitrary host mount
// can hang (e.g. a stale NFS mount).
let candidates: Set<String> = ["/", "/proc", "/sys", "/dev", "/dev/shm", "/run"]
var verified = 0
for (mountPoint, options) in mounts where candidates.contains(mountPoint) {
guard let statfs = try? StatFS(FilePath(mountPoint)) else { continue }
for (option, flag) in checks {
#expect(
statfs.mountFlags.contains(flag) == options.contains(option),
"\(mountPoint): flag \(flag) disagrees with options \(options)"
)
}
verified += 1
}
// Guard against a parser that silently matched nothing: "/" always works.
#expect(verified > 0)
}
#endif
#if os(Linux) || os(Android)
@available(System 1.9.0, *)
@Test func typeIsMagicNumber() throws {
// PROC_SUPER_MAGIC from <linux/magic.h>.
#expect(try StatFS("/proc").type == FileSystemType(0x9FA0))
// Magic numbers from 0x80000000 up should round-trip correctly even
// on platforms where they're signed.
var statfs = StatFS(rawValue: CInterop.StatFS())
statfs.type = FileSystemType(0x9123_683E) // BTRFS_SUPER_MAGIC
#expect(statfs.type == FileSystemType(0x9123_683E))
}
// The kernel sets ST_VALID (0x20) in every `f_flags` to mark the field as
// filled in, though Bionic's `statfs()` clears it.
@available(System 1.9.0, *)
@Test func mountFlagsOmitValidBit() throws {
var raw = CInterop.StatFS()
raw.f_flags = 0x20 | 0x01 // ST_VALID | ST_RDONLY
var statfs = StatFS(rawValue: raw)
#expect(statfs.mountFlags == .readOnly)
statfs.mountFlags = .noExecution
#expect(statfs.rawValue.f_flags == 0x20 | 0x08) // ST_VALID | ST_NOEXEC
let root = try StatFS("/")
#if os(Linux)
#expect(root.rawValue.f_flags & 0x20 != 0)
#endif
#expect(root.mountFlags.rawValue & 0x20 == 0)
}
#endif
#if os(Linux) || os(Android)
@available(System 1.9.0, *)
@Test func mountFlagBitsMatchLibc() throws {
let expected: [(name: String, literal: CInterop.MountFlags, libc: UInt64)] = [
("ST_RDONLY", _ST_RDONLY_BIT, _system_get_ST_RDONLY()),
("ST_NOSUID", _ST_NOSUID_BIT, _system_get_ST_NOSUID()),
("ST_NODEV", _ST_NODEV_BIT, _system_get_ST_NODEV()),
("ST_NOEXEC", _ST_NOEXEC_BIT, _system_get_ST_NOEXEC()),
("ST_SYNCHRONOUS", _ST_SYNCHRONOUS_BIT, _system_get_ST_SYNCHRONOUS()),
("ST_MANDLOCK", _ST_MANDLOCK_BIT, _system_get_ST_MANDLOCK()),
("ST_NOATIME", _ST_NOATIME_BIT, _system_get_ST_NOATIME()),
("ST_NODIRATIME", _ST_NODIRATIME_BIT, _system_get_ST_NODIRATIME()),
("ST_RELATIME", _ST_RELATIME_BIT, _system_get_ST_RELATIME()),
("ST_NOSYMFOLLOW", _ST_NOSYMFOLLOW_BIT, _system_get_ST_NOSYMFOLLOW()),
]
for (name, literal, libc) in expected {
#expect(
UInt64(literal) == libc,
"\(name): literal \(literal) disagrees with libc value \(libc)"
)
}
}
#endif
@available(System 1.9.0, *)
@Test func fileSystemIDConformances() throws {
let id = FileSystemID(_words: (1, 2))
#expect(id == FileSystemID(_words: (1, 2)))
#expect(id != FileSystemID(_words: (1, 3)))
#expect(id != FileSystemID(_words: (3, 2)))
#expect(id.hashValue != FileSystemID(_words: (1, 3)).hashValue)
#if canImport(Foundation)
let data = try JSONEncoder().encode(id)
#expect(String(decoding: data, as: UTF8.self) == "[1,2]")
#expect(try JSONDecoder().decode(FileSystemID.self, from: data) == id)
#endif
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 1.9.0, *)
@Test func fileSystemTypeNameConformances() throws {
let name: FileSystemTypeName = "apfs"
#expect(name == FileSystemTypeName(rawValue: "apfs"))
#expect(name == FileSystemTypeName("apfs"))
#expect(name != "hfs")
#expect(name.hashValue == FileSystemTypeName("apfs").hashValue)
#expect(name.description == "apfs")
#expect(name.debugDescription == #""apfs""#)
#if canImport(Foundation)
let data = try JSONEncoder().encode(name)
#expect(String(decoding: data, as: UTF8.self) == #""apfs""#)
#expect(try JSONDecoder().decode(FileSystemTypeName.self, from: data) == name)
#endif
}
#endif
#if SYSTEM_PACKAGE_DARWIN
@available(System 1.9.0, *)
@Test func fileSystemTypeNameConstants() throws {
#expect(FileSystemTypeName.apfs.rawValue == "apfs")
#expect(FileSystemTypeName.hfs.rawValue == "hfs")
// The root volume is APFS on every supported Apple platform.
#expect(try StatFS("/").typeName == .apfs)
}
#endif
@available(System 1.9.0, *)
@Test func descriptions() throws {
#expect(MountFlags.readOnly.description == "[.readOnly]")
let flags: MountFlags = [.readOnly, .noExecution]
#expect(flags.description == "[.readOnly, .noExecution]")
#expect(flags.debugDescription == flags.description)
#expect(MountFlags(rawValue: 0).description == "[]")
#expect(FileSystemID(_words: (1, 2)).description == "FileSystemID(1, 2)")
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// A name buffer with no NUL terminator (malformed) is read in full.
@available(System 1.9.0, *)
@Test func unterminatedNameBuffers() throws {
var raw = CInterop.StatFS()
withUnsafeMutableBytes(of: &raw.f_fstypename) { buffer in
for i in buffer.indices { buffer[i] = UInt8(ascii: "a") }
}
withUnsafeMutableBytes(of: &raw.f_mntonname) { buffer in
for i in buffer.indices { buffer[i] = UInt8(ascii: "b") }
}
let s = StatFS(rawValue: raw)
let typeNameLength = MemoryLayout.size(ofValue: raw.f_fstypename)
let mountPointLength = MemoryLayout.size(ofValue: raw.f_mntonname)
#expect(s.typeName.rawValue == String(repeating: "a", count: typeNameLength))
#expect(s.mountPoint.string == String(repeating: "b", count: mountPointLength))
}
#endif
@available(System 1.9.0, *)
@Test func equalityAndHashing() throws {
try withTemporaryFilePath(basename: "StatFS_equality") { tempDir in
let statfs = try StatFS(tempDir)
let copy = statfs
#expect(statfs == copy)
#expect(statfs.hashValue == copy.hashValue)
#expect(Set([statfs, copy]).count == 1)
var mutated = statfs
mutated.totalBlocks &+= 1
#expect(statfs != mutated)
// Reserved fields are not part of the value.
#if SYSTEM_PACKAGE_DARWIN
var reserved = statfs
reserved.rawValue.f_reserved.0 &+= 1
#expect(statfs == reserved)
#expect(statfs.hashValue == reserved.hashValue)
// Fields without a property, like `f_flags_ext`, are.
var extended = statfs
extended.rawValue.f_flags_ext ^= 1
#expect(statfs != extended)
#endif
// Name buffers are read only up to their NUL terminator, so bytes past
// it don't affect the value.
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
var trailing = statfs
try withUnsafeMutableBytes(of: &trailing.rawValue.f_mntonname) { buffer in
// The kernel always NUL-terminates the name buffers.
let terminator = try #require(buffer.firstIndex(of: 0))
if terminator + 1 < buffer.count {
buffer[terminator + 1] &+= 1
}
}
#expect(statfs == trailing)
#expect(statfs.hashValue == trailing.hashValue)
#endif
}
}
}
#endif
+50 -16
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
@@ -16,10 +16,8 @@ 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
@@ -39,7 +37,7 @@ import Android
@Suite("Stat")
private struct StatTests {
@available(System 99, *)
@available(System 1.7.0, *)
@Test func basics() async throws {
try withTemporaryFilePath(basename: "Stat_basics") { tempDir in
let dirStatFromFilePath = try tempDir.stat()
@@ -81,7 +79,7 @@ private struct StatTests {
}
}
@available(System 99, *)
@available(System 1.7.0, *)
@Test func followSymlinkInits() async throws {
try withTemporaryFilePath(basename: "Stat_followSymlinkInits") { tempDir in
let targetFilePath = tempDir.appending("target.txt")
@@ -190,7 +188,7 @@ private struct StatTests {
}
}
@available(System 99, *)
@available(System 1.7.0, *)
@Test func permissions() async throws {
try withTemporaryFilePath(basename: "Stat_permissions") { tempDir in
let testFile = tempDir.appending("test.txt")
@@ -220,8 +218,13 @@ private struct StatTests {
}
}
@available(System 99, *)
@available(System 1.7.0, *)
@Test func times() async throws {
// This test pauses with `usleep` between some measurements to ensure that
// the timestamp used by the filesystem will advance. On Linux and Android
// the granularity of that clock may be as much as 10ms. We use 50ms
// in order to have a comfortable margin.
let timestampSleep: useconds_t = 50_000
var start = timespec()
try #require(clock_gettime(CLOCK_REALTIME, &start) == 0, "\(Errno.current)")
start.tv_sec -= 1 // A little wiggle room
@@ -247,8 +250,7 @@ private struct StatTests {
#expect(dirCreationTime0 < startUpperBound)
#endif
// Fails intermittently if less than 5ms
usleep(10000)
usleep(timestampSleep)
let file1 = tempDir.appending("test1.txt")
let fd1 = try FileDescriptor.open(file1, .writeOnly, options: .create, permissions: .ownerReadWrite)
@@ -274,7 +276,7 @@ private struct StatTests {
#expect(dirCreationTime1 == dirCreationTime0)
#endif
usleep(10000)
usleep(timestampSleep)
// Changing permissions only updates directory change time
@@ -302,7 +304,7 @@ private struct StatTests {
let file1CreationTime1 = stat1.st_birthtim
#endif
usleep(10000)
usleep(timestampSleep)
try fd1.writeAll("Hello, world!".utf8)
stat1 = try file1.stat()
@@ -330,7 +332,7 @@ private struct StatTests {
#expect(dirStat.st_birthtim == dirCreationTime1)
#endif
usleep(10000)
usleep(timestampSleep)
let file2 = tempDir.appending("test2.txt")
let fd2 = try FileDescriptor.open(file2, .writeOnly, options: .create, permissions: .ownerReadWrite)
@@ -339,9 +341,9 @@ private struct StatTests {
}
let stat2 = try file2.stat()
#expect(stat2.st_atim > file1AccessTime2)
#expect(stat2.st_mtim > file1ModificationTime2)
#expect(stat2.st_ctim > file1ChangeTime2)
#expect(stat2.st_atim >= file1AccessTime2)
#expect(stat2.st_mtim >= file1ModificationTime2)
#expect(stat2.st_ctim >= file1ChangeTime2)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#expect(stat2.st_birthtim > file1CreationTime2)
#endif
@@ -349,7 +351,7 @@ private struct StatTests {
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 99, *)
@available(System 1.7.0, *)
@Test func flags() async throws {
try withTemporaryFilePath(basename: "Stat_flags") { tempDir in
let filePath = tempDir.appending("test.txt")
@@ -397,6 +399,38 @@ private struct StatTests {
}
#endif
@available(System 1.7.0, *)
@Test func equalityAndHashing() async throws {
try withTemporaryFilePath(basename: "Stat_equality") { tempDir in
let file = tempDir.appending("test.txt")
let fd = try FileDescriptor.open(
file, .writeOnly, options: .create, permissions: .ownerReadWrite)
defer { try? fd.close() }
// Two stats of the same, unchanged file compare equal and hash equal,
// so they coalesce in a Set.
let stat1 = try file.stat()
var stat2 = try file.stat()
stat2.st_atim = stat1.st_atim // stat() can bump access time
#expect(stat1 == stat2)
#expect(stat1.hashValue == stat2.hashValue)
#expect(Set([stat1, stat2]).count == 1)
// Reserved/"spare" and padding bytes must not affect equality.
// Poke a reserved field and confirm equality/hashing are stable.
#if SYSTEM_PACKAGE_DARWIN
var stat3 = stat1
stat3.rawValue.st_lspare = stat1.rawValue.st_lspare &+ 1
#expect(stat1 == stat3)
#expect(stat1.hashValue == stat3.hashValue)
#endif
// A stat of a different file (the containing directory) is not equal.
let dirStat = try tempDir.stat()
#expect(stat1 != dirStat)
}
}
}
// Comparison operators for timespec until UTCClock.Instant properties are available