mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f1a3aceb1 | ||
|
|
1dc5cdc944 | ||
|
|
781b0cfab5 | ||
|
|
e96ba28879 | ||
|
|
c0e3eea428 | ||
|
|
53b1815f41 | ||
|
|
8e71dd3e0d | ||
|
|
677e51f1f2 | ||
|
|
cf29202fc7 | ||
|
|
406f7634f1 | ||
|
|
1da023b4ca | ||
|
|
abc83c2de1 | ||
|
|
2949c1bfcb | ||
|
|
fa6a245b37 | ||
|
|
640e5755b5 | ||
|
|
1c44ed678c | ||
|
|
6c5077b2d2 | ||
|
|
762c819b0f | ||
|
|
013178c00e | ||
|
|
70505cf6fc | ||
|
|
d1b4ed40f2 | ||
|
|
20dddc22ed | ||
|
|
f6105a8be1 | ||
|
|
65df702254 | ||
|
|
77882a1fc8 | ||
|
|
402eb4b586 | ||
|
|
7f6a009cc4 | ||
|
|
8f2745da9a | ||
|
|
74c1ef0581 | ||
|
|
6dbc60a373 | ||
|
|
443e03c16f | ||
|
|
1e6e65ede7 | ||
|
|
90a005db2f | ||
|
|
98517ef93b | ||
|
|
f28e22fbc1 | ||
|
|
e16b3f1066 | ||
|
|
a3e9687c91 | ||
|
|
b1f3496e31 | ||
|
|
15479b53b9 | ||
|
|
688716f8a2 | ||
|
|
6374a4ab3a | ||
|
|
feb66db229 | ||
|
|
a51425f6d8 | ||
|
|
da235b4503 | ||
|
|
86fdc1dd1d | ||
|
|
d0f7d75929 | ||
|
|
f325ebf78f | ||
|
|
4179b2cce5 | ||
|
|
f5fe750a57 | ||
|
|
9bf5df3d10 | ||
|
|
d27cb52754 | ||
|
|
faae10c4ec | ||
|
|
a85b97fc62 | ||
|
|
92481cc056 | ||
|
|
f0d63f4282 | ||
|
|
b832f4134a | ||
|
|
0eab740450 | ||
|
|
cf36a2fe7b | ||
|
|
9a9b78e4e9 | ||
|
|
292eb44442 | ||
|
|
b2237390d8 | ||
|
|
671a219316 | ||
|
|
5cf1e06016 | ||
|
|
411318ca34 |
No files matched your search
@@ -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.18
|
||||
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.18
|
||||
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
|
||||
@@ -5,58 +5,45 @@ 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.15
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.18
|
||||
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": "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.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.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_android_sdk_build: true
|
||||
@@ -65,14 +52,17 @@ jobs:
|
||||
|
||||
build-abi-stable:
|
||||
name: Build ABI Stable
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.15
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.18
|
||||
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"
|
||||
|
||||
@@ -85,7 +75,10 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
- name: Install Dependencies
|
||||
shell: bash
|
||||
run: apt update && apt install -y cmake ninja-build jq
|
||||
run: |
|
||||
apt update && apt install -y curl ninja-build jq
|
||||
curl -fsSL "https://github.com/Kitware/CMake/releases/download/v4.0.2/cmake-4.0.2-linux-$(uname -m).tar.gz" \
|
||||
| tar --strip-components=1 -xz -C /usr/local
|
||||
- name: Configure Project
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -112,7 +105,7 @@ jobs:
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.15
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.18
|
||||
with:
|
||||
license_header_check_project_name: "Swift.org"
|
||||
# https://github.com/apple/swift-system/issues/224
|
||||
|
||||
@@ -7,4 +7,3 @@ xcuserdata/
|
||||
.*.sw?
|
||||
/.swiftpm
|
||||
.docc-build
|
||||
Package.resolved
|
||||
+1
-1
@@ -7,7 +7,7 @@ Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16.0)
|
||||
cmake_minimum_required(VERSION 3.29)
|
||||
project(SwiftSystem
|
||||
LANGUAGES C Swift)
|
||||
|
||||
|
||||
+11
-27
@@ -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
|
||||
@@ -61,6 +61,8 @@ let availability: [Available] = [
|
||||
|
||||
Available("1.7.0", "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0"),
|
||||
|
||||
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"),
|
||||
]
|
||||
|
||||
@@ -117,21 +119,23 @@ let package = Package(
|
||||
platforms: platforms,
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
.library(name: "SystemSockets", targets: ["SystemSockets"]),
|
||||
.executable(name: "system-samples", targets: ["Samples"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(
|
||||
name: "CSystem",
|
||||
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,26 +152,6 @@ let package = Package(
|
||||
name: "MemberImportVisibility",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]),
|
||||
.target(
|
||||
name: "SystemSockets",
|
||||
dependencies: ["SystemPackage", "CSystem"],
|
||||
path: "Sources/SystemSockets",
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
name: "SystemSocketsTests",
|
||||
dependencies: ["SystemSockets"],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.executableTarget(
|
||||
name: "Samples",
|
||||
dependencies: [
|
||||
"SystemPackage",
|
||||
"SystemSockets",
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
path: "Sources/Samples",
|
||||
swiftSettings: swiftSettings),
|
||||
],
|
||||
swiftLanguageModes: [.v6]
|
||||
)
|
||||
@@ -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 |
|
||||
@@ -114,13 +114,13 @@ We maintain separate branches for each active minor version of the package:
|
||||
| swift-system 1.6.x | release/1.6.0 |
|
||||
| swift-system 1.7.x | release/1.7.0 |
|
||||
| swift-system 1.8.x | release/1.8.x |
|
||||
| swift-system 1.9.x (unreleased) | |
|
||||
| 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.7.0` → `release/1.8.x` → `main`
|
||||
`release/1.8.x` → `release/1.9.x` → `main`
|
||||
|
||||
For example, anything landing on `release/1.6.0` will eventually appear on `release/1.7.0`, then `release/1.8.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.)
|
||||
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
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -13,12 +13,9 @@ target_include_directories(CSystem PUBLIC
|
||||
$<INSTALL_INTERFACE:include/CSystem>)
|
||||
|
||||
install(FILES
|
||||
include/CSystemDarwin.h
|
||||
include/CSystemLinux.h
|
||||
include/CSystemShared.h
|
||||
include/CSystemWASI.h
|
||||
include/CSystemWindows.h
|
||||
include/CSystemFreeBSD.h
|
||||
include/io_uring.h
|
||||
include/module.modulemap
|
||||
DESTINATION include/CSystem)
|
||||
|
||||
@@ -1,20 +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(__APPLE__)
|
||||
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifdef O_CLOFORK
|
||||
#define COMPATIBILITY_O_CLOFORK O_CLOFORK
|
||||
#else
|
||||
#define COMPATIBILITY_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#endif // defined(__APPLE__)
|
||||
@@ -1,20 +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 COMPATIBILITY_O_CLOFORK O_CLOFORK
|
||||
#else
|
||||
#define COMPATIBILITY_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#endif // defined(__FreeBSD__)
|
||||
@@ -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__
|
||||
@@ -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);
|
||||
@@ -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
|
||||
@@ -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; \
|
||||
@@ -193,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;
|
||||
@@ -220,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, sz);
|
||||
}
|
||||
|
||||
static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete,
|
||||
unsigned int flags, sigset_t *sig)
|
||||
{
|
||||
return io_uring_enter2(fd, to_submit, min_complete, flags, sig, _NSIG / 8);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,9 +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 "CSystemDarwin.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"
|
||||
}
|
||||
+108
-7
@@ -14,20 +14,85 @@
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#if defined(__FreeBSD__)
|
||||
#include <CSystemFreeBSD.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
|
||||
@@ -70,3 +135,39 @@ extern int csystem_posix_dup3(int fildes, int fildes2, int flag) {
|
||||
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__)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
module CSystemStatFS [system] {
|
||||
header "CSystemStatFS.h"
|
||||
export *
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct Connect: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Connect to a TCP server and send/receive messages"
|
||||
)
|
||||
|
||||
@Argument(help: "The host to connect to")
|
||||
var host: String
|
||||
|
||||
@Argument(help: "The port to connect to")
|
||||
var port: UInt16
|
||||
|
||||
@Option(name: .shortAndLong, help: "Message to send")
|
||||
var message: String = "Hello from swift-system sockets!"
|
||||
|
||||
func run() throws {
|
||||
print("Resolving \(host)...")
|
||||
|
||||
// Resolve the hostname
|
||||
let hints = SocketAddress.ResolutionHints(family: .ipv4, socketType: .stream, protocol: .tcp)
|
||||
let addresses = try SocketAddress.resolve(hostname: host, service: "\(port)", hints: hints)
|
||||
|
||||
guard let first = addresses.first else {
|
||||
print("No addresses found for \(host)")
|
||||
return
|
||||
}
|
||||
|
||||
print("Connecting to \(first.address.ipv4?.description ?? "unknown")...")
|
||||
|
||||
// Create socket
|
||||
let socket = try SocketDescriptor.open(first.family, first.socketType, protocol: first.protocol)
|
||||
defer { try? socket.close() }
|
||||
|
||||
// Connect
|
||||
try socket.connect(to: first.address)
|
||||
print("Connected!")
|
||||
|
||||
// Send message
|
||||
let messageBytes = Array(message.utf8)
|
||||
let sent = try messageBytes.withUnsafeBytes { buffer in
|
||||
try socket.send(UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
print("Sent \(sent) bytes: \(message)")
|
||||
|
||||
// Receive response
|
||||
var buffer = [UInt8](repeating: 0, count: 4096)
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try socket.receive(into: buffer)
|
||||
}
|
||||
|
||||
if received > 0 {
|
||||
let response = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
print("Received \(received) bytes: \(response)")
|
||||
} else {
|
||||
print("Connection closed by server")
|
||||
}
|
||||
|
||||
print("Done!")
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct Listen: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Run a simple TCP echo server"
|
||||
)
|
||||
|
||||
@Option(name: .shortAndLong, help: "The port to listen on")
|
||||
var port: UInt16 = 8080
|
||||
|
||||
@Option(name: .shortAndLong, help: "Maximum number of connections to accept (0 for unlimited)")
|
||||
var maxConnections: Int = 0
|
||||
|
||||
func run() throws {
|
||||
// Create socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? server.close() }
|
||||
|
||||
// Set reuse address
|
||||
try server.setReuseAddress(true)
|
||||
|
||||
// Bind
|
||||
let address = SocketAddress(ipv4: IPv4Address.any(port: port))
|
||||
try server.bind(to: address)
|
||||
|
||||
// Listen
|
||||
try server.listen(backlog: 5)
|
||||
|
||||
var localAddr = SocketAddress()
|
||||
try server.getLocalAddress(into: &localAddr)
|
||||
print("Listening on \(localAddr.ipv4?.description ?? "unknown")...")
|
||||
|
||||
var connectionCount = 0
|
||||
while maxConnections == 0 || connectionCount < maxConnections {
|
||||
print("Waiting for connection...")
|
||||
|
||||
var peerAddr = SocketAddress()
|
||||
let client = try server.accept(client: &peerAddr)
|
||||
connectionCount += 1
|
||||
|
||||
print("[\(connectionCount)] Connection from \(peerAddr.ipv4?.description ?? "unknown")")
|
||||
|
||||
// Handle client in a simple blocking manner
|
||||
defer { try? client.close() }
|
||||
|
||||
var buffer = [UInt8](repeating: 0, count: 4096)
|
||||
|
||||
while true {
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try client.receive(into: buffer)
|
||||
}
|
||||
if received == 0 {
|
||||
print("[\(connectionCount)] Client disconnected")
|
||||
break
|
||||
}
|
||||
|
||||
let message = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
print("[\(connectionCount)] Received \(received) bytes: \(message)")
|
||||
|
||||
// Echo back
|
||||
let sent = try buffer.prefix(received).withUnsafeBytes { buffer in
|
||||
try client.send(UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
print("[\(connectionCount)] Echoed \(sent) bytes")
|
||||
}
|
||||
}
|
||||
|
||||
print("Server shutting down after \(connectionCount) connections")
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct Resolve: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Resolve a hostname to IP addresses using getaddrinfo"
|
||||
)
|
||||
|
||||
@Argument(help: "The hostname to resolve")
|
||||
var hostname: String
|
||||
|
||||
@Option(name: .shortAndLong, help: "Service name or port number")
|
||||
var service: String?
|
||||
|
||||
@Flag(name: .long, help: "Show only IPv4 addresses")
|
||||
var ipv4Only: Bool = false
|
||||
|
||||
@Flag(name: .long, help: "Show only IPv6 addresses")
|
||||
var ipv6Only: Bool = false
|
||||
|
||||
func run() throws {
|
||||
let family: SocketDescriptor.Domain?
|
||||
if ipv4Only {
|
||||
family = .ipv4
|
||||
} else if ipv6Only {
|
||||
family = .ipv6
|
||||
} else {
|
||||
family = nil
|
||||
}
|
||||
|
||||
let hints = SocketAddress.ResolutionHints(family: family)
|
||||
|
||||
print("Resolving \(hostname)...")
|
||||
|
||||
let addresses = try SocketAddress.resolve(
|
||||
hostname: hostname,
|
||||
service: service,
|
||||
hints: hints
|
||||
)
|
||||
|
||||
if addresses.isEmpty {
|
||||
print("No addresses found")
|
||||
return
|
||||
}
|
||||
|
||||
print("Found \(addresses.count) address(es):\n")
|
||||
|
||||
for (index, info) in addresses.enumerated() {
|
||||
print("[\(index + 1)] Family: \(familyName(info.family))")
|
||||
print(" Type: \(typeName(info.socketType))")
|
||||
print(" Protocol: \(protocolName(info.protocol))")
|
||||
|
||||
if let ipv4 = info.address.ipv4 {
|
||||
print(" Address: \(ipv4.addressString):\(ipv4.port)")
|
||||
} else if let ipv6 = info.address.ipv6 {
|
||||
print(" Address: [\(ipv6.addressString)]:\(ipv6.port)")
|
||||
}
|
||||
|
||||
if let canonName = info.canonicalName {
|
||||
print(" Canonical: \(canonName)")
|
||||
}
|
||||
|
||||
print()
|
||||
}
|
||||
}
|
||||
|
||||
private func familyName(_ domain: SocketDescriptor.Domain) -> String {
|
||||
switch domain {
|
||||
case .ipv4: return "IPv4"
|
||||
case .ipv6: return "IPv6"
|
||||
case .local: return "Unix"
|
||||
default: return "Unknown (\(domain.rawValue))"
|
||||
}
|
||||
}
|
||||
|
||||
private func typeName(_ type: SocketDescriptor.ConnectionType) -> String {
|
||||
switch type {
|
||||
case .stream: return "Stream (TCP)"
|
||||
case .datagram: return "Datagram (UDP)"
|
||||
case .raw: return "Raw"
|
||||
default: return "Unknown (\(type.rawValue))"
|
||||
}
|
||||
}
|
||||
|
||||
private func protocolName(_ proto: SocketDescriptor.ProtocolID) -> String {
|
||||
switch proto {
|
||||
case .tcp: return "TCP"
|
||||
case .udp: return "UDP"
|
||||
case .ip: return "IP"
|
||||
default: return "Unknown (\(proto.rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
import SystemSockets
|
||||
|
||||
struct ReverseResolve: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
abstract: "Reverse resolve an IP address to a hostname using getnameinfo"
|
||||
)
|
||||
|
||||
@Argument(help: "The IP address to resolve (IPv4 or IPv6)")
|
||||
var address: String
|
||||
|
||||
@Option(name: .shortAndLong, help: "Port number")
|
||||
var port: UInt16 = 0
|
||||
|
||||
@Flag(name: .long, help: "Request numeric host (don't resolve)")
|
||||
var numericHost: Bool = false
|
||||
|
||||
@Flag(name: .long, help: "Request numeric service (don't resolve)")
|
||||
var numericService: Bool = false
|
||||
|
||||
func run() throws {
|
||||
// Try to parse as IPv4
|
||||
if let ipv4 = IPv4Address(address, port: port) {
|
||||
let sockAddr = SocketAddress(ipv4: ipv4)
|
||||
try resolve(sockAddr)
|
||||
return
|
||||
}
|
||||
|
||||
// Try to parse as IPv6
|
||||
if let ipv6 = IPv6Address(address, port: port) {
|
||||
let sockAddr = SocketAddress(ipv6: ipv6)
|
||||
try resolve(sockAddr)
|
||||
return
|
||||
}
|
||||
|
||||
print("Error: '\(address)' is not a valid IPv4 or IPv6 address")
|
||||
}
|
||||
|
||||
private func resolve(_ address: SocketAddress) throws {
|
||||
var flags: SocketAddress.ReverseResolutionFlags = []
|
||||
if numericHost {
|
||||
flags.insert(.numericHost)
|
||||
}
|
||||
if numericService {
|
||||
flags.insert(.numericService)
|
||||
}
|
||||
|
||||
print("Resolving \(addressDescription(address))...")
|
||||
|
||||
let info = try address.reverseLookup(flags: flags)
|
||||
|
||||
print()
|
||||
if let host = info.hostname {
|
||||
print("Host: \(host)")
|
||||
} else {
|
||||
print("Host: (not resolved)")
|
||||
}
|
||||
|
||||
if let service = info.service {
|
||||
print("Service: \(service)")
|
||||
} else {
|
||||
print("Service: (not resolved)")
|
||||
}
|
||||
}
|
||||
|
||||
private func addressDescription(_ address: SocketAddress) -> String {
|
||||
if let ipv4 = address.ipv4 {
|
||||
return "\(ipv4.addressString):\(ipv4.port)"
|
||||
} else if let ipv6 = address.ipv6 {
|
||||
return "[\(ipv6.addressString)]:\(ipv6.port)"
|
||||
} else {
|
||||
return "(unknown address)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
import SystemSockets
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
// Glibc declares `stdin`, `stdout` and `stderr` as mutable globals.
|
||||
@preconcurrency import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// Turn off libc's input/output buffering.
|
||||
internal func disableBuffering() {
|
||||
setbuf(stdin, nil)
|
||||
setbuf(stdout, nil)
|
||||
setbuf(stderr, nil)
|
||||
}
|
||||
|
||||
internal func complain(_ message: String) {
|
||||
var message = message + "\n"
|
||||
message.withUTF8 { buffer in
|
||||
_ = try? FileDescriptor.standardError.writeAll(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketAddress.ResolvedAddress {
|
||||
var niceDescription: String {
|
||||
var proto = ""
|
||||
switch self.protocol {
|
||||
case .udp: proto = "udp"
|
||||
case .tcp: proto = "tcp"
|
||||
default: proto = "\(self.protocol)"
|
||||
}
|
||||
return "\(address.niceDescription) (\(proto))"
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketAddress {
|
||||
var niceDescription: String {
|
||||
if let ipv4 = self.ipv4 { return ipv4.description }
|
||||
if let ipv6 = self.ipv6 { return ipv6.description }
|
||||
if let unix = self.unix { return unix.description }
|
||||
return self.description
|
||||
}
|
||||
}
|
||||
|
||||
extension SocketDescriptor.ConnectionType {
|
||||
var isConnectionless: Bool {
|
||||
self == .datagram || self == .reliablyDeliveredMessage
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
struct SystemSamples: ParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "system-samples",
|
||||
abstract: "A collection of little programs exercising some System features.",
|
||||
subcommands: [
|
||||
Resolve.self,
|
||||
ReverseResolve.self,
|
||||
Connect.self,
|
||||
Listen.self,
|
||||
])
|
||||
}
|
||||
|
||||
disableBuffering()
|
||||
SystemSamples.main()
|
||||
@@ -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
|
||||
@@ -31,7 +31,7 @@ set_target_properties(SystemPackage PROPERTIES
|
||||
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.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")
|
||||
@@ -61,7 +61,9 @@ target_sources(SystemPackage PRIVATE
|
||||
FileSystem/FileMode.swift
|
||||
FileSystem/FileType.swift
|
||||
FileSystem/Identifiers.swift
|
||||
FileSystem/Stat.swift)
|
||||
FileSystem/MountFlags.swift
|
||||
FileSystem/Stat.swift
|
||||
FileSystem/StatFS.swift)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
IORing/IOCompletion.swift
|
||||
@@ -82,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)
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
|
||||
@@ -381,7 +381,7 @@ extension FileDescriptor {
|
||||
/// Duplicates this file descriptor and returns the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
/// - 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 duplicate operation
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@@ -17,6 +16,7 @@ import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
internal import CSystem // For the members of system_dirent
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
|
||||
@@ -113,13 +113,15 @@ public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// Indicates that the file is executed as the owner.
|
||||
///
|
||||
/// For more information, see the `setuid(2)` man page.
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISUID` (the set-user-ID bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setUserID: FilePermissions { .init(rawValue: 0o4000) }
|
||||
|
||||
/// Indicates that the file is executed as the group.
|
||||
///
|
||||
/// For more information, see the `setgid(2)` man page.
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISGID` (the set-group-ID bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setGroupID: FilePermissions { .init(rawValue: 0o2000) }
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
@@ -10,7 +10,7 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
public import CSystemIOUring
|
||||
|
||||
public extension IORing {
|
||||
struct Completion: ~Copyable {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
public import CSystemIOUring
|
||||
|
||||
@usableFromInline
|
||||
internal enum IORequestCore {
|
||||
@@ -114,51 +114,6 @@ internal enum IORequestCore {
|
||||
flags: UInt32,
|
||||
target: IORing.RegisteredFile
|
||||
)
|
||||
case socket(
|
||||
domain: CInt,
|
||||
type: CInt,
|
||||
protocol: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case connect(
|
||||
socket: FileDescriptor,
|
||||
address: PendingSocketAddress,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case bind(
|
||||
socket: FileDescriptor,
|
||||
address: PendingSocketAddress,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case listen(
|
||||
socket: FileDescriptor,
|
||||
backlog: UInt32,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case accept(
|
||||
socket: FileDescriptor,
|
||||
peerAddress: UnsafeMutablePointer<sockaddr>?,
|
||||
peerAddressLength: UnsafeMutablePointer<socklen_t>?,
|
||||
flags: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case send(
|
||||
socket: FileDescriptor,
|
||||
buffer: UnsafeRawBufferPointer,
|
||||
flags: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case receive(
|
||||
socket: FileDescriptor,
|
||||
buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
case shutdown(
|
||||
socket: FileDescriptor,
|
||||
how: CInt,
|
||||
context: UInt64 = 0
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
@@ -413,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,
|
||||
@@ -423,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,
|
||||
@@ -434,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
|
||||
@@ -679,152 +692,10 @@ extension IORing.Request {
|
||||
request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI
|
||||
}
|
||||
request.pollEvents = events
|
||||
case .socket(let domain, let type, let `protocol`, let context):
|
||||
request.operation = .socket
|
||||
request.rawValue.fd = domain
|
||||
request.rawValue.off = UInt64(UInt32(bitPattern: type))
|
||||
request.rawValue.len = UInt32(bitPattern: `protocol`)
|
||||
request.rawValue.user_data = context
|
||||
case .connect(let socket, let address, let context):
|
||||
request.operation = .connect
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: pathBuffers.pin(address)))
|
||||
request.rawValue.addr2 = UInt64(address.length)
|
||||
request.rawValue.user_data = context
|
||||
case .bind(let socket, let address, let context):
|
||||
request.operation = .bind
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: pathBuffers.pin(address)))
|
||||
request.rawValue.addr2 = UInt64(address.length)
|
||||
request.rawValue.user_data = context
|
||||
case .listen(let socket, let backlog, let context):
|
||||
request.operation = .listen
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.len = backlog
|
||||
request.rawValue.user_data = context
|
||||
case .accept(let socket, let peerAddress, let peerAddressLength, let flags, let context):
|
||||
request.operation = .accept
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: peerAddress))
|
||||
request.rawValue.addr2 = UInt64(UInt(bitPattern: peerAddressLength))
|
||||
request.rawValue.accept_flags = UInt32(bitPattern: flags)
|
||||
request.rawValue.user_data = context
|
||||
case .send(let socket, let buffer, let flags, let context):
|
||||
request.operation = .send
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: buffer.baseAddress))
|
||||
request.rawValue.len = UInt32(exactly: buffer.count)!
|
||||
request.rawValue.msg_flags = UInt32(bitPattern: flags)
|
||||
request.rawValue.user_data = context
|
||||
case .receive(let socket, let buffer, let flags, let context):
|
||||
request.operation = .receive
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.addr = UInt64(UInt(bitPattern: buffer.baseAddress))
|
||||
request.rawValue.len = UInt32(exactly: buffer.count)!
|
||||
request.rawValue.msg_flags = UInt32(bitPattern: flags)
|
||||
request.rawValue.user_data = context
|
||||
case .shutdown(let socket, let how, let context):
|
||||
request.operation = .shutdown
|
||||
request.fileDescriptor = socket
|
||||
request.rawValue.len = UInt32(bitPattern: how)
|
||||
request.rawValue.user_data = context
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket requests
|
||||
|
||||
// These are the raw building blocks of the socket requests. The public,
|
||||
// typed API lives in `SystemSockets`, which owns the socket types.
|
||||
extension IORing.Request {
|
||||
package static func _socket(
|
||||
domain: CInt,
|
||||
type: CInt,
|
||||
protocol: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .socket(domain: domain, type: type, protocol: `protocol`, context: context))
|
||||
}
|
||||
|
||||
/// The address is copied, so `address` only has to be valid during this call.
|
||||
package static func _connect(
|
||||
_ socket: FileDescriptor,
|
||||
to address: UnsafePointer<sockaddr>,
|
||||
length: socklen_t,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .connect(
|
||||
socket: socket,
|
||||
address: PendingSocketAddress(copying: address, length: length),
|
||||
context: context
|
||||
))
|
||||
}
|
||||
|
||||
/// The address is copied, so `address` only has to be valid during this call.
|
||||
package static func _bind(
|
||||
_ socket: FileDescriptor,
|
||||
to address: UnsafePointer<sockaddr>,
|
||||
length: socklen_t,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .bind(
|
||||
socket: socket,
|
||||
address: PendingSocketAddress(copying: address, length: length),
|
||||
context: context
|
||||
))
|
||||
}
|
||||
|
||||
package static func _listen(
|
||||
_ socket: FileDescriptor,
|
||||
backlog: UInt32,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .listen(socket: socket, backlog: backlog, context: context))
|
||||
}
|
||||
|
||||
package static func _accept(
|
||||
_ socket: FileDescriptor,
|
||||
peerAddress: UnsafeMutablePointer<sockaddr>?,
|
||||
peerAddressLength: UnsafeMutablePointer<socklen_t>?,
|
||||
flags: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .accept(
|
||||
socket: socket,
|
||||
peerAddress: peerAddress,
|
||||
peerAddressLength: peerAddressLength,
|
||||
flags: flags,
|
||||
context: context
|
||||
))
|
||||
}
|
||||
|
||||
package static func _send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to socket: FileDescriptor,
|
||||
flags: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .send(socket: socket, buffer: buffer, flags: flags, context: context))
|
||||
}
|
||||
|
||||
package static func _receive(
|
||||
_ socket: FileDescriptor,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .receive(socket: socket, buffer: buffer, flags: flags, context: context))
|
||||
}
|
||||
|
||||
package static func _shutdown(
|
||||
_ socket: FileDescriptor,
|
||||
how: CInt,
|
||||
context: UInt64
|
||||
) -> IORing.Request {
|
||||
.init(core: .shutdown(socket: socket, how: how, context: context))
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -10,14 +10,15 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
internal import CSystem
|
||||
public import CSystemIOUring
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// Throwing wrapper around the `io_uring_enter2` shim.
|
||||
/// 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
|
||||
@@ -32,14 +33,14 @@ internal func _ioUringEnter2(
|
||||
argsSize: Int
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_enter2(
|
||||
csystem_io_uring_enter2(
|
||||
ringDescriptor, toSubmit, minComplete, flags, args, argsSize
|
||||
)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `io_uring_enter` shim.
|
||||
/// 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
|
||||
@@ -53,12 +54,12 @@ internal func _ioUringEnter(
|
||||
sig: UnsafeMutablePointer<sigset_t>?
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig)
|
||||
csystem_io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `io_uring_register` shim.
|
||||
/// 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.
|
||||
@@ -70,7 +71,7 @@ internal func _ioUringRegister(
|
||||
nrArgs: UInt32
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_register(ringDescriptor, opcode, arg, nrArgs)
|
||||
csystem_io_uring_register(ringDescriptor, opcode, arg, nrArgs)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
internal import CSystem
|
||||
public import CSystemIOUring
|
||||
// needed for mmap
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
@@ -59,11 +60,6 @@ internal final class PendingPathBuffers {
|
||||
@usableFromInline
|
||||
var paths: [FilePath] = []
|
||||
|
||||
/// The socket addresses of pending connect and bind requests. Like paths,
|
||||
/// the kernel copies them during `io_uring_enter`.
|
||||
@usableFromInline
|
||||
var socketAddresses: [PendingSocketAddress] = []
|
||||
|
||||
init(reservedCapacity: Int) {
|
||||
paths.reserveCapacity(reservedCapacity)
|
||||
}
|
||||
@@ -76,44 +72,9 @@ internal final class PendingPathBuffers {
|
||||
return paths.last!.withPlatformString { $0 }
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func pin(_ address: PendingSocketAddress) -> UnsafePointer<sockaddr> {
|
||||
socketAddresses.append(address)
|
||||
// Safe to escape: `socketAddresses` keeps the allocation alive until
|
||||
// clear() or class deinit.
|
||||
return UnsafePointer(address.address)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func clear() {
|
||||
paths.removeAll(keepingCapacity: true)
|
||||
socketAddresses.removeAll(keepingCapacity: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of the socket address of a connect or bind request.
|
||||
///
|
||||
/// The copy has a stable address, so the request can point the kernel at it.
|
||||
@usableFromInline
|
||||
internal final class PendingSocketAddress {
|
||||
@usableFromInline
|
||||
let address: UnsafeMutablePointer<sockaddr>
|
||||
|
||||
@usableFromInline
|
||||
let length: socklen_t
|
||||
|
||||
init(copying address: UnsafePointer<sockaddr>, length: socklen_t) {
|
||||
let raw = UnsafeMutableRawPointer.allocate(
|
||||
byteCount: Int(length),
|
||||
alignment: MemoryLayout<sockaddr_storage>.alignment
|
||||
)
|
||||
raw.copyMemory(from: address, byteCount: Int(length))
|
||||
self.address = raw.bindMemory(to: sockaddr.self, capacity: 1)
|
||||
self.length = length
|
||||
}
|
||||
|
||||
deinit {
|
||||
UnsafeMutableRawPointer(address).deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,7 +233,7 @@ private func setUpRing(
|
||||
|
||||
var err: Errno? = nil
|
||||
let ringDescriptor = withUnsafeMutablePointer(to: ¶ms) {
|
||||
let result = io_uring_setup(queueDepth, $0)
|
||||
let result = csystem_io_uring_setup(queueDepth, $0)
|
||||
if result < 0 {
|
||||
err = Errno.current
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
public import CSystemIOUring
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@@ -43,10 +43,8 @@ extension RawIORequest {
|
||||
case sendMessage = 9
|
||||
case receiveMessage = 10
|
||||
// ...
|
||||
case accept = 13
|
||||
case asyncCancel = 14
|
||||
case link_timeout = 15
|
||||
case connect = 16
|
||||
// ...
|
||||
case openAt = 18
|
||||
case close = 19
|
||||
@@ -55,18 +53,9 @@ extension RawIORequest {
|
||||
case read = 22
|
||||
case write = 23
|
||||
// ...
|
||||
case send = 26
|
||||
case receive = 27
|
||||
case openAt2 = 28
|
||||
// ...
|
||||
case shutdown = 34
|
||||
// ...
|
||||
case unlinkAt = 36
|
||||
// ...
|
||||
case socket = 45
|
||||
// ...
|
||||
case bind = 56
|
||||
case listen = 57
|
||||
}
|
||||
|
||||
public struct Flags: OptionSet, Hashable, Codable {
|
||||
|
||||
@@ -10,19 +10,20 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
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)
|
||||
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
|
||||
@@ -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
|
||||
@@ -11,11 +11,11 @@
|
||||
// they can be used anywhere without imports and without confusion to
|
||||
// unavailable local decls.
|
||||
|
||||
import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
import WinSDK
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@@ -28,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
|
||||
@@ -629,7 +634,7 @@ internal var _O_CLOEXEC: CInt {
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOFORK: CInt {
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
COMPATIBILITY_O_CLOFORK
|
||||
0x0800_0000 // O_CLOFORK, which SDKs before macOS 27 and older FreeBSD lack
|
||||
#elseif !os(WASI) && !os(Linux) && !os(Android)
|
||||
O_CLOFORK
|
||||
#else
|
||||
@@ -796,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)
|
||||
@@ -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)
|
||||
import CSystem
|
||||
#if os(Linux)
|
||||
import CSystemStatFS
|
||||
#endif
|
||||
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")
|
||||
@@ -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)
|
||||
}
|
||||
@@ -108,6 +102,17 @@ internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
|
||||
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
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import CSystem
|
||||
internal import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@@ -27,6 +27,16 @@ import Android
|
||||
// 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
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
extension String {
|
||||
internal init(
|
||||
_unsafeUninitializedCapacity capacity: Int,
|
||||
initializingUTF8With body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
|
||||
) rethrows {
|
||||
if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
|
||||
self = try String(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: body)
|
||||
return
|
||||
}
|
||||
|
||||
let array = try Array<UInt8>(
|
||||
unsafeUninitializedCapacity: capacity
|
||||
) { buffer, count in
|
||||
count = try body(buffer)
|
||||
}
|
||||
self = String(decoding: array, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// C interoperability types for socket operations
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 199, *)
|
||||
extension CInterop {
|
||||
/// Socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr`.
|
||||
public typealias SockAddr = sockaddr
|
||||
|
||||
/// Socket address length type.
|
||||
///
|
||||
/// The corresponding C type is `socklen_t`.
|
||||
public typealias SockLen = socklen_t
|
||||
|
||||
/// Socket address family type.
|
||||
///
|
||||
/// The corresponding C type is `sa_family_t`.
|
||||
public typealias SAFamily = sa_family_t
|
||||
|
||||
/// IPv4 socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr_in`.
|
||||
public typealias SockAddrIn = sockaddr_in
|
||||
|
||||
/// IPv4 address structure.
|
||||
///
|
||||
/// The corresponding C type is `in_addr`.
|
||||
public typealias InAddr = in_addr
|
||||
|
||||
/// IPv4 address type.
|
||||
///
|
||||
/// The corresponding C type is `in_addr_t`.
|
||||
public typealias InAddrT = in_addr_t
|
||||
|
||||
/// IPv6 address structure.
|
||||
///
|
||||
/// The corresponding C type is `in6_addr`.
|
||||
public typealias In6Addr = in6_addr
|
||||
|
||||
/// Port number type.
|
||||
///
|
||||
/// The corresponding C type is `in_port_t`.
|
||||
public typealias InPort = in_port_t
|
||||
|
||||
/// IPv6 socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr_in6`.
|
||||
public typealias SockAddrIn6 = sockaddr_in6
|
||||
|
||||
/// Unix domain socket address structure.
|
||||
///
|
||||
/// The corresponding C type is `sockaddr_un`.
|
||||
public typealias SockAddrUn = sockaddr_un
|
||||
|
||||
/// I/O vector structure for scatter/gather I/O.
|
||||
///
|
||||
/// The corresponding C type is `iovec`.
|
||||
public typealias IOVec = iovec
|
||||
|
||||
/// Message header structure for sendmsg/recvmsg.
|
||||
///
|
||||
/// The corresponding C type is `msghdr`.
|
||||
public typealias MsgHdr = msghdr
|
||||
|
||||
/// Control message header structure.
|
||||
///
|
||||
/// The corresponding C type is `cmsghdr`.
|
||||
public typealias CMsgHdr = cmsghdr
|
||||
|
||||
/// Address info structure for getaddrinfo.
|
||||
///
|
||||
/// The corresponding C type is `addrinfo`.
|
||||
public typealias AddrInfo = addrinfo
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Internal wrappers and typedefs for socket operations
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
// MARK: - errno access
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
internal var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Glibc)
|
||||
internal var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Musl)
|
||||
internal var system_errno: CInt {
|
||||
get { Musl.errno }
|
||||
set { Musl.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Android)
|
||||
internal var system_errno: CInt {
|
||||
get { Android.errno }
|
||||
set { Android.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - C stdlib functions
|
||||
|
||||
@usableFromInline
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
internal func system_memset(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
to byte: UInt8
|
||||
) {
|
||||
guard buffer.count > 0 else { return }
|
||||
memset(buffer.baseAddress!, CInt(byte), buffer.count)
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Syscall mocking support for SystemSockets
|
||||
//
|
||||
// This mirrors the mocking infrastructure from SystemPackage for use in socket tests.
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
internal struct Trace {
|
||||
internal struct Entry {
|
||||
internal var name: String
|
||||
internal var arguments: [AnyHashable]
|
||||
|
||||
internal init(name: String, _ arguments: [AnyHashable]) {
|
||||
self.name = name
|
||||
self.arguments = arguments
|
||||
}
|
||||
}
|
||||
|
||||
private var entries: [Entry] = []
|
||||
private var firstEntry: Int = 0
|
||||
|
||||
internal var isEmpty: Bool { firstEntry >= entries.count }
|
||||
|
||||
internal mutating func dequeue() -> Entry? {
|
||||
guard !self.isEmpty else { return nil }
|
||||
defer { firstEntry += 1 }
|
||||
return entries[firstEntry]
|
||||
}
|
||||
|
||||
fileprivate mutating func add(_ e: Entry) {
|
||||
entries.append(e)
|
||||
}
|
||||
}
|
||||
|
||||
internal enum ForceErrno: Equatable {
|
||||
case none
|
||||
case always(errno: CInt)
|
||||
case counted(errno: CInt, count: Int)
|
||||
}
|
||||
|
||||
internal class MockingDriver {
|
||||
internal var trace = Trace()
|
||||
internal var forceErrno = ForceErrno.none
|
||||
}
|
||||
|
||||
// TLS support
|
||||
#if os(Windows)
|
||||
internal typealias _PlatformTLSKey = DWORD
|
||||
#else
|
||||
internal typealias _PlatformTLSKey = pthread_key_t
|
||||
#endif
|
||||
|
||||
private func makeTLSKey() -> _PlatformTLSKey {
|
||||
#if os(Windows)
|
||||
let raw: DWORD = FlsAlloc(nil)
|
||||
if raw == FLS_OUT_OF_INDEXES {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#else
|
||||
var raw = pthread_key_t()
|
||||
guard 0 == pthread_key_create(&raw, nil) else {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#endif
|
||||
}
|
||||
|
||||
private func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) {
|
||||
#if os(Windows)
|
||||
guard FlsSetValue(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
#else
|
||||
guard 0 == pthread_setspecific(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
|
||||
#if os(Windows)
|
||||
return FlsGetValue(key)
|
||||
#else
|
||||
return pthread_getspecific(key)
|
||||
#endif
|
||||
}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
|
||||
internal var currentMockingDriver: MockingDriver? {
|
||||
guard let rawPtr = getTLS(driverKey) else { return nil }
|
||||
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
internal static func withMockingEnabled(
|
||||
_ f: (MockingDriver) throws -> ()
|
||||
) rethrows {
|
||||
let priorMocking = currentMockingDriver
|
||||
let driver = MockingDriver()
|
||||
|
||||
defer {
|
||||
if let object = priorMocking {
|
||||
setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
|
||||
} else {
|
||||
setTLS(driverKey, nil)
|
||||
}
|
||||
_fixLifetime(driver)
|
||||
}
|
||||
|
||||
setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
|
||||
return try f(driver)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
private var contextualMockingEnabled: Bool {
|
||||
return currentMockingDriver != nil
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
internal static var enabled: Bool { mockingEnabled }
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
@inline(__always)
|
||||
internal var mockingEnabled: Bool {
|
||||
#if ENABLE_MOCKING
|
||||
return contextualMockingEnabled
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
private func originalSyscallName(_ function: String) -> String {
|
||||
precondition(function.starts(with: "system_"))
|
||||
return String(function.dropFirst("system_".count).prefix { $0 != "(" })
|
||||
}
|
||||
|
||||
private func mockImpl(
|
||||
name: String,
|
||||
_ args: [AnyHashable]
|
||||
) -> CInt {
|
||||
precondition(mockingEnabled)
|
||||
let origName = originalSyscallName(name)
|
||||
guard let driver = currentMockingDriver else {
|
||||
fatalError("Mocking requested from non-mocking context")
|
||||
}
|
||||
driver.trace.add(Trace.Entry(name: origName, args))
|
||||
|
||||
switch driver.forceErrno {
|
||||
case .none: break
|
||||
case .always(let e):
|
||||
system_errno = e
|
||||
return -1
|
||||
case .counted(let e, let count):
|
||||
assert(count >= 1)
|
||||
system_errno = e
|
||||
driver.forceErrno = count > 1 ? .counted(errno: e, count: count - 1) : .none
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
internal func _mock(
|
||||
name: String = #function, _ args: AnyHashable...
|
||||
) -> CInt {
|
||||
return mockImpl(name: name, args)
|
||||
}
|
||||
|
||||
internal func _mockInt(
|
||||
name: String = #function, _ args: AnyHashable...
|
||||
) -> Int {
|
||||
Int(mockImpl(name: name, args))
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// A copy-on-write fixed-size buffer of raw memory.
|
||||
internal struct _RawBuffer {
|
||||
internal var _storage: Storage?
|
||||
|
||||
internal init() {
|
||||
self._storage = nil
|
||||
}
|
||||
|
||||
internal init(minimumCapacity: Int) {
|
||||
if minimumCapacity > 0 {
|
||||
self._storage = Storage.create(minimumCapacity: minimumCapacity)
|
||||
} else {
|
||||
self._storage = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal var capacity: Int {
|
||||
_storage?.header ?? 0 // Note: not capacity!
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique() {
|
||||
guard _storage != nil else { return }
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique {
|
||||
_storage = _copy(capacity: capacity)
|
||||
}
|
||||
}
|
||||
|
||||
internal func _grow(desired: Int) -> Int {
|
||||
let next = Int(1.75 * Double(self.capacity))
|
||||
return Swift.max(next, desired)
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique(capacity: Int) {
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique || self.capacity < capacity {
|
||||
_storage = _copy(capacity: _grow(desired: capacity))
|
||||
}
|
||||
}
|
||||
|
||||
internal func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let storage = _storage else {
|
||||
return try body(UnsafeRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
return try storage.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func withUnsafeMutableBytes<R>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard _storage != nil else {
|
||||
return try body(UnsafeMutableRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
ensureUnique()
|
||||
return try _storage!.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeMutableRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal class Storage: ManagedBuffer<Int, UInt8> {
|
||||
internal static func create(minimumCapacity: Int) -> Storage {
|
||||
Storage.create(
|
||||
minimumCapacity: minimumCapacity,
|
||||
makingHeaderWith: { $0.capacity }
|
||||
) as! Storage
|
||||
}
|
||||
}
|
||||
|
||||
internal func _copy(capacity: Int) -> Storage {
|
||||
let copy = Storage.create(minimumCapacity: capacity)
|
||||
copy.withUnsafeMutablePointers { dstlen, dst in
|
||||
self.withUnsafeBytes { src in
|
||||
guard src.count > 0 else { return }
|
||||
assert(src.count <= dstlen.pointee)
|
||||
UnsafeMutableRawPointer(dst)
|
||||
.copyMemory(
|
||||
from: src.baseAddress!,
|
||||
byteCount: Swift.min(src.count, dstlen.pointee))
|
||||
}
|
||||
}
|
||||
return copy
|
||||
}
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// System call wrappers for socket operations
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
// MARK: - Socket creation and management
|
||||
|
||||
internal func system_socket(_ domain: CInt, _ type: CInt, _ protocol: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(domain, type, `protocol`) }
|
||||
#endif
|
||||
return socket(domain, type, `protocol`)
|
||||
}
|
||||
|
||||
internal func system_shutdown(_ socket: CInt, _ how: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, how) }
|
||||
#endif
|
||||
return shutdown(socket, how)
|
||||
}
|
||||
|
||||
internal func system_close(_ fd: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
#endif
|
||||
return close(fd)
|
||||
}
|
||||
|
||||
// MARK: - Connection operations
|
||||
|
||||
internal func system_bind(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafePointer<sockaddr>?,
|
||||
_ len: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return bind(socket, addr, len)
|
||||
}
|
||||
|
||||
internal func system_listen(_ socket: CInt, _ backlog: CInt) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, backlog) }
|
||||
#endif
|
||||
return listen(socket, backlog)
|
||||
}
|
||||
|
||||
internal func system_accept(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafeMutablePointer<sockaddr>?,
|
||||
_ len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return accept(socket, addr, len)
|
||||
}
|
||||
|
||||
internal func system_connect(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafePointer<sockaddr>?,
|
||||
_ len: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return connect(socket, addr, len)
|
||||
}
|
||||
|
||||
// MARK: - Data transfer
|
||||
|
||||
internal func system_send(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeRawPointer?,
|
||||
_ len: Int,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, buffer, len, flags) }
|
||||
#endif
|
||||
return send(socket, buffer, len, flags)
|
||||
}
|
||||
|
||||
internal func system_recv(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeMutableRawPointer?,
|
||||
_ len: Int,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, buffer, len, flags) }
|
||||
#endif
|
||||
return recv(socket, buffer, len, flags)
|
||||
}
|
||||
|
||||
internal func system_sendto(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeRawPointer?,
|
||||
_ length: Int,
|
||||
_ flags: CInt,
|
||||
_ dest_addr: UnsafePointer<sockaddr>?,
|
||||
_ dest_len: socklen_t
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mockInt(socket, buffer, length, flags, dest_addr, dest_len)
|
||||
}
|
||||
#endif
|
||||
return sendto(socket, buffer, length, flags, dest_addr, dest_len)
|
||||
}
|
||||
|
||||
internal func system_recvfrom(
|
||||
_ socket: CInt,
|
||||
_ buffer: UnsafeMutableRawPointer?,
|
||||
_ length: Int,
|
||||
_ flags: CInt,
|
||||
_ address: UnsafeMutablePointer<sockaddr>?,
|
||||
_ address_len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mockInt(socket, buffer, length, flags, address, address_len)
|
||||
}
|
||||
#endif
|
||||
return recvfrom(socket, buffer, length, flags, address, address_len)
|
||||
}
|
||||
|
||||
internal func system_sendmsg(
|
||||
_ socket: CInt,
|
||||
_ message: UnsafePointer<msghdr>?,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, message, flags) }
|
||||
#endif
|
||||
return sendmsg(socket, message, flags)
|
||||
}
|
||||
|
||||
internal func system_recvmsg(
|
||||
_ socket: CInt,
|
||||
_ message: UnsafeMutablePointer<msghdr>?,
|
||||
_ flags: CInt
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(socket, message, flags) }
|
||||
#endif
|
||||
return recvmsg(socket, message, flags)
|
||||
}
|
||||
|
||||
// MARK: - Socket options
|
||||
|
||||
internal func system_getsockopt(
|
||||
_ socket: CInt,
|
||||
_ level: CInt,
|
||||
_ option: CInt,
|
||||
_ value: UnsafeMutableRawPointer?,
|
||||
_ length: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, level, option, value, length) }
|
||||
#endif
|
||||
return getsockopt(socket, level, option, value, length)
|
||||
}
|
||||
|
||||
internal func system_setsockopt(
|
||||
_ socket: CInt,
|
||||
_ level: CInt,
|
||||
_ option: CInt,
|
||||
_ value: UnsafeRawPointer?,
|
||||
_ length: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, level, option, value, length) }
|
||||
#endif
|
||||
return setsockopt(socket, level, option, value, length)
|
||||
}
|
||||
|
||||
internal func system_getsockname(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafeMutablePointer<sockaddr>?,
|
||||
_ len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return getsockname(socket, addr, len)
|
||||
}
|
||||
|
||||
internal func system_getpeername(
|
||||
_ socket: CInt,
|
||||
_ addr: UnsafeMutablePointer<sockaddr>?,
|
||||
_ len: UnsafeMutablePointer<socklen_t>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(socket, addr, len) }
|
||||
#endif
|
||||
return getpeername(socket, addr, len)
|
||||
}
|
||||
|
||||
// MARK: - Address conversion
|
||||
|
||||
@usableFromInline
|
||||
internal func system_inet_ntop(
|
||||
_ af: CInt,
|
||||
_ src: UnsafeRawPointer,
|
||||
_ dst: UnsafeMutablePointer<CChar>,
|
||||
_ size: socklen_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(af, src, dst, size) }
|
||||
#endif
|
||||
let res = inet_ntop(af, src, dst, size)
|
||||
if Int(bitPattern: res) == 0 { return -1 }
|
||||
return 0
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func system_inet_pton(
|
||||
_ af: CInt,
|
||||
_ src: UnsafePointer<CChar>,
|
||||
_ dst: UnsafeMutableRawPointer
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(af, src, dst) }
|
||||
#endif
|
||||
return inet_pton(af, src, dst)
|
||||
}
|
||||
|
||||
// MARK: - Name resolution
|
||||
|
||||
internal func system_getaddrinfo(
|
||||
_ hostname: UnsafePointer<CChar>?,
|
||||
_ servname: UnsafePointer<CChar>?,
|
||||
_ hints: UnsafePointer<addrinfo>?,
|
||||
_ res: UnsafeMutablePointer<UnsafeMutablePointer<addrinfo>?>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(
|
||||
hostname.map { String(cString: $0) },
|
||||
servname.map { String(cString: $0) },
|
||||
hints,
|
||||
res
|
||||
)
|
||||
}
|
||||
#endif
|
||||
return getaddrinfo(hostname, servname, hints, res)
|
||||
}
|
||||
|
||||
internal func system_getnameinfo(
|
||||
_ sa: UnsafePointer<sockaddr>?,
|
||||
_ salen: socklen_t,
|
||||
_ host: UnsafeMutablePointer<CChar>?,
|
||||
_ hostlen: socklen_t,
|
||||
_ serv: UnsafeMutablePointer<CChar>?,
|
||||
_ servlen: socklen_t,
|
||||
_ flags: CInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(sa, salen, host, hostlen, serv, servlen, flags)
|
||||
}
|
||||
#endif
|
||||
return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
|
||||
}
|
||||
|
||||
internal func system_freeaddrinfo(
|
||||
_ addrinfo: UnsafeMutablePointer<addrinfo>?
|
||||
) {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
_ = _mock(addrinfo)
|
||||
return
|
||||
}
|
||||
#endif
|
||||
freeaddrinfo(addrinfo)
|
||||
}
|
||||
|
||||
internal func system_gai_strerror(_ error: CInt) -> UnsafePointer<CChar> {
|
||||
gai_strerror(error)
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
extension FixedWidthInteger {
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
internal var _networkOrder: Self {
|
||||
bigEndian
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
internal init(_networkOrder value: Self) {
|
||||
self.init(bigEndian: value)
|
||||
}
|
||||
}
|
||||
@@ -1,297 +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 compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
// MARK: - Socket requests
|
||||
|
||||
@available(System 199, *)
|
||||
extension IORing.Request {
|
||||
/// Creates a socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the file
|
||||
/// descriptor of the new socket. Wrap it with
|
||||
/// `SocketDescriptor(rawValue:)`. The caller owns the socket and has to
|
||||
/// close it.
|
||||
///
|
||||
/// The corresponding C function is `socket`, and the operation is
|
||||
/// `IORING_OP_SOCKET`. It requires Linux 5.19 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - domain: The communication domain of the socket.
|
||||
/// - type: The type of the socket.
|
||||
/// - protocol: The protocol of the socket.
|
||||
/// - flags: Flags for the new socket.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that creates the socket.
|
||||
public static func socket(
|
||||
_ domain: SocketDescriptor.Domain,
|
||||
_ type: SocketDescriptor.ConnectionType,
|
||||
protocol: SocketDescriptor.ProtocolID = .default,
|
||||
flags: SocketDescriptor.SocketFlags = [],
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._socket(
|
||||
domain: domain.rawValue,
|
||||
type: type.rawValue | flags.rawValue,
|
||||
protocol: `protocol`.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Connects a socket to an address.
|
||||
///
|
||||
/// The address is copied when the request is created. The kernel copies it
|
||||
/// again when the request is submitted, so `address` doesn't need to stay
|
||||
/// alive.
|
||||
///
|
||||
/// The corresponding C function is `connect`, and the operation is
|
||||
/// `IORING_OP_CONNECT`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to connect.
|
||||
/// - address: The address to connect to.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that connects the socket.
|
||||
public static func connect(
|
||||
_ socket: SocketDescriptor,
|
||||
to address: SocketAddress,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
address.withUnsafePointer { address, length in
|
||||
._connect(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
to: address,
|
||||
length: length,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Binds a socket to an address.
|
||||
///
|
||||
/// The address is copied when the request is created. The kernel copies it
|
||||
/// again when the request is submitted, so `address` doesn't need to stay
|
||||
/// alive.
|
||||
///
|
||||
/// The corresponding C function is `bind`, and the operation is
|
||||
/// `IORING_OP_BIND`. It requires Linux 6.11 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to bind.
|
||||
/// - address: The address to bind to.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that binds the socket.
|
||||
public static func bind(
|
||||
_ socket: SocketDescriptor,
|
||||
to address: SocketAddress,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
address.withUnsafePointer { address, length in
|
||||
._bind(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
to: address,
|
||||
length: length,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts listening for connections on a socket.
|
||||
///
|
||||
/// The corresponding C function is `listen`, and the operation is
|
||||
/// `IORING_OP_LISTEN`. It requires Linux 6.11 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to listen on.
|
||||
/// - backlog: The maximum number of pending connections.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that starts listening.
|
||||
public static func listen(
|
||||
_ socket: SocketDescriptor,
|
||||
backlog: Int,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._listen(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
backlog: UInt32(clamping: backlog),
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Accepts a connection on a listening socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the file
|
||||
/// descriptor of the accepted socket. Wrap it with
|
||||
/// `SocketDescriptor(rawValue:)`. The caller owns the socket and has to
|
||||
/// close it.
|
||||
///
|
||||
/// The corresponding C function is `accept4`, and the operation is
|
||||
/// `IORING_OP_ACCEPT`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The listening socket.
|
||||
/// - flags: Flags for the accepted socket.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that accepts a connection.
|
||||
public static func accept(
|
||||
_ socket: SocketDescriptor,
|
||||
flags: SocketDescriptor.SocketFlags = [],
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._accept(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
peerAddress: nil,
|
||||
peerAddressLength: nil,
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Accepts a connection on a listening socket and writes the peer's
|
||||
/// address into the given storage.
|
||||
///
|
||||
/// Before submitting the request, set the value that `peerAddressLength`
|
||||
/// points to to the size of the storage that `peerAddress` points to. When
|
||||
/// the request completes, the kernel has written the peer's address and its
|
||||
/// length there.
|
||||
///
|
||||
/// - Important: The kernel writes to `peerAddress` and `peerAddressLength`
|
||||
/// when the request completes, so both have to stay valid until the
|
||||
/// completion has been consumed.
|
||||
///
|
||||
/// The corresponding C function is `accept4`, and the operation is
|
||||
/// `IORING_OP_ACCEPT`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The listening socket.
|
||||
/// - peerAddress: The storage for the peer's address.
|
||||
/// - peerAddressLength: The size of the storage, replaced with the length
|
||||
/// of the peer's address.
|
||||
/// - flags: Flags for the accepted socket.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that accepts a connection.
|
||||
public static func accept(
|
||||
_ socket: SocketDescriptor,
|
||||
peerAddress: UnsafeMutablePointer<CInterop.SockAddr>,
|
||||
peerAddressLength: UnsafeMutablePointer<CInterop.SockLen>,
|
||||
flags: SocketDescriptor.SocketFlags = [],
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._accept(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
peerAddress: peerAddress,
|
||||
peerAddressLength: peerAddressLength,
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Sends bytes on a connected socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the number
|
||||
/// of bytes sent, which can be less than the size of `buffer`.
|
||||
///
|
||||
/// Unlike a write request, a send request doesn't raise `SIGPIPE` when the
|
||||
/// connection is closed for writing. io_uring sets `MSG_NOSIGNAL` for it,
|
||||
/// so the completion fails with ``Errno/brokenPipe`` instead.
|
||||
///
|
||||
/// - Important: The kernel reads from `buffer` until the request completes,
|
||||
/// so it has to stay valid until the completion has been consumed.
|
||||
///
|
||||
/// The corresponding C function is `send`, and the operation is
|
||||
/// `IORING_OP_SEND`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The bytes to send.
|
||||
/// - socket: The socket to send on.
|
||||
/// - flags: Flags for sending.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that sends the bytes.
|
||||
public static func send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to socket: SocketDescriptor,
|
||||
flags: SocketDescriptor.MessageFlags = .none,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._send(
|
||||
buffer,
|
||||
to: FileDescriptor(rawValue: socket.rawValue),
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Receives bytes from a connected socket.
|
||||
///
|
||||
/// On success, the completion's ``IORing/Completion/result`` is the number
|
||||
/// of bytes received. Zero means that the peer closed its side of the
|
||||
/// connection.
|
||||
///
|
||||
/// - Important: The kernel writes into `buffer` until the request completes,
|
||||
/// so it has to stay valid until the completion has been consumed.
|
||||
///
|
||||
/// The corresponding C function is `recv`, and the operation is
|
||||
/// `IORING_OP_RECV`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to receive from.
|
||||
/// - buffer: The buffer to receive into.
|
||||
/// - flags: Flags for receiving.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that receives bytes.
|
||||
public static func receive(
|
||||
_ socket: SocketDescriptor,
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: SocketDescriptor.MessageFlags = .none,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._receive(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
into: buffer,
|
||||
flags: flags.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Shuts down one or both directions of a socket.
|
||||
///
|
||||
/// The corresponding C function is `shutdown`, and the operation is
|
||||
/// `IORING_OP_SHUTDOWN`. It requires Linux 5.11 or later.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - socket: The socket to shut down.
|
||||
/// - how: The directions to shut down.
|
||||
/// - context: A value passed through to the completion.
|
||||
/// - Returns: A request that shuts down the socket.
|
||||
public static func shutdown(
|
||||
_ socket: SocketDescriptor,
|
||||
_ how: SocketDescriptor.ShutdownKind,
|
||||
context: UInt64 = 0
|
||||
) -> IORing.Request {
|
||||
._shutdown(
|
||||
FileDescriptor(rawValue: socket.rawValue),
|
||||
how: how.rawValue,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -1,110 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
@frozen
|
||||
/// The address family identifier
|
||||
public struct Family: RawRepresentable, Hashable {
|
||||
public let rawValue: CInterop.SAFamily
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.SAFamily) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ rawValue: CInterop.SAFamily) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Unspecified address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_UNSPEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var unspecified: Family { Family(CInterop.SAFamily(AF_UNSPEC)) }
|
||||
|
||||
/// Local address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_LOCAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var local: Family { Family(CInterop.SAFamily(AF_LOCAL)) }
|
||||
|
||||
/// UNIX address family. (Renamed `local`.)
|
||||
///
|
||||
/// The corresponding C constant is `AF_UNIX`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "local")
|
||||
public static var unix: Family { Family(CInterop.SAFamily(AF_UNIX)) }
|
||||
|
||||
/// IPv4 address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_INET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: Family { Family(CInterop.SAFamily(AF_INET)) }
|
||||
|
||||
/// Internal routing address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_ROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var routing: Family { Family(CInterop.SAFamily(AF_ROUTE)) }
|
||||
|
||||
/// IPv6 address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_INET6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: Family { Family(CInterop.SAFamily(AF_INET6)) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// System address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_SYSTEM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var system: Family { Family(CInterop.SAFamily(AF_SYSTEM)) }
|
||||
|
||||
/// Raw network device address family.
|
||||
///
|
||||
/// The corresponding C constant is `AF_NDRV`
|
||||
@_alwaysEmitIntoClient
|
||||
public static var networkDevice: Family { Family(CInterop.SAFamily(AF_NDRV)) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress.Family: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .unspecified: return "unspecified"
|
||||
case .local: return "local"
|
||||
case .ipv4: return "ipv4"
|
||||
case .routing: return "routing"
|
||||
case .ipv6: return "ipv6"
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
case .system: return "system"
|
||||
case .networkDevice: return "networkDevice"
|
||||
#endif
|
||||
default:
|
||||
return rawValue.description
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// An IPv4 socket address.
|
||||
///
|
||||
/// An IPv4 address consists of a 32-bit IP address and a 16-bit port number.
|
||||
@frozen
|
||||
@available(System 199, *)
|
||||
public struct IPv4Address: Sendable, Equatable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_in
|
||||
|
||||
/// Creates an IPv4 address from a raw sockaddr_in.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ sockaddr: sockaddr_in) {
|
||||
_storage = sockaddr
|
||||
}
|
||||
|
||||
/// Creates an IPv4 address from an address string and port.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - address: The IPv4 address string (e.g., "127.0.0.1").
|
||||
/// - port: The port number in host byte order.
|
||||
/// - Returns: `nil` if the address string is invalid.
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(_ address: String, port: UInt16) {
|
||||
var addr = sockaddr_in()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
#endif
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_port = port.bigEndian
|
||||
|
||||
let result = address.withCString { cString in
|
||||
system_inet_pton(AF_INET, cString, &addr.sin_addr)
|
||||
}
|
||||
|
||||
guard result == 1 else { return nil }
|
||||
_storage = addr
|
||||
}
|
||||
|
||||
/// Creates an IPv4 address representing any address (0.0.0.0).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func any(port: UInt16) -> IPv4Address {
|
||||
var addr = sockaddr_in()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
#endif
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_port = port.bigEndian
|
||||
addr.sin_addr.s_addr = INADDR_ANY.bigEndian
|
||||
return IPv4Address(addr)
|
||||
}
|
||||
|
||||
/// Creates an IPv4 address representing the loopback address (127.0.0.1).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func loopback(port: UInt16) -> IPv4Address {
|
||||
var addr = sockaddr_in()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
#endif
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_port = port.bigEndian
|
||||
addr.sin_addr.s_addr = INADDR_LOOPBACK.bigEndian
|
||||
return IPv4Address(addr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv4Address {
|
||||
/// The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public var port: UInt16 {
|
||||
UInt16(bigEndian: _storage.sin_port)
|
||||
}
|
||||
|
||||
/// The IP address as a string.
|
||||
public var addressString: String {
|
||||
var buffer = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
|
||||
var addr = _storage.sin_addr
|
||||
_ = Swift.withUnsafePointer(to: &addr) { ptr in
|
||||
system_inet_ntop(AF_INET, ptr, &buffer, socklen_t(buffer.count))
|
||||
}
|
||||
return String(cString: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv4Address {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, CInterop.SockLen(MemoryLayout<sockaddr_in>.size))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv4Address: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"\(addressString):\(port)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringLiteral
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv4Address: ExpressibleByStringLiteral {
|
||||
/// Creates an IPv4 address from a string literal.
|
||||
///
|
||||
/// The format is "address:port" (e.g., "127.0.0.1:8080").
|
||||
/// If no port is specified, port 0 is used.
|
||||
public init(stringLiteral value: String) {
|
||||
let parts = value.split(separator: ":", maxSplits: 1)
|
||||
let address = String(parts[0])
|
||||
let port: UInt16 = parts.count > 1 ? UInt16(parts[1]) ?? 0 : 0
|
||||
|
||||
guard let addr = IPv4Address(address, port: port) else {
|
||||
fatalError("Invalid IPv4 address literal: \(value)")
|
||||
}
|
||||
self = addr
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv4Address {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: IPv4Address, rhs: IPv4Address) -> Bool {
|
||||
lhs._storage.sin_family == rhs._storage.sin_family &&
|
||||
lhs._storage.sin_port == rhs._storage.sin_port &&
|
||||
lhs._storage.sin_addr.s_addr == rhs._storage.sin_addr.s_addr
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_storage.sin_family)
|
||||
hasher.combine(_storage.sin_port)
|
||||
hasher.combine(_storage.sin_addr.s_addr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from an IPv4 address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(ipv4: IPv4Address) {
|
||||
self.init()
|
||||
ipv4.withUnsafePointer { addr, len in
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
|
||||
}
|
||||
_length = len
|
||||
}
|
||||
}
|
||||
|
||||
/// The address as an IPv4 address, if applicable.
|
||||
@_alwaysEmitIntoClient
|
||||
public var ipv4: IPv4Address? {
|
||||
guard family == .ipv4 else { return nil }
|
||||
return Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
buffer.baseAddress!.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { ptr in
|
||||
IPv4Address(ptr.pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// An IPv6 socket address.
|
||||
///
|
||||
/// An IPv6 address consists of a 128-bit IP address, a 16-bit port number,
|
||||
/// a flow label, and a scope ID.
|
||||
@frozen
|
||||
@available(System 199, *)
|
||||
public struct IPv6Address: Sendable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_in6
|
||||
|
||||
/// Creates an IPv6 address from a raw sockaddr_in6.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ sockaddr: sockaddr_in6) {
|
||||
_storage = sockaddr
|
||||
}
|
||||
|
||||
/// Creates an IPv6 address from an address string and port.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - address: The IPv6 address string (e.g., "::1" or "2001:db8::1").
|
||||
/// - port: The port number in host byte order.
|
||||
/// - Returns: `nil` if the address string is invalid.
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(_ address: String, port: UInt16) {
|
||||
var addr = sockaddr_in6()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
|
||||
#endif
|
||||
addr.sin6_family = sa_family_t(AF_INET6)
|
||||
addr.sin6_port = port.bigEndian
|
||||
|
||||
let result = address.withCString { cString in
|
||||
system_inet_pton(AF_INET6, cString, &addr.sin6_addr)
|
||||
}
|
||||
|
||||
guard result == 1 else { return nil }
|
||||
_storage = addr
|
||||
}
|
||||
|
||||
/// Creates an IPv6 address representing any address (::).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func any(port: UInt16) -> IPv6Address {
|
||||
var addr = sockaddr_in6()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
|
||||
#endif
|
||||
addr.sin6_family = sa_family_t(AF_INET6)
|
||||
addr.sin6_port = port.bigEndian
|
||||
addr.sin6_addr = in6addr_any
|
||||
return IPv6Address(addr)
|
||||
}
|
||||
|
||||
/// Creates an IPv6 address representing the loopback address (::1).
|
||||
///
|
||||
/// - Parameter port: The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func loopback(port: UInt16) -> IPv6Address {
|
||||
var addr = sockaddr_in6()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
|
||||
#endif
|
||||
addr.sin6_family = sa_family_t(AF_INET6)
|
||||
addr.sin6_port = port.bigEndian
|
||||
addr.sin6_addr = in6addr_loopback
|
||||
return IPv6Address(addr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv6Address {
|
||||
/// The port number in host byte order.
|
||||
@_alwaysEmitIntoClient
|
||||
public var port: UInt16 {
|
||||
UInt16(bigEndian: _storage.sin6_port)
|
||||
}
|
||||
|
||||
/// The flow label.
|
||||
@_alwaysEmitIntoClient
|
||||
public var flowLabel: UInt32 {
|
||||
_storage.sin6_flowinfo
|
||||
}
|
||||
|
||||
/// The scope ID.
|
||||
@_alwaysEmitIntoClient
|
||||
public var scopeID: UInt32 {
|
||||
_storage.sin6_scope_id
|
||||
}
|
||||
|
||||
/// The IP address as a string.
|
||||
public var addressString: String {
|
||||
var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
|
||||
var addr = _storage.sin6_addr
|
||||
_ = Swift.withUnsafePointer(to: &addr) { ptr in
|
||||
system_inet_ntop(AF_INET6, ptr, &buffer, socklen_t(buffer.count))
|
||||
}
|
||||
return String(cString: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv6Address {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, CInterop.SockLen(MemoryLayout<sockaddr_in6>.size))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv6Address: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"[\(addressString)]:\(port)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringLiteral
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv6Address: ExpressibleByStringLiteral {
|
||||
/// Creates an IPv6 address from a string literal.
|
||||
///
|
||||
/// The format is "[address]:port" (e.g., "[::1]:8080") or "address"
|
||||
/// for port 0.
|
||||
public init(stringLiteral value: String) {
|
||||
var address = value
|
||||
var port: UInt16 = 0
|
||||
|
||||
// Handle [address]:port format
|
||||
if value.hasPrefix("[") {
|
||||
if let closeBracket = value.lastIndex(of: "]") {
|
||||
address = String(value[value.index(after: value.startIndex)..<closeBracket])
|
||||
let afterBracket = value.index(after: closeBracket)
|
||||
if afterBracket < value.endIndex && value[afterBracket] == ":" {
|
||||
let portStart = value.index(after: afterBracket)
|
||||
if let p = UInt16(value[portStart...]) {
|
||||
port = p
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
guard let addr = IPv6Address(address, port: port) else {
|
||||
fatalError("Invalid IPv6 address literal: \(value)")
|
||||
}
|
||||
self = addr
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 199, *)
|
||||
extension IPv6Address {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: IPv6Address, rhs: IPv6Address) -> Bool {
|
||||
Swift.withUnsafeBytes(of: lhs._storage) { lhsBytes in
|
||||
Swift.withUnsafeBytes(of: rhs._storage) { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
Swift.withUnsafeBytes(of: _storage) { bytes in
|
||||
hasher.combine(bytes: bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from an IPv6 address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(ipv6: IPv6Address) {
|
||||
self.init()
|
||||
ipv6.withUnsafePointer { addr, len in
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
|
||||
}
|
||||
_length = len
|
||||
}
|
||||
}
|
||||
|
||||
/// The address as an IPv6 address, if applicable.
|
||||
@_alwaysEmitIntoClient
|
||||
public var ipv6: IPv6Address? {
|
||||
guard family == .ipv6 else { return nil }
|
||||
return Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
buffer.baseAddress!.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { ptr in
|
||||
IPv6Address(ptr.pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Address Resolution Error
|
||||
|
||||
/// An error returned by address resolution functions.
|
||||
@frozen
|
||||
@available(System 199, *)
|
||||
public struct AddressResolutionError: Error, Hashable, Sendable {
|
||||
/// The error code returned by getaddrinfo or getnameinfo.
|
||||
public let code: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(code: CInt) {
|
||||
self.code = code
|
||||
}
|
||||
|
||||
/// A human-readable error message.
|
||||
public var message: String {
|
||||
String(cString: system_gai_strerror(code))
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
extension AddressResolutionError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"AddressResolutionError(\(code)): \(message)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Resolution Hints
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Hints for address resolution.
|
||||
public struct ResolutionHints: Sendable {
|
||||
/// The protocol family to search for.
|
||||
public var family: SocketDescriptor.Domain?
|
||||
|
||||
/// The socket type to search for.
|
||||
public var socketType: SocketDescriptor.ConnectionType?
|
||||
|
||||
/// The protocol to search for.
|
||||
public var `protocol`: SocketDescriptor.ProtocolID?
|
||||
|
||||
/// Resolution flags.
|
||||
public var flags: ResolutionFlags
|
||||
|
||||
/// Creates resolution hints with the given parameters.
|
||||
public init(
|
||||
family: SocketDescriptor.Domain? = nil,
|
||||
socketType: SocketDescriptor.ConnectionType? = nil,
|
||||
protocol: SocketDescriptor.ProtocolID? = nil,
|
||||
flags: ResolutionFlags = []
|
||||
) {
|
||||
self.family = family
|
||||
self.socketType = socketType
|
||||
self.protocol = `protocol`
|
||||
self.flags = flags
|
||||
}
|
||||
}
|
||||
|
||||
/// Flags for address resolution.
|
||||
@frozen
|
||||
public struct ResolutionFlags: OptionSet, Sendable {
|
||||
public var rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Use passive socket for binding.
|
||||
///
|
||||
/// The corresponding C constant is `AI_PASSIVE`.
|
||||
public static var passive: ResolutionFlags { ResolutionFlags(rawValue: AI_PASSIVE) }
|
||||
|
||||
/// Return canonical name.
|
||||
///
|
||||
/// The corresponding C constant is `AI_CANONNAME`.
|
||||
public static var canonicalName: ResolutionFlags { ResolutionFlags(rawValue: AI_CANONNAME) }
|
||||
|
||||
/// Address must be numeric.
|
||||
///
|
||||
/// The corresponding C constant is `AI_NUMERICHOST`.
|
||||
public static var numericHost: ResolutionFlags { ResolutionFlags(rawValue: AI_NUMERICHOST) }
|
||||
|
||||
/// Service must be numeric.
|
||||
///
|
||||
/// The corresponding C constant is `AI_NUMERICSERV`.
|
||||
public static var numericService: ResolutionFlags { ResolutionFlags(rawValue: AI_NUMERICSERV) }
|
||||
|
||||
/// Return IPv4-mapped IPv6 addresses.
|
||||
///
|
||||
/// The corresponding C constant is `AI_V4MAPPED`.
|
||||
public static var v4Mapped: ResolutionFlags { ResolutionFlags(rawValue: AI_V4MAPPED) }
|
||||
|
||||
/// Return both IPv4 and IPv6 addresses.
|
||||
///
|
||||
/// The corresponding C constant is `AI_ALL`.
|
||||
public static var all: ResolutionFlags { ResolutionFlags(rawValue: AI_ALL) }
|
||||
|
||||
/// Return addresses only if configured.
|
||||
///
|
||||
/// The corresponding C constant is `AI_ADDRCONFIG`.
|
||||
public static var addressConfigured: ResolutionFlags { ResolutionFlags(rawValue: AI_ADDRCONFIG) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Resolution Result
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// A result from address resolution.
|
||||
public struct ResolvedAddress: Sendable {
|
||||
/// The socket domain.
|
||||
public let family: SocketDescriptor.Domain
|
||||
|
||||
/// The socket type.
|
||||
public let socketType: SocketDescriptor.ConnectionType
|
||||
|
||||
/// The socket protocol.
|
||||
public let `protocol`: SocketDescriptor.ProtocolID
|
||||
|
||||
/// The resolved socket address.
|
||||
public let address: SocketAddress
|
||||
|
||||
/// The canonical name, if requested and available.
|
||||
public let canonicalName: String?
|
||||
|
||||
internal init(
|
||||
family: SocketDescriptor.Domain,
|
||||
socketType: SocketDescriptor.ConnectionType,
|
||||
protocol: SocketDescriptor.ProtocolID,
|
||||
address: SocketAddress,
|
||||
canonicalName: String?
|
||||
) {
|
||||
self.family = family
|
||||
self.socketType = socketType
|
||||
self.protocol = `protocol`
|
||||
self.address = address
|
||||
self.canonicalName = canonicalName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Address Resolution
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Resolves a hostname and service to a list of socket addresses.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hostname: The hostname to resolve, or `nil` for the local host.
|
||||
/// - service: The service name or port number, or `nil`.
|
||||
/// - hints: Hints to narrow the search.
|
||||
/// - Returns: An array of resolved addresses.
|
||||
/// - Throws: `AddressResolutionError` if resolution fails.
|
||||
///
|
||||
/// The corresponding C function is `getaddrinfo`.
|
||||
public static func resolve(
|
||||
hostname: String? = nil,
|
||||
service: String? = nil,
|
||||
hints: ResolutionHints = ResolutionHints()
|
||||
) throws -> [ResolvedAddress] {
|
||||
var hintsStruct = addrinfo()
|
||||
hintsStruct.ai_flags = hints.flags.rawValue
|
||||
if let family = hints.family {
|
||||
hintsStruct.ai_family = family.rawValue
|
||||
}
|
||||
if let socketType = hints.socketType {
|
||||
hintsStruct.ai_socktype = socketType.rawValue
|
||||
}
|
||||
if let proto = hints.protocol {
|
||||
hintsStruct.ai_protocol = proto.rawValue
|
||||
}
|
||||
|
||||
var result: UnsafeMutablePointer<addrinfo>?
|
||||
|
||||
let errorCode: CInt = hostname._withOptionalCString { hostnamePtr in
|
||||
service._withOptionalCString { servicePtr in
|
||||
system_getaddrinfo(hostnamePtr, servicePtr, &hintsStruct, &result)
|
||||
}
|
||||
}
|
||||
|
||||
guard errorCode == 0 else {
|
||||
throw AddressResolutionError(code: errorCode)
|
||||
}
|
||||
|
||||
defer { system_freeaddrinfo(result) }
|
||||
|
||||
var addresses: [ResolvedAddress] = []
|
||||
var current = result
|
||||
|
||||
while let info = current {
|
||||
let family = SocketDescriptor.Domain(rawValue: info.pointee.ai_family)
|
||||
let socketType = SocketDescriptor.ConnectionType(rawValue: info.pointee.ai_socktype)
|
||||
let proto = SocketDescriptor.ProtocolID(rawValue: info.pointee.ai_protocol)
|
||||
|
||||
let address: SocketAddress
|
||||
if let addr = info.pointee.ai_addr {
|
||||
address = SocketAddress(
|
||||
address: addr,
|
||||
length: info.pointee.ai_addrlen
|
||||
)
|
||||
} else {
|
||||
address = SocketAddress()
|
||||
}
|
||||
|
||||
let canonicalName: String?
|
||||
if let name = info.pointee.ai_canonname {
|
||||
canonicalName = String(cString: name)
|
||||
} else {
|
||||
canonicalName = nil
|
||||
}
|
||||
|
||||
addresses.append(ResolvedAddress(
|
||||
family: family,
|
||||
socketType: socketType,
|
||||
protocol: proto,
|
||||
address: address,
|
||||
canonicalName: canonicalName
|
||||
))
|
||||
|
||||
current = info.pointee.ai_next
|
||||
}
|
||||
|
||||
return addresses
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Reverse Resolution
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Flags for reverse resolution.
|
||||
@frozen
|
||||
public struct ReverseResolutionFlags: OptionSet, Sendable {
|
||||
public var rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Return numeric host.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NUMERICHOST`.
|
||||
public static var numericHost: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NUMERICHOST) }
|
||||
|
||||
/// Return numeric service.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NUMERICSERV`.
|
||||
public static var numericService: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NUMERICSERV) }
|
||||
|
||||
/// Look up datagram service.
|
||||
///
|
||||
/// The corresponding C constant is `NI_DGRAM`.
|
||||
public static var datagram: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_DGRAM) }
|
||||
|
||||
/// Return only the hostname part of FQDN.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NOFQDN`.
|
||||
public static var noFullyQualified: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NOFQDN) }
|
||||
|
||||
/// Fail if name cannot be determined.
|
||||
///
|
||||
/// The corresponding C constant is `NI_NAMEREQD`.
|
||||
public static var nameRequired: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NAMEREQD) }
|
||||
}
|
||||
|
||||
/// A result from reverse resolution.
|
||||
public struct ReverseLookupResult: Sendable {
|
||||
/// The hostname.
|
||||
public let hostname: String?
|
||||
|
||||
/// The service name.
|
||||
public let service: String?
|
||||
}
|
||||
|
||||
/// Resolves this address to a hostname and service.
|
||||
///
|
||||
/// - Parameter flags: Flags controlling the resolution.
|
||||
/// - Returns: The hostname and service.
|
||||
/// - Throws: `AddressResolutionError` if resolution fails.
|
||||
///
|
||||
/// The corresponding C function is `getnameinfo`.
|
||||
public func reverseLookup(
|
||||
flags: ReverseResolutionFlags = []
|
||||
) throws -> ReverseLookupResult {
|
||||
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
var service = [CChar](repeating: 0, count: Int(NI_MAXSERV))
|
||||
|
||||
let errorCode = withUnsafePointer { addr, len in
|
||||
system_getnameinfo(
|
||||
addr,
|
||||
len,
|
||||
&hostname,
|
||||
socklen_t(hostname.count),
|
||||
&service,
|
||||
socklen_t(service.count),
|
||||
flags.rawValue
|
||||
)
|
||||
}
|
||||
|
||||
guard errorCode == 0 else {
|
||||
throw AddressResolutionError(code: errorCode)
|
||||
}
|
||||
|
||||
let hostnameStr = hostname[0] != 0 ? String(cString: hostname) : nil
|
||||
let serviceStr = service[0] != 0 ? String(cString: service) : nil
|
||||
|
||||
return ReverseLookupResult(hostname: hostnameStr, service: serviceStr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
extension Optional where Wrapped == String {
|
||||
func _withOptionalCString<R>(_ body: (UnsafePointer<CChar>?) throws -> R) rethrows -> R {
|
||||
switch self {
|
||||
case .none:
|
||||
return try body(nil)
|
||||
case .some(let string):
|
||||
return try string.withCString(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// A Unix domain socket address.
|
||||
///
|
||||
/// Unix domain socket addresses use a filesystem path to identify the socket.
|
||||
@frozen
|
||||
@available(System 199, *)
|
||||
public struct UnixAddress: Sendable, Equatable, Hashable {
|
||||
/// The underlying C structure.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_un
|
||||
|
||||
/// The length of the path (not including null terminator).
|
||||
@usableFromInline
|
||||
internal var _pathLength: Int
|
||||
|
||||
/// Creates a Unix address from a raw sockaddr_un.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ sockaddr: sockaddr_un) {
|
||||
_storage = sockaddr
|
||||
// Calculate path length from the stored data
|
||||
_pathLength = withUnsafeBytes(of: sockaddr.sun_path) { bytes in
|
||||
bytes.prefix(while: { $0 != 0 }).count
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a Unix address from a path string.
|
||||
///
|
||||
/// - Parameter path: The filesystem path for the socket.
|
||||
/// - Returns: `nil` if the path is too long.
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(_ path: String) {
|
||||
var addr = sockaddr_un()
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
|
||||
#endif
|
||||
addr.sun_family = sa_family_t(AF_UNIX)
|
||||
|
||||
let maxPathLength = MemoryLayout.size(ofValue: addr.sun_path) - 1 // Leave room for null
|
||||
|
||||
let copied = path.withCString { cString in
|
||||
let len = system_strlen(cString)
|
||||
guard len <= maxPathLength else { return -1 }
|
||||
|
||||
withUnsafeMutableBytes(of: &addr.sun_path) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: cString, count: len + 1))
|
||||
}
|
||||
return len
|
||||
}
|
||||
|
||||
guard copied >= 0 else { return nil }
|
||||
|
||||
_storage = addr
|
||||
_pathLength = copied
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 199, *)
|
||||
extension UnixAddress {
|
||||
/// The path as a string.
|
||||
public var path: String {
|
||||
withUnsafeBytes(of: _storage.sun_path) { bytes in
|
||||
let pathBytes = bytes.prefix(_pathLength)
|
||||
return pathBytes.withMemoryRebound(to: CChar.self) { chars in
|
||||
String(cString: chars.baseAddress!)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pointer Access
|
||||
|
||||
@available(System 199, *)
|
||||
extension UnixAddress {
|
||||
/// Calls the given closure with a pointer to the underlying sockaddr.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
// Length includes sun_family plus the path (including null terminator)
|
||||
let length = MemoryLayout<sa_family_t>.size + _pathLength + 1
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
let actualLength = MemoryLayout<UInt8>.size + length // Include sun_len
|
||||
#else
|
||||
let actualLength = length
|
||||
#endif
|
||||
return try body(sockaddr, CInterop.SockLen(actualLength))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 199, *)
|
||||
extension UnixAddress: CustomStringConvertible {
|
||||
public var description: String {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 199, *)
|
||||
extension UnixAddress {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: UnixAddress, rhs: UnixAddress) -> Bool {
|
||||
lhs._pathLength == rhs._pathLength &&
|
||||
Swift.withUnsafeBytes(of: lhs._storage.sun_path) { lhsBytes in
|
||||
Swift.withUnsafeBytes(of: rhs._storage.sun_path) { rhsBytes in
|
||||
lhsBytes.prefix(lhs._pathLength).elementsEqual(rhsBytes.prefix(rhs._pathLength))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_pathLength)
|
||||
Swift.withUnsafeBytes(of: _storage.sun_path) { bytes in
|
||||
hasher.combine(bytes: UnsafeRawBufferPointer(rebasing: bytes.prefix(_pathLength)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Integration
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Creates a socket address from a Unix address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(unix: UnixAddress) {
|
||||
self.init()
|
||||
unix.withUnsafePointer { addr, len in
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
|
||||
}
|
||||
_length = len
|
||||
}
|
||||
}
|
||||
|
||||
/// The address as a Unix address, if applicable.
|
||||
@_alwaysEmitIntoClient
|
||||
public var unix: UnixAddress? {
|
||||
guard family == .local else { return nil }
|
||||
return Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
buffer.baseAddress!.withMemoryRebound(to: sockaddr_un.self, capacity: 1) { ptr in
|
||||
UnixAddress(ptr.pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// An opaque type representing a socket address.
|
||||
///
|
||||
/// `SocketAddress` is a type-erased container that can hold any socket address,
|
||||
/// including IPv4, IPv6, and Unix domain addresses. It provides a unified
|
||||
/// interface for socket operations that work with different address families.
|
||||
///
|
||||
/// To create a socket address for a specific family, use one of the convenience
|
||||
/// initializers:
|
||||
///
|
||||
/// ```swift
|
||||
/// // IPv4 address
|
||||
/// let ipv4 = SocketAddress(ipv4: IPv4Address("127.0.0.1", port: 8080)!)
|
||||
///
|
||||
/// // IPv6 address
|
||||
/// let ipv6 = SocketAddress(ipv6: IPv6Address.loopback(port: 80))
|
||||
///
|
||||
/// // Unix domain socket
|
||||
/// let local = SocketAddress(unix: UnixAddress("/tmp/socket.sock")!)
|
||||
/// ```
|
||||
///
|
||||
/// `SocketAddress` uses `sockaddr_storage` internally, which is large enough
|
||||
/// to hold any socket address type.
|
||||
@frozen
|
||||
@available(System 199, *)
|
||||
public struct SocketAddress: Sendable {
|
||||
/// The underlying storage using sockaddr_storage.
|
||||
@usableFromInline
|
||||
internal var _storage: sockaddr_storage
|
||||
|
||||
/// The actual length of the address data.
|
||||
@usableFromInline
|
||||
internal var _length: CInterop.SockLen
|
||||
|
||||
/// Creates an empty socket address with unspecified family.
|
||||
@_alwaysEmitIntoClient
|
||||
public init() {
|
||||
_storage = sockaddr_storage()
|
||||
_length = 0
|
||||
}
|
||||
|
||||
/// Creates a socket address from raw bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - address: Pointer to the socket address.
|
||||
/// - length: The length of the address.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(
|
||||
address: UnsafePointer<CInterop.SockAddr>,
|
||||
length: CInterop.SockLen
|
||||
) {
|
||||
_storage = sockaddr_storage()
|
||||
_length = min(length, CInterop.SockLen(MemoryLayout<sockaddr_storage>.size))
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(start: address, count: Int(_length)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a socket address from a raw buffer.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_ buffer: UnsafeRawBufferPointer) {
|
||||
_storage = sockaddr_storage()
|
||||
_length = CInterop.SockLen(min(buffer.count, MemoryLayout<sockaddr_storage>.size))
|
||||
if buffer.count > 0 {
|
||||
withUnsafeMutableBytes(of: &_storage) { dest in
|
||||
dest.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer.prefix(Int(_length))))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// The address family of this socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
public var family: SocketDescriptor.Domain {
|
||||
Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
let sockaddr = buffer.baseAddress!.assumingMemoryBound(to: sockaddr.self)
|
||||
return SocketDescriptor.Domain(rawValue: CInt(sockaddr.pointee.sa_family))
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of this socket address in bytes.
|
||||
@_alwaysEmitIntoClient
|
||||
public var length: Int {
|
||||
Int(_length)
|
||||
}
|
||||
|
||||
/// Whether this address is empty (length is 0).
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool {
|
||||
_length == 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Accessing Raw Bytes
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress {
|
||||
/// Calls the given closure with a pointer to the underlying socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafePointer<R>(
|
||||
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafePointer(to: _storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, _length)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure with a mutable pointer to the underlying storage.
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func _withUnsafeMutablePointer<R>(
|
||||
_ body: (UnsafeMutablePointer<sockaddr>, inout CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
var len = CInterop.SockLen(MemoryLayout<sockaddr_storage>.size)
|
||||
let result = try Swift.withUnsafeMutablePointer(to: &_storage) { storage in
|
||||
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
|
||||
try body(sockaddr, &len)
|
||||
}
|
||||
}
|
||||
_length = len
|
||||
return result
|
||||
}
|
||||
|
||||
/// Accesses the raw bytes of the socket address.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try Swift.withUnsafeBytes(of: _storage) { buffer in
|
||||
try body(UnsafeRawBufferPointer(rebasing: buffer.prefix(Int(_length))))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets this address to an empty state.
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func clear() {
|
||||
_storage = sockaddr_storage()
|
||||
_length = 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func == (lhs: SocketAddress, rhs: SocketAddress) -> Bool {
|
||||
guard lhs._length == rhs._length else { return false }
|
||||
return lhs.withUnsafeBytes { lhsBytes in
|
||||
rhs.withUnsafeBytes { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_length)
|
||||
withUnsafeBytes { buffer in
|
||||
hasher.combine(bytes: buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketAddress: CustomStringConvertible {
|
||||
public var description: String {
|
||||
if isEmpty {
|
||||
return "SocketAddress(empty)"
|
||||
}
|
||||
|
||||
switch family {
|
||||
case .ipv4:
|
||||
if let ipv4 = self.ipv4 {
|
||||
return "SocketAddress(\(ipv4))"
|
||||
}
|
||||
case .ipv6:
|
||||
if let ipv6 = self.ipv6 {
|
||||
return "SocketAddress(\(ipv6))"
|
||||
}
|
||||
case .local:
|
||||
if let unix = self.unix {
|
||||
return "SocketAddress(\(unix))"
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
return "SocketAddress(family: \(family), length: \(_length))"
|
||||
}
|
||||
}
|
||||
@@ -1,507 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// Glibc imports the socket types as a C enum, every other platform imports
|
||||
// them as plain integers.
|
||||
#if canImport(Glibc)
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _socketType(_ type: __socket_type) -> CInt { CInt(type.rawValue) }
|
||||
#else
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _socketType(_ type: CInt) -> CInt { type }
|
||||
#endif
|
||||
|
||||
/// A socket descriptor.
|
||||
///
|
||||
/// A `SocketDescriptor` is a type-safe wrapper around an operating system
|
||||
/// socket handle. It provides a strongly-typed interface for socket operations.
|
||||
///
|
||||
/// Unlike `FileDescriptor`, a `SocketDescriptor` explicitly represents a
|
||||
/// socket rather than a general file descriptor, enabling socket-specific
|
||||
/// operations like `bind`, `listen`, `accept`, and `connect`.
|
||||
@frozen
|
||||
@available(System 199, *)
|
||||
public struct SocketDescriptor: RawRepresentable, Hashable, Codable, Sendable {
|
||||
/// The raw C socket handle.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a strongly-typed socket descriptor from a raw C socket handle.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// The file descriptor for this socket.
|
||||
///
|
||||
/// On POSIX systems, sockets are file descriptors and can be used with
|
||||
/// file descriptor operations like `read`, `write`, and `close`.
|
||||
@_alwaysEmitIntoClient
|
||||
public var fileDescriptor: FileDescriptor {
|
||||
FileDescriptor(rawValue: rawValue)
|
||||
}
|
||||
|
||||
/// Creates a socket descriptor from a file descriptor without verification.
|
||||
///
|
||||
/// This initializer does not verify that the file descriptor actually
|
||||
/// refers to a socket. Use with caution.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(unchecked fd: FileDescriptor) {
|
||||
self.init(rawValue: fd.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Domain (Protocol Family)
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Communications domain, identifying the protocol family.
|
||||
///
|
||||
/// The domain specifies the protocol family to be used for communication.
|
||||
/// Common domains include `.ipv4` for IPv4, `.ipv6` for IPv6, and `.local`
|
||||
/// for Unix domain sockets.
|
||||
@frozen
|
||||
public struct Domain: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Unspecified protocol.
|
||||
///
|
||||
/// The corresponding C constant is `PF_UNSPEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var unspecified: Domain { Domain(PF_UNSPEC) }
|
||||
|
||||
/// Local (Unix domain) communication.
|
||||
///
|
||||
/// The corresponding C constant is `PF_LOCAL` (also known as `PF_UNIX`).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var local: Domain { Domain(PF_LOCAL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "local")
|
||||
public static var unix: Domain { Domain(PF_UNIX) }
|
||||
|
||||
/// Internet Protocol version 4.
|
||||
///
|
||||
/// The corresponding C constant is `PF_INET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: Domain { Domain(PF_INET) }
|
||||
|
||||
/// Internet Protocol version 6.
|
||||
///
|
||||
/// The corresponding C constant is `PF_INET6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: Domain { Domain(PF_INET6) }
|
||||
|
||||
/// Internal routing protocol.
|
||||
///
|
||||
/// The corresponding C constant is `PF_ROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var routing: Domain { Domain(PF_ROUTE) }
|
||||
|
||||
/// Internal key-management function.
|
||||
///
|
||||
/// The corresponding C constant is `PF_KEY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keyManagement: Domain { Domain(PF_KEY) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// System domain.
|
||||
///
|
||||
/// The corresponding C constant is `PF_SYSTEM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var system: Domain { Domain(PF_SYSTEM) }
|
||||
|
||||
/// Raw access to network device.
|
||||
///
|
||||
/// The corresponding C constant is `PF_NDRV`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var networkDevice: Domain { Domain(PF_NDRV) }
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .unspecified: return "unspecified"
|
||||
case .local: return "local"
|
||||
case .ipv4: return "ipv4"
|
||||
case .ipv6: return "ipv6"
|
||||
case .routing: return "routing"
|
||||
case .keyManagement: return "keyManagement"
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
case .system: return "system"
|
||||
case .networkDevice: return "networkDevice"
|
||||
#endif
|
||||
default: return "Domain(\(rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Connection Type (Socket Type)
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// The socket type, specifying the semantics of communication.
|
||||
///
|
||||
/// The connection type determines how data is transmitted. Stream sockets
|
||||
/// provide reliable, ordered byte streams, while datagram sockets provide
|
||||
/// connectionless, unreliable messages.
|
||||
@frozen
|
||||
public struct ConnectionType: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Sequenced, reliable, two-way, connection-based byte streams.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_STREAM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var stream: ConnectionType { ConnectionType(_socketType(SOCK_STREAM)) }
|
||||
|
||||
/// Connectionless, unreliable datagrams of a fixed maximum length.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_DGRAM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var datagram: ConnectionType { ConnectionType(_socketType(SOCK_DGRAM)) }
|
||||
|
||||
/// Raw network protocol access.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_RAW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var raw: ConnectionType { ConnectionType(_socketType(SOCK_RAW)) }
|
||||
|
||||
/// Reliably-delivered message.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_RDM`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reliablyDeliveredMessage: ConnectionType {
|
||||
ConnectionType(_socketType(SOCK_RDM))
|
||||
}
|
||||
|
||||
/// Sequenced packet stream.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_SEQPACKET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sequencedPacketStream: ConnectionType {
|
||||
ConnectionType(_socketType(SOCK_SEQPACKET))
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .stream: return "stream"
|
||||
case .datagram: return "datagram"
|
||||
case .raw: return "raw"
|
||||
case .reliablyDeliveredMessage: return "rdm"
|
||||
case .sequencedPacketStream: return "seqpacket"
|
||||
default: return "ConnectionType(\(rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket Flags
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Flags for a socket that is created or accepted.
|
||||
///
|
||||
/// The flags are combined with the socket type when a socket is created,
|
||||
/// and passed as `flags` to `accept4` when a connection is accepted. They
|
||||
/// apply atomically, so no other thread can observe the socket without them.
|
||||
///
|
||||
/// Darwin has no equivalent flags.
|
||||
@frozen
|
||||
public struct SocketFlags: OptionSet, Sendable, Hashable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Closes the socket when the process executes another program.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: SocketFlags {
|
||||
SocketFlags(rawValue: _socketType(SOCK_CLOEXEC))
|
||||
}
|
||||
|
||||
/// Opens the socket in non-blocking mode.
|
||||
///
|
||||
/// The corresponding C constant is `SOCK_NONBLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nonBlocking: SocketFlags {
|
||||
SocketFlags(rawValue: _socketType(SOCK_NONBLOCK))
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.closeOnExec, ".closeOnExec"),
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
]
|
||||
return _buildDescription(descriptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Protocol ID
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Identifies a particular protocol to use for communication.
|
||||
///
|
||||
/// Protocol numbers are specific to the communication domain. Some symbolic
|
||||
/// names may have the same underlying value in different contexts.
|
||||
@frozen
|
||||
public struct ProtocolID: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
/// Default protocol for the socket type.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var `default`: ProtocolID { Self(0) }
|
||||
|
||||
/// Internet Protocol (IP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ip: ProtocolID { Self(CInt(IPPROTO_IP)) }
|
||||
|
||||
/// Transmission Control Protocol (TCP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_TCP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tcp: ProtocolID { Self(CInt(IPPROTO_TCP)) }
|
||||
|
||||
/// User Datagram Protocol (UDP).
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_UDP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var udp: ProtocolID { Self(CInt(IPPROTO_UDP)) }
|
||||
|
||||
/// IPv4 encapsulation.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV4`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv4: ProtocolID {
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
// Linux names this protocol `IPPROTO_IPIP`.
|
||||
Self(CInt(IPPROTO_IPIP))
|
||||
#else
|
||||
Self(CInt(IPPROTO_IPV4))
|
||||
#endif
|
||||
}
|
||||
|
||||
/// IPv6 header.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: ProtocolID { Self(CInt(IPPROTO_IPV6)) }
|
||||
|
||||
/// Raw IP packet.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_RAW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var raw: ProtocolID { Self(CInt(IPPROTO_RAW)) }
|
||||
|
||||
public var description: String {
|
||||
rawValue.description
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Message Flags
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Flags for send and receive operations.
|
||||
@frozen
|
||||
public struct MessageFlags: OptionSet, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInt) { self.init(rawValue: raw) }
|
||||
|
||||
/// No flags.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var none: MessageFlags { MessageFlags(0) }
|
||||
|
||||
/// Process out-of-band data.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_OOB`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var outOfBand: MessageFlags { MessageFlags(CInt(MSG_OOB)) }
|
||||
|
||||
/// Bypass routing, use direct interface.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_DONTROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var doNotRoute: MessageFlags { MessageFlags(CInt(MSG_DONTROUTE)) }
|
||||
|
||||
/// Peek at incoming message without removing it.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_PEEK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var peek: MessageFlags { MessageFlags(CInt(MSG_PEEK)) }
|
||||
|
||||
/// Wait for full request or error.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_WAITALL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var waitForAll: MessageFlags { MessageFlags(CInt(MSG_WAITALL)) }
|
||||
|
||||
/// End-of-record marker.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_EOR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var endOfRecord: MessageFlags { MessageFlags(CInt(MSG_EOR)) }
|
||||
|
||||
/// Data was truncated.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_TRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dataTruncated: MessageFlags { MessageFlags(CInt(MSG_TRUNC)) }
|
||||
|
||||
/// Control data was truncated.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_CTRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var controlTruncated: MessageFlags { MessageFlags(CInt(MSG_CTRUNC)) }
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
/// Do not generate SIGPIPE on broken pipe.
|
||||
///
|
||||
/// The corresponding C constant is `MSG_NOSIGNAL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSignal: MessageFlags { MessageFlags(CInt(MSG_NOSIGNAL)) }
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
var descriptions: [(Element, StaticString)] = [
|
||||
(.outOfBand, ".outOfBand"),
|
||||
(.doNotRoute, ".doNotRoute"),
|
||||
(.peek, ".peek"),
|
||||
(.waitForAll, ".waitForAll"),
|
||||
(.endOfRecord, ".endOfRecord"),
|
||||
(.dataTruncated, ".dataTruncated"),
|
||||
(.controlTruncated, ".controlTruncated"),
|
||||
]
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
descriptions.append((.noSignal, ".noSignal"))
|
||||
#endif
|
||||
return _buildDescription(descriptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Shutdown Kind
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Specifies which parts of a full-duplex connection to shut down.
|
||||
@frozen
|
||||
public struct ShutdownKind: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Disallow further receives.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_RD`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var read: ShutdownKind { ShutdownKind(rawValue: CInt(SHUT_RD)) }
|
||||
|
||||
/// Disallow further sends.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_WR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var write: ShutdownKind { ShutdownKind(rawValue: CInt(SHUT_WR)) }
|
||||
|
||||
/// Disallow further sends and receives.
|
||||
///
|
||||
/// The corresponding C constant is `SHUT_RDWR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var readWrite: ShutdownKind { ShutdownKind(rawValue: CInt(SHUT_RDWR)) }
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .read: return "read"
|
||||
case .write: return "write"
|
||||
case .readWrite: return "readWrite"
|
||||
default: return "ShutdownKind(\(rawValue))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket Option
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// A generic socket option identifier.
|
||||
///
|
||||
/// This type represents raw socket option constants that can be used
|
||||
/// with ancillary messages or generic get/set socket option operations.
|
||||
@frozen
|
||||
public struct Option: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
|
||||
|
||||
public var description: String { "Option(\(rawValue))" }
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Writes a sequence of bytes to the socket
|
||||
///
|
||||
/// This is equivalent to calling `fileDescriptor.writeAll(_:)`
|
||||
///
|
||||
/// - Parameter sequence: The bytes to write.
|
||||
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func writeAll<S: Sequence>(
|
||||
_ sequence: S
|
||||
) throws -> Int where S.Element == UInt8 {
|
||||
try fileDescriptor.writeAll(sequence)
|
||||
}
|
||||
|
||||
/// Runs a closure and then closes the socket, even if an error occurs.
|
||||
///
|
||||
/// This is equivalent to calling `fileDescriptor.closeAfter(_:)`
|
||||
///
|
||||
/// - Parameter body: The closure to run.
|
||||
/// If the closure throws an error,
|
||||
/// this method closes the socket before it rethrows that error.
|
||||
///
|
||||
/// - Returns: The value returned by the closure.
|
||||
///
|
||||
/// If `body` throws an error
|
||||
/// or an error occurs while closing the socket,
|
||||
/// this method rethrows that error.
|
||||
@_alwaysEmitIntoClient
|
||||
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
|
||||
try fileDescriptor.closeAfter(body)
|
||||
}
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// A reusable collection of variable-sized ancillary messages
|
||||
/// sent or received over a socket. These represent protocol control
|
||||
/// related messages or other miscellaneous ancillary data.
|
||||
///
|
||||
/// Corresponds to a buffer of `struct cmsghdr` messages in C, as used
|
||||
/// by `sendmsg` and `recmsg`.
|
||||
public struct AncillaryMessageBuffer {
|
||||
internal var _buffer: _RawBuffer
|
||||
internal var _endOffset: Int
|
||||
|
||||
/// Initialize a new empty ancillary message buffer with no preallocated
|
||||
/// storage.
|
||||
public init() {
|
||||
_buffer = _RawBuffer()
|
||||
_endOffset = 0
|
||||
}
|
||||
|
||||
/// Initialize a new empty ancillary message buffer of the
|
||||
/// specified minimum capacity (in bytes).
|
||||
internal init(minimumCapacity: Int) {
|
||||
let headerSize = MemoryLayout<CInterop.CMsgHdr>.size
|
||||
let capacity = Swift.max(headerSize + 1, minimumCapacity)
|
||||
_buffer = _RawBuffer(minimumCapacity: capacity)
|
||||
_endOffset = 0
|
||||
}
|
||||
|
||||
internal var _headerSize: Int { MemoryLayout<CInterop.CMsgHdr>.size }
|
||||
internal var _capacity: Int { _buffer.capacity }
|
||||
|
||||
/// Remove all messages currently in this buffer, preserving storage
|
||||
/// capacity.
|
||||
///
|
||||
/// This invalidates all indices in the collection.
|
||||
///
|
||||
/// - Complexity: O(1). Does not reallocate the buffer.
|
||||
public mutating func removeAll() {
|
||||
_endOffset = 0
|
||||
}
|
||||
|
||||
/// Reserve enough storage capacity to hold `minimumCapacity` bytes' worth
|
||||
/// of messages without having to reallocate storage.
|
||||
///
|
||||
/// This does not invalidate any indices.
|
||||
///
|
||||
/// - Complexity: O(max(`minimumCapacity`, `capacity`)), where `capacity` is
|
||||
/// the current storage capacity. This potentially needs to reallocate
|
||||
/// the buffer and copy existing messages.
|
||||
public mutating func reserveCapacity(_ minimumCapacity: Int) {
|
||||
_buffer.ensureUnique(capacity: minimumCapacity)
|
||||
}
|
||||
|
||||
/// Append a message with the specified data to the end of this buffer,
|
||||
/// resizing it if necessary.
|
||||
///
|
||||
/// This does not invalidate any existing indices, but it updates `endIndex`.
|
||||
///
|
||||
/// - Complexity: Amortized O(`data.count`), when averaged over multiple
|
||||
/// calls. This method reallocates the buffer if there isn't enough
|
||||
/// capacity or if the storage is shared with another value.
|
||||
public mutating func appendMessage(
|
||||
level: SocketDescriptor.ProtocolID,
|
||||
type: SocketDescriptor.Option,
|
||||
bytes: UnsafeRawBufferPointer
|
||||
) {
|
||||
appendMessage(
|
||||
level: level,
|
||||
type: type,
|
||||
unsafeUninitializedCapacity: bytes.count
|
||||
) { buffer in
|
||||
assert(buffer.count >= bytes.count)
|
||||
if bytes.count > 0 {
|
||||
buffer.baseAddress!.copyMemory(
|
||||
from: bytes.baseAddress!,
|
||||
byteCount: bytes.count)
|
||||
}
|
||||
return bytes.count
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a message with the supplied data to the end of this buffer,
|
||||
/// resizing it if necessary. The message payload is initialized with the
|
||||
/// supplied closure, which needs to return the final message length.
|
||||
///
|
||||
/// This does not invalidate any existing indices, but it updates `endIndex`.
|
||||
///
|
||||
/// - Complexity: Amortized O(`data.count`), when averaged over multiple
|
||||
/// calls. This method reallocates the buffer if there isn't enough
|
||||
/// capacity or if the storage is shared with another value.
|
||||
public mutating func appendMessage(
|
||||
level: SocketDescriptor.ProtocolID,
|
||||
type: SocketDescriptor.Option,
|
||||
unsafeUninitializedCapacity capacity: Int,
|
||||
initializingWith body: (UnsafeMutableRawBufferPointer) throws -> Int
|
||||
) rethrows {
|
||||
precondition(capacity >= 0)
|
||||
let headerSize = _headerSize
|
||||
let delta = _headerSize + capacity
|
||||
_buffer.ensureUnique(capacity: _endOffset + delta)
|
||||
let messageLength: Int = try _buffer.withUnsafeMutableBytes { buffer in
|
||||
assert(buffer.count >= _endOffset + delta)
|
||||
let p = buffer.baseAddress! + _endOffset
|
||||
let header = p.bindMemory(to: CInterop.CMsgHdr.self, capacity: 1)
|
||||
header.pointee = CInterop.CMsgHdr()
|
||||
header.pointee.cmsg_level = level.rawValue
|
||||
header.pointee.cmsg_type = type.rawValue
|
||||
let length = try body(
|
||||
UnsafeMutableRawBufferPointer(start: p + headerSize, count: capacity))
|
||||
precondition(length >= 0 && length <= capacity)
|
||||
// `cmsg_len` is a `socklen_t` on Darwin and a `size_t` on Linux.
|
||||
header.pointee.cmsg_len = numericCast(headerSize + length)
|
||||
return headerSize + length
|
||||
}
|
||||
_endOffset += messageLength
|
||||
}
|
||||
|
||||
internal func _withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try _buffer.withUnsafeBytes { buffer in
|
||||
assert(buffer.count >= _endOffset)
|
||||
let buffer = UnsafeRawBufferPointer(rebasing: buffer.prefix(_endOffset))
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func _withUnsafeMutableBytes<R>(
|
||||
entireCapacity: Bool,
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
return try _buffer.withUnsafeMutableBytes { buffer in
|
||||
assert(buffer.count >= _endOffset)
|
||||
if entireCapacity {
|
||||
return try body(buffer)
|
||||
} else {
|
||||
return try body(.init(rebasing: buffer.prefix(_endOffset)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func _withMutableCInterop<R>(
|
||||
entireCapacity: Bool,
|
||||
_ body: (UnsafeMutableRawPointer?, inout CInterop.SockLen) throws -> R
|
||||
) rethrows -> R {
|
||||
let (result, length): (R, Int) = try _withUnsafeMutableBytes(
|
||||
entireCapacity: entireCapacity
|
||||
) { buffer in
|
||||
var length = CInterop.SockLen(buffer.count)
|
||||
let result = try body(buffer.baseAddress, &length)
|
||||
precondition(length >= 0 && length <= buffer.count)
|
||||
return (result, Int(length))
|
||||
}
|
||||
_endOffset = length
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor.AncillaryMessageBuffer: Collection {
|
||||
/// The index type in an ancillary message buffer.
|
||||
@frozen
|
||||
public struct Index: Comparable, Hashable {
|
||||
@usableFromInline
|
||||
var _offset: Int
|
||||
|
||||
@inlinable
|
||||
internal init(_offset: Int) {
|
||||
self._offset = _offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func == (left: Self, right: Self) -> Bool {
|
||||
left._offset == right._offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func < (left: Self, right: Self) -> Bool {
|
||||
left._offset < right._offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_offset)
|
||||
}
|
||||
}
|
||||
|
||||
/// An individual message inside an ancillary message buffer.
|
||||
///
|
||||
/// Note that this is merely a reference to a slice of the underlying buffer,
|
||||
/// so it contains a shared copy of its entire storage. To prevent buffer
|
||||
/// reallocations due to copy-on-write copies, do not save instances
|
||||
/// of this type. Instead, immediately copy out any data you need to hold onto
|
||||
/// into standalone buffers.
|
||||
public struct Message {
|
||||
internal var _base: SocketDescriptor.AncillaryMessageBuffer
|
||||
internal var _offset: Int
|
||||
|
||||
internal init(_base: SocketDescriptor.AncillaryMessageBuffer, offset: Int) {
|
||||
self._base = _base
|
||||
self._offset = offset
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the first message in the collection, or `endIndex` if
|
||||
/// the collection contains no messages.
|
||||
///
|
||||
/// This roughly corresponds to the C macro `CMSG_FIRSTHDR`.
|
||||
public var startIndex: Index { Index(_offset: 0) }
|
||||
|
||||
/// The index after the last message in the collection.
|
||||
public var endIndex: Index { Index(_offset: _endOffset) }
|
||||
|
||||
/// True if the collection contains no elements.
|
||||
public var isEmpty: Bool { _endOffset == 0 }
|
||||
|
||||
/// Return the length (in bytes) of the message at the specified index, or
|
||||
/// nil if the index isn't valid, or it addresses a corrupt message.
|
||||
internal func _length(at i: Index) -> Int? {
|
||||
_withUnsafeBytes { buffer in
|
||||
guard i._offset >= 0 && i._offset + _headerSize <= buffer.count else {
|
||||
return nil
|
||||
}
|
||||
let p = (buffer.baseAddress! + i._offset)
|
||||
.assumingMemoryBound(to: CInterop.CMsgHdr.self)
|
||||
let length = Int(p.pointee.cmsg_len)
|
||||
|
||||
// Cut the list short at the first sign of corrupt data.
|
||||
// Messages must not be shorter than their header, and they must fit
|
||||
// entirely in the buffer.
|
||||
if length < _headerSize || i._offset + length > buffer.count {
|
||||
return nil
|
||||
}
|
||||
return length
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the index immediately following `i` in the collection.
|
||||
///
|
||||
/// This roughly corresponds to the C macro `CMSG_NXTHDR`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
public func index(after i: Index) -> Index {
|
||||
precondition(i._offset != _endOffset, "Can't advance past endIndex")
|
||||
precondition(i._offset >= 0 && i._offset + _headerSize <= _endOffset,
|
||||
"Invalid index")
|
||||
guard let length = _length(at: i) else { return endIndex }
|
||||
return Index(_offset: i._offset + length)
|
||||
}
|
||||
|
||||
/// Returns the message at the given position, which must be a valid index
|
||||
/// in this collection.
|
||||
///
|
||||
/// The returned value merely refers to a slice of the entire buffer, so
|
||||
/// it contains a shared regerence to it.
|
||||
///
|
||||
/// To reduce memory use and to prevent unnecessary copy-on-write copying, do
|
||||
/// not save `Message` values -- instead, copy out the data you need to hold
|
||||
/// on to into standalone storage.
|
||||
public subscript(position: Index) -> Message {
|
||||
guard let _ = _length(at: position) else {
|
||||
preconditionFailure("Invalid index")
|
||||
}
|
||||
return Element(_base: self, offset: position._offset)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor.AncillaryMessageBuffer.Message {
|
||||
internal var _header: CInterop.CMsgHdr {
|
||||
_base._withUnsafeBytes { buffer in
|
||||
assert(_offset + _base._headerSize <= buffer.count)
|
||||
let p = buffer.baseAddress! + _offset
|
||||
let header = p.assumingMemoryBound(to: CInterop.CMsgHdr.self)
|
||||
return header.pointee
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol level of the message. Socket-level command messages
|
||||
/// use the special protocol value `SocketDescriptor.ProtocolID.socketOption`.
|
||||
public var level: SocketDescriptor.ProtocolID {
|
||||
.init(rawValue: _header.cmsg_level)
|
||||
}
|
||||
|
||||
/// The protocol-specific type of the message.
|
||||
public var type: SocketDescriptor.Option {
|
||||
.init(rawValue: _header.cmsg_type)
|
||||
}
|
||||
|
||||
/// Calls `body` with an unsafe raw buffer pointer containing the
|
||||
/// message payload.
|
||||
///
|
||||
/// This roughly corresponds to the C macro `CMSG_DATA`.
|
||||
///
|
||||
/// - Note: The buffer passed to `body` does not include storage reserved
|
||||
/// for holding the message header, such as the `level` and `type` values.
|
||||
/// To access header information, you have to use the corresponding
|
||||
/// properties.
|
||||
public func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try _base._withUnsafeBytes { buffer in
|
||||
let headerSize = _base._headerSize
|
||||
assert(_offset + headerSize <= buffer.count)
|
||||
let p = buffer.baseAddress! + _offset
|
||||
let header = p.assumingMemoryBound(to: CInterop.CMsgHdr.self)
|
||||
let data = p + headerSize
|
||||
let count = Swift.min(Int(header.pointee.cmsg_len) - headerSize,
|
||||
buffer.count)
|
||||
return try body(UnsafeRawBufferPointer(start: data, count: count))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Socket Creation and Lifecycle
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Creates an endpoint for communication.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - domain: The protocol family for communication.
|
||||
/// - type: The semantics of communication.
|
||||
/// - protocol: The particular protocol to use. The default is `.default`,
|
||||
/// which typically selects the appropriate protocol for the domain/type
|
||||
/// combination (e.g., TCP for IPv4/stream).
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted. The default is `true`.
|
||||
/// - Returns: A new socket descriptor.
|
||||
///
|
||||
/// The corresponding C function is `socket`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ domain: Domain,
|
||||
_ type: ConnectionType,
|
||||
protocol: ProtocolID = .default,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> SocketDescriptor {
|
||||
try _open(domain, type, protocol: `protocol`, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _open(
|
||||
_ domain: Domain,
|
||||
_ type: ConnectionType,
|
||||
protocol: ProtocolID,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<SocketDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_socket(domain.rawValue, type.rawValue, `protocol`.rawValue)
|
||||
}.map(SocketDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
/// Closes the socket.
|
||||
///
|
||||
/// The corresponding C function is `close`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func close() throws {
|
||||
try _close().get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _close() -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_close(self.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shuts down part of a full-duplex connection.
|
||||
///
|
||||
/// - Parameter how: Which parts of the connection to shut down.
|
||||
///
|
||||
/// The corresponding C function is `shutdown`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func shutdown(_ how: ShutdownKind) throws {
|
||||
try _shutdown(how).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _shutdown(_ how: ShutdownKind) -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_shutdown(self.rawValue, how.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Connection Operations
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Binds a socket to an address.
|
||||
///
|
||||
/// - Parameter address: The socket address to bind to.
|
||||
///
|
||||
/// The corresponding C function is `bind`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func bind(to address: SocketAddress) throws {
|
||||
try _bind(to: address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _bind(to address: SocketAddress) -> Result<(), Errno> {
|
||||
address.withUnsafePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_bind(self.rawValue, addr, len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Listens for connections on the socket.
|
||||
///
|
||||
/// Only applies to sockets of type `.stream`.
|
||||
///
|
||||
/// - Parameter backlog: The maximum length of the pending connections queue.
|
||||
///
|
||||
/// The corresponding C function is `listen`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func listen(backlog: Int) throws {
|
||||
try _listen(backlog: backlog).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _listen(backlog: Int) -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_listen(self.rawValue, CInt(backlog))
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a connection on the socket.
|
||||
///
|
||||
/// - Parameter retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: A new socket descriptor for the accepted connection.
|
||||
///
|
||||
/// The corresponding C function is `accept`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func accept(retryOnInterrupt: Bool = true) throws -> SocketDescriptor {
|
||||
try _accept(retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _accept(retryOnInterrupt: Bool) -> Result<SocketDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_accept(self.rawValue, nil, nil)
|
||||
}.map(SocketDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
/// Accepts a connection and returns the client's address.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - client: A socket address buffer to receive the client's address.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: A new socket descriptor for the accepted connection.
|
||||
///
|
||||
/// The corresponding C function is `accept`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func accept(
|
||||
client: inout SocketAddress,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> SocketDescriptor {
|
||||
try _accept(client: &client, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _accept(
|
||||
client: inout SocketAddress,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<SocketDescriptor, Errno> {
|
||||
client._withUnsafeMutablePointer { addr, len in
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_accept(self.rawValue, addr, &len)
|
||||
}.map(SocketDescriptor.init(rawValue:))
|
||||
}
|
||||
}
|
||||
|
||||
/// Initiates a connection on the socket.
|
||||
///
|
||||
/// - Parameter address: The address to connect to.
|
||||
///
|
||||
/// The corresponding C function is `connect`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func connect(to address: SocketAddress) throws {
|
||||
try _connect(to: address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _connect(to address: SocketAddress) -> Result<(), Errno> {
|
||||
address.withUnsafePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_connect(self.rawValue, addr, len)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Send and Receive
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Sends data on the socket.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The data to send.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes sent.
|
||||
///
|
||||
/// The corresponding C function is `send`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _send(buffer, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_send(self.rawValue, buffer.baseAddress, buffer.count, flags.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives data from the socket.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The buffer to receive data into.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes received.
|
||||
///
|
||||
/// The corresponding C function is `recv`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _receive(into: buffer, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_recv(self.rawValue, buffer.baseAddress, buffer.count, flags.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends data to a specific address.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The data to send.
|
||||
/// - address: The destination address.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes sent.
|
||||
///
|
||||
/// The corresponding C function is `sendto`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to address: SocketAddress,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _send(buffer, to: address, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _send(
|
||||
_ buffer: UnsafeRawBufferPointer,
|
||||
to address: SocketAddress,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
address.withUnsafePointer { addr, addrlen in
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_sendto(
|
||||
self.rawValue,
|
||||
buffer.baseAddress,
|
||||
buffer.count,
|
||||
flags.rawValue,
|
||||
addr,
|
||||
addrlen
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives data and returns the sender's address.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: The buffer to receive data into.
|
||||
/// - sender: A buffer to receive the sender's address.
|
||||
/// - flags: Message flags.
|
||||
/// - retryOnInterrupt: Whether to retry if interrupted.
|
||||
/// - Returns: The number of bytes received.
|
||||
///
|
||||
/// The corresponding C function is `recvfrom`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
sender: inout SocketAddress,
|
||||
flags: MessageFlags = .none,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int {
|
||||
try _receive(into: buffer, sender: &sender, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _receive(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
sender: inout SocketAddress,
|
||||
flags: MessageFlags,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
sender._withUnsafeMutablePointer { addr, len in
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_recvfrom(
|
||||
self.rawValue,
|
||||
buffer.baseAddress,
|
||||
buffer.count,
|
||||
flags.rawValue,
|
||||
addr,
|
||||
&len
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket Information
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets the local address of the socket.
|
||||
///
|
||||
/// - Parameter address: A buffer to receive the local address.
|
||||
///
|
||||
/// The corresponding C function is `getsockname`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getLocalAddress(into address: inout SocketAddress) throws {
|
||||
try _getLocalAddress(into: &address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getLocalAddress(into address: inout SocketAddress) -> Result<(), Errno> {
|
||||
address._withUnsafeMutablePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getsockname(self.rawValue, addr, &len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the remote address of the socket.
|
||||
///
|
||||
/// - Parameter address: A buffer to receive the peer address.
|
||||
///
|
||||
/// The corresponding C function is `getpeername`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getPeerAddress(into address: inout SocketAddress) throws {
|
||||
try _getPeerAddress(into: &address).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getPeerAddress(into address: inout SocketAddress) -> Result<(), Errno> {
|
||||
address._withUnsafeMutablePointer { addr, len in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getpeername(self.rawValue, addr, &len)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,355 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: - Option Level
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Socket option levels.
|
||||
@frozen
|
||||
public struct OptionLevel: RawRepresentable, Hashable, Sendable {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Socket-level options.
|
||||
///
|
||||
/// The corresponding C constant is `SOL_SOCKET`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var socket: OptionLevel { OptionLevel(rawValue: SOL_SOCKET) }
|
||||
|
||||
/// IPv4 protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ip: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_IP)) }
|
||||
|
||||
/// IPv6 protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_IPV6`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ipv6: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_IPV6)) }
|
||||
|
||||
/// TCP protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_TCP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var tcp: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_TCP)) }
|
||||
|
||||
/// UDP protocol options.
|
||||
///
|
||||
/// The corresponding C constant is `IPPROTO_UDP`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var udp: OptionLevel { OptionLevel(rawValue: CInt(IPPROTO_UDP)) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Socket-Level Options
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Socket-level options for use with `getOption` and `setOption`.
|
||||
@frozen
|
||||
public struct SocketOption: RawRepresentable, Hashable, Sendable {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Enable debugging.
|
||||
///
|
||||
/// The corresponding C constant is `SO_DEBUG`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var debug: SocketOption { SocketOption(rawValue: SO_DEBUG) }
|
||||
|
||||
/// Allow local address reuse.
|
||||
///
|
||||
/// The corresponding C constant is `SO_REUSEADDR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reuseAddress: SocketOption { SocketOption(rawValue: SO_REUSEADDR) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux)
|
||||
/// Allow local port reuse.
|
||||
///
|
||||
/// The corresponding C constant is `SO_REUSEPORT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var reusePort: SocketOption { SocketOption(rawValue: SO_REUSEPORT) }
|
||||
#endif
|
||||
|
||||
/// Keep connections alive.
|
||||
///
|
||||
/// The corresponding C constant is `SO_KEEPALIVE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAlive: SocketOption { SocketOption(rawValue: SO_KEEPALIVE) }
|
||||
|
||||
/// Don't route, use direct interface.
|
||||
///
|
||||
/// The corresponding C constant is `SO_DONTROUTE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var dontRoute: SocketOption { SocketOption(rawValue: SO_DONTROUTE) }
|
||||
|
||||
/// Linger on close if data present.
|
||||
///
|
||||
/// The corresponding C constant is `SO_LINGER`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var linger: SocketOption { SocketOption(rawValue: SO_LINGER) }
|
||||
|
||||
/// Permit sending of broadcast messages.
|
||||
///
|
||||
/// The corresponding C constant is `SO_BROADCAST`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var broadcast: SocketOption { SocketOption(rawValue: SO_BROADCAST) }
|
||||
|
||||
/// Send buffer size.
|
||||
///
|
||||
/// The corresponding C constant is `SO_SNDBUF`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sendBufferSize: SocketOption { SocketOption(rawValue: SO_SNDBUF) }
|
||||
|
||||
/// Receive buffer size.
|
||||
///
|
||||
/// The corresponding C constant is `SO_RCVBUF`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var receiveBufferSize: SocketOption { SocketOption(rawValue: SO_RCVBUF) }
|
||||
|
||||
/// Send low water mark.
|
||||
///
|
||||
/// The corresponding C constant is `SO_SNDLOWAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sendLowWaterMark: SocketOption { SocketOption(rawValue: SO_SNDLOWAT) }
|
||||
|
||||
/// Receive low water mark.
|
||||
///
|
||||
/// The corresponding C constant is `SO_RCVLOWAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var receiveLowWaterMark: SocketOption { SocketOption(rawValue: SO_RCVLOWAT) }
|
||||
|
||||
/// Get socket error.
|
||||
///
|
||||
/// The corresponding C constant is `SO_ERROR`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var error: SocketOption { SocketOption(rawValue: SO_ERROR) }
|
||||
|
||||
/// Get socket type.
|
||||
///
|
||||
/// The corresponding C constant is `SO_TYPE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var type: SocketOption { SocketOption(rawValue: SO_TYPE) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Don't generate SIGPIPE on broken pipe.
|
||||
///
|
||||
/// The corresponding C constant is `SO_NOSIGPIPE`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noSigPipe: SocketOption { SocketOption(rawValue: SO_NOSIGPIPE) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TCP Options
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// TCP-level options for use with `getOption` and `setOption`.
|
||||
@frozen
|
||||
public struct TCPOption: RawRepresentable, Hashable, Sendable {
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
|
||||
/// Disable Nagle algorithm.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_NODELAY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noDelay: TCPOption { TCPOption(rawValue: TCP_NODELAY) }
|
||||
|
||||
/// Maximum segment size.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_MAXSEG`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var maxSegmentSize: TCPOption { TCPOption(rawValue: TCP_MAXSEG) }
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(Linux)
|
||||
/// Keep alive idle time.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_KEEPIDLE` on Linux
|
||||
/// or `TCP_KEEPALIVE` on Darwin.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAliveIdle: TCPOption {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
TCPOption(rawValue: TCP_KEEPALIVE)
|
||||
#else
|
||||
TCPOption(rawValue: TCP_KEEPIDLE)
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(Linux)
|
||||
/// Keep alive interval.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_KEEPINTVL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAliveInterval: TCPOption { TCPOption(rawValue: TCP_KEEPINTVL) }
|
||||
|
||||
/// Keep alive probe count.
|
||||
///
|
||||
/// The corresponding C constant is `TCP_KEEPCNT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var keepAliveCount: TCPOption { TCPOption(rawValue: TCP_KEEPCNT) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Get and Set Options
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets a socket option value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The protocol level.
|
||||
/// - option: The option to get.
|
||||
/// - Returns: The option value.
|
||||
///
|
||||
/// The corresponding C function is `getsockopt`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt
|
||||
) throws -> T {
|
||||
try _getOption(level, option).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _getOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt
|
||||
) -> Result<T, Errno> {
|
||||
// Allocate zeroed storage for the option value
|
||||
var storage = [UInt8](repeating: 0, count: MemoryLayout<T>.size)
|
||||
var length = socklen_t(MemoryLayout<T>.size)
|
||||
|
||||
let result = storage.withUnsafeMutableBytes { buffer in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_getsockopt(
|
||||
self.rawValue,
|
||||
level.rawValue,
|
||||
option,
|
||||
buffer.baseAddress,
|
||||
&length
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return result.map {
|
||||
storage.withUnsafeBytes { buffer in
|
||||
buffer.load(as: T.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a socket option value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - level: The protocol level.
|
||||
/// - option: The option to set.
|
||||
/// - value: The value to set.
|
||||
///
|
||||
/// The corresponding C function is `setsockopt`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt,
|
||||
to value: T
|
||||
) throws {
|
||||
try _setOption(level, option, to: value).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal func _setOption<T>(
|
||||
_ level: OptionLevel,
|
||||
_ option: CInt,
|
||||
to value: T
|
||||
) -> Result<(), Errno> {
|
||||
withUnsafePointer(to: value) { valuePtr in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_setsockopt(
|
||||
self.rawValue,
|
||||
level.rawValue,
|
||||
option,
|
||||
valuePtr,
|
||||
socklen_t(MemoryLayout<T>.size)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Convenience Methods
|
||||
|
||||
@available(System 199, *)
|
||||
extension SocketDescriptor {
|
||||
/// Gets a socket-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getSocketOption(_ option: SocketOption) throws -> CInt {
|
||||
try getOption(.socket, option.rawValue)
|
||||
}
|
||||
|
||||
/// Sets a socket-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setSocketOption(_ option: SocketOption, to value: CInt) throws {
|
||||
try setOption(.socket, option.rawValue, to: value)
|
||||
}
|
||||
|
||||
/// Gets a TCP-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func getTCPOption(_ option: TCPOption) throws -> CInt {
|
||||
try getOption(.tcp, option.rawValue)
|
||||
}
|
||||
|
||||
/// Sets a TCP-level option as an integer.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setTCPOption(_ option: TCPOption, to value: CInt) throws {
|
||||
try setOption(.tcp, option.rawValue, to: value)
|
||||
}
|
||||
|
||||
/// Enables reuse of local addresses.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setReuseAddress(_ enabled: Bool = true) throws {
|
||||
try setSocketOption(.reuseAddress, to: enabled ? 1 : 0)
|
||||
}
|
||||
|
||||
/// Disables the Nagle algorithm.
|
||||
@_alwaysEmitIntoClient
|
||||
public func setNoDelay(_ enabled: Bool = true) throws {
|
||||
try setTCPOption(.noDelay, to: enabled ? 1 : 0)
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// Utility functions for socket operations
|
||||
|
||||
import SystemPackage
|
||||
|
||||
extension Errno {
|
||||
internal static var current: Errno {
|
||||
get { Errno(rawValue: system_errno) }
|
||||
set { system_errno = newValue.rawValue }
|
||||
}
|
||||
}
|
||||
|
||||
// Results in errno if i == -1
|
||||
@available(System 0.0.1, *)
|
||||
private func valueOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<I, Errno> {
|
||||
i == -1 ? .failure(Errno.current) : .success(i)
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
private func nothingOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(i).map { _ in () }
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<I, Errno> {
|
||||
repeat {
|
||||
switch valueOrErrno(f()) {
|
||||
case .success(let r): return .success(r)
|
||||
case .failure(let err):
|
||||
guard retryOnInterrupt && err == .interrupted else { return .failure(err) }
|
||||
break
|
||||
}
|
||||
} while true
|
||||
}
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
internal func nothingOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () }
|
||||
}
|
||||
|
||||
// Run a precondition for debug client builds
|
||||
internal func _debugPrecondition(
|
||||
_ condition: @autoclosure () -> Bool,
|
||||
_ message: StaticString = StaticString(),
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) {
|
||||
if _slowPath(_isDebugAssertConfiguration()) {
|
||||
precondition(
|
||||
condition(), String(describing: message), file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
extension OptionSet {
|
||||
@inline(never)
|
||||
internal func _buildDescription(
|
||||
_ descriptions: [(Element, StaticString)]
|
||||
) -> String {
|
||||
var copy = self
|
||||
var result = "["
|
||||
|
||||
for (option, name) in descriptions {
|
||||
if _slowPath(copy.contains(option)) {
|
||||
result += name.description
|
||||
copy.remove(option)
|
||||
if !copy.isEmpty { result += ", " }
|
||||
}
|
||||
}
|
||||
|
||||
if _slowPath(!copy.isEmpty) {
|
||||
result += "\(Self.self)(rawValue: \(copy.rawValue))"
|
||||
}
|
||||
result += "]"
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
internal func _withOptionalUnsafePointerOrNull<T, R>(
|
||||
to value: T?,
|
||||
_ body: (UnsafePointer<T>?) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let value = value else {
|
||||
return try body(nil)
|
||||
}
|
||||
return try withUnsafePointer(to: value, body)
|
||||
}
|
||||
@@ -16,8 +16,9 @@
|
||||
// - 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) || canImport(Android)
|
||||
#if canImport(Glibc)
|
||||
@@ -43,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
|
||||
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import Testing
|
||||
import SystemPackage
|
||||
@testable import SystemSockets
|
||||
|
||||
@Suite("Ancillary Message Buffer")
|
||||
struct AncillaryMessageBufferTests {
|
||||
@Test("Append and iterate messages")
|
||||
func testAppend() {
|
||||
// Create a buffer of 100 messages, with varying payload lengths.
|
||||
var buffer = SocketDescriptor.AncillaryMessageBuffer(minimumCapacity: 0)
|
||||
for i in 0 ..< 100 {
|
||||
let bytes = UnsafeMutableRawBufferPointer.allocate(byteCount: i, alignment: 1)
|
||||
defer { bytes.deallocate() }
|
||||
system_memset(bytes, to: UInt8(i))
|
||||
buffer.appendMessage(level: .init(rawValue: CInt(100 * i)),
|
||||
type: .init(rawValue: CInt(1000 * i)),
|
||||
bytes: UnsafeRawBufferPointer(bytes))
|
||||
}
|
||||
// Check that we can access appended messages.
|
||||
var i = 0
|
||||
for message in buffer {
|
||||
#expect(Int(message.level.rawValue) == 100 * i)
|
||||
#expect(Int(message.type.rawValue) == 1000 * i)
|
||||
message.withUnsafeBytes { buffer in
|
||||
#expect(buffer.count == i)
|
||||
for idx in buffer.indices {
|
||||
#expect(buffer[idx] == UInt8(i), "byte #\(idx)")
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
#expect(i == 100, "Too many messages in buffer")
|
||||
}
|
||||
}
|
||||
@@ -1,338 +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 compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import Testing
|
||||
|
||||
#if canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
/// Whether the environment can create an `IORing` at all.
|
||||
private let ioRingAvailable: Bool = {
|
||||
do {
|
||||
_ = try IORing(queueDepth: 1)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}()
|
||||
|
||||
/// Whether the kernel knows the operation of the given request.
|
||||
///
|
||||
/// The request has to target an invalid descriptor or argument. A kernel that
|
||||
/// doesn't know the operation fails it with `EINVAL`, one that does fails it
|
||||
/// with another error.
|
||||
@available(System 199, *)
|
||||
private func kernelSupports(_ request: IORing.Request) -> Bool {
|
||||
guard ioRingAvailable else { return false }
|
||||
do {
|
||||
var ring = try IORing(queueDepth: 1)
|
||||
guard try ring.submit(linkedRequests: request) else { return false }
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
return completion.error != .invalidArgument
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
private let invalidSocket = SocketDescriptor(rawValue: -1)
|
||||
|
||||
@available(System 199, *)
|
||||
private let socketSupported = kernelSupports(
|
||||
.socket(SocketDescriptor.Domain(rawValue: -1), .stream)
|
||||
)
|
||||
|
||||
@available(System 199, *)
|
||||
private let shutdownSupported = kernelSupports(.shutdown(invalidSocket, .write))
|
||||
|
||||
@available(System 199, *)
|
||||
private let bindAndListenSupported = kernelSupports(.listen(invalidSocket, backlog: 1))
|
||||
|
||||
/// Whether the environment has an IPv6 loopback interface.
|
||||
@available(System 199, *)
|
||||
private let ipv6LoopbackAvailable: Bool = {
|
||||
do {
|
||||
let socket = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
try socket.bind(to: SocketAddress(ipv6: .loopback(port: 0)))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}()
|
||||
|
||||
/// Consumes the given number of completions and returns their results by context.
|
||||
private func consumeResults(
|
||||
_ count: Int,
|
||||
from ring: borrowing IORing
|
||||
) throws -> [UInt64: Int32] {
|
||||
var results: [UInt64: Int32] = [:]
|
||||
for _ in 0..<count {
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
results[completion.context] = completion.result
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
@Suite("IORing socket requests", .enabled(if: ioRingAvailable))
|
||||
private struct IORingSocketTests {
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Creates a listening socket on the loopback interface.
|
||||
@available(System 199, *)
|
||||
private func makeListener() throws -> (SocketDescriptor, SocketAddress) {
|
||||
let listener = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
try listener.bind(to: SocketAddress(ipv4: .loopback(port: 0)))
|
||||
try listener.listen(backlog: 8)
|
||||
var address = SocketAddress()
|
||||
try listener.getLocalAddress(into: &address)
|
||||
return (listener, address)
|
||||
}
|
||||
|
||||
/// Creates a connected pair of sockets on the loopback interface.
|
||||
@available(System 199, *)
|
||||
private func makeConnectedPair() throws -> (client: SocketDescriptor, server: SocketDescriptor) {
|
||||
let (listener, address) = try makeListener()
|
||||
defer { try? listener.close() }
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
try client.connect(to: address)
|
||||
let server = try listener.accept()
|
||||
return (client, server)
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: socketSupported))
|
||||
func socketCreatesSocket() throws {
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests:
|
||||
.socket(.ipv4, .stream, protocol: .tcp, flags: .closeOnExec, context: 1)
|
||||
)
|
||||
#expect(submitted)
|
||||
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 1)
|
||||
#expect(completion.error == nil)
|
||||
|
||||
let socket = SocketDescriptor(rawValue: completion.result)
|
||||
defer { try? socket.close() }
|
||||
#expect(fcntl(socket.rawValue, F_GETFD) & FD_CLOEXEC != 0)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: bindAndListenSupported))
|
||||
func bindAndListen() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests:
|
||||
.bind(socket, to: SocketAddress(ipv4: .loopback(port: 0)), context: 1),
|
||||
.listen(socket, backlog: 8, context: 2)
|
||||
)
|
||||
#expect(submitted)
|
||||
let results = try consumeResults(2, from: ring)
|
||||
#expect(results[1] == 0)
|
||||
#expect(results[2] == 0)
|
||||
|
||||
// A client can connect, so the socket is listening.
|
||||
var address = SocketAddress()
|
||||
try socket.getLocalAddress(into: &address)
|
||||
#expect(address.ipv4?.port != 0)
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
try client.connect(to: address)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: shutdownSupported))
|
||||
func acceptConnectSendReceiveAndShutdown() throws {
|
||||
let (listener, address) = try makeListener()
|
||||
defer { try? listener.close() }
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
var ring = try IORing(queueDepth: 8)
|
||||
let acceptPrepared = ring.prepare(request: .accept(listener, flags: .closeOnExec, context: 1))
|
||||
#expect(acceptPrepared)
|
||||
let connectPrepared = ring.prepare(request: .connect(client, to: address, context: 2))
|
||||
#expect(connectPrepared)
|
||||
try ring.submitPreparedRequests()
|
||||
let connected = try consumeResults(2, from: ring)
|
||||
#expect(connected[2] == 0)
|
||||
let acceptedFD = try #require(connected[1])
|
||||
#expect(acceptedFD >= 0)
|
||||
let server = SocketDescriptor(rawValue: acceptedFD)
|
||||
defer { try? server.close() }
|
||||
|
||||
let message: [UInt8] = Array("Hello, io_uring!".utf8)
|
||||
var received = [UInt8](repeating: 0, count: 64)
|
||||
let exchanged = try message.withUnsafeBytes { sendBuffer in
|
||||
try received.withUnsafeMutableBytes { receiveBuffer in
|
||||
let sendPrepared = ring.prepare(request: .send(sendBuffer, to: client, context: 3))
|
||||
#expect(sendPrepared)
|
||||
let receivePrepared = ring.prepare(request: .receive(server, into: receiveBuffer, context: 4))
|
||||
#expect(receivePrepared)
|
||||
try ring.submitPreparedRequests()
|
||||
return try consumeResults(2, from: ring)
|
||||
}
|
||||
}
|
||||
#expect(exchanged[3] == Int32(message.count))
|
||||
#expect(exchanged[4] == Int32(message.count))
|
||||
#expect(Array(received.prefix(message.count)) == message)
|
||||
|
||||
// Once the client shuts down writing, the server reads the end of the stream.
|
||||
let endOfStream = try received.withUnsafeMutableBytes { receiveBuffer in
|
||||
let shutdownSubmitted = try ring.submit(linkedRequests: .shutdown(client, .write, context: 5))
|
||||
#expect(shutdownSubmitted)
|
||||
let receiveSubmitted = try ring.submit(linkedRequests: .receive(server, into: receiveBuffer, context: 6))
|
||||
#expect(receiveSubmitted)
|
||||
return try consumeResults(2, from: ring)
|
||||
}
|
||||
#expect(endOfStream[5] == 0)
|
||||
#expect(endOfStream[6] == 0)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func acceptWritesPeerAddress() throws {
|
||||
let (listener, address) = try makeListener()
|
||||
defer { try? listener.close() }
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
// The kernel writes the peer's address when the accept completes, so both
|
||||
// pointers have to stay valid until the completion is consumed.
|
||||
var peerStorage = sockaddr_storage()
|
||||
var peerLength = CInterop.SockLen(MemoryLayout<sockaddr_storage>.size)
|
||||
let acceptedFD = try withUnsafeMutablePointer(to: &peerLength) { peerAddressLength in
|
||||
try withUnsafeMutablePointer(to: &peerStorage) { storage in
|
||||
try storage.withMemoryRebound(to: CInterop.SockAddr.self, capacity: 1) { peerAddress in
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests: .accept(
|
||||
listener, peerAddress: peerAddress, peerAddressLength: peerAddressLength, context: 1
|
||||
))
|
||||
#expect(submitted)
|
||||
try client.connect(to: address)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 1)
|
||||
return completion.result
|
||||
}
|
||||
}
|
||||
}
|
||||
#expect(acceptedFD >= 0)
|
||||
try? SocketDescriptor(rawValue: acceptedFD).close()
|
||||
|
||||
var clientAddress = SocketAddress()
|
||||
try client.getLocalAddress(into: &clientAddress)
|
||||
let peer = withUnsafePointer(to: &peerStorage) { storage in
|
||||
storage.withMemoryRebound(to: CInterop.SockAddr.self, capacity: 1) {
|
||||
SocketAddress(address: $0, length: peerLength)
|
||||
}
|
||||
}
|
||||
#expect(peer.ipv4?.port == clientAddress.ipv4?.port)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func sendDoesNotRaiseSigpipe() throws {
|
||||
let (client, server) = try makeConnectedPair()
|
||||
defer {
|
||||
try? client.close()
|
||||
try? server.close()
|
||||
}
|
||||
// Writing to a socket that is shut down for writing raises `SIGPIPE`. A
|
||||
// send request doesn't, since io_uring sets `MSG_NOSIGNAL` for it, even
|
||||
// without passing `.noSignal`.
|
||||
try client.shutdown(.write)
|
||||
|
||||
// The test process might ignore `SIGPIPE`, which would hide it. Blocking
|
||||
// it on this thread keeps a raised `SIGPIPE` pending, so we can check
|
||||
// for it. The send fails right away, so it runs on this thread.
|
||||
var sigpipe = sigset_t()
|
||||
sigemptyset(&sigpipe)
|
||||
sigaddset(&sigpipe, SIGPIPE)
|
||||
var previousMask = sigset_t()
|
||||
pthread_sigmask(SIG_BLOCK, &sigpipe, &previousMask)
|
||||
defer {
|
||||
// Consume a pending `SIGPIPE` so that it isn't delivered once unblocked.
|
||||
var noWait = timespec()
|
||||
while sigtimedwait(&sigpipe, nil, &noWait) == SIGPIPE {}
|
||||
pthread_sigmask(SIG_SETMASK, &previousMask, nil)
|
||||
}
|
||||
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let message: [UInt8] = [1, 2, 3]
|
||||
let results = try message.withUnsafeBytes { buffer in
|
||||
let submitted = try ring.submit(linkedRequests: .send(buffer, to: client, context: 1))
|
||||
#expect(submitted)
|
||||
return try consumeResults(1, from: ring)
|
||||
}
|
||||
#expect(results[1] == -Errno.brokenPipe.rawValue)
|
||||
|
||||
var pending = sigset_t()
|
||||
sigpending(&pending)
|
||||
#expect(sigismember(&pending, SIGPIPE) == 0, "the send raised SIGPIPE")
|
||||
}
|
||||
|
||||
// An IPv6 address is longer than an IPv4 one, so this checks that connect
|
||||
// passes the length of the given address.
|
||||
@available(System 199, *)
|
||||
@Test(.enabled(if: ipv6LoopbackAvailable))
|
||||
func connectOverIPv6() throws {
|
||||
let listener = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
defer { try? listener.close() }
|
||||
try listener.bind(to: SocketAddress(ipv6: .loopback(port: 0)))
|
||||
try listener.listen(backlog: 8)
|
||||
var address = SocketAddress()
|
||||
try listener.getLocalAddress(into: &address)
|
||||
|
||||
let client = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests: .connect(client, to: address, context: 1))
|
||||
#expect(submitted)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 1)
|
||||
// Accepting blocks, so it only runs once the client is connected.
|
||||
try #require(completion.error == nil)
|
||||
|
||||
let server = try listener.accept()
|
||||
try server.close()
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func connectToClosedPortFails() throws {
|
||||
// Bind a socket to get a free port, then close it so nothing listens there.
|
||||
let (listener, address) = try makeListener()
|
||||
try listener.close()
|
||||
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let submitted = try ring.submit(linkedRequests: .connect(client, to: address, context: 7))
|
||||
#expect(submitted)
|
||||
let completion = try ring.blockingConsumeCompletion(timeout: .seconds(5))
|
||||
#expect(completion.context == 7)
|
||||
#expect(completion.error == .connectionRefused)
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -1,197 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
@Suite("Socket Addresses")
|
||||
private struct SocketAddressTests {
|
||||
|
||||
// MARK: - IPv4 Address Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4BasicCreation() {
|
||||
let addr = IPv4Address("127.0.0.1", port: 8080)
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.port == 8080)
|
||||
#expect(addr?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4InvalidAddress() {
|
||||
let addr = IPv4Address("not.an.ip.address", port: 8080)
|
||||
#expect(addr == nil)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Any() {
|
||||
let addr = IPv4Address.any(port: 0)
|
||||
#expect(addr.port == 0)
|
||||
#expect(addr.addressString == "0.0.0.0")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Loopback() {
|
||||
let addr = IPv4Address.loopback(port: 80)
|
||||
#expect(addr.port == 80)
|
||||
#expect(addr.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4StringLiteral() {
|
||||
let addr: IPv4Address = "192.168.1.1:443"
|
||||
#expect(addr.port == 443)
|
||||
#expect(addr.addressString == "192.168.1.1")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Equality() {
|
||||
let addr1 = IPv4Address("10.0.0.1", port: 8080)!
|
||||
let addr2 = IPv4Address("10.0.0.1", port: 8080)!
|
||||
let addr3 = IPv4Address("10.0.0.2", port: 8080)!
|
||||
let addr4 = IPv4Address("10.0.0.1", port: 9090)!
|
||||
|
||||
#expect(addr1 == addr2)
|
||||
#expect(addr1 != addr3)
|
||||
#expect(addr1 != addr4)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv4Description() {
|
||||
let addr = IPv4Address("8.8.8.8", port: 53)!
|
||||
#expect(addr.description == "8.8.8.8:53")
|
||||
}
|
||||
|
||||
// MARK: - IPv6 Address Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv6BasicCreation() {
|
||||
let addr = IPv6Address("::1", port: 8080)
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.port == 8080)
|
||||
#expect(addr?.addressString == "::1")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv6InvalidAddress() {
|
||||
let addr = IPv6Address("not:an:ipv6:address", port: 8080)
|
||||
#expect(addr == nil)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv6Any() {
|
||||
let addr = IPv6Address.any(port: 0)
|
||||
#expect(addr.port == 0)
|
||||
#expect(addr.addressString == "::")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv6Loopback() {
|
||||
let addr = IPv6Address.loopback(port: 80)
|
||||
#expect(addr.port == 80)
|
||||
#expect(addr.addressString == "::1")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv6Description() {
|
||||
let addr = IPv6Address("2001:db8::1", port: 443)!
|
||||
#expect(addr.description == "[2001:db8::1]:443")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func ipv6StringLiteral() {
|
||||
let addr: IPv6Address = "[::1]:8080"
|
||||
#expect(addr.port == 8080)
|
||||
#expect(addr.addressString == "::1")
|
||||
}
|
||||
|
||||
// MARK: - Unix Address Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func unixBasicCreation() {
|
||||
let addr = UnixAddress("/tmp/test.sock")
|
||||
#expect(addr != nil)
|
||||
#expect(addr?.path == "/tmp/test.sock")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func unixDescription() {
|
||||
let addr = UnixAddress("/var/run/daemon.sock")!
|
||||
#expect(addr.description == "/var/run/daemon.sock")
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func unixEquality() {
|
||||
let addr1 = UnixAddress("/tmp/a.sock")!
|
||||
let addr2 = UnixAddress("/tmp/a.sock")!
|
||||
let addr3 = UnixAddress("/tmp/b.sock")!
|
||||
|
||||
#expect(addr1 == addr2)
|
||||
#expect(addr1 != addr3)
|
||||
}
|
||||
|
||||
// MARK: - SocketAddress Container Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func socketAddressFromIPv4() {
|
||||
let ipv4 = IPv4Address.loopback(port: 8080)
|
||||
let sockAddr = SocketAddress(ipv4: ipv4)
|
||||
|
||||
#expect(sockAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
#expect(sockAddr.ipv4 != nil)
|
||||
#expect(sockAddr.ipv4?.port == 8080)
|
||||
#expect(sockAddr.ipv6 == nil)
|
||||
#expect(sockAddr.unix == nil)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func socketAddressFromIPv6() {
|
||||
let ipv6 = IPv6Address.loopback(port: 443)
|
||||
let sockAddr = SocketAddress(ipv6: ipv6)
|
||||
|
||||
#expect(sockAddr.family == SocketDescriptor.Domain.ipv6)
|
||||
#expect(sockAddr.ipv6 != nil)
|
||||
#expect(sockAddr.ipv6?.port == 443)
|
||||
#expect(sockAddr.ipv4 == nil)
|
||||
#expect(sockAddr.unix == nil)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func socketAddressFromUnix() {
|
||||
let unix = UnixAddress("/tmp/test.sock")!
|
||||
let sockAddr = SocketAddress(unix: unix)
|
||||
|
||||
#expect(sockAddr.family == SocketDescriptor.Domain.local)
|
||||
#expect(sockAddr.unix != nil)
|
||||
#expect(sockAddr.unix?.path == "/tmp/test.sock")
|
||||
#expect(sockAddr.ipv4 == nil)
|
||||
#expect(sockAddr.ipv6 == nil)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
@Suite("Socket Descriptor")
|
||||
private struct SocketDescriptorTests {
|
||||
|
||||
// MARK: - Type Tests
|
||||
|
||||
@Test func domainValues() {
|
||||
#expect(SocketDescriptor.Domain.ipv4.rawValue == AF_INET)
|
||||
#expect(SocketDescriptor.Domain.ipv6.rawValue == AF_INET6)
|
||||
#expect(SocketDescriptor.Domain.local.rawValue == AF_UNIX)
|
||||
}
|
||||
|
||||
@Test func connectionTypeValues() {
|
||||
// Glibc imports the socket types as a C enum.
|
||||
#if canImport(Glibc)
|
||||
#expect(SocketDescriptor.ConnectionType.stream.rawValue == CInt(SOCK_STREAM.rawValue))
|
||||
#expect(SocketDescriptor.ConnectionType.datagram.rawValue == CInt(SOCK_DGRAM.rawValue))
|
||||
#else
|
||||
#expect(SocketDescriptor.ConnectionType.stream.rawValue == SOCK_STREAM)
|
||||
#expect(SocketDescriptor.ConnectionType.datagram.rawValue == SOCK_DGRAM)
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
@Test func socketFlagsValues() {
|
||||
#if canImport(Glibc)
|
||||
#expect(SocketDescriptor.SocketFlags.closeOnExec.rawValue == CInt(SOCK_CLOEXEC.rawValue))
|
||||
#expect(SocketDescriptor.SocketFlags.nonBlocking.rawValue == CInt(SOCK_NONBLOCK.rawValue))
|
||||
#else
|
||||
#expect(SocketDescriptor.SocketFlags.closeOnExec.rawValue == SOCK_CLOEXEC)
|
||||
#expect(SocketDescriptor.SocketFlags.nonBlocking.rawValue == SOCK_NONBLOCK)
|
||||
#endif
|
||||
#expect(
|
||||
"\(SocketDescriptor.SocketFlags([.closeOnExec, .nonBlocking]))" == "[.closeOnExec, .nonBlocking]"
|
||||
)
|
||||
}
|
||||
#endif
|
||||
|
||||
@Test func protocolValues() {
|
||||
#expect(SocketDescriptor.ProtocolID.tcp.rawValue == CInt(IPPROTO_TCP))
|
||||
#expect(SocketDescriptor.ProtocolID.udp.rawValue == CInt(IPPROTO_UDP))
|
||||
}
|
||||
|
||||
// MARK: - Socket Creation Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func createTCPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func createUDPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func createIPv6TCPSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func createUnixSocket() throws {
|
||||
let socket = try SocketDescriptor.open(.local, .stream)
|
||||
#expect(socket.rawValue >= 0)
|
||||
try socket.close()
|
||||
}
|
||||
|
||||
// MARK: - Shutdown Tests
|
||||
|
||||
@Test func shutdownKindValues() {
|
||||
#expect(SocketDescriptor.ShutdownKind.read.rawValue == SHUT_RD)
|
||||
#expect(SocketDescriptor.ShutdownKind.write.rawValue == SHUT_WR)
|
||||
#expect(SocketDescriptor.ShutdownKind.readWrite.rawValue == SHUT_RDWR)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,228 +0,0 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if !os(Windows)
|
||||
|
||||
import Testing
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
@testable import SystemSockets
|
||||
import SystemPackage
|
||||
|
||||
@Suite("Socket Operations")
|
||||
private struct SocketOperationsTests {
|
||||
|
||||
// MARK: - Bind Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func bindToAnyPort() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let address = SocketAddress(ipv4: IPv4Address.any(port: 0))
|
||||
try socket.bind(to: address)
|
||||
|
||||
// Verify we can get the local address after binding
|
||||
var localAddr = SocketAddress()
|
||||
try socket.getLocalAddress(into: &localAddr)
|
||||
#expect(localAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
#expect(localAddr.ipv4?.port != 0) // Port should be assigned
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func bindToLoopback() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let address = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try socket.bind(to: address)
|
||||
|
||||
var localAddr = SocketAddress()
|
||||
try socket.getLocalAddress(into: &localAddr)
|
||||
#expect(localAddr.ipv4?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
// MARK: - Listen Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func listenWithDefaultBacklog() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let address = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try socket.bind(to: address)
|
||||
try socket.listen(backlog: 5)
|
||||
}
|
||||
|
||||
// MARK: - Connect and Accept Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func tcpConnectAndAccept() throws {
|
||||
// Create server socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? server.close() }
|
||||
|
||||
let serverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try server.bind(to: serverAddr)
|
||||
try server.listen(backlog: 1)
|
||||
|
||||
// Get the actual port
|
||||
var boundAddr = SocketAddress()
|
||||
try server.getLocalAddress(into: &boundAddr)
|
||||
let port = boundAddr.ipv4!.port
|
||||
|
||||
// Create client socket and connect
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
let connectAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
|
||||
try client.connect(to: connectAddr)
|
||||
|
||||
// Accept connection
|
||||
var peerAddr = SocketAddress()
|
||||
let acceptedSocket = try server.accept(client: &peerAddr)
|
||||
defer { try? acceptedSocket.close() }
|
||||
|
||||
#expect(peerAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
#expect(peerAddr.ipv4?.addressString == "127.0.0.1")
|
||||
}
|
||||
|
||||
// MARK: - Send and Receive Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func tcpSendReceive() throws {
|
||||
// Create server socket
|
||||
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? server.close() }
|
||||
|
||||
let serverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try server.bind(to: serverAddr)
|
||||
try server.listen(backlog: 1)
|
||||
|
||||
var boundAddr = SocketAddress()
|
||||
try server.getLocalAddress(into: &boundAddr)
|
||||
let port = boundAddr.ipv4!.port
|
||||
|
||||
// Create client socket and connect
|
||||
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? client.close() }
|
||||
|
||||
let connectAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
|
||||
try client.connect(to: connectAddr)
|
||||
|
||||
// Accept connection
|
||||
let acceptedSocket = try server.accept()
|
||||
defer { try? acceptedSocket.close() }
|
||||
|
||||
// Send data from client
|
||||
let message = "Hello, World!"
|
||||
let messageBytes = Array(message.utf8)
|
||||
let sent = try messageBytes.withUnsafeBytes { buffer in
|
||||
try client.send(UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
#expect(sent == messageBytes.count)
|
||||
|
||||
// Receive data on server
|
||||
var buffer = [UInt8](repeating: 0, count: 1024)
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try acceptedSocket.receive(into: buffer)
|
||||
}
|
||||
#expect(received == messageBytes.count)
|
||||
|
||||
let receivedMessage = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
#expect(receivedMessage == message)
|
||||
}
|
||||
|
||||
// MARK: - UDP Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func udpSendReceive() throws {
|
||||
// Create receiver socket
|
||||
let receiver = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
defer { try? receiver.close() }
|
||||
|
||||
let receiverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
|
||||
try receiver.bind(to: receiverAddr)
|
||||
|
||||
var boundAddr = SocketAddress()
|
||||
try receiver.getLocalAddress(into: &boundAddr)
|
||||
let port = boundAddr.ipv4!.port
|
||||
|
||||
// Create sender socket
|
||||
let sender = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
|
||||
defer { try? sender.close() }
|
||||
|
||||
// Send datagram
|
||||
let message = "UDP Message"
|
||||
let messageBytes = Array(message.utf8)
|
||||
let targetAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
|
||||
let sent = try messageBytes.withUnsafeBytes { buffer in
|
||||
try sender.send(UnsafeRawBufferPointer(buffer), to: targetAddr)
|
||||
}
|
||||
#expect(sent == messageBytes.count)
|
||||
|
||||
// Receive datagram
|
||||
var buffer = [UInt8](repeating: 0, count: 1024)
|
||||
var fromAddr = SocketAddress()
|
||||
let received = try buffer.withUnsafeMutableBytes { buffer in
|
||||
try receiver.receive(into: buffer, sender: &fromAddr)
|
||||
}
|
||||
#expect(received == messageBytes.count)
|
||||
#expect(fromAddr.family == SocketDescriptor.Domain.ipv4)
|
||||
|
||||
let receivedMessage = String(decoding: buffer.prefix(received), as: UTF8.self)
|
||||
#expect(receivedMessage == message)
|
||||
}
|
||||
|
||||
// MARK: - Socket Options Tests
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func setReuseAddress() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
try socket.setReuseAddress(true)
|
||||
let value = try socket.getSocketOption(SocketDescriptor.SocketOption.reuseAddress)
|
||||
#expect(value != 0)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func getSendBufferSize() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let size = try socket.getSocketOption(SocketDescriptor.SocketOption.sendBufferSize)
|
||||
#expect(size > 0)
|
||||
}
|
||||
|
||||
@available(System 199, *)
|
||||
@Test func getReceiveBufferSize() throws {
|
||||
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
|
||||
defer { try? socket.close() }
|
||||
|
||||
let size = try socket.getSocketOption(SocketDescriptor.SocketOption.receiveBufferSize)
|
||||
#expect(size > 0)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 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
|
||||
}
|
||||
@@ -179,11 +179,12 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
|
||||
func testAdHocPipeWithOptions() throws {
|
||||
#if !SYSTEM_PACKAGE_DARWIN || canImport(Darwin, _version: 428)
|
||||
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`.
|
||||
// Ad-hoc test: `MockTestCase` can't match the pointer to the local array
|
||||
// that `pipe` receives, because its address isn't known in advance.
|
||||
let options: FileDescriptor.PipeOptions = [.closeOnExec]
|
||||
let pipe: (readEnd: FileDescriptor, writeEnd: FileDescriptor)
|
||||
pipe = try FileDescriptor.pipe(options: options)
|
||||
@@ -194,12 +195,52 @@ final class FileOperationsTest: XCTestCase {
|
||||
_ = try pipe.writeEnd.write(UnsafeRawBufferPointer($0))
|
||||
}
|
||||
let readLen = 3
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { buf, count in
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) {
|
||||
buf, count in
|
||||
count = try pipe.readEnd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
XCTAssertEqual(readBytes, Array(abc.utf8))
|
||||
}
|
||||
}
|
||||
#else
|
||||
throw XCTSkip("pipe2 requires a Darwin SDK for anyAppleOS 27 or newer")
|
||||
#endif
|
||||
}
|
||||
|
||||
func testAdHocPipeCloseOnFork() throws {
|
||||
#if canImport(Darwin, _version: 428)
|
||||
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 {
|
||||
let flags = fcntl(pipe.readEnd.rawValue, F_GETFD)
|
||||
XCTAssertEqual(flags & FD_CLOFORK, FD_CLOFORK)
|
||||
}
|
||||
}
|
||||
#elseif os(FreeBSD)
|
||||
let pipe: (readEnd: FileDescriptor, writeEnd: FileDescriptor)
|
||||
do {
|
||||
pipe = try FileDescriptor.pipe(options: .closeOnFork)
|
||||
} catch {
|
||||
if (error as? Errno) == .invalidArgument {
|
||||
throw XCTSkip("pipe2 does not support O_CLOFORK before FreeBSD 15")
|
||||
}
|
||||
throw error
|
||||
}
|
||||
try pipe.readEnd.closeAfter {
|
||||
try pipe.writeEnd.closeAfter {
|
||||
let flags = fcntl(pipe.readEnd.rawValue, F_GETFD)
|
||||
XCTAssertEqual(flags & FD_CLOEXEC, 0)
|
||||
XCTAssertNotEqual(flags, 0)
|
||||
}
|
||||
}
|
||||
#else
|
||||
throw XCTSkip("O_CLOFORK requires a Darwin SDK for anyAppleOS 27 or newer")
|
||||
#endif
|
||||
}
|
||||
#endif // !os(WASI)
|
||||
|
||||
@@ -242,6 +283,7 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
|
||||
func testAdHocDuplicate3() throws {
|
||||
#if !SYSTEM_PACKAGE_DARWIN || canImport(Darwin, _version: 428)
|
||||
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")
|
||||
}
|
||||
@@ -276,6 +318,9 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
throw XCTSkip("dup3 requires a Darwin SDK for anyAppleOS 27 or newer")
|
||||
#endif
|
||||
}
|
||||
#endif // !os(Windows)
|
||||
|
||||
|
||||
@@ -20,9 +20,20 @@ import XCTest
|
||||
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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,15 +16,6 @@ import XCTest
|
||||
#endif
|
||||
|
||||
final class TemporaryPathTest: XCTestCase {
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
func testNotInSlashTmp() throws {
|
||||
try withTemporaryFilePath(basename: "NotInSlashTmp") { path in
|
||||
// We shouldn't be using "/tmp" on Darwin
|
||||
XCTAssertNotEqual(path.components.first!, "tmp")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testUnique() throws {
|
||||
try withTemporaryFilePath(basename: "test") { path in
|
||||
let strPath = String(decoding: path)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
#if os(Linux)
|
||||
|
||||
import XCTest
|
||||
import CSystem //for eventfd
|
||||
import CSystem // for eventfd and csystem_io_uring_setup
|
||||
import CSystemIOUring
|
||||
#if canImport(Glibc)
|
||||
import Glibc // for errno
|
||||
#elseif canImport(Musl)
|
||||
@@ -30,7 +31,7 @@ let failureMessage = "Runtime environment does not support IORing."
|
||||
func isUringEnabled() throws -> Bool {
|
||||
// Even if the kernel supports io_uring, the SystemPackage build may have
|
||||
// been compiled against older kernel headers that lack features it needs
|
||||
// (gated on IORING_TIMEOUT_BOOTTIME in CSystem); in that configuration
|
||||
// (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) {
|
||||
@@ -61,7 +62,7 @@ func isUringEnabled() throws -> Bool {
|
||||
// - EPERM or EACCES -> treat as disabled
|
||||
// - propagate any other error.
|
||||
var params = io_uring_params()
|
||||
let raw = io_uring_setup(1, ¶ms)
|
||||
let raw = csystem_io_uring_setup(1, ¶ms)
|
||||
if raw < 0 {
|
||||
let err = Errno(rawValue: errno)
|
||||
switch err {
|
||||
@@ -125,6 +126,30 @@ 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 {
|
||||
try XCTSkipIf(!uringEnabled, failureMessage)
|
||||
var ring: IORing = try IORing(queueDepth: 1)
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user