Compare commits

..
Author SHA1 Message Date
Guillaume Lessard 9899bcd558 add some more availability annotations 2026-01-26 14:53:30 -08:00
Guillaume Lessard 1f5b29b866 better names for Availability computed properties 2026-01-26 09:04:30 -08:00
Guillaume Lessard 25a67eab0c extra tweaks 2026-01-23 18:50:31 -08:00
Guillaume Lessard 0f949fecf3 Availability macro support for back-deployed Span 2026-01-23 18:38:58 -08:00
Michael Ilseman 81fded4dd9 [staging] Add Span-based file I/O APIs (#290)
* Add Span-based file I/O APIs

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

* wip: cleanup

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

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

Original Co-authored-by: Karoy Lorentey <karoly@apple.com>
2026-01-09 21:25:40 -07:00
66 changed files with 5799 additions and 1857 deletions

No files matched your search

+8 -7
View File
@@ -10,7 +10,7 @@ on:
jobs:
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
enable_linux_checks: true
@@ -19,7 +19,6 @@ jobs:
[
{"swift_version": "5.9"},
{"swift_version": "5.10"},
{"swift_version": "6.0"},
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
@@ -32,8 +31,7 @@ jobs:
windows_exclude_swift_versions: |
[
{"swift_version": "5.9"},
{"swift_version": "5.10"},
{"swift_version": "6.0"},
{"swift_version": "5.10"}
]
enable_linux_static_sdk_build: true
linux_static_sdk_exclude_swift_versions: |
@@ -54,11 +52,14 @@ jobs:
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_android_sdk_build: true
enable_android_sdk_checks: true
android_exclude_swift_versions: |
[
{"os_version": "focal", "swift_version": "nightly-main"},
]
build-abi-stable:
name: Build ABI Stable
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
enable_linux_checks: false
enable_macos_checks: true
@@ -71,7 +72,7 @@ jobs:
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "Swift.org"
# https://github.com/apple/swift-system/issues/224
+1
View File
@@ -7,3 +7,4 @@ xcuserdata/
.*.sw?
/.swiftpm
.docc-build
Package.resolved
+67 -55
View File
@@ -1,9 +1,9 @@
// swift-tools-version:6.1
// swift-tools-version:6.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
// 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
@@ -12,63 +12,57 @@
import PackageDescription
struct Available {
struct Availability {
var name: String
var version: String
var osAvailability: String
var sourceAvailability: String
init(
_ version: String,
_ osAvailability: String
) {
self.name = "System"
self.version = version
self.osAvailability = osAvailability
self.sourceAvailability = "macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0"
var minSwiftPMVersions: String {
"macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0"
}
var minSpanDeploymentVersions: String {
"macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0"
}
var swiftSetting: SwiftSetting {
#if SYSTEM_ABI_STABLE
// Use availability matching Darwin API.
let availability = self.osAvailability
#else
// Use availability matching SwiftPM default.
let availability = self.sourceAvailability
#endif
return .enableExperimentalFeature(
"AvailabilityMacro=\(self.name) \(version):\(availability)")
}
var isStandardAvailability: Bool { name == "System" }
}
let availability: [Available] = [
Available("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
let availabilityMap: [(String, String)] = [
("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
("0.0.2", "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0"),
("1.1.0", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
("1.2.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("0.0.2", "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0"),
Available("0.0.3", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
Available("1.1.0", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
Available("1.1.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.2.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.2.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.3.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.3.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("1.3.2", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("1.4.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.4.2", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.5.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.6.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.6.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("99", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
("99", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
]
let swiftSettingsAvailability = availability.map(\.swiftSetting)
let availabilities: [Availability] =
availabilityMap.map {
Availability(name: "System", version: $0.0, osAvailability: $0.1)
} + availabilityMap.prefix(5).map {
Availability(name: "SystemWithSpan", version: $0.0, osAvailability: $0.1)
}
let swiftSettingsAvailability = availabilities.map {
availability -> SwiftSetting in
let osVersionList: String
#if SYSTEM_ABI_STABLE
// Use availability matching Darwin API.
osVersionList = availability.osAvailability
#else
if availability.isStandardAvailability {
// Use availability matching SwiftPM minimum.
osVersionList = availability.minSwiftPMVersions
} else {
// Use availability matching Span deployment minimum.
osVersionList = availability.minSpanDeploymentVersions
}
#endif
return .enableExperimentalFeature(
"AvailabilityMacro=\(availability.name) \(availability.version):\(osVersionList)"
)
}
#if SYSTEM_CI
let swiftSettingsCI: [SwiftSetting] = [
@@ -120,8 +114,12 @@ 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",
@@ -141,12 +139,26 @@ let package = Package(
exclude: testsToExclude,
cSettings: cSettings,
swiftSettings: swiftSettings),
// Builds a SystemPackage consumer with MemberImportVisibility enabled.
// Fails if a C member of a vended type is attributed to the CSystem module.
.target(
name: "SystemSockets",
dependencies: ["SystemPackage", "CSystem"],
path: "Sources/SystemSockets",
cSettings: cSettings,
swiftSettings: swiftSettings),
.testTarget(
name: "MemberImportVisibility",
dependencies: ["SystemPackage"],
swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]),
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: [.v5]
swiftLanguageVersions: [.v5]
)
+1 -1
View File
@@ -417,7 +417,7 @@ public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
### Stat
`Stat` can be initialized from a `FilePath`, `UnsafePointer<CChar>`, or `FileDescriptor`. This proposal also includes functions on `FileDescriptor` and `FilePath` for creating a `Stat` object, seen in the section below.
`Stat` can be initialized from a `FilePath`, `UnsafePointer<CChar>`, or `FileDescriptor`. This proposal also includes functions on `FileDescriptor` and `FilePath` for creating a `Stat` object, seen in the section below.
The initializer accepting a `FileDescriptor` corresponds to `fstat()`. If the file descriptor points to a symlink, this will return information about the symlink itself.
-182
View File
@@ -1,182 +0,0 @@
# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor`
* Proposal: SYS-0007
- Author(s): Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
* Other Reviews: [Swift Forums Pitch](https://forums.swift.org/t/82486)
##### Revision history
* **v1** Initial version
- **v2** Add Windows version of `pipe(options:)`
## Introduction
Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively.
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD and Android.
## Motivation
It is considered best practice to set the `O_CLOEXEC` (close-on-exec) bit on newly created file descriptors to prevent them from being inherited by subprocesses.
Some POSIX functions such as `open` provide a "flags" parameter allowing this the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`.
POSIX 2024 corrects this deficiency for `dup2` and `pipe` by introducing `dup3` and `pipe2` variants that allow the close-on-exec bit to be set atomically.
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defence in depth with respect to opened file descriptors.
## Proposed solution
This proposal adds new overloads to `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` that will wrap the functionality of the `dup3` and `pipe2` functions.
## Example usage
```swift
import System
let fd0 = try FileDescriptor.open("/tmp/test.txt", .readOnly)
let fd1 = FileDescriptor(rawValue: 731)
let fd2 = fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec])
```
## Detailed design
`FileDescriptor` will add the following overloads and types:
```swift
struct FileDescriptor {
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
///
/// - Parameters:
/// - options: The behavior for creating the pipe.
///
/// - Returns: The pair of file descriptors.
///
/// The corresponding C function is `pipe2`.
public static func pipe(
options: PipeOptions
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor)
/// Duplicate this file descriptor and return the newly created copy.
///
/// - Parameters:
/// - target: The desired target file descriptor.
/// - options: The behavior for creating the target file descriptor.
/// - retryOnInterrupt: Whether to retry the operation
/// if it throws ``Errno/interrupted``. The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The new file descriptor.
///
/// If the `target` descriptor is already in use, then it is first
/// deallocated as if a close(2) call had been done first.
///
/// File descriptors are merely references to some underlying system resource.
/// The system does not distinguish between the original and the new file
/// descriptor in any way. For example, read, write and seek operations on
/// one of them also affect the logical file position in the other, and
/// append mode, non-blocking I/O and asynchronous I/O options are shared
/// between the references. If a separate pointer into the file is desired,
/// a different object reference to the file must be obtained by issuing an
/// additional call to `open`.
///
/// However, each file descriptor maintains its own close-on-exec and
/// close-on-fork flags.
///
/// The corresponding C function is `dup3`.
@discardableResult
public func duplicate(
as target: FileDescriptor,
options: DuplicateOptions,
retryOnInterrupt: Bool = true
) throws(Errno) -> FileDescriptor
/// Options that specify behavior for a newly-created pipe.
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
public init(rawValue: CInt)
/// Indicates that all subsequent input and output operations
/// on the pipe's file descriptors will be nonblocking.
///
/// The corresponding C constant is `O_NONBLOCK`.
public static var nonBlocking: PipeOptions
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `exec(2)`
/// family of functions. If you specify this option, the system closes the
/// file descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
public static var closeOnExec: PipeOptions
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `fork(2)`
/// function. If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
public static var closeOnFork: PipeOptions
}
/// Options that specify behavior for a duplicated file descriptor.
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
public init(rawValue: CInt)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `exec(2)`
/// family of functions. If you specify this option, the system closes the
/// file descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
public static var closeOnExec: DuplicateOptions
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open across calls to the `fork(2)`
/// function. If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
public static var closeOnFork: DuplicateOptions
}
}
```
These API additions are unavailable on Darwin, as the underlying `dup3` and `pipe2` APIs do not exist.
`pipe(options:)` is added for Windows with the option `.closeOnExec`, but `duplicate(as:options:)` is not added because the underlying API does not match `dup3`.
`closeOnFork` is unavailable on Linux and Android, as the underlying `O_CLOFORK` constant does not exist.
## Impact on existing code
This change will have no impact on existing code, as it is purely additive.
## Alternatives considered
None. The underlying POSIX API are additions that help C developers follow best practices, and these overloads provide the same value to Swift developers.
-262
View File
@@ -1,262 +0,0 @@
# Back-Deploy CInterop.stat for Migration Compatibility
* Proposal: SYS-0008
* Author: [Jonathan Flat](https://github.com/jrflat)
* Status: **Awaiting review**
* Implementation: [apple/swift-system#299](https://github.com/apple/swift-system/pull/299)
* Review: ([pitch](https://forums.swift.org/t/pitch-back-deploy-system-cinterop-stat-for-migration-compatibility/84930))
#### Revision history
* **v1** Initial version
* **v2** Clarify that `CInterop.stat(_:_:)` is a new function
* **v3** Explain why this proposal should not set a precedence for future System APIs
## Introduction
This proposal introduces `CInterop.stat(_:_:)` and back-deploys the `CInterop.Stat` typealias from System to make them available on older OS versions, enabling a migration path for clients who may encounter naming conflicts with `FilePath.stat()` or `FileDescriptor.stat()` when System's new `Stat` API ships.
## Motivation
The introduction of `FilePath.stat()` and `FileDescriptor.stat()` in [SYS-0006](0006-system-stat.md) creates a potential source compatibility issue for a small number of clients. While we estimate this affects an exceedingly rare set of developers (1 case found in public GitHub repositories), we want to provide a clear migration path.
### Compatibility scenario
Some clients may have extended `FilePath` or `FileDescriptor` with custom functions that use `Darwin.stat()` and `Darwin.stat(_:_:)` **without** the `Darwin.` (or other libc) module qualification inside the function body:
```swift
extension FilePath {
func isRegularFile() -> Bool {
var s = stat() // Calls Darwin.stat(_:_:) - unqualified!
guard stat(self.string, &s) == 0 else { // Calls Darwin.stat(_:_:) - unqualified!
return false
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
When the new `FilePath.stat()` API from SYS-0006 ships, these unqualified calls to `stat()` and `stat(_:_:)` will refer to the new instance method, causing build errors:
```
error: Call can throw, but it is not marked with 'try' and the error is not handled
error: Use of 'stat' refers to instance method rather than global function 'stat' in module 'Darwin'
```
### Why not just use `Darwin.stat`?
Clients could resolve the ambiguity by qualifying their calls with `Darwin.`, `Glibc.`, etc. However, this approach has several limitations:
1. **Cross-platform code**: Clients writing code for multiple platforms would need platform-specific `#if` blocks with code for each platform's libc module.
2. **Awkward syntax**: Due to the overload between the `stat` type and `stat(_:_:)` function, clients must use the verbose `Darwin.stat(_:_:)(path, &s)` syntax to call the function, which is unintuitive.
3. **Older deployment targets**: Clients supporting older deployment targets can't use the new `System.Stat` API on older OS versions but still need to avoid build breakage when compiled with an SDK that includes the new `FilePath.stat()`
By back-deploying `CInterop.stat(_:_:)` to `System 0.0.2 (macOS 12.0, iOS 15.0)`, we provide a cross-platform, ergonomic solution: clients can replace `stat(_:_:)` with `CInterop.stat(_:_:)` for older deployment targets, and use the new `Stat` API moving forward.
## Proposed solution
Back-deploy `CInterop.Stat` and `CInterop.stat(_:_:)` to `@available(System 0.0.2, *)`, making them available on `macOS 12.0, iOS 15.0` and aligned. Note that `System 0.0.2` already maps to earliest source availability when System is used as a package, so the back-deployment is only relevant for System as an OS framework.
### API Overview
```swift
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
public typealias Stat = stat
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32
}
#endif
```
The implementation uses `@_alwaysEmitIntoClient` to make the function available on older OS versions by embedding the implementation in client code. This makes sense for a widely-available and standardized C function like `stat()`.
### Migration guidance
If you have `FilePath` or `FileDescriptor` extensions that use unqualified `stat()` calls and need to support older deployment targets, migrate to `CInterop.Stat` (type) and `CInterop.stat(_:_:)` (function):
#### Before:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
var s = stat()
guard stat(self.string, &s) == 0 else {
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
#### After:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
var s = CInterop.Stat() // stat() --> CInterop.Stat()
guard CInterop.stat(self.string, &s) == 0 else { // stat(_:_:) --> CInterop.stat(_:_:)
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
#### Migrate to the new `Stat` API:
Migrate to the more ergonomic interface on newer OS versions using `if #available`:
```swift
extension FilePath {
func isRegularFile() throws -> Bool {
if #available(macOS X, iOS Y, *) {
return try stat().type == .regular // Calls FilePath.stat()
}
var s = CInterop.Stat()
guard CInterop.stat(self.string, &s) == 0 else {
throw Errno.current
}
return s.st_mode & S_IFMT == S_IFREG
}
}
```
Alternatively, you may use just the new API if your deployment target supports it.
#### Who should use `CInterop.stat(_:_:)`?
This scenario is rare and only occurs when a project meets **all** of the following conditions:
1. Has a custom extension on `FilePath` or `FileDescriptor`, that
2. Uses **unqualified** `stat()` or `stat(_:_:)` calls inside that method, and
3. Needs to support deployment targets older than the new `Stat` API availability
If your code uses qualified calls, e.g. `Darwin.stat()`, or uses a wrapper around `stat()` already, it is **not** affected by this issue and no migration is needed.
## Detailed design
### CInterop extension
```swift
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
/// The C `stat` struct.
public typealias Stat = stat
/// Calls the C `stat()` function.
///
/// This is a direct wrapper around the C `stat()` system call.
/// For a more ergonomic Swift API, use `Stat` instead.
///
/// - Warning: This API is primarily intended for migration purposes when
/// supporting older deployment targets. If your deployment target supports
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
/// type-safe, ergonomic access to file metadata in Swift.
///
/// - Parameters:
/// - path: A null-terminated C string representing the file path.
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
system_stat(path, &s)
}
}
#endif
```
### Internal wrapper
The `system_stat` wrapper is also marked `@_alwaysEmitIntoClient` so it can be inlined. `system_stat` calls the global `stat` function for the current platform.
```swift
#if !os(Windows)
@_alwaysEmitIntoClient
internal func system_stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
stat(path, &s)
}
#endif
```
## Source compatibility
This proposal is additive and source-compatible.
## ABI compatibility
This proposal is ABI-compatible. The use of `@_alwaysEmitIntoClient` ensures that the implementation is embedded in client code.
## Implications on adoption
Clients can adopt `CInterop.Stat` and `CInterop.stat(_:_:)` to support older deployment targets when building with the new SDK.
## Future directions
Once clients can raise their deployment targets to support the new `Stat` API introduced in SYS-0006, they should migrate to it, which provides:
- Type-safe, ergonomic Swift interfaces
- Strongly-typed wrappers (`FileType`, `FileMode`, `FilePermissions`, etc.)
- Proper error handling with typed throws
## Why this should not set a precedent for CInterop functions
We should not expose `CInterop` functions for most, if not all, other methods that shadow a global function. `stat` is a special case for a few reasons:
- Many other syscalls gain a more Swift-y API name, e.g. `dup/dup2` → `duplicate(as:)`, `ftruncate` → `resize(to:)`, `umask` → `FilePermissions.creationMask` if that becomes API, etc. Those renames mean user extensions are unlikely to collide with future System API. `stat` is one of the few syscalls whose C name is already clear and idiomatic enough to use directly as the Swift API name.
- Many syscalls that do keep their C name (e.g. `open`, `close`, `read`, `write`) have been in System since the beginning, so there was never a window where someone would have needed to create their own extension for that functionality.
- `stat` is both widely used and was missing from System for some time, which creates a better chance for migration friction.
- Other syscalls that could be added to System naturally disambiguate through parameter labels. Names like `rename`, `link`, and `unlink` would require non-optional arguments (e.g. `rename(to:)`, `link(to:)`), so their Swift signatures wouldn't collide with the bare C functions. `stat` is unusual in that it works as a zero-argument call on `FilePath`/`FileDescriptor` and has the same shape as the global C `stat()` struct initializer.
## Alternatives considered
### Do nothing
We could choose not to provide a migration path and let affected clients handle the ambiguity by:
1. Qualifying their calls with platform-specific modules (e.g. `Darwin.stat`)
2. Wrapping `stat()` in another function
3. Raising their deployment target to use the new `Stat` API
However, this creates an unnecessary burden for the (admittedly rare) affected clients, especially those who need to maintain backward compatibility with older OS versions.
### Use a different name for `FilePath.stat()`
We could use a different name such as `FilePath.statInfo()`, `FilePath.status()`, `FilePath.Stat()`, or `FilePath.fileInfo()`. However, considering the rarity of the issue, changing to a less concise, discoverable, and expressive function name is not preferrable when we can offer a migration solution.
### Create `stat()` overloads directly on `FilePath`
We could create `stat()` extensions on `FilePath` within System that guide a developer to use the new instance method via `try stat()`, e.g:
```swift
extension FilePath {
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
public func stat() -> CInterop.Stat {
CInterop.Stat()
}
@available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.")
public func stat(
_ path: UnsafePointer<CChar>,
_ s: inout CInterop.Stat
) -> Int32 {
system_stat(path, &s)
}
}
```
This is beneficial because it prevents any SDK breakage with only a System change. However, this is not a great long-term solution to have as public API because:
- It makes choosing the right `stat()` more confusing with 5 total overloads.
- It hurts discoverability for the new `Stat` API.
### Expose the internal `system_stat` wrapper directly
This would achieve the same effect as exposing `CInterop.stat(_:_:)`, but goes against the API naming/organization patterns in System. `CInterop` seems like a clear place for the direct C `stat` wrapper to belong.
### Back-deploy the full `Stat` API
Unlike functions and typealiases, types such as `Stat`, `FileType`, `FileMode`, etc. would require significant coordination and effort to back-deploy, making this alternative less desirable, especially considering it's not required to address the issue.
+8 -10
View File
@@ -32,7 +32,7 @@ To use the `SystemPackage` library in a SwiftPM project,
add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-system", from: "1.7.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
```
Finally, include `"SystemPackage"` as a dependency for your executable target:
@@ -41,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
let package = Package(
// name, platforms, products, etc.
dependencies: [
.package(url: "https://github.com/apple/swift-system", from: "1.7.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
// other dependencies
],
targets: [
@@ -88,7 +88,6 @@ The following table maps existing package releases to their minimum required Swi
| ----------------------- | --------------- | ------------- |
| swift-system 1.3.x | >= Swift 5.8 | >= Xcode 14.3 |
| swift-system 1.4.x through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 |
| swift-system 1.7.x | >= Swift 6.1 | >= Xcode 16.3 |
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so.
@@ -108,16 +107,15 @@ We maintain separate branches for each active minor version of the package:
| Package version | Branch |
| ----------------------- | ----------- |
| swift-system 1.3.x | release/1.3.0 |
| swift-system 1.4.x | release/1.4.0 |
| swift-system 1.5.x | release/1.5.0 |
| swift-system 1.6.x | release/1.6.0 |
| swift-system 1.7.x | release/1.7.0 |
| swift-system 1.8.x (unreleased) | main |
| swift-system 1.3.x | release/1.3 |
| swift-system 1.4.x | release/1.4 |
| swift-system 1.5.x | release/1.5 |
| swift-system 1.6.x | release/1.6 |
| swift-system 1.7.x (unreleased) | main |
Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction:
`release/1.6.0` → `release/1.7.0` → `main`
`release/1.3` → `release/1.4` → `main`
For example, anything landing on `release/1.3` will eventually appear on `release/1.4` and then `main` too; there is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.)
+3 -5
View File
@@ -1,22 +1,20 @@
#[[
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
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
#]]
add_library(CSystem STATIC shims.c)
target_include_directories(CSystem PUBLIC
add_library(CSystem INTERFACE)
target_include_directories(CSystem INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
$<INSTALL_INTERFACE:include/CSystem>)
install(FILES
include/CSystemLinux.h
include/CSystemShared.h
include/CSystemWindows.h
include/CSystemFreeBSD.h
include/module.modulemap
DESTINATION include/CSystem)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
-21
View File
@@ -1,21 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if defined(__FreeBSD__)
#include <fcntl.h>
#ifdef O_CLOFORK
#define FREEBSD_O_CLOFORK O_CLOFORK
#else
#define FREEBSD_O_CLOFORK 0
#endif
#endif
+2
View File
@@ -11,11 +11,13 @@
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/sysinfo.h>
#include <sys/timerfd.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
-14
View File
@@ -1,14 +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(_WIN32)
extern int csystem_posix_pipe2(int fildes[2], int flag);
#endif
extern int csystem_posix_dup3(int fildes, int fildes2, int flag);
-2
View File
@@ -1,8 +1,6 @@
module CSystem {
header "CSystemShared.h"
header "CSystemLinux.h"
header "CSystemWASI.h"
header "CSystemWindows.h"
header "CSystemFreeBSD.h"
export *
}
+3 -39
View File
@@ -1,54 +1,18 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
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(__FreeBSD__) || defined(__OpenBSD__)
#define __BSD_VISIBLE
#include <unistd.h>
#endif
#if defined(__FreeBSD__)
#include <CSystemFreeBSD.h>
#endif
#ifdef __linux__
#define _GNU_SOURCE
#include <CSystemLinux.h>
#endif
#if defined(_WIN32)
#include <CSystemWindows.h>
#endif
#include <errno.h>
#if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__)
#define HAVE_PIPE2_DUP3
#endif
// Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h
#if !defined(_WIN32)
extern int csystem_posix_pipe2(int fildes[2], int flag) {
#ifdef HAVE_PIPE2_DUP3
return pipe2(fildes, flag);
#else
errno = ENOSYS;
return -1;
#endif
}
#endif // !defined(_WIN32)
extern int csystem_posix_dup3(int fildes, int fildes2, int flag) {
#ifdef HAVE_PIPE2_DUP3
return dup3(fildes, fildes2, flag);
#else
errno = ENOSYS;
return -1;
#endif
}
+72
View File
@@ -0,0 +1,72 @@
/*
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!"
@available(System 99, *)
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!")
}
}
+81
View File
@@ -0,0 +1,81 @@
/*
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
@available(System 99, *)
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")
}
}
+106
View File
@@ -0,0 +1,106 @@
/*
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
@available(System 99, *)
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()
}
}
@available(System 99, *)
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))"
}
}
@available(System 99, *)
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))"
}
}
@available(System 99, *)
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))"
}
}
}
+85
View File
@@ -0,0 +1,85 @@
/*
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
@available(System 99, *)
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)"
}
}
}
+67
View File
@@ -0,0 +1,67 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
import SystemSockets
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
/// Turn off libc's input/output buffering.
internal func disableBuffering() {
setbuf(stdin, nil)
setbuf(stdout, nil)
setbuf(stderr, nil)
}
internal func complain(_ message: String) {
var message = message + "\n"
message.withUTF8 { buffer in
_ = try? FileDescriptor.standardError.writeAll(buffer)
}
}
@available(System 99, *)
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))"
}
}
@available(System 99, *)
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
}
}
@available(System 99, *)
extension SocketDescriptor.ConnectionType {
var isConnectionless: Bool {
self == .datagram || self == .reliablyDeliveredMessage
}
}
+27
View File
@@ -0,0 +1,27 @@
/*
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 {
@available(System 99, *)
static var configuration = CommandConfiguration(
commandName: "system-samples",
abstract: "A collection of little programs exercising some System features.",
subcommands: [
Resolve.self,
ReverseResolve.self,
Connect.self,
Listen.self,
])
}
disableBuffering()
SystemSamples.main()
+1 -1
View File
@@ -160,7 +160,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
/// No child processes.
///
/// A `wait(2)` or `waitpid(2)` function was executed
/// by a process that doesn't have any existing child processes
/// by a process that dosn't have any existing child processes
/// or whose child processes are all already being waited for.
///
/// The corresponding C error is `ECHILD`.
+6 -136
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -306,10 +306,12 @@ extension FileDescriptor {
///
/// Normally, file descriptors remain open
/// across calls to the `exec(2)` family of functions.
/// If you specify this option, the system closes the file
/// descriptor when replacing this process with another process.
/// If you specify this option,
/// the file descriptor is closed when replacing this process
/// with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// The state of the file
/// descriptor flags can be inspected using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
@@ -322,138 +324,6 @@ extension FileDescriptor {
#endif
}
/// Options that specify behavior for a newly-created pipe.
@frozen
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
#if !os(Windows)
/// Indicates that all subsequent input and output operations
/// on the pipe's file descriptors will be nonblocking.
///
/// The corresponding C constant is `O_NONBLOCK`.
@_alwaysEmitIntoClient
public static var nonBlocking: PipeOptions { .init(rawValue: _O_NONBLOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "nonBlocking")
public static var O_NONBLOCK: PipeOptions { nonBlocking }
#endif // !os(Windows)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `exec(2)` family of functions.
/// If you specify this option, the system closes the file
/// descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
@_alwaysEmitIntoClient
public static var closeOnExec: PipeOptions { .init(rawValue: _O_CLOEXEC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_CLOEXEC: PipeOptions { closeOnExec }
#if os(Windows)
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_NOINHERIT: PipeOptions { closeOnExec }
#endif
#if !os(Windows) && !os(WASI) && !os(Linux) && !os(Android)
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `fork(2)` function.
/// If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
@_alwaysEmitIntoClient
public static var closeOnFork: PipeOptions { .init(rawValue: _O_CLOFORK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnFork")
public static var O_CLOFORK: PipeOptions { closeOnFork }
#endif
}
/// Options that specify behavior for a duplicated file descriptor.
@frozen
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
public var rawValue: CInt
/// Create a strongly-typed options value from raw C options.
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
#if !os(Windows)
/// Indicates that executing a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `exec(2)` family of functions.
/// If you specify this option, the system closes the file
/// descriptor when replacing this process with another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOEXEC`.
@_alwaysEmitIntoClient
public static var closeOnExec: DuplicateOptions { .init(rawValue: _O_CLOEXEC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
public static var O_CLOEXEC: DuplicateOptions { closeOnExec }
#if !os(WASI) && !os(Linux) && !os(Android)
/// Indicates that forking a program closes the file.
///
/// Normally, file descriptors remain open
/// across calls to the `fork(2)` function.
/// If you specify this option, the system closes the file
/// descriptor when forking this process into another process.
///
/// You can inspect the file descriptor flag state using `F_GETFD`,
/// as described in the `fcntl(2)` man page.
///
/// The corresponding C constant is `O_CLOFORK`.
@_alwaysEmitIntoClient
public static var closeOnFork: DuplicateOptions { .init(rawValue: _O_CLOFORK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnFork")
public static var O_CLOFORK: DuplicateOptions { closeOnFork }
#endif
#endif
}
/// Options for specifying what a file descriptor's offset is relative to.
@frozen
@available(System 0.0.1, *)
+170 -25
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -20,6 +20,7 @@ extension FileDescriptor {
/// If `body` throws an error
/// or an error occurs while closing the file descriptor,
/// this method rethrows that error.
@available(System 0.0.1, *)
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
// No underscore helper, since the closure's throw isn't necessarily typed.
let result: R
@@ -49,6 +50,7 @@ extension FileDescriptor {
/// If `sequence` doesn't implement
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
/// temporary space will be allocated as needed.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
@@ -62,20 +64,27 @@ extension FileDescriptor {
_ sequence: S
) -> Result<Int, Errno> where S.Element == UInt8 {
sequence._withRawBufferPointer { buffer in
var idx = 0
while idx < buffer.count {
switch _write(
UnsafeRawBufferPointer(rebasing: buffer[idx...]), retryOnInterrupt: true
) {
case .success(let numBytes): idx += numBytes
case .failure(let err): return .failure(err)
}
}
assert(idx == buffer.count)
return .success(buffer.count)
_writeAllBuffer(buffer)
}
}
@_alwaysEmitIntoClient
internal func _writeAllBuffer(
_ buffer: UnsafeRawBufferPointer
) -> Result<Int, Errno> {
var idx = 0
while idx < buffer.count {
switch _write(
UnsafeRawBufferPointer(rebasing: buffer[idx...]), retryOnInterrupt: true
) {
case .success(let numBytes): idx += numBytes
case .failure(let err): return .failure(err)
}
}
assert(idx == buffer.count)
return .success(buffer.count)
}
/// Writes a sequence of bytes to the given offset.
///
/// - Parameters:
@@ -91,6 +100,7 @@ extension FileDescriptor {
/// If `sequence` doesn't implement
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
/// temporary space will be allocated as needed.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
@@ -99,24 +109,159 @@ extension FileDescriptor {
try _writeAll(toAbsoluteOffset: offset, sequence).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal func _writeAll<S: Sequence>(
toAbsoluteOffset offset: Int64, _ sequence: S
) -> Result<Int, Errno> where S.Element == UInt8 {
sequence._withRawBufferPointer { buffer in
var idx = 0
while idx < buffer.count {
switch _write(
toAbsoluteOffset: offset + Int64(idx),
UnsafeRawBufferPointer(rebasing: buffer[idx...]),
retryOnInterrupt: true
) {
case .success(let numBytes): idx += numBytes
case .failure(let err): return .failure(err)
}
}
assert(idx == buffer.count)
return .success(buffer.count)
_writeAllBuffer(toAbsoluteOffset: offset, buffer)
}
}
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
internal func _writeAllBuffer(
toAbsoluteOffset offset: Int64, _ buffer: UnsafeRawBufferPointer
) -> Result<Int, Errno> {
var idx = 0
while idx < buffer.count {
switch _write(
toAbsoluteOffset: offset + Int64(idx),
UnsafeRawBufferPointer(rebasing: buffer[idx...]),
retryOnInterrupt: true
) {
case .success(let numBytes): idx += numBytes
case .failure(let err): return .failure(err)
}
}
assert(idx == buffer.count)
return .success(buffer.count)
}
#if compiler(>=6.2)
/// Writes the entire contents of a buffer, retrying on partial writes.
///
/// - Parameters:
/// - data: The region of memory that contains the data being written.
/// - retryOnInterrupt: Whether to retry the write operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were written.
///
/// After writing,
/// this method increments the file's offset by the number of bytes written.
/// To change the file's offset,
/// call the ``seek(offset:from:)`` method.
///
/// The corresponding C function is `write`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
public func writeAll(
_ data: RawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
try data.withUnsafeBytes { buffer throws(Errno) -> Int in
try _writeAllBuffer(buffer).get()
}
}
/// Writes the entire contents of a buffer at the specified offset,
/// retrying on partial writes.
///
/// - Parameters:
/// - offset: The file offset where writing begins.
/// - data: The region of memory that contains the data being written.
/// - retryOnInterrupt: Whether to retry the write operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were written.
///
/// Unlike ``writeAll(_:retryOnInterrupt:)``,
/// this method leaves the file's existing offset unchanged.
///
/// The corresponding C function is `pwrite`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
public func writeAll(
toAbsoluteOffset offset: Int64,
_ data: RawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
try data.withUnsafeBytes { buffer throws(Errno) -> Int in
try _writeAllBuffer(toAbsoluteOffset: offset, buffer).get()
}
}
/// Reads bytes into a buffer, retrying until it is full.
///
/// - Parameters:
/// - buffer: The region of memory to read into.
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were read.
///
/// After reading,
/// this method increments the file's offset by the number of bytes read.
/// To change the file's offset,
/// call the ``seek(offset:from:)`` method.
///
/// The corresponding C function is `read`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
@discardableResult
public func read(
filling buffer: inout OutputRawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
let originalCapacity = buffer.freeCapacity
while buffer.freeCapacity > 0 {
let bytesRead = try read(into: &buffer, retryOnInterrupt: retryOnInterrupt)
if bytesRead == 0 {
break // EOF
}
}
return originalCapacity - buffer.freeCapacity
}
/// Reads bytes at the specified offset into a buffer,
/// retrying until it is full.
///
/// - Parameters:
/// - offset: The file offset where reading begins.
/// - buffer: The region of memory to read into.
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were read.
///
/// Unlike ``read(filling:retryOnInterrupt:)``,
/// this method leaves the file's existing offset unchanged.
///
/// The corresponding C function is `pread`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
@discardableResult
public func read(
fromAbsoluteOffset offset: Int64,
filling buffer: inout OutputRawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
let originalCapacity = buffer.freeCapacity
var currentOffset = offset
while buffer.freeCapacity > 0 {
let bytesRead = try read(fromAbsoluteOffset: currentOffset, into: &buffer, retryOnInterrupt: retryOnInterrupt)
if bytesRead == 0 {
break // EOF
}
currentOffset += Int64(bytesRead)
}
return originalCapacity - buffer.freeCapacity
}
#endif // swift(>=6.2)
}
+168 -132
View File
@@ -23,6 +23,7 @@ extension FileDescriptor {
/// - Returns: A file descriptor for the open file
///
/// The corresponding C function is `open`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public static func open(
_ path: FilePath,
@@ -62,6 +63,7 @@ extension FileDescriptor {
/// - Returns: A file descriptor for the open file
///
/// The corresponding C function is `open`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public static func open(
_ path: UnsafePointer<CChar>,
@@ -75,6 +77,7 @@ extension FileDescriptor {
).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal static func _open(
_ path: UnsafePointer<CChar>,
@@ -148,6 +151,7 @@ extension FileDescriptor {
/// the object will be deactivated.
///
/// The corresponding C function is `close`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public func close() throws { try _close().get() }
@@ -165,6 +169,7 @@ extension FileDescriptor {
/// in bytes from the beginning of the file.
///
/// The corresponding C function is `lseek`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
@discardableResult
public func seek(
@@ -173,6 +178,7 @@ extension FileDescriptor {
try _seek(offset: offset, from: whence).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal func _seek(
offset: Int64, from whence: FileDescriptor.SeekOrigin
@@ -210,6 +216,7 @@ extension FileDescriptor {
/// call the ``seek(offset:from:)`` method.
///
/// The corresponding C function is `read`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public func read(
into buffer: UnsafeMutableRawBufferPointer,
@@ -218,6 +225,7 @@ extension FileDescriptor {
try _read(into: buffer, retryOnInterrupt: retryOnInterrupt).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal func _read(
into buffer: UnsafeMutableRawBufferPointer,
@@ -246,6 +254,7 @@ extension FileDescriptor {
/// this method leaves the file's existing offset unchanged.
///
/// The corresponding C function is `pread`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public func read(
fromAbsoluteOffset offset: Int64,
@@ -259,6 +268,7 @@ extension FileDescriptor {
).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal func _read(
fromAbsoluteOffset offset: Int64,
@@ -299,6 +309,7 @@ extension FileDescriptor {
/// call the ``seek(offset:from:)`` method.
///
/// The corresponding C function is `write`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public func write(
_ buffer: UnsafeRawBufferPointer,
@@ -307,6 +318,7 @@ extension FileDescriptor {
try _write(buffer, retryOnInterrupt: retryOnInterrupt).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal func _write(
_ buffer: UnsafeRawBufferPointer,
@@ -332,6 +344,7 @@ extension FileDescriptor {
/// this method leaves the file's existing offset unchanged.
///
/// The corresponding C function is `pwrite`.
@available(System 0.0.1, *)
@_alwaysEmitIntoClient
public func write(
toAbsoluteOffset offset: Int64,
@@ -341,6 +354,7 @@ extension FileDescriptor {
try _write(toAbsoluteOffset: offset, buffer, retryOnInterrupt: retryOnInterrupt).get()
}
@available(System 0.0.1, *)
@usableFromInline
internal func _write(
toAbsoluteOffset offset: Int64,
@@ -365,6 +379,152 @@ extension FileDescriptor {
buffer,
retryOnInterrupt: retryOnInterrupt)
}
#if compiler(>=6.2)
/// Writes the contents of a buffer at the current file offset.
///
/// - Parameters:
/// - data: The region of memory that contains the data being written.
/// - retryOnInterrupt: Whether to retry the write operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were written.
///
/// After writing,
/// this method increments the file's offset by the number of bytes written.
/// To change the file's offset,
/// call the ``seek(offset:from:)`` method.
///
/// The corresponding C function is `write`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
public func write(
_ data: RawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
try data.withUnsafeBytes { bytes throws(Errno) -> Int in
try _write(bytes, retryOnInterrupt: retryOnInterrupt).get()
}
}
/// Writes the contents of a buffer at the specified offset.
///
/// - Parameters:
/// - offset: The file offset where writing begins.
/// - data: The region of memory that contains the data being written.
/// - retryOnInterrupt: Whether to retry the write operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were written.
///
/// Unlike ``write(_:retryOnInterrupt:)``,
/// this method leaves the file's existing offset unchanged.
///
/// The corresponding C function is `pwrite`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
public func write(
toAbsoluteOffset offset: Int64,
_ data: RawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
try data.withUnsafeBytes { bytes throws(Errno) -> Int in
try _write(toAbsoluteOffset: offset, bytes, retryOnInterrupt: retryOnInterrupt).get()
}
}
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
internal func _readIntoOutputBuffer(
_ buffer: UnsafeMutableRawBufferPointer,
initializedCount: inout Int,
retryOnInterrupt: Bool
) -> Result<Int, Errno> {
// Read into the uninitialized portion (starting at offset 'initializedCount')
let uninitializedPortion = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress?.advanced(by: initializedCount),
count: buffer.count - initializedCount
)
do {
let result = try _read(into: uninitializedPortion, retryOnInterrupt: retryOnInterrupt)
if case .success(let bytesRead) = result {
initializedCount += bytesRead // Add to existing count, don't replace it!
}
return result
} catch {
fatalError("Unexpected error from _read")
}
}
/// Reads bytes at the current file offset into a buffer.
///
/// - Parameters:
/// - buffer: The region of memory to read into.
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were read.
///
/// After reading,
/// this method increments the file's offset by the number of bytes read.
/// To change the file's offset,
/// call the ``seek(offset:from:)`` method.
///
/// The corresponding C function is `read`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
public func read(
into buffer: inout OutputRawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
try buffer.withUnsafeMutableBytes { buf, count throws(Errno) -> Int in
try _readIntoOutputBuffer(buf, initializedCount: &count, retryOnInterrupt: retryOnInterrupt).get()
}
}
/// Reads bytes at the specified offset into a buffer.
///
/// - Parameters:
/// - offset: The file offset where reading begins.
/// - buffer: The region of memory to read into.
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The number of bytes that were read.
///
/// Unlike ``read(into:retryOnInterrupt:)``,
/// this method leaves the file's existing offset unchanged.
///
/// The corresponding C function is `pread`.
@available(SystemWithSpan 0.0.1, *)
@_alwaysEmitIntoClient
public func read(
fromAbsoluteOffset offset: Int64,
into buffer: inout OutputRawSpan,
retryOnInterrupt: Bool = true
) throws(Errno) -> Int {
do {
return try buffer.withUnsafeMutableBytes { buf, count in
// Read into the uninitialized portion (starting at offset 'count')
let uninitializedPortion = UnsafeMutableRawBufferPointer(
start: buf.baseAddress?.advanced(by: count),
count: buf.count - count
)
let bytesRead = try read(fromAbsoluteOffset: offset, into: uninitializedPortion, retryOnInterrupt: retryOnInterrupt)
count += bytesRead // Add to existing count, don't replace it!
return bytesRead
}
} catch let error as Errno {
throw error
} catch {
fatalError("Unexpected error type")
}
}
#endif // compiler(>=6.2)
}
#if !os(WASI)
@@ -395,6 +555,7 @@ extension FileDescriptor {
///
/// However, each file descriptor maintains its own close-on-exec flag.
///
///
/// The corresponding C functions are `dup` and `dup2`.
@_alwaysEmitIntoClient
@available(System 0.0.2, *)
@@ -405,82 +566,17 @@ extension FileDescriptor {
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
}
/// Duplicate this file descriptor and return the newly created copy.
///
/// - Parameters:
/// - target: The desired target file descriptor.
/// - options: The behavior for creating the target file descriptor.
/// - retryOnInterrupt: Whether to retry the operation
/// if it throws ``Errno/interrupted``. The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: The new file descriptor.
///
/// If the `target` descriptor the same as `self`, then EINVAL is thrown.
/// If the `target` descriptor is already in use, then it is first
/// deallocated as if a close(2) call had been done first.
///
/// NOTE: This overload called with an empty option set is not necessarily
/// equivalent to calling the overload with no options, because `dup3` with
/// no set options is not required to behave identically to `dup2`.
///
/// File descriptors are merely references to some underlying system resource.
/// The system does not distinguish between the original and the new file
/// descriptor in any way. For example, read, write and seek operations on
/// one of them also affect the logical file position in the other, and
/// append mode, non-blocking I/O and asynchronous I/O options are shared
/// between the references. If a separate pointer into the file is desired,
/// a different object reference to the file must be obtained by issuing an
/// additional call to `open`.
///
/// However, each file descriptor maintains its own close-on-exec and
/// close-on-fork flags.
///
/// The corresponding C function is `dup3`.
@discardableResult
@_alwaysEmitIntoClient
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public func duplicate(
as target: FileDescriptor,
options: DuplicateOptions,
retryOnInterrupt: Bool = true
) throws(Errno) -> FileDescriptor {
try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get()
}
@available(System 0.0.2, *)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor?,
retryOnInterrupt: Bool
) -> Result<FileDescriptor, Errno> {
) throws -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
if let target {
system_dup2(self.rawValue, target.rawValue)
} else {
system_dup(self.rawValue)
if let target = target {
return system_dup2(self.rawValue, target.rawValue)
}
}.map(FileDescriptor.init(rawValue:))
}
@available(Windows, unavailable)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor,
options: Int32,
retryOnInterrupt: Bool
) -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_dup3(self.rawValue, target.rawValue, options)
return system_dup(self.rawValue)
}.map(FileDescriptor.init(rawValue:))
}
@@ -495,61 +591,26 @@ extension FileDescriptor {
public func dup2() throws -> FileDescriptor {
fatalError("Not implemented")
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "duplicate")
public func dup3() throws -> FileDescriptor {
fatalError("Not implemented")
}
}
#endif
#if !os(WASI)
@available(System 1.1.0, *)
extension FileDescriptor {
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
/// Creates a unidirectional data channel, which can be used for interprocess communication.
///
/// - Returns: The pair of file descriptors.
///
/// The corresponding C function is `pipe`.
@_alwaysEmitIntoClient
@available(System 1.1.0, *)
public static func pipe(
) throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe().get()
}
/// Creates a unidirectional data channel, which can be used for
/// interprocess communication.
///
/// NOTE: This overload called with an empty option set is not necessarily
/// equivalent to calling the overload with no options. On Windows, this
/// overload with empty options disables the `closeOnExec` behaviour,
/// which is enabled by the overload without options.
///
/// - Parameters:
/// - options: The behavior for creating the pipe.
///
/// - Returns: The pair of file descriptors.
///
/// The corresponding C function is `pipe2`.
@_alwaysEmitIntoClient
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
public static func pipe(
options: PipeOptions
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe(options: options.rawValue).get()
}
@available(System 1.1.0, *)
@usableFromInline
internal static func _pipe(
) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
var fds: (Int32, Int32) = (-1, -1)
return withUnsafeMutablePointer(to: &fds) { pointer in
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
@@ -559,31 +620,6 @@ extension FileDescriptor {
}
}
}
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(visionOS, unavailable)
@usableFromInline
internal static func _pipe(
options: Int32,
) -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
var fds: (Int32, Int32) = (-1, -1)
return withUnsafeMutablePointer(to: &fds) { pointer in
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
valueOrErrno(retryOnInterrupt: false) {
system_pipe2(fds, options)
}.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) }
}
}
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "pipe")
public static func pipe2() throws -> FileDescriptor {
fatalError("Not implemented")
}
}
#endif
@@ -9,23 +9,6 @@
#if !os(Windows)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import CSystem
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Android)
import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
/// Get the path to the system temporary directory.
internal func _getTemporaryDirectory() throws -> FilePath {
guard let tmp = system_getenv("TMPDIR") else {
@@ -73,7 +73,7 @@ internal func _recursiveRemove(
) throws {
// First, deal with subdirectories
try forEachFile(at: path) { findData in
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 {
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 {
let name = withUnsafeBytes(of: findData.cFileName) {
return SystemString(platformString: $0.assumingMemoryBound(
to: CInterop.PlatformChar.self).baseAddress!)
@@ -94,7 +94,7 @@ internal func _recursiveRemove(
let component = FilePath.Component(name)!
let subpath = path.appending(component)
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 {
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 {
try subpath.withPlatformString { subpath in
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
throw Errno(windowsError: GetLastError())
@@ -517,7 +517,7 @@ fileprivate func HRESULT_CODE(_ hr: HRESULT) -> DWORD {
@inline(__always)
fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD {
DWORD(hr >> 16) & 0x1fff
DWORD(hr << 16) & 0x1fff
}
@inline(__always)
@@ -529,7 +529,7 @@ fileprivate func SUCCEEDED(_ hr: HRESULT) -> Bool {
// an HRESULT to a Win32 error code.
@inline(__always)
fileprivate func WIN32_FROM_HRESULT(_ hr: HRESULT) -> DWORD {
if SUCCEEDED(hr) { return ERROR_SUCCESS }
if SUCCEEDED(hr) { return DWORD(ERROR_SUCCESS) }
if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
return HRESULT_CODE(hr)
}
+17 -6
View File
@@ -388,9 +388,7 @@ extension IORing.Request {
}
@inline(__always) @inlinable
internal consuming func makeRawRequest(
pathBuffers: PendingPathBuffers
) -> RawIORequest {
internal consuming func makeRawRequest() -> RawIORequest {
var request = RawIORequest()
switch extractCore() {
case .nop:
@@ -402,19 +400,27 @@ extension IORing.Request {
request.operation = .openAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(bitPattern: pathBuffers.pin(path)))
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0
request.rawValue.file_index = UInt32(fileSlot.index + 1)
request.path = path
request.rawValue.user_data = context
case .openat(
let atDirectory, let path, let mode, let options, let permissions, let context):
request.operation = .openAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(bitPattern: pathBuffers.pin(path)))
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0
request.path = path
request.rawValue.user_data = context
case .write(let file, let buffer, let offset, let context):
request.operation = .writeFixed
@@ -460,7 +466,12 @@ extension IORing.Request {
request.operation = .unlinkAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(bitPattern: pathBuffers.pin(path)))
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
})
)
request.path = path
request.rawValue.user_data = context
case .cancelContext(let flags, let targetContext):
request.operation = .asyncCancel
+6 -54
View File
@@ -41,33 +41,6 @@ extension UnsafeMutableRawBufferPointer {
}
}
/// Owns the FilePaths whose interior pointers have been written into pending
/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to
/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap
/// This is a class purely to avoid making methods calling `pin` mutating, which would be an API break
@usableFromInline
internal final class PendingPathBuffers {
@usableFromInline
var paths: [FilePath] = []
init(reservedCapacity: Int) {
paths.reserveCapacity(reservedCapacity)
}
@usableFromInline
func pin(_ path: FilePath) -> UnsafePointer<CInterop.PlatformChar> {
paths.append(path)
// Safe to escape: `paths` keeps the FilePath (and its underlying
// [SystemChar] buffer) alive until clear() or class deinit.
return paths.last!.withPlatformString { $0 }
}
@usableFromInline
func clear() {
paths.removeAll(keepingCapacity: true)
}
}
// all pointers in this struct reference kernel-visible memory
@usableFromInline struct SQRing: ~Copyable {
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
@@ -227,14 +200,7 @@ private func setUpRing(
throw err
}
// We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced
// pathnames (and other inline data) out of userspace before io_uring_enter
// returns; the path-buffer side store on IORing relies on this to free
// path buffers as soon as a submission completes.
let requiredFeatures =
IORing.Features.nonDroppingCompletions.rawValue
| IORing.Features.stableSubmissions.rawValue
if params.features & requiredFeatures != requiredFeatures
if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0
{
close(ringDescriptor)
throw Errno.invalidArgument
@@ -358,8 +324,6 @@ public struct IORing: ~Copyable {
@usableFromInline var _registeredFiles: [UInt32]
@usableFromInline var _registeredBuffers: [iovec]
@usableFromInline let _pendingPathBuffers: PendingPathBuffers
var features = Features(rawValue: 0)
/// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them.
@@ -480,7 +444,6 @@ public struct IORing: ~Copyable {
self.completionRingSize = tmpCQSize
self._registeredFiles = []
self._registeredBuffers = []
self._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries))
self.submissionRing = submissionRing
self.completionRing = completionRing
self.submissionQueueEntries = submissionQueueEntries
@@ -802,10 +765,6 @@ public struct IORing: ~Copyable {
@inlinable
public func submitPreparedRequests() throws(Errno) {
try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor)
// IORING_FEAT_SUBMIT_STABLE guarantees the kernel has copied any
// SQE-referenced data (e.g. openat/unlinkAt pathnames) before
// io_uring_enter returns; safe to release path storage now.
_pendingPathBuffers.clear()
}
/// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available.
@@ -831,14 +790,9 @@ public struct IORing: ~Copyable {
/// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request
@inlinable
public mutating func prepare(request: __owned Request) -> Bool {
guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else {
return false
}
var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers)
let ok = _tryWriteRequest(
var raw: RawIORequest? = request.makeRawRequest()
return _tryWriteRequest(
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(ok)
return ok
}
/// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order.
@@ -852,20 +806,18 @@ public struct IORing: ~Copyable {
return false
}
let last = linkedRequests.last!
var allAdded = true
for req in linkedRequests.dropLast() {
var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers)
var raw = req.makeRawRequest()
raw.linkToNextRequest()
let successfullyAdded = _tryWriteRequest(
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
allAdded = allAdded && successfullyAdded
}
let successfullyAdded = _tryWriteRequest(
last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing,
last.makeRawRequest(), ring: &submissionRing,
submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
return allAdded && successfullyAdded
return true
}
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
+1
View File
@@ -8,6 +8,7 @@ internal struct RawIORequest: ~Copyable {
// swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where
// IORing is supported (currently requires kernel version >= 5.15).
@usableFromInline var rawValue: swift_io_uring_sqe
@usableFromInline var path: FilePath? //buffer owner for the path pointer that the sqe may have
@inlinable public init() {
self.rawValue = swift_io_uring_sqe()
+1 -25
View File
@@ -81,33 +81,9 @@ public enum CInterop {
}
#if !os(Windows)
@available(System 0.0.2, *) // Original availability of CInterop
extension CInterop {
/// The C `stat` struct.
public typealias Stat = stat
/// Calls the C `stat()` function.
///
/// This is a direct wrapper around the C `stat()` system call.
/// For a more ergonomic Swift API, use `Stat` instead.
///
/// - Warning: This API is primarily intended for migration purposes when
/// supporting older deployment targets. If your deployment target supports
/// it, prefer using the `Stat` API introduced in SYS-0006, which provides
/// type-safe, ergonomic access to file metadata in Swift.
///
/// - Parameters:
/// - path: A null-terminated C string representing the file path.
/// - s: An `inout` reference to a `CInterop.Stat` struct to populate.
/// - Returns: 0 on success, -1 on error (check `Errno.current`).
@_alwaysEmitIntoClient
public static func stat(_ path: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
system_stat(path, &s)
}
}
@available(System 99, *)
extension CInterop {
public typealias Stat = stat
public typealias DeviceID = dev_t
public typealias Inode = ino_t
public typealias UserID = uid_t
+3 -21
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -619,26 +619,9 @@ internal var _O_DIRECTORY: CInt {
internal var _O_SYMLINK: CInt { O_SYMLINK }
#endif
@_alwaysEmitIntoClient
internal var _O_CLOEXEC: CInt {
#if os(Windows)
O_NOINHERIT
#else
O_CLOEXEC
#endif
}
#if !os(Windows)
@_alwaysEmitIntoClient
internal var _O_CLOFORK: CInt {
#if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD)
O_CLOFORK
#elseif os(FreeBSD)
FREEBSD_O_CLOFORK
#else
0
#endif
}
internal var _O_CLOEXEC: CInt { O_CLOEXEC }
#endif
@_alwaysEmitIntoClient
@@ -710,9 +693,8 @@ internal var _S_IFLNK: mode_t { S_IFLNK }
internal var _S_IFSOCK: mode_t { S_IFSOCK }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
// `S_IFWHT` is `Int32` on FreeBSD.
@_alwaysEmitIntoClient
internal var _S_IFWHT: mode_t { .init(S_IFWHT) }
internal var _S_IFWHT: mode_t { S_IFWHT }
#endif
// MARK: - stat/chflags File Flags
+1 -2
View File
@@ -91,8 +91,7 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
}
#if !os(Windows)
@available(System 0.0.2, *)
@_alwaysEmitIntoClient
@available(System 99, *)
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
stat(p, &s)
}
+2 -17
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -14,6 +14,7 @@ import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
import CSystem
import WASILibc
#elseif os(Windows)
import ucrt
@@ -23,8 +24,6 @@ import Android
#error("Unsupported Platform")
#endif
import CSystem
// Interacting with the mocking system, tracing, etc., is a potentially significant
// amount of code size, so we hand outline that code for every syscall
@@ -140,13 +139,6 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
#endif
return dup2(fd, fd2)
}
internal func system_dup3(_ fd: Int32, _ fd2: Int32, _ oflag: Int32) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, fd2, oflag) }
#endif
return csystem_posix_dup3(fd, fd2, oflag)
}
#endif
#if !os(WASI)
@@ -156,13 +148,6 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#endif
return pipe(fds)
}
internal func system_pipe2(_ fds: UnsafeMutablePointer<Int32>, _ oflag: Int32) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fds, oflag) }
#endif
return csystem_posix_pipe2(fds, oflag)
}
#endif
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
@@ -38,9 +38,9 @@ internal func open(
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
@@ -80,9 +80,9 @@ internal func open(
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
@@ -149,12 +149,6 @@ internal func pread(
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows ReadFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -177,12 +171,6 @@ internal func pwrite(
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows WriteFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -201,18 +189,11 @@ internal func pwrite(
@inline(__always)
internal func pipe(
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 4096
) -> CInt {
return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
}
@inline(__always)
internal func csystem_posix_pipe2(
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 0, _ oflag: Int32
) -> CInt {
return _pipe(fds, bytesReserved, _O_BINARY | oflag)
}
@inline(__always)
internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
let handle: intptr_t = _get_osfhandle(fd)
@@ -225,16 +206,16 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
// Save the current position and restore it when we're done
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
FILE_CURRENT) {
DWORD(FILE_CURRENT)) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
defer {
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN);
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN));
}
// Truncate (or extend) the file
if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN)
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN))
|| !SetEndOfFile(hFile) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
@@ -286,7 +267,7 @@ internal func rmdir(
}
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
switch errorCode {
switch Int32(errorCode) {
case ERROR_SUCCESS:
return 0
case ERROR_INVALID_FUNCTION,
@@ -365,28 +346,28 @@ fileprivate func rightsFromModeBits(
var rights: DWORD = 0
if (bits & 0o4) != 0 {
rights |= (FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
rights |= DWORD(FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
}
if (bits & 0o2) != 0 {
rights |= (FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
rights |= DWORD(FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
if fileOrDirectory == .directory && !sticky {
rights |= FILE_DELETE_CHILD
rights |= DWORD(FILE_DELETE_CHILD)
}
}
if (bits & 0o1) != 0 {
rights |= (FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
rights |= DWORD(FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
}
return rights
@@ -454,7 +435,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var everyone: PSID? = nil
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
DWORD(SECURITY_WORLD_RID),
0, 0, 0, 0, 0, 0, 0,
&everyone) else {
return nil
@@ -495,7 +476,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -508,7 +489,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -521,7 +502,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: otherRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -538,7 +519,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -556,7 +537,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: NO_INHERITANCE,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -585,13 +566,13 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var descriptor = SECURITY_DESCRIPTOR()
guard InitializeSecurityDescriptor(&descriptor,
SECURITY_DESCRIPTOR_REVISION) else {
DWORD(SECURITY_DESCRIPTOR_REVISION)) else {
return nil
}
guard SetSecurityDescriptorControl(&descriptor,
SE_DACL_PROTECTED,
SE_DACL_PROTECTED)
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED),
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED))
&& SetSecurityDescriptorOwner(&descriptor, user, false)
&& SetSecurityDescriptorGroup(&descriptor, group, false)
&& SetSecurityDescriptorDacl(&descriptor,
@@ -631,15 +612,15 @@ fileprivate struct DecodedOpenFlags {
init(_ oflag: Int32) {
switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) {
case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC:
dwCreationDisposition = CREATE_NEW
dwCreationDisposition = DWORD(CREATE_NEW)
case _O_CREAT:
dwCreationDisposition = OPEN_ALWAYS
dwCreationDisposition = DWORD(OPEN_ALWAYS)
case _O_CREAT | _O_TRUNC:
dwCreationDisposition = CREATE_ALWAYS
dwCreationDisposition = DWORD(CREATE_ALWAYS)
case _O_TRUNC:
dwCreationDisposition = TRUNCATE_EXISTING
dwCreationDisposition = DWORD(TRUNCATE_EXISTING)
default:
dwCreationDisposition = OPEN_EXISTING
dwCreationDisposition = DWORD(OPEN_EXISTING)
}
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
@@ -648,11 +629,11 @@ fileprivate struct DecodedOpenFlags {
dwDesiredAccess = 0
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
case _O_RDONLY:
dwDesiredAccess |= GENERIC_READ
dwDesiredAccess |= DWORD(GENERIC_READ)
case _O_WRONLY:
dwDesiredAccess |= GENERIC_WRITE
dwDesiredAccess |= DWORD(GENERIC_WRITE)
case _O_RDWR:
dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE)
default:
break
}
@@ -661,19 +642,19 @@ fileprivate struct DecodedOpenFlags {
dwFlagsAndAttributes = 0
if (oflag & _O_SEQUENTIAL) != 0 {
dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN)
}
if (oflag & _O_RANDOM) != 0 {
dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS)
}
if (oflag & _O_TEMPORARY) != 0 {
dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE)
}
if (oflag & _O_SHORT_LIVED) != 0 {
dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY)
} else {
dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL)
}
}
}
+3 -2
View File
@@ -145,7 +145,6 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// The underlying port right will be automatically deallocated when
/// the Mach.Port object is destroyed.
@available(System 1.4.0, *)
public init(name: mach_port_name_t, context: mach_port_context_t) {
precondition(name != mach_port_name_t(MACH_PORT_NULL),
"Mach.Port cannot be initialized with MACH_PORT_NULL")
@@ -181,6 +180,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(System 1.4.0, *)
public consuming func relinquish(
) -> (name: mach_port_name_t, context: mach_port_context_t) {
@@ -322,7 +322,7 @@ extension Mach.Port where RightType == Mach.SendRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@available(System 1.4.0, *)
@inlinable
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
@@ -365,6 +365,7 @@ extension Mach.Port where RightType == Mach.SendOnceRight {
///
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
@available(System 1.4.0, *)
public consuming func relinquish() -> mach_port_name_t {
let name = _name
-439
View File
@@ -1,439 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2024 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(Windows)
import WinSDK
@_transparent
internal var CREATE_ALWAYS: DWORD {
DWORD(WinSDK.CREATE_ALWAYS)
}
@_transparent
internal var CREATE_NEW: DWORD {
DWORD(WinSDK.CREATE_NEW)
}
@_transparent
internal var ERROR_ACCESS_DENIED: DWORD {
DWORD(WinSDK.ERROR_ACCESS_DENIED)
}
@_transparent
internal var ERROR_ALREADY_EXISTS: DWORD {
DWORD(WinSDK.ERROR_ALREADY_EXISTS)
}
@_transparent
internal var ERROR_ARENA_TRASHED: DWORD {
DWORD(WinSDK.ERROR_ARENA_TRASHED)
}
@_transparent
internal var ERROR_BAD_ENVIRONMENT: DWORD {
DWORD(WinSDK.ERROR_BAD_ENVIRONMENT)
}
@_transparent
internal var ERROR_BAD_FORMAT: DWORD {
DWORD(WinSDK.ERROR_BAD_FORMAT)
}
@_transparent
internal var ERROR_BAD_NET_NAME: DWORD {
DWORD(WinSDK.ERROR_BAD_NET_NAME)
}
@_transparent
internal var ERROR_BAD_NETPATH: DWORD {
DWORD(WinSDK.ERROR_BAD_NETPATH)
}
@_transparent
internal var ERROR_BAD_PATHNAME: DWORD {
DWORD(WinSDK.ERROR_BAD_PATHNAME)
}
@_transparent
internal var ERROR_BROKEN_PIPE: DWORD {
DWORD(WinSDK.ERROR_BROKEN_PIPE)
}
@_transparent
internal var ERROR_CANNOT_MAKE: DWORD {
DWORD(WinSDK.ERROR_CANNOT_MAKE)
}
@_transparent
internal var ERROR_CHILD_NOT_COMPLETE: DWORD {
DWORD(WinSDK.ERROR_CHILD_NOT_COMPLETE)
}
@_transparent
internal var ERROR_CURRENT_DIRECTORY: DWORD {
DWORD(WinSDK.ERROR_CURRENT_DIRECTORY)
}
@_transparent
internal var ERROR_DIR_NOT_EMPTY: DWORD {
DWORD(WinSDK.ERROR_DIR_NOT_EMPTY)
}
@_transparent
internal var ERROR_DISK_FULL: DWORD {
DWORD(WinSDK.ERROR_DISK_FULL)
}
@_transparent
internal var ERROR_DRIVE_LOCKED: DWORD {
DWORD(WinSDK.ERROR_DRIVE_LOCKED)
}
@_transparent
internal var ERROR_DIRECT_ACCESS_HANDLE: DWORD {
DWORD(WinSDK.ERROR_DIRECT_ACCESS_HANDLE)
}
@_transparent
internal var ERROR_FILE_EXISTS: DWORD {
DWORD(WinSDK.ERROR_FILE_EXISTS)
}
@_transparent
internal var ERROR_FILE_NOT_FOUND: DWORD {
DWORD(WinSDK.ERROR_FILE_NOT_FOUND)
}
@_transparent
internal var ERROR_FAIL_I24: DWORD {
DWORD(WinSDK.ERROR_FAIL_I24)
}
@_transparent
internal var ERROR_FILENAME_EXCED_RANGE: DWORD {
DWORD(WinSDK.ERROR_FILENAME_EXCED_RANGE)
}
@_transparent
internal var ERROR_NEGATIVE_SEEK: DWORD {
DWORD(WinSDK.ERROR_NEGATIVE_SEEK)
}
@_transparent
internal var ERROR_NO_MORE_FILES: DWORD {
DWORD(WinSDK.ERROR_NO_MORE_FILES)
}
@_transparent
internal var ERROR_NO_UNICODE_TRANSLATION: DWORD {
DWORD(WinSDK.ERROR_NO_UNICODE_TRANSLATION)
}
@_transparent
internal var ERROR_NOT_ENOUGH_MEMORY: DWORD {
DWORD(WinSDK.ERROR_NOT_ENOUGH_MEMORY)
}
@_transparent
internal var ERROR_INVALID_ACCESS: DWORD {
DWORD(WinSDK.ERROR_INVALID_ACCESS)
}
@_transparent
internal var ERROR_INVALID_BLOCK: DWORD {
DWORD(WinSDK.ERROR_INVALID_BLOCK)
}
@_transparent
internal var ERROR_INVALID_DATA: DWORD {
DWORD(WinSDK.ERROR_INVALID_DATA)
}
@_transparent
internal var ERROR_INVALID_DRIVE: DWORD {
DWORD(WinSDK.ERROR_INVALID_DRIVE)
}
@_transparent
internal var ERROR_INVALID_FUNCTION: DWORD {
DWORD(WinSDK.ERROR_INVALID_FUNCTION)
}
@_transparent
internal var ERROR_INVALID_HANDLE: DWORD {
DWORD(WinSDK.ERROR_INVALID_HANDLE)
}
@_transparent
internal var ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD {
DWORD(WinSDK.ERROR_INFLOOP_IN_RELOC_CHAIN)
}
@_transparent
internal var ERROR_INVALID_PARAMETER: DWORD {
DWORD(WinSDK.ERROR_INVALID_PARAMETER)
}
@_transparent
internal var ERROR_INVALID_STARTING_CODESEG: DWORD {
DWORD(WinSDK.ERROR_INVALID_STARTING_CODESEG)
}
@_transparent
internal var ERROR_INVALID_TARGET_HANDLE: DWORD {
DWORD(WinSDK.ERROR_INVALID_TARGET_HANDLE)
}
@_transparent
internal var ERROR_LOCK_FAILED: DWORD {
DWORD(WinSDK.ERROR_LOCK_FAILED)
}
@_transparent
internal var ERROR_LOCK_VIOLATION: DWORD {
DWORD(WinSDK.ERROR_LOCK_VIOLATION)
}
@_transparent
internal var ERROR_MAX_THRDS_REACHED: DWORD {
DWORD(WinSDK.ERROR_MAX_THRDS_REACHED)
}
@_transparent
internal var ERROR_NESTING_NOT_ALLOWED: DWORD {
DWORD(WinSDK.ERROR_NESTING_NOT_ALLOWED)
}
@_transparent
internal var ERROR_NETWORK_ACCESS_DENIED: DWORD {
DWORD(WinSDK.ERROR_NETWORK_ACCESS_DENIED)
}
@_transparent
internal var ERROR_NO_PROC_SLOTS: DWORD {
DWORD(WinSDK.ERROR_NO_PROC_SLOTS)
}
@_transparent
internal var ERROR_NOT_ENOUGH_QUOTA: DWORD {
DWORD(WinSDK.ERROR_NOT_ENOUGH_QUOTA)
}
@_transparent
internal var ERROR_NOT_LOCKED: DWORD {
DWORD(WinSDK.ERROR_NOT_LOCKED)
}
@_transparent
internal var ERROR_NOT_SAME_DEVICE: DWORD {
DWORD(WinSDK.ERROR_NOT_SAME_DEVICE)
}
@_transparent
internal var ERROR_PATH_NOT_FOUND: DWORD {
DWORD(WinSDK.ERROR_PATH_NOT_FOUND)
}
@_transparent
internal var ERROR_SEEK_ON_DEVICE: DWORD {
DWORD(WinSDK.ERROR_SEEK_ON_DEVICE)
}
@_transparent
internal var ERROR_SHARING_BUFFER_EXCEEDED: DWORD {
DWORD(WinSDK.ERROR_SHARING_BUFFER_EXCEEDED)
}
@_transparent
internal var ERROR_SUCCESS: DWORD {
DWORD(WinSDK.ERROR_SUCCESS)
}
@_transparent
internal var ERROR_WAIT_NO_CHILDREN: DWORD {
DWORD(WinSDK.ERROR_WAIT_NO_CHILDREN)
}
@_transparent
internal var ERROR_WRITE_PROTECT: DWORD {
DWORD(WinSDK.ERROR_WRITE_PROTECT)
}
@_transparent
internal var ERROR_TOO_MANY_OPEN_FILES: DWORD {
DWORD(WinSDK.ERROR_TOO_MANY_OPEN_FILES)
}
@_transparent
internal var FILE_APPEND_DATA: DWORD {
DWORD(WinSDK.FILE_APPEND_DATA)
}
@_transparent
internal var FILE_ATTRIBUTE_DIRECTORY: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_DIRECTORY)
}
@_transparent
internal var FILE_ATTRIBUTE_NORMAL: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_NORMAL)
}
@_transparent
internal var FILE_ATTRIBUTE_TEMPORARY: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_TEMPORARY)
}
@_transparent
internal var FILE_BEGIN: DWORD {
DWORD(WinSDK.FILE_BEGIN)
}
@_transparent
internal var FILE_CURRENT: DWORD {
DWORD(WinSDK.FILE_CURRENT)
}
@_transparent
internal var FILE_DELETE_CHILD: DWORD {
DWORD(WinSDK.FILE_DELETE_CHILD)
}
@_transparent
package var FILE_EXECUTE: DWORD {
DWORD(WinSDK.FILE_EXECUTE)
}
@_transparent
internal var FILE_FLAG_DELETE_ON_CLOSE: DWORD {
DWORD(WinSDK.FILE_FLAG_DELETE_ON_CLOSE)
}
@_transparent
internal var FILE_FLAG_RANDOM_ACCESS: DWORD {
DWORD(WinSDK.FILE_FLAG_RANDOM_ACCESS)
}
@_transparent
internal var FILE_FLAG_SEQUENTIAL_SCAN: DWORD {
DWORD(WinSDK.FILE_FLAG_SEQUENTIAL_SCAN)
}
@_transparent
package var FILE_READ_ATTRIBUTES: DWORD {
DWORD(WinSDK.FILE_READ_ATTRIBUTES)
}
@_transparent
internal var FILE_READ_DATA: DWORD {
DWORD(WinSDK.FILE_READ_DATA)
}
@_transparent
internal var FILE_READ_EA: DWORD {
DWORD(WinSDK.FILE_READ_EA)
}
@_transparent
internal var FILE_SHARE_DELETE: DWORD {
DWORD(WinSDK.FILE_SHARE_DELETE)
}
@_transparent
internal var FILE_SHARE_READ: DWORD {
DWORD(WinSDK.FILE_SHARE_READ)
}
@_transparent
internal var FILE_SHARE_WRITE: DWORD {
DWORD(WinSDK.FILE_SHARE_WRITE)
}
@_transparent
package var FILE_WRITE_ATTRIBUTES: DWORD {
DWORD(WinSDK.FILE_WRITE_ATTRIBUTES)
}
@_transparent
internal var FILE_WRITE_DATA: DWORD {
DWORD(WinSDK.FILE_WRITE_DATA)
}
@_transparent
internal var FILE_WRITE_EA: DWORD {
DWORD(WinSDK.FILE_WRITE_EA)
}
@_transparent
internal var GENERIC_READ: DWORD {
DWORD(WinSDK.GENERIC_READ)
}
@_transparent
internal var GENERIC_WRITE: DWORD {
DWORD(WinSDK.GENERIC_WRITE)
}
@_transparent
internal var NO_INHERITANCE: DWORD {
DWORD(WinSDK.NO_INHERITANCE)
}
@_transparent
internal var OPEN_ALWAYS: DWORD {
DWORD(WinSDK.OPEN_ALWAYS)
}
@_transparent
internal var OPEN_EXISTING: DWORD {
DWORD(WinSDK.OPEN_EXISTING)
}
@_transparent
internal var SE_DACL_PROTECTED: SECURITY_DESCRIPTOR_CONTROL {
SECURITY_DESCRIPTOR_CONTROL(WinSDK.SE_DACL_PROTECTED)
}
@_transparent
internal var SECURITY_DESCRIPTOR_REVISION: DWORD {
DWORD(WinSDK.SECURITY_DESCRIPTOR_REVISION)
}
@_transparent
internal var SECURITY_WORLD_RID: DWORD {
DWORD(WinSDK.SECURITY_WORLD_RID)
}
@_transparent
internal var STANDARD_RIGHTS_READ: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_READ)
}
@_transparent
internal var STANDARD_RIGHTS_EXECUTE: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE)
}
@_transparent
internal var STANDARD_RIGHTS_WRITE: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_WRITE)
}
@_transparent
internal var SYNCHRONIZE: DWORD {
DWORD(WinSDK.SYNCHRONIZE)
}
@_transparent
internal var TRUNCATE_EXISTING: DWORD {
DWORD(WinSDK.TRUNCATE_EXISTING)
}
#endif
+29
View File
@@ -0,0 +1,29 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
extension String {
internal init(
_unsafeUninitializedCapacity capacity: Int,
initializingUTF8With body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows {
if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
self = try String(
unsafeUninitializedCapacity: capacity,
initializingUTF8With: body)
return
}
let array = try Array<UInt8>(
unsafeUninitializedCapacity: capacity
) { buffer, count in
count = try body(buffer)
}
self = String(decoding: array, as: UTF8.self)
}
}
@@ -0,0 +1,100 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// C interoperability types for socket operations
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(Android)
@_implementationOnly import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
import SystemPackage
@available(System 99, *)
extension CInterop {
/// Socket address structure.
///
/// The corresponding C type is `sockaddr`.
public typealias SockAddr = sockaddr
/// Socket address length type.
///
/// The corresponding C type is `socklen_t`.
public typealias SockLen = socklen_t
/// Socket address family type.
///
/// The corresponding C type is `sa_family_t`.
public typealias SAFamily = sa_family_t
/// IPv4 socket address structure.
///
/// The corresponding C type is `sockaddr_in`.
public typealias SockAddrIn = sockaddr_in
/// IPv4 address structure.
///
/// The corresponding C type is `in_addr`.
public typealias InAddr = in_addr
/// IPv4 address type.
///
/// The corresponding C type is `in_addr_t`.
public typealias InAddrT = in_addr_t
/// IPv6 address structure.
///
/// The corresponding C type is `in6_addr`.
public typealias In6Addr = in6_addr
/// Port number type.
///
/// The corresponding C type is `in_port_t`.
public typealias InPort = in_port_t
/// IPv6 socket address structure.
///
/// The corresponding C type is `sockaddr_in6`.
public typealias SockAddrIn6 = sockaddr_in6
/// Unix domain socket address structure.
///
/// The corresponding C type is `sockaddr_un`.
public typealias SockAddrUn = sockaddr_un
/// I/O vector structure for scatter/gather I/O.
///
/// The corresponding C type is `iovec`.
public typealias IOVec = iovec
/// Message header structure for sendmsg/recvmsg.
///
/// The corresponding C type is `msghdr`.
public typealias MsgHdr = msghdr
/// Control message header structure.
///
/// The corresponding C type is `cmsghdr`.
public typealias CMsgHdr = cmsghdr
/// Address info structure for getaddrinfo.
///
/// The corresponding C type is `addrinfo`.
public typealias AddrInfo = addrinfo
}
@@ -0,0 +1,71 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Internal wrappers and typedefs for socket operations
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(Android)
@_implementationOnly import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
import SystemPackage
// MARK: - errno access
#if SYSTEM_PACKAGE_DARWIN
internal var system_errno: CInt {
get { Darwin.errno }
set { Darwin.errno = newValue }
}
#elseif canImport(Glibc)
internal var system_errno: CInt {
get { Glibc.errno }
set { Glibc.errno = newValue }
}
#elseif canImport(Musl)
internal var system_errno: CInt {
get { Musl.errno }
set { Musl.errno = newValue }
}
#elseif canImport(Android)
internal var system_errno: CInt {
get { Android.errno }
set { Android.errno = newValue }
}
#endif
// MARK: - C stdlib functions
@usableFromInline
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
strlen(s)
}
@usableFromInline
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
strlen(s)
}
internal func system_memset(
_ buffer: UnsafeMutableRawBufferPointer,
to byte: UInt8
) {
guard buffer.count > 0 else { return }
memset(buffer.baseAddress!, CInt(byte), buffer.count)
}
@@ -0,0 +1,198 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Syscall mocking support for SystemSockets
//
// This mirrors the mocking infrastructure from SystemPackage for use in socket tests.
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#endif
import SystemPackage
#if ENABLE_MOCKING
internal struct Trace {
internal struct Entry {
internal var name: String
internal var arguments: [AnyHashable]
internal init(name: String, _ arguments: [AnyHashable]) {
self.name = name
self.arguments = arguments
}
}
private var entries: [Entry] = []
private var firstEntry: Int = 0
internal var isEmpty: Bool { firstEntry >= entries.count }
internal mutating func dequeue() -> Entry? {
guard !self.isEmpty else { return nil }
defer { firstEntry += 1 }
return entries[firstEntry]
}
fileprivate mutating func add(_ e: Entry) {
entries.append(e)
}
}
internal enum ForceErrno: Equatable {
case none
case always(errno: CInt)
case counted(errno: CInt, count: Int)
}
internal class MockingDriver {
internal var trace = Trace()
internal var forceErrno = ForceErrno.none
}
// TLS support
#if os(Windows)
internal typealias _PlatformTLSKey = DWORD
#else
internal typealias _PlatformTLSKey = pthread_key_t
#endif
private func makeTLSKey() -> _PlatformTLSKey {
#if os(Windows)
let raw: DWORD = FlsAlloc(nil)
if raw == FLS_OUT_OF_INDEXES {
fatalError("Unable to create key")
}
return raw
#else
var raw = pthread_key_t()
guard 0 == pthread_key_create(&raw, nil) else {
fatalError("Unable to create key")
}
return raw
#endif
}
private func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) {
#if os(Windows)
guard FlsSetValue(key, p) else {
fatalError("Unable to set TLS")
}
#else
guard 0 == pthread_setspecific(key, p) else {
fatalError("Unable to set TLS")
}
#endif
}
private func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
#if os(Windows)
return FlsGetValue(key)
#else
return pthread_getspecific(key)
#endif
}
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
internal var currentMockingDriver: MockingDriver? {
guard let rawPtr = getTLS(driverKey) else { return nil }
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
}
extension MockingDriver {
internal static func withMockingEnabled(
_ f: (MockingDriver) throws -> ()
) rethrows {
let priorMocking = currentMockingDriver
let driver = MockingDriver()
defer {
if let object = priorMocking {
setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
} else {
setTLS(driverKey, nil)
}
_fixLifetime(driver)
}
setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
return try f(driver)
}
}
@inline(never)
private var contextualMockingEnabled: Bool {
return currentMockingDriver != nil
}
extension MockingDriver {
internal static var enabled: Bool { mockingEnabled }
}
#endif // ENABLE_MOCKING
@inline(__always)
internal var mockingEnabled: Bool {
#if ENABLE_MOCKING
return contextualMockingEnabled
#else
return false
#endif
}
#if ENABLE_MOCKING
private func originalSyscallName(_ function: String) -> String {
precondition(function.starts(with: "system_"))
return String(function.dropFirst("system_".count).prefix { $0 != "(" })
}
private func mockImpl(
name: String,
_ args: [AnyHashable]
) -> CInt {
precondition(mockingEnabled)
let origName = originalSyscallName(name)
guard let driver = currentMockingDriver else {
fatalError("Mocking requested from non-mocking context")
}
driver.trace.add(Trace.Entry(name: origName, args))
switch driver.forceErrno {
case .none: break
case .always(let e):
system_errno = e
return -1
case .counted(let e, let count):
assert(count >= 1)
system_errno = e
driver.forceErrno = count > 1 ? .counted(errno: e, count: count - 1) : .none
return -1
}
return 0
}
internal func _mock(
name: String = #function, _ args: AnyHashable...
) -> CInt {
return mockImpl(name: name, args)
}
internal func _mockInt(
name: String = #function, _ args: AnyHashable...
) -> Int {
Int(mockImpl(name: name, args))
}
#endif // ENABLE_MOCKING
@@ -0,0 +1,102 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// A copy-on-write fixed-size buffer of raw memory.
internal struct _RawBuffer {
internal var _storage: Storage?
internal init() {
self._storage = nil
}
internal init(minimumCapacity: Int) {
if minimumCapacity > 0 {
self._storage = Storage.create(minimumCapacity: minimumCapacity)
} else {
self._storage = nil
}
}
}
extension _RawBuffer {
internal var capacity: Int {
_storage?.header ?? 0 // Note: not capacity!
}
internal mutating func ensureUnique() {
guard _storage != nil else { return }
let unique = isKnownUniquelyReferenced(&_storage)
if !unique {
_storage = _copy(capacity: capacity)
}
}
internal func _grow(desired: Int) -> Int {
let next = Int(1.75 * Double(self.capacity))
return Swift.max(next, desired)
}
internal mutating func ensureUnique(capacity: Int) {
let unique = isKnownUniquelyReferenced(&_storage)
if !unique || self.capacity < capacity {
_storage = _copy(capacity: _grow(desired: capacity))
}
}
internal func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
guard let storage = _storage else {
return try body(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try storage.withUnsafeMutablePointers { count, bytes in
let buffer = UnsafeRawBufferPointer(start: bytes, count: count.pointee)
return try body(buffer)
}
}
internal mutating func withUnsafeMutableBytes<R>(
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
guard _storage != nil else {
return try body(UnsafeMutableRawBufferPointer(start: nil, count: 0))
}
ensureUnique()
return try _storage!.withUnsafeMutablePointers { count, bytes in
let buffer = UnsafeMutableRawBufferPointer(start: bytes, count: count.pointee)
return try body(buffer)
}
}
}
extension _RawBuffer {
internal class Storage: ManagedBuffer<Int, UInt8> {
internal static func create(minimumCapacity: Int) -> Storage {
Storage.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: { $0.capacity }
) as! Storage
}
}
internal func _copy(capacity: Int) -> Storage {
let copy = Storage.create(minimumCapacity: capacity)
copy.withUnsafeMutablePointers { dstlen, dst in
self.withUnsafeBytes { src in
guard src.count > 0 else { return }
assert(src.count <= dstlen.pointee)
UnsafeMutableRawPointer(dst)
.copyMemory(
from: src.baseAddress!,
byteCount: Swift.min(src.count, dstlen.pointee))
}
}
return copy
}
}
@@ -0,0 +1,305 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// System call wrappers for socket operations
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(Android)
@_implementationOnly import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
import SystemPackage
// MARK: - Socket creation and management
internal func system_socket(_ domain: CInt, _ type: CInt, _ protocol: CInt) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(domain, type, `protocol`) }
#endif
return socket(domain, type, `protocol`)
}
internal func system_shutdown(_ socket: CInt, _ how: CInt) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, how) }
#endif
return shutdown(socket, how)
}
internal func system_close(_ fd: CInt) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd) }
#endif
return close(fd)
}
// MARK: - Connection operations
internal func system_bind(
_ socket: CInt,
_ addr: UnsafePointer<sockaddr>?,
_ len: socklen_t
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, addr, len) }
#endif
return bind(socket, addr, len)
}
internal func system_listen(_ socket: CInt, _ backlog: CInt) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, backlog) }
#endif
return listen(socket, backlog)
}
internal func system_accept(
_ socket: CInt,
_ addr: UnsafeMutablePointer<sockaddr>?,
_ len: UnsafeMutablePointer<socklen_t>?
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, addr, len) }
#endif
return accept(socket, addr, len)
}
internal func system_connect(
_ socket: CInt,
_ addr: UnsafePointer<sockaddr>?,
_ len: socklen_t
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, addr, len) }
#endif
return connect(socket, addr, len)
}
// MARK: - Data transfer
internal func system_send(
_ socket: CInt,
_ buffer: UnsafeRawPointer?,
_ len: Int,
_ flags: CInt
) -> Int {
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(socket, buffer, len, flags) }
#endif
return send(socket, buffer, len, flags)
}
internal func system_recv(
_ socket: CInt,
_ buffer: UnsafeMutableRawPointer?,
_ len: Int,
_ flags: CInt
) -> Int {
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(socket, buffer, len, flags) }
#endif
return recv(socket, buffer, len, flags)
}
internal func system_sendto(
_ socket: CInt,
_ buffer: UnsafeRawPointer?,
_ length: Int,
_ flags: CInt,
_ dest_addr: UnsafePointer<sockaddr>?,
_ dest_len: socklen_t
) -> Int {
#if ENABLE_MOCKING
if mockingEnabled {
return _mockInt(socket, buffer, length, flags, dest_addr, dest_len)
}
#endif
return sendto(socket, buffer, length, flags, dest_addr, dest_len)
}
internal func system_recvfrom(
_ socket: CInt,
_ buffer: UnsafeMutableRawPointer?,
_ length: Int,
_ flags: CInt,
_ address: UnsafeMutablePointer<sockaddr>?,
_ address_len: UnsafeMutablePointer<socklen_t>?
) -> Int {
#if ENABLE_MOCKING
if mockingEnabled {
return _mockInt(socket, buffer, length, flags, address, address_len)
}
#endif
return recvfrom(socket, buffer, length, flags, address, address_len)
}
internal func system_sendmsg(
_ socket: CInt,
_ message: UnsafePointer<msghdr>?,
_ flags: CInt
) -> Int {
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(socket, message, flags) }
#endif
return sendmsg(socket, message, flags)
}
internal func system_recvmsg(
_ socket: CInt,
_ message: UnsafeMutablePointer<msghdr>?,
_ flags: CInt
) -> Int {
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(socket, message, flags) }
#endif
return recvmsg(socket, message, flags)
}
// MARK: - Socket options
internal func system_getsockopt(
_ socket: CInt,
_ level: CInt,
_ option: CInt,
_ value: UnsafeMutableRawPointer?,
_ length: UnsafeMutablePointer<socklen_t>?
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, level, option, value, length) }
#endif
return getsockopt(socket, level, option, value, length)
}
internal func system_setsockopt(
_ socket: CInt,
_ level: CInt,
_ option: CInt,
_ value: UnsafeRawPointer?,
_ length: socklen_t
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, level, option, value, length) }
#endif
return setsockopt(socket, level, option, value, length)
}
internal func system_getsockname(
_ socket: CInt,
_ addr: UnsafeMutablePointer<sockaddr>?,
_ len: UnsafeMutablePointer<socklen_t>?
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, addr, len) }
#endif
return getsockname(socket, addr, len)
}
internal func system_getpeername(
_ socket: CInt,
_ addr: UnsafeMutablePointer<sockaddr>?,
_ len: UnsafeMutablePointer<socklen_t>?
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(socket, addr, len) }
#endif
return getpeername(socket, addr, len)
}
// MARK: - Address conversion
@usableFromInline
internal func system_inet_ntop(
_ af: CInt,
_ src: UnsafeRawPointer,
_ dst: UnsafeMutablePointer<CChar>,
_ size: socklen_t
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(af, src, dst, size) }
#endif
let res = inet_ntop(af, src, dst, size)
if Int(bitPattern: res) == 0 { return -1 }
return 0
}
@usableFromInline
internal func system_inet_pton(
_ af: CInt,
_ src: UnsafePointer<CChar>,
_ dst: UnsafeMutableRawPointer
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(af, src, dst) }
#endif
return inet_pton(af, src, dst)
}
// MARK: - Name resolution
internal func system_getaddrinfo(
_ hostname: UnsafePointer<CChar>?,
_ servname: UnsafePointer<CChar>?,
_ hints: UnsafePointer<addrinfo>?,
_ res: UnsafeMutablePointer<UnsafeMutablePointer<addrinfo>?>?
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled {
return _mock(
hostname.map { String(cString: $0) },
servname.map { String(cString: $0) },
hints,
res
)
}
#endif
return getaddrinfo(hostname, servname, hints, res)
}
internal func system_getnameinfo(
_ sa: UnsafePointer<sockaddr>?,
_ salen: socklen_t,
_ host: UnsafeMutablePointer<CChar>?,
_ hostlen: socklen_t,
_ serv: UnsafeMutablePointer<CChar>?,
_ servlen: socklen_t,
_ flags: CInt
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled {
return _mock(sa, salen, host, hostlen, serv, servlen, flags)
}
#endif
return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
}
internal func system_freeaddrinfo(
_ addrinfo: UnsafeMutablePointer<addrinfo>?
) {
#if ENABLE_MOCKING
if mockingEnabled {
_ = _mock(addrinfo)
return
}
#endif
freeaddrinfo(addrinfo)
}
internal func system_gai_strerror(_ error: CInt) -> UnsafePointer<CChar> {
gai_strerror(error)
}
+22
View File
@@ -0,0 +1,22 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
extension FixedWidthInteger {
@_alwaysEmitIntoClient
@inline(__always)
internal var _networkOrder: Self {
bigEndian
}
@_alwaysEmitIntoClient
@inline(__always)
internal init(_networkOrder value: Self) {
self.init(bigEndian: value)
}
}
@@ -0,0 +1,110 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(Android)
@_implementationOnly import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
import SystemPackage
@available(System 99, *)
extension SocketAddress {
@frozen
/// The address family identifier
public struct Family: RawRepresentable, Hashable {
public let rawValue: CInterop.SAFamily
@_alwaysEmitIntoClient
public init(rawValue: CInterop.SAFamily) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ rawValue: CInterop.SAFamily) { self.init(rawValue: rawValue) }
/// Unspecified address family.
///
/// The corresponding C constant is `AF_UNSPEC`.
@_alwaysEmitIntoClient
public static var unspecified: Family { Family(CInterop.SAFamily(AF_UNSPEC)) }
/// Local address family.
///
/// The corresponding C constant is `AF_LOCAL`.
@_alwaysEmitIntoClient
public static var local: Family { Family(CInterop.SAFamily(AF_LOCAL)) }
/// UNIX address family. (Renamed `local`.)
///
/// The corresponding C constant is `AF_UNIX`.
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "local")
public static var unix: Family { Family(CInterop.SAFamily(AF_UNIX)) }
/// IPv4 address family.
///
/// The corresponding C constant is `AF_INET`.
@_alwaysEmitIntoClient
public static var ipv4: Family { Family(CInterop.SAFamily(AF_INET)) }
/// Internal routing address family.
///
/// The corresponding C constant is `AF_ROUTE`.
@_alwaysEmitIntoClient
public static var routing: Family { Family(CInterop.SAFamily(AF_ROUTE)) }
/// IPv6 address family.
///
/// The corresponding C constant is `AF_INET6`.
@_alwaysEmitIntoClient
public static var ipv6: Family { Family(CInterop.SAFamily(AF_INET6)) }
#if SYSTEM_PACKAGE_DARWIN
/// System address family.
///
/// The corresponding C constant is `AF_SYSTEM`.
@_alwaysEmitIntoClient
public static var system: Family { Family(CInterop.SAFamily(AF_SYSTEM)) }
/// Raw network device address family.
///
/// The corresponding C constant is `AF_NDRV`
@_alwaysEmitIntoClient
public static var networkDevice: Family { Family(CInterop.SAFamily(AF_NDRV)) }
#endif
}
}
@available(System 99, *)
extension SocketAddress.Family: CustomStringConvertible {
public var description: String {
switch self {
case .unspecified: return "unspecified"
case .local: return "local"
case .ipv4: return "ipv4"
case .routing: return "routing"
case .ipv6: return "ipv6"
#if SYSTEM_PACKAGE_DARWIN
case .system: return "system"
case .networkDevice: return "networkDevice"
#endif
default:
return rawValue.description
}
}
}
@@ -0,0 +1,206 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
/// An IPv4 socket address.
///
/// An IPv4 address consists of a 32-bit IP address and a 16-bit port number.
@frozen
@available(System 99, *)
public struct IPv4Address: Sendable, Equatable, Hashable {
/// The underlying C structure.
@usableFromInline
internal var _storage: sockaddr_in
/// Creates an IPv4 address from a raw sockaddr_in.
@_alwaysEmitIntoClient
public init(_ sockaddr: sockaddr_in) {
_storage = sockaddr
}
/// Creates an IPv4 address from an address string and port.
///
/// - Parameters:
/// - address: The IPv4 address string (e.g., "127.0.0.1").
/// - port: The port number in host byte order.
/// - Returns: `nil` if the address string is invalid.
@_alwaysEmitIntoClient
public init?(_ address: String, port: UInt16) {
var addr = sockaddr_in()
#if SYSTEM_PACKAGE_DARWIN
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
#endif
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = port.bigEndian
let result = address.withCString { cString in
system_inet_pton(AF_INET, cString, &addr.sin_addr)
}
guard result == 1 else { return nil }
_storage = addr
}
/// Creates an IPv4 address representing any address (0.0.0.0).
///
/// - Parameter port: The port number in host byte order.
@_alwaysEmitIntoClient
public static func any(port: UInt16) -> IPv4Address {
var addr = sockaddr_in()
#if SYSTEM_PACKAGE_DARWIN
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
#endif
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = port.bigEndian
addr.sin_addr.s_addr = INADDR_ANY.bigEndian
return IPv4Address(addr)
}
/// Creates an IPv4 address representing the loopback address (127.0.0.1).
///
/// - Parameter port: The port number in host byte order.
@_alwaysEmitIntoClient
public static func loopback(port: UInt16) -> IPv4Address {
var addr = sockaddr_in()
#if SYSTEM_PACKAGE_DARWIN
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
#endif
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = port.bigEndian
addr.sin_addr.s_addr = INADDR_LOOPBACK.bigEndian
return IPv4Address(addr)
}
}
// MARK: - Properties
@available(System 99, *)
extension IPv4Address {
/// The port number in host byte order.
@_alwaysEmitIntoClient
public var port: UInt16 {
UInt16(bigEndian: _storage.sin_port)
}
/// The IP address as a string.
public var addressString: String {
var buffer = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
var addr = _storage.sin_addr
_ = Swift.withUnsafePointer(to: &addr) { ptr in
system_inet_ntop(AF_INET, ptr, &buffer, socklen_t(buffer.count))
}
return String(cString: buffer)
}
}
// MARK: - Pointer Access
@available(System 99, *)
extension IPv4Address {
/// Calls the given closure with a pointer to the underlying sockaddr.
@_alwaysEmitIntoClient
public func withUnsafePointer<R>(
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
) rethrows -> R {
try Swift.withUnsafePointer(to: _storage) { storage in
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
try body(sockaddr, CInterop.SockLen(MemoryLayout<sockaddr_in>.size))
}
}
}
}
// MARK: - CustomStringConvertible
@available(System 99, *)
extension IPv4Address: CustomStringConvertible {
public var description: String {
"\(addressString):\(port)"
}
}
// MARK: - ExpressibleByStringLiteral
@available(System 99, *)
extension IPv4Address: ExpressibleByStringLiteral {
/// Creates an IPv4 address from a string literal.
///
/// The format is "address:port" (e.g., "127.0.0.1:8080").
/// If no port is specified, port 0 is used.
public init(stringLiteral value: String) {
let parts = value.split(separator: ":", maxSplits: 1)
let address = String(parts[0])
let port: UInt16 = parts.count > 1 ? UInt16(parts[1]) ?? 0 : 0
guard let addr = IPv4Address(address, port: port) else {
fatalError("Invalid IPv4 address literal: \(value)")
}
self = addr
}
}
// MARK: - Equatable and Hashable
@available(System 99, *)
extension IPv4Address {
@_alwaysEmitIntoClient
public static func == (lhs: IPv4Address, rhs: IPv4Address) -> Bool {
lhs._storage.sin_family == rhs._storage.sin_family &&
lhs._storage.sin_port == rhs._storage.sin_port &&
lhs._storage.sin_addr.s_addr == rhs._storage.sin_addr.s_addr
}
@_alwaysEmitIntoClient
public func hash(into hasher: inout Hasher) {
hasher.combine(_storage.sin_family)
hasher.combine(_storage.sin_port)
hasher.combine(_storage.sin_addr.s_addr)
}
}
// MARK: - SocketAddress Integration
@available(System 99, *)
extension SocketAddress {
/// Creates a socket address from an IPv4 address.
@_alwaysEmitIntoClient
public init(ipv4: IPv4Address) {
self.init()
ipv4.withUnsafePointer { addr, len in
withUnsafeMutableBytes(of: &_storage) { dest in
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
}
_length = len
}
}
/// The address as an IPv4 address, if applicable.
@_alwaysEmitIntoClient
public var ipv4: IPv4Address? {
guard family == .ipv4 else { return nil }
return Swift.withUnsafeBytes(of: _storage) { buffer in
buffer.baseAddress!.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { ptr in
IPv4Address(ptr.pointee)
}
}
}
}
@@ -0,0 +1,234 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
/// An IPv6 socket address.
///
/// An IPv6 address consists of a 128-bit IP address, a 16-bit port number,
/// a flow label, and a scope ID.
@frozen
@available(System 99, *)
public struct IPv6Address: Sendable, Hashable {
/// The underlying C structure.
@usableFromInline
internal var _storage: sockaddr_in6
/// Creates an IPv6 address from a raw sockaddr_in6.
@_alwaysEmitIntoClient
public init(_ sockaddr: sockaddr_in6) {
_storage = sockaddr
}
/// Creates an IPv6 address from an address string and port.
///
/// - Parameters:
/// - address: The IPv6 address string (e.g., "::1" or "2001:db8::1").
/// - port: The port number in host byte order.
/// - Returns: `nil` if the address string is invalid.
@_alwaysEmitIntoClient
public init?(_ address: String, port: UInt16) {
var addr = sockaddr_in6()
#if SYSTEM_PACKAGE_DARWIN
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
#endif
addr.sin6_family = sa_family_t(AF_INET6)
addr.sin6_port = port.bigEndian
let result = address.withCString { cString in
system_inet_pton(AF_INET6, cString, &addr.sin6_addr)
}
guard result == 1 else { return nil }
_storage = addr
}
/// Creates an IPv6 address representing any address (::).
///
/// - Parameter port: The port number in host byte order.
@_alwaysEmitIntoClient
public static func any(port: UInt16) -> IPv6Address {
var addr = sockaddr_in6()
#if SYSTEM_PACKAGE_DARWIN
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
#endif
addr.sin6_family = sa_family_t(AF_INET6)
addr.sin6_port = port.bigEndian
addr.sin6_addr = in6addr_any
return IPv6Address(addr)
}
/// Creates an IPv6 address representing the loopback address (::1).
///
/// - Parameter port: The port number in host byte order.
@_alwaysEmitIntoClient
public static func loopback(port: UInt16) -> IPv6Address {
var addr = sockaddr_in6()
#if SYSTEM_PACKAGE_DARWIN
addr.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
#endif
addr.sin6_family = sa_family_t(AF_INET6)
addr.sin6_port = port.bigEndian
addr.sin6_addr = in6addr_loopback
return IPv6Address(addr)
}
}
// MARK: - Properties
@available(System 99, *)
extension IPv6Address {
/// The port number in host byte order.
@_alwaysEmitIntoClient
public var port: UInt16 {
UInt16(bigEndian: _storage.sin6_port)
}
/// The flow label.
@_alwaysEmitIntoClient
public var flowLabel: UInt32 {
_storage.sin6_flowinfo
}
/// The scope ID.
@_alwaysEmitIntoClient
public var scopeID: UInt32 {
_storage.sin6_scope_id
}
/// The IP address as a string.
public var addressString: String {
var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
var addr = _storage.sin6_addr
_ = Swift.withUnsafePointer(to: &addr) { ptr in
system_inet_ntop(AF_INET6, ptr, &buffer, socklen_t(buffer.count))
}
return String(cString: buffer)
}
}
// MARK: - Pointer Access
@available(System 99, *)
extension IPv6Address {
/// Calls the given closure with a pointer to the underlying sockaddr.
@_alwaysEmitIntoClient
public func withUnsafePointer<R>(
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
) rethrows -> R {
try Swift.withUnsafePointer(to: _storage) { storage in
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
try body(sockaddr, CInterop.SockLen(MemoryLayout<sockaddr_in6>.size))
}
}
}
}
// MARK: - CustomStringConvertible
@available(System 99, *)
extension IPv6Address: CustomStringConvertible {
public var description: String {
"[\(addressString)]:\(port)"
}
}
// MARK: - ExpressibleByStringLiteral
@available(System 99, *)
extension IPv6Address: ExpressibleByStringLiteral {
/// Creates an IPv6 address from a string literal.
///
/// The format is "[address]:port" (e.g., "[::1]:8080") or "address"
/// for port 0.
public init(stringLiteral value: String) {
var address = value
var port: UInt16 = 0
// Handle [address]:port format
if value.hasPrefix("[") {
if let closeBracket = value.lastIndex(of: "]") {
address = String(value[value.index(after: value.startIndex)..<closeBracket])
let afterBracket = value.index(after: closeBracket)
if afterBracket < value.endIndex && value[afterBracket] == ":" {
let portStart = value.index(after: afterBracket)
if let p = UInt16(value[portStart...]) {
port = p
}
}
}
}
guard let addr = IPv6Address(address, port: port) else {
fatalError("Invalid IPv6 address literal: \(value)")
}
self = addr
}
}
// MARK: - Equatable and Hashable
@available(System 99, *)
extension IPv6Address {
@_alwaysEmitIntoClient
public static func == (lhs: IPv6Address, rhs: IPv6Address) -> Bool {
Swift.withUnsafeBytes(of: lhs._storage) { lhsBytes in
Swift.withUnsafeBytes(of: rhs._storage) { rhsBytes in
lhsBytes.elementsEqual(rhsBytes)
}
}
}
@_alwaysEmitIntoClient
public func hash(into hasher: inout Hasher) {
Swift.withUnsafeBytes(of: _storage) { bytes in
hasher.combine(bytes: bytes)
}
}
}
// MARK: - SocketAddress Integration
@available(System 99, *)
extension SocketAddress {
/// Creates a socket address from an IPv6 address.
@_alwaysEmitIntoClient
public init(ipv6: IPv6Address) {
self.init()
ipv6.withUnsafePointer { addr, len in
withUnsafeMutableBytes(of: &_storage) { dest in
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
}
_length = len
}
}
/// The address as an IPv6 address, if applicable.
@_alwaysEmitIntoClient
public var ipv6: IPv6Address? {
guard family == .ipv6 else { return nil }
return Swift.withUnsafeBytes(of: _storage) { buffer in
buffer.baseAddress!.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { ptr in
IPv6Address(ptr.pointee)
}
}
}
}
@@ -0,0 +1,346 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: - Address Resolution Error
/// An error returned by address resolution functions.
@frozen
@available(System 99, *)
public struct AddressResolutionError: Error, Hashable, Sendable {
/// The error code returned by getaddrinfo or getnameinfo.
public let code: CInt
@_alwaysEmitIntoClient
public init(code: CInt) {
self.code = code
}
/// A human-readable error message.
public var message: String {
String(cString: system_gai_strerror(code))
}
}
@available(System 99, *)
extension AddressResolutionError: CustomStringConvertible {
public var description: String {
"AddressResolutionError(\(code)): \(message)"
}
}
// MARK: - Resolution Hints
@available(System 99, *)
extension SocketAddress {
/// Hints for address resolution.
public struct ResolutionHints: Sendable {
/// The protocol family to search for.
public var family: SocketDescriptor.Domain?
/// The socket type to search for.
public var socketType: SocketDescriptor.ConnectionType?
/// The protocol to search for.
public var `protocol`: SocketDescriptor.ProtocolID?
/// Resolution flags.
public var flags: ResolutionFlags
/// Creates resolution hints with the given parameters.
public init(
family: SocketDescriptor.Domain? = nil,
socketType: SocketDescriptor.ConnectionType? = nil,
protocol: SocketDescriptor.ProtocolID? = nil,
flags: ResolutionFlags = []
) {
self.family = family
self.socketType = socketType
self.protocol = `protocol`
self.flags = flags
}
}
/// Flags for address resolution.
@frozen
public struct ResolutionFlags: OptionSet, Sendable {
public var rawValue: CInt
public init(rawValue: CInt) {
self.rawValue = rawValue
}
/// Use passive socket for binding.
///
/// The corresponding C constant is `AI_PASSIVE`.
public static var passive: ResolutionFlags { ResolutionFlags(rawValue: AI_PASSIVE) }
/// Return canonical name.
///
/// The corresponding C constant is `AI_CANONNAME`.
public static var canonicalName: ResolutionFlags { ResolutionFlags(rawValue: AI_CANONNAME) }
/// Address must be numeric.
///
/// The corresponding C constant is `AI_NUMERICHOST`.
public static var numericHost: ResolutionFlags { ResolutionFlags(rawValue: AI_NUMERICHOST) }
/// Service must be numeric.
///
/// The corresponding C constant is `AI_NUMERICSERV`.
public static var numericService: ResolutionFlags { ResolutionFlags(rawValue: AI_NUMERICSERV) }
/// Return IPv4-mapped IPv6 addresses.
///
/// The corresponding C constant is `AI_V4MAPPED`.
public static var v4Mapped: ResolutionFlags { ResolutionFlags(rawValue: AI_V4MAPPED) }
/// Return both IPv4 and IPv6 addresses.
///
/// The corresponding C constant is `AI_ALL`.
public static var all: ResolutionFlags { ResolutionFlags(rawValue: AI_ALL) }
/// Return addresses only if configured.
///
/// The corresponding C constant is `AI_ADDRCONFIG`.
public static var addressConfigured: ResolutionFlags { ResolutionFlags(rawValue: AI_ADDRCONFIG) }
}
}
// MARK: - Resolution Result
@available(System 99, *)
extension SocketAddress {
/// A result from address resolution.
public struct ResolvedAddress: Sendable {
/// The socket domain.
public let family: SocketDescriptor.Domain
/// The socket type.
public let socketType: SocketDescriptor.ConnectionType
/// The socket protocol.
public let `protocol`: SocketDescriptor.ProtocolID
/// The resolved socket address.
public let address: SocketAddress
/// The canonical name, if requested and available.
public let canonicalName: String?
internal init(
family: SocketDescriptor.Domain,
socketType: SocketDescriptor.ConnectionType,
protocol: SocketDescriptor.ProtocolID,
address: SocketAddress,
canonicalName: String?
) {
self.family = family
self.socketType = socketType
self.protocol = `protocol`
self.address = address
self.canonicalName = canonicalName
}
}
}
// MARK: - Address Resolution
@available(System 99, *)
extension SocketAddress {
/// Resolves a hostname and service to a list of socket addresses.
///
/// - Parameters:
/// - hostname: The hostname to resolve, or `nil` for the local host.
/// - service: The service name or port number, or `nil`.
/// - hints: Hints to narrow the search.
/// - Returns: An array of resolved addresses.
/// - Throws: `AddressResolutionError` if resolution fails.
///
/// The corresponding C function is `getaddrinfo`.
public static func resolve(
hostname: String? = nil,
service: String? = nil,
hints: ResolutionHints = ResolutionHints()
) throws -> [ResolvedAddress] {
var hintsStruct = addrinfo()
hintsStruct.ai_flags = hints.flags.rawValue
if let family = hints.family {
hintsStruct.ai_family = family.rawValue
}
if let socketType = hints.socketType {
hintsStruct.ai_socktype = socketType.rawValue
}
if let proto = hints.protocol {
hintsStruct.ai_protocol = proto.rawValue
}
var result: UnsafeMutablePointer<addrinfo>?
let errorCode: CInt = hostname._withOptionalCString { hostnamePtr in
service._withOptionalCString { servicePtr in
system_getaddrinfo(hostnamePtr, servicePtr, &hintsStruct, &result)
}
}
guard errorCode == 0 else {
throw AddressResolutionError(code: errorCode)
}
defer { system_freeaddrinfo(result) }
var addresses: [ResolvedAddress] = []
var current = result
while let info = current {
let family = SocketDescriptor.Domain(rawValue: info.pointee.ai_family)
let socketType = SocketDescriptor.ConnectionType(rawValue: info.pointee.ai_socktype)
let proto = SocketDescriptor.ProtocolID(rawValue: info.pointee.ai_protocol)
let address: SocketAddress
if let addr = info.pointee.ai_addr {
address = SocketAddress(
address: addr,
length: info.pointee.ai_addrlen
)
} else {
address = SocketAddress()
}
let canonicalName: String?
if let name = info.pointee.ai_canonname {
canonicalName = String(cString: name)
} else {
canonicalName = nil
}
addresses.append(ResolvedAddress(
family: family,
socketType: socketType,
protocol: proto,
address: address,
canonicalName: canonicalName
))
current = info.pointee.ai_next
}
return addresses
}
}
// MARK: - Reverse Resolution
@available(System 99, *)
extension SocketAddress {
/// Flags for reverse resolution.
@frozen
public struct ReverseResolutionFlags: OptionSet, Sendable {
public var rawValue: CInt
public init(rawValue: CInt) {
self.rawValue = rawValue
}
/// Return numeric host.
///
/// The corresponding C constant is `NI_NUMERICHOST`.
public static var numericHost: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NUMERICHOST) }
/// Return numeric service.
///
/// The corresponding C constant is `NI_NUMERICSERV`.
public static var numericService: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NUMERICSERV) }
/// Look up datagram service.
///
/// The corresponding C constant is `NI_DGRAM`.
public static var datagram: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_DGRAM) }
/// Return only the hostname part of FQDN.
///
/// The corresponding C constant is `NI_NOFQDN`.
public static var noFullyQualified: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NOFQDN) }
/// Fail if name cannot be determined.
///
/// The corresponding C constant is `NI_NAMEREQD`.
public static var nameRequired: ReverseResolutionFlags { ReverseResolutionFlags(rawValue: NI_NAMEREQD) }
}
/// A result from reverse resolution.
public struct ReverseLookupResult: Sendable {
/// The hostname.
public let hostname: String?
/// The service name.
public let service: String?
}
/// Resolves this address to a hostname and service.
///
/// - Parameter flags: Flags controlling the resolution.
/// - Returns: The hostname and service.
/// - Throws: `AddressResolutionError` if resolution fails.
///
/// The corresponding C function is `getnameinfo`.
public func reverseLookup(
flags: ReverseResolutionFlags = []
) throws -> ReverseLookupResult {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
var service = [CChar](repeating: 0, count: Int(NI_MAXSERV))
let errorCode = withUnsafePointer { addr, len in
system_getnameinfo(
addr,
len,
&hostname,
socklen_t(hostname.count),
&service,
socklen_t(service.count),
flags.rawValue
)
}
guard errorCode == 0 else {
throw AddressResolutionError(code: errorCode)
}
let hostnameStr = hostname[0] != 0 ? String(cString: hostname) : nil
let serviceStr = service[0] != 0 ? String(cString: service) : nil
return ReverseLookupResult(hostname: hostnameStr, service: serviceStr)
}
}
// MARK: - Helpers
extension Optional where Wrapped == String {
func _withOptionalCString<R>(_ body: (UnsafePointer<CChar>?) throws -> R) rethrows -> R {
switch self {
case .none:
return try body(nil)
case .some(let string):
return try string.withCString(body)
}
}
}
@@ -0,0 +1,176 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
/// A Unix domain socket address.
///
/// Unix domain socket addresses use a filesystem path to identify the socket.
@frozen
@available(System 99, *)
public struct UnixAddress: Sendable, Equatable, Hashable {
/// The underlying C structure.
@usableFromInline
internal var _storage: sockaddr_un
/// The length of the path (not including null terminator).
@usableFromInline
internal var _pathLength: Int
/// Creates a Unix address from a raw sockaddr_un.
@_alwaysEmitIntoClient
public init(_ sockaddr: sockaddr_un) {
_storage = sockaddr
// Calculate path length from the stored data
_pathLength = withUnsafeBytes(of: sockaddr.sun_path) { bytes in
bytes.prefix(while: { $0 != 0 }).count
}
}
/// Creates a Unix address from a path string.
///
/// - Parameter path: The filesystem path for the socket.
/// - Returns: `nil` if the path is too long.
@_alwaysEmitIntoClient
public init?(_ path: String) {
var addr = sockaddr_un()
#if SYSTEM_PACKAGE_DARWIN
addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
#endif
addr.sun_family = sa_family_t(AF_UNIX)
let maxPathLength = MemoryLayout.size(ofValue: addr.sun_path) - 1 // Leave room for null
let copied = path.withCString { cString in
let len = system_strlen(cString)
guard len <= maxPathLength else { return -1 }
withUnsafeMutableBytes(of: &addr.sun_path) { dest in
dest.copyMemory(from: UnsafeRawBufferPointer(start: cString, count: len + 1))
}
return len
}
guard copied >= 0 else { return nil }
_storage = addr
_pathLength = copied
}
}
// MARK: - Properties
@available(System 99, *)
extension UnixAddress {
/// The path as a string.
public var path: String {
withUnsafeBytes(of: _storage.sun_path) { bytes in
let pathBytes = bytes.prefix(_pathLength)
return pathBytes.withMemoryRebound(to: CChar.self) { chars in
String(cString: chars.baseAddress!)
}
}
}
}
// MARK: - Pointer Access
@available(System 99, *)
extension UnixAddress {
/// Calls the given closure with a pointer to the underlying sockaddr.
@_alwaysEmitIntoClient
public func withUnsafePointer<R>(
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
) rethrows -> R {
try Swift.withUnsafePointer(to: _storage) { storage in
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
// Length includes sun_family plus the path (including null terminator)
let length = MemoryLayout<sa_family_t>.size + _pathLength + 1
#if SYSTEM_PACKAGE_DARWIN
let actualLength = MemoryLayout<UInt8>.size + length // Include sun_len
#else
let actualLength = length
#endif
return try body(sockaddr, CInterop.SockLen(actualLength))
}
}
}
}
// MARK: - CustomStringConvertible
@available(System 99, *)
extension UnixAddress: CustomStringConvertible {
public var description: String {
path
}
}
// MARK: - Equatable and Hashable
@available(System 99, *)
extension UnixAddress {
@_alwaysEmitIntoClient
public static func == (lhs: UnixAddress, rhs: UnixAddress) -> Bool {
lhs._pathLength == rhs._pathLength &&
Swift.withUnsafeBytes(of: lhs._storage.sun_path) { lhsBytes in
Swift.withUnsafeBytes(of: rhs._storage.sun_path) { rhsBytes in
lhsBytes.prefix(lhs._pathLength).elementsEqual(rhsBytes.prefix(rhs._pathLength))
}
}
}
@_alwaysEmitIntoClient
public func hash(into hasher: inout Hasher) {
hasher.combine(_pathLength)
Swift.withUnsafeBytes(of: _storage.sun_path) { bytes in
hasher.combine(bytes: UnsafeRawBufferPointer(rebasing: bytes.prefix(_pathLength)))
}
}
}
// MARK: - SocketAddress Integration
@available(System 99, *)
extension SocketAddress {
/// Creates a socket address from a Unix address.
@_alwaysEmitIntoClient
public init(unix: UnixAddress) {
self.init()
unix.withUnsafePointer { addr, len in
withUnsafeMutableBytes(of: &_storage) { dest in
dest.copyMemory(from: UnsafeRawBufferPointer(start: addr, count: Int(len)))
}
_length = len
}
}
/// The address as a Unix address, if applicable.
@_alwaysEmitIntoClient
public var unix: UnixAddress? {
guard family == .local else { return nil }
return Swift.withUnsafeBytes(of: _storage) { buffer in
buffer.baseAddress!.withMemoryRebound(to: sockaddr_un.self, capacity: 1) { ptr in
UnixAddress(ptr.pointee)
}
}
}
}
@@ -0,0 +1,223 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
/// An opaque type representing a socket address.
///
/// `SocketAddress` is a type-erased container that can hold any socket address,
/// including IPv4, IPv6, and Unix domain addresses. It provides a unified
/// interface for socket operations that work with different address families.
///
/// To create a socket address for a specific family, use one of the convenience
/// initializers:
///
/// ```swift
/// // IPv4 address
/// let ipv4 = SocketAddress(ipv4: IPv4Address("127.0.0.1", port: 8080)!)
///
/// // IPv6 address
/// let ipv6 = SocketAddress(ipv6: IPv6Address.loopback(port: 80))
///
/// // Unix domain socket
/// let local = SocketAddress(unix: UnixAddress("/tmp/socket.sock")!)
/// ```
///
/// `SocketAddress` uses `sockaddr_storage` internally, which is large enough
/// to hold any socket address type.
@frozen
@available(System 99, *)
public struct SocketAddress: Sendable {
/// The underlying storage using sockaddr_storage.
@usableFromInline
internal var _storage: sockaddr_storage
/// The actual length of the address data.
@usableFromInline
internal var _length: CInterop.SockLen
/// Creates an empty socket address with unspecified family.
@_alwaysEmitIntoClient
public init() {
_storage = sockaddr_storage()
_length = 0
}
/// Creates a socket address from raw bytes.
///
/// - Parameters:
/// - address: Pointer to the socket address.
/// - length: The length of the address.
@_alwaysEmitIntoClient
public init(
address: UnsafePointer<CInterop.SockAddr>,
length: CInterop.SockLen
) {
_storage = sockaddr_storage()
_length = min(length, CInterop.SockLen(MemoryLayout<sockaddr_storage>.size))
withUnsafeMutableBytes(of: &_storage) { dest in
dest.copyMemory(from: UnsafeRawBufferPointer(start: address, count: Int(_length)))
}
}
/// Creates a socket address from a raw buffer.
@_alwaysEmitIntoClient
public init(_ buffer: UnsafeRawBufferPointer) {
_storage = sockaddr_storage()
_length = CInterop.SockLen(min(buffer.count, MemoryLayout<sockaddr_storage>.size))
if buffer.count > 0 {
withUnsafeMutableBytes(of: &_storage) { dest in
dest.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer.prefix(Int(_length))))
}
}
}
}
// MARK: - Properties
@available(System 99, *)
extension SocketAddress {
/// The address family of this socket address.
@_alwaysEmitIntoClient
public var family: SocketDescriptor.Domain {
Swift.withUnsafeBytes(of: _storage) { buffer in
let sockaddr = buffer.baseAddress!.assumingMemoryBound(to: sockaddr.self)
return SocketDescriptor.Domain(rawValue: CInt(sockaddr.pointee.sa_family))
}
}
/// The length of this socket address in bytes.
@_alwaysEmitIntoClient
public var length: Int {
Int(_length)
}
/// Whether this address is empty (length is 0).
@_alwaysEmitIntoClient
public var isEmpty: Bool {
_length == 0
}
}
// MARK: - Accessing Raw Bytes
@available(System 99, *)
extension SocketAddress {
/// Calls the given closure with a pointer to the underlying socket address.
@_alwaysEmitIntoClient
public func withUnsafePointer<R>(
_ body: (UnsafePointer<sockaddr>, CInterop.SockLen) throws -> R
) rethrows -> R {
try Swift.withUnsafePointer(to: _storage) { storage in
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
try body(sockaddr, _length)
}
}
}
/// Calls the given closure with a mutable pointer to the underlying storage.
@_alwaysEmitIntoClient
public mutating func _withUnsafeMutablePointer<R>(
_ body: (UnsafeMutablePointer<sockaddr>, inout CInterop.SockLen) throws -> R
) rethrows -> R {
var len = CInterop.SockLen(MemoryLayout<sockaddr_storage>.size)
let result = try Swift.withUnsafeMutablePointer(to: &_storage) { storage in
try storage.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddr in
try body(sockaddr, &len)
}
}
_length = len
return result
}
/// Accesses the raw bytes of the socket address.
@_alwaysEmitIntoClient
public func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
try Swift.withUnsafeBytes(of: _storage) { buffer in
try body(UnsafeRawBufferPointer(rebasing: buffer.prefix(Int(_length))))
}
}
/// Resets this address to an empty state.
@_alwaysEmitIntoClient
public mutating func clear() {
_storage = sockaddr_storage()
_length = 0
}
}
// MARK: - Equatable and Hashable
@available(System 99, *)
extension SocketAddress: Equatable {
@_alwaysEmitIntoClient
public static func == (lhs: SocketAddress, rhs: SocketAddress) -> Bool {
guard lhs._length == rhs._length else { return false }
return lhs.withUnsafeBytes { lhsBytes in
rhs.withUnsafeBytes { rhsBytes in
lhsBytes.elementsEqual(rhsBytes)
}
}
}
}
@available(System 99, *)
extension SocketAddress: Hashable {
@_alwaysEmitIntoClient
public func hash(into hasher: inout Hasher) {
hasher.combine(_length)
withUnsafeBytes { buffer in
hasher.combine(bytes: buffer)
}
}
}
// MARK: - CustomStringConvertible
@available(System 99, *)
extension SocketAddress: CustomStringConvertible {
public var description: String {
if isEmpty {
return "SocketAddress(empty)"
}
switch family {
case .ipv4:
if let ipv4 = self.ipv4 {
return "SocketAddress(\(ipv4))"
}
case .ipv6:
if let ipv6 = self.ipv6 {
return "SocketAddress(\(ipv6))"
}
case .local:
if let unix = self.unix {
return "SocketAddress(\(unix))"
}
default:
break
}
return "SocketAddress(family: \(family), length: \(_length))"
}
}
@@ -0,0 +1,440 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
/// A socket descriptor.
///
/// A `SocketDescriptor` is a type-safe wrapper around an operating system
/// socket handle. It provides a strongly-typed interface for socket operations.
///
/// Unlike `FileDescriptor`, a `SocketDescriptor` explicitly represents a
/// socket rather than a general file descriptor, enabling socket-specific
/// operations like `bind`, `listen`, `accept`, and `connect`.
@frozen
@available(System 99, *)
public struct SocketDescriptor: RawRepresentable, Hashable, Codable, Sendable {
/// The raw C socket handle.
@_alwaysEmitIntoClient
public let rawValue: CInt
/// Creates a strongly-typed socket descriptor from a raw C socket handle.
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
}
@available(System 99, *)
extension SocketDescriptor {
/// The file descriptor for this socket.
///
/// On POSIX systems, sockets are file descriptors and can be used with
/// file descriptor operations like `read`, `write`, and `close`.
@_alwaysEmitIntoClient
public var fileDescriptor: FileDescriptor {
FileDescriptor(rawValue: rawValue)
}
/// Creates a socket descriptor from a file descriptor without verification.
///
/// This initializer does not verify that the file descriptor actually
/// refers to a socket. Use with caution.
@_alwaysEmitIntoClient
public init(unchecked fd: FileDescriptor) {
self.init(rawValue: fd.rawValue)
}
}
// MARK: - Domain (Protocol Family)
@available(System 99, *)
extension SocketDescriptor {
/// Communications domain, identifying the protocol family.
///
/// The domain specifies the protocol family to be used for communication.
/// Common domains include `.ipv4` for IPv4, `.ipv6` for IPv6, and `.local`
/// for Unix domain sockets.
@frozen
public struct Domain: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
/// Unspecified protocol.
///
/// The corresponding C constant is `PF_UNSPEC`.
@_alwaysEmitIntoClient
public static var unspecified: Domain { Domain(PF_UNSPEC) }
/// Local (Unix domain) communication.
///
/// The corresponding C constant is `PF_LOCAL` (also known as `PF_UNIX`).
@_alwaysEmitIntoClient
public static var local: Domain { Domain(PF_LOCAL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "local")
public static var unix: Domain { Domain(PF_UNIX) }
/// Internet Protocol version 4.
///
/// The corresponding C constant is `PF_INET`.
@_alwaysEmitIntoClient
public static var ipv4: Domain { Domain(PF_INET) }
/// Internet Protocol version 6.
///
/// The corresponding C constant is `PF_INET6`.
@_alwaysEmitIntoClient
public static var ipv6: Domain { Domain(PF_INET6) }
/// Internal routing protocol.
///
/// The corresponding C constant is `PF_ROUTE`.
@_alwaysEmitIntoClient
public static var routing: Domain { Domain(PF_ROUTE) }
/// Internal key-management function.
///
/// The corresponding C constant is `PF_KEY`.
@_alwaysEmitIntoClient
public static var keyManagement: Domain { Domain(PF_KEY) }
#if SYSTEM_PACKAGE_DARWIN
/// System domain.
///
/// The corresponding C constant is `PF_SYSTEM`.
@_alwaysEmitIntoClient
public static var system: Domain { Domain(PF_SYSTEM) }
/// Raw access to network device.
///
/// The corresponding C constant is `PF_NDRV`.
@_alwaysEmitIntoClient
public static var networkDevice: Domain { Domain(PF_NDRV) }
#endif
public var description: String {
switch self {
case .unspecified: return "unspecified"
case .local: return "local"
case .ipv4: return "ipv4"
case .ipv6: return "ipv6"
case .routing: return "routing"
case .keyManagement: return "keyManagement"
#if SYSTEM_PACKAGE_DARWIN
case .system: return "system"
case .networkDevice: return "networkDevice"
#endif
default: return "Domain(\(rawValue))"
}
}
}
}
// MARK: - Connection Type (Socket Type)
@available(System 99, *)
extension SocketDescriptor {
/// The socket type, specifying the semantics of communication.
///
/// The connection type determines how data is transmitted. Stream sockets
/// provide reliable, ordered byte streams, while datagram sockets provide
/// connectionless, unreliable messages.
@frozen
public struct ConnectionType: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
/// Sequenced, reliable, two-way, connection-based byte streams.
///
/// The corresponding C constant is `SOCK_STREAM`.
@_alwaysEmitIntoClient
public static var stream: ConnectionType { ConnectionType(SOCK_STREAM) }
/// Connectionless, unreliable datagrams of a fixed maximum length.
///
/// The corresponding C constant is `SOCK_DGRAM`.
@_alwaysEmitIntoClient
public static var datagram: ConnectionType { ConnectionType(SOCK_DGRAM) }
/// Raw network protocol access.
///
/// The corresponding C constant is `SOCK_RAW`.
@_alwaysEmitIntoClient
public static var raw: ConnectionType { ConnectionType(SOCK_RAW) }
/// Reliably-delivered message.
///
/// The corresponding C constant is `SOCK_RDM`.
@_alwaysEmitIntoClient
public static var reliablyDeliveredMessage: ConnectionType {
ConnectionType(SOCK_RDM)
}
/// Sequenced packet stream.
///
/// The corresponding C constant is `SOCK_SEQPACKET`.
@_alwaysEmitIntoClient
public static var sequencedPacketStream: ConnectionType {
ConnectionType(SOCK_SEQPACKET)
}
public var description: String {
switch self {
case .stream: return "stream"
case .datagram: return "datagram"
case .raw: return "raw"
case .reliablyDeliveredMessage: return "rdm"
case .sequencedPacketStream: return "seqpacket"
default: return "ConnectionType(\(rawValue))"
}
}
}
}
// MARK: - Protocol ID
@available(System 99, *)
extension SocketDescriptor {
/// Identifies a particular protocol to use for communication.
///
/// Protocol numbers are specific to the communication domain. Some symbolic
/// names may have the same underlying value in different contexts.
@frozen
public struct ProtocolID: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
internal init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
/// Default protocol for the socket type.
@_alwaysEmitIntoClient
public static var `default`: ProtocolID { Self(0) }
/// Internet Protocol (IP).
///
/// The corresponding C constant is `IPPROTO_IP`.
@_alwaysEmitIntoClient
public static var ip: ProtocolID { Self(IPPROTO_IP) }
/// Transmission Control Protocol (TCP).
///
/// The corresponding C constant is `IPPROTO_TCP`.
@_alwaysEmitIntoClient
public static var tcp: ProtocolID { Self(IPPROTO_TCP) }
/// User Datagram Protocol (UDP).
///
/// The corresponding C constant is `IPPROTO_UDP`.
@_alwaysEmitIntoClient
public static var udp: ProtocolID { Self(IPPROTO_UDP) }
/// IPv4 encapsulation.
///
/// The corresponding C constant is `IPPROTO_IPV4`.
@_alwaysEmitIntoClient
public static var ipv4: ProtocolID { Self(IPPROTO_IPV4) }
/// IPv6 header.
///
/// The corresponding C constant is `IPPROTO_IPV6`.
@_alwaysEmitIntoClient
public static var ipv6: ProtocolID { Self(IPPROTO_IPV6) }
/// Raw IP packet.
///
/// The corresponding C constant is `IPPROTO_RAW`.
@_alwaysEmitIntoClient
public static var raw: ProtocolID { Self(IPPROTO_RAW) }
public var description: String {
rawValue.description
}
}
}
// MARK: - Message Flags
@available(System 99, *)
extension SocketDescriptor {
/// Flags for send and receive operations.
@frozen
public struct MessageFlags: OptionSet, Sendable, CustomStringConvertible {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInt) { self.init(rawValue: raw) }
/// No flags.
@_alwaysEmitIntoClient
public static var none: MessageFlags { MessageFlags(0) }
/// Process out-of-band data.
///
/// The corresponding C constant is `MSG_OOB`.
@_alwaysEmitIntoClient
public static var outOfBand: MessageFlags { MessageFlags(MSG_OOB) }
/// Bypass routing, use direct interface.
///
/// The corresponding C constant is `MSG_DONTROUTE`.
@_alwaysEmitIntoClient
public static var doNotRoute: MessageFlags { MessageFlags(MSG_DONTROUTE) }
/// Peek at incoming message without removing it.
///
/// The corresponding C constant is `MSG_PEEK`.
@_alwaysEmitIntoClient
public static var peek: MessageFlags { MessageFlags(MSG_PEEK) }
/// Wait for full request or error.
///
/// The corresponding C constant is `MSG_WAITALL`.
@_alwaysEmitIntoClient
public static var waitForAll: MessageFlags { MessageFlags(MSG_WAITALL) }
/// End-of-record marker.
///
/// The corresponding C constant is `MSG_EOR`.
@_alwaysEmitIntoClient
public static var endOfRecord: MessageFlags { MessageFlags(MSG_EOR) }
/// Data was truncated.
///
/// The corresponding C constant is `MSG_TRUNC`.
@_alwaysEmitIntoClient
public static var dataTruncated: MessageFlags { MessageFlags(MSG_TRUNC) }
/// Control data was truncated.
///
/// The corresponding C constant is `MSG_CTRUNC`.
@_alwaysEmitIntoClient
public static var controlTruncated: MessageFlags { MessageFlags(MSG_CTRUNC) }
#if !SYSTEM_PACKAGE_DARWIN
/// Do not generate SIGPIPE on broken pipe.
///
/// The corresponding C constant is `MSG_NOSIGNAL`.
@_alwaysEmitIntoClient
public static var noSignal: MessageFlags { MessageFlags(MSG_NOSIGNAL) }
#endif
public var description: String {
var descriptions: [(Element, StaticString)] = [
(.outOfBand, ".outOfBand"),
(.doNotRoute, ".doNotRoute"),
(.peek, ".peek"),
(.waitForAll, ".waitForAll"),
(.endOfRecord, ".endOfRecord"),
(.dataTruncated, ".dataTruncated"),
(.controlTruncated, ".controlTruncated"),
]
#if !SYSTEM_PACKAGE_DARWIN
descriptions.append((.noSignal, ".noSignal"))
#endif
return _buildDescription(descriptions)
}
}
}
// MARK: - Shutdown Kind
@available(System 99, *)
extension SocketDescriptor {
/// Specifies which parts of a full-duplex connection to shut down.
@frozen
public struct ShutdownKind: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
/// Disallow further receives.
///
/// The corresponding C constant is `SHUT_RD`.
@_alwaysEmitIntoClient
public static var read: ShutdownKind { ShutdownKind(rawValue: SHUT_RD) }
/// Disallow further sends.
///
/// The corresponding C constant is `SHUT_WR`.
@_alwaysEmitIntoClient
public static var write: ShutdownKind { ShutdownKind(rawValue: SHUT_WR) }
/// Disallow further sends and receives.
///
/// The corresponding C constant is `SHUT_RDWR`.
@_alwaysEmitIntoClient
public static var readWrite: ShutdownKind { ShutdownKind(rawValue: SHUT_RDWR) }
public var description: String {
switch self {
case .read: return "read"
case .write: return "write"
case .readWrite: return "readWrite"
default: return "ShutdownKind(\(rawValue))"
}
}
}
}
// MARK: - Socket Option
@available(System 99, *)
extension SocketDescriptor {
/// A generic socket option identifier.
///
/// This type represents raw socket option constants that can be used
/// with ancillary messages or generic get/set socket option operations.
@frozen
public struct Option: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ rawValue: CInt) { self.init(rawValue: rawValue) }
public var description: String { "Option(\(rawValue))" }
}
}
@@ -0,0 +1,45 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
@available(System 99, *)
extension SocketDescriptor {
/// Writes a sequence of bytes to the socket
///
/// This is equivalent to calling `fileDescriptor.writeAll(_:)`
///
/// - Parameter sequence: The bytes to write.
/// - Returns: The number of bytes written, equal to the number of elements in `sequence`.
@_alwaysEmitIntoClient
@discardableResult
public func writeAll<S: Sequence>(
_ sequence: S
) throws -> Int where S.Element == UInt8 {
try fileDescriptor.writeAll(sequence)
}
/// Runs a closure and then closes the socket, even if an error occurs.
///
/// This is equivalent to calling `fileDescriptor.closeAfter(_:)`
///
/// - Parameter body: The closure to run.
/// If the closure throws an error,
/// this method closes the socket before it rethrows that error.
///
/// - Returns: The value returned by the closure.
///
/// If `body` throws an error
/// or an error occurs while closing the socket,
/// this method rethrows that error.
@_alwaysEmitIntoClient
public func closeAfter<R>(_ body: () throws -> R) throws -> R {
try fileDescriptor.closeAfter(body)
}
}
@@ -0,0 +1,324 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
@available(System 99, *)
extension SocketDescriptor {
/// A reusable collection of variable-sized ancillary messages
/// sent or received over a socket. These represent protocol control
/// related messages or other miscellaneous ancillary data.
///
/// Corresponds to a buffer of `struct cmsghdr` messages in C, as used
/// by `sendmsg` and `recmsg`.
public struct AncillaryMessageBuffer {
internal var _buffer: _RawBuffer
internal var _endOffset: Int
/// Initialize a new empty ancillary message buffer with no preallocated
/// storage.
public init() {
_buffer = _RawBuffer()
_endOffset = 0
}
/// Initialize a new empty ancillary message buffer of the
/// specified minimum capacity (in bytes).
internal init(minimumCapacity: Int) {
let headerSize = MemoryLayout<CInterop.CMsgHdr>.size
let capacity = Swift.max(headerSize + 1, minimumCapacity)
_buffer = _RawBuffer(minimumCapacity: capacity)
_endOffset = 0
}
internal var _headerSize: Int { MemoryLayout<CInterop.CMsgHdr>.size }
internal var _capacity: Int { _buffer.capacity }
/// Remove all messages currently in this buffer, preserving storage
/// capacity.
///
/// This invalidates all indices in the collection.
///
/// - Complexity: O(1). Does not reallocate the buffer.
public mutating func removeAll() {
_endOffset = 0
}
/// Reserve enough storage capacity to hold `minimumCapacity` bytes' worth
/// of messages without having to reallocate storage.
///
/// This does not invalidate any indices.
///
/// - Complexity: O(max(`minimumCapacity`, `capacity`)), where `capacity` is
/// the current storage capacity. This potentially needs to reallocate
/// the buffer and copy existing messages.
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_buffer.ensureUnique(capacity: minimumCapacity)
}
/// Append a message with the specified data to the end of this buffer,
/// resizing it if necessary.
///
/// This does not invalidate any existing indices, but it updates `endIndex`.
///
/// - Complexity: Amortized O(`data.count`), when averaged over multiple
/// calls. This method reallocates the buffer if there isn't enough
/// capacity or if the storage is shared with another value.
public mutating func appendMessage(
level: SocketDescriptor.ProtocolID,
type: SocketDescriptor.Option,
bytes: UnsafeRawBufferPointer
) {
appendMessage(
level: level,
type: type,
unsafeUninitializedCapacity: bytes.count
) { buffer in
assert(buffer.count >= bytes.count)
if bytes.count > 0 {
buffer.baseAddress!.copyMemory(
from: bytes.baseAddress!,
byteCount: bytes.count)
}
return bytes.count
}
}
/// Append a message with the supplied data to the end of this buffer,
/// resizing it if necessary. The message payload is initialized with the
/// supplied closure, which needs to return the final message length.
///
/// This does not invalidate any existing indices, but it updates `endIndex`.
///
/// - Complexity: Amortized O(`data.count`), when averaged over multiple
/// calls. This method reallocates the buffer if there isn't enough
/// capacity or if the storage is shared with another value.
public mutating func appendMessage(
level: SocketDescriptor.ProtocolID,
type: SocketDescriptor.Option,
unsafeUninitializedCapacity capacity: Int,
initializingWith body: (UnsafeMutableRawBufferPointer) throws -> Int
) rethrows {
precondition(capacity >= 0)
let headerSize = _headerSize
let delta = _headerSize + capacity
_buffer.ensureUnique(capacity: _endOffset + delta)
let messageLength: Int = try _buffer.withUnsafeMutableBytes { buffer in
assert(buffer.count >= _endOffset + delta)
let p = buffer.baseAddress! + _endOffset
let header = p.bindMemory(to: CInterop.CMsgHdr.self, capacity: 1)
header.pointee = CInterop.CMsgHdr()
header.pointee.cmsg_level = level.rawValue
header.pointee.cmsg_type = type.rawValue
let length = try body(
UnsafeMutableRawBufferPointer(start: p + headerSize, count: capacity))
precondition(length >= 0 && length <= capacity)
header.pointee.cmsg_len = CInterop.SockLen(headerSize + length)
return headerSize + length
}
_endOffset += messageLength
}
internal func _withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
try _buffer.withUnsafeBytes { buffer in
assert(buffer.count >= _endOffset)
let buffer = UnsafeRawBufferPointer(rebasing: buffer.prefix(_endOffset))
return try body(buffer)
}
}
internal mutating func _withUnsafeMutableBytes<R>(
entireCapacity: Bool,
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
return try _buffer.withUnsafeMutableBytes { buffer in
assert(buffer.count >= _endOffset)
if entireCapacity {
return try body(buffer)
} else {
return try body(.init(rebasing: buffer.prefix(_endOffset)))
}
}
}
internal mutating func _withMutableCInterop<R>(
entireCapacity: Bool,
_ body: (UnsafeMutableRawPointer?, inout CInterop.SockLen) throws -> R
) rethrows -> R {
let (result, length): (R, Int) = try _withUnsafeMutableBytes(
entireCapacity: entireCapacity
) { buffer in
var length = CInterop.SockLen(buffer.count)
let result = try body(buffer.baseAddress, &length)
precondition(length >= 0 && length <= buffer.count)
return (result, Int(length))
}
_endOffset = length
return result
}
}
}
@available(System 99, *)
extension SocketDescriptor.AncillaryMessageBuffer: Collection {
/// The index type in an ancillary message buffer.
@frozen
public struct Index: Comparable, Hashable {
@usableFromInline
var _offset: Int
@inlinable
internal init(_offset: Int) {
self._offset = _offset
}
@inlinable
public static func == (left: Self, right: Self) -> Bool {
left._offset == right._offset
}
@inlinable
public static func < (left: Self, right: Self) -> Bool {
left._offset < right._offset
}
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(_offset)
}
}
/// An individual message inside an ancillary message buffer.
///
/// Note that this is merely a reference to a slice of the underlying buffer,
/// so it contains a shared copy of its entire storage. To prevent buffer
/// reallocations due to copy-on-write copies, do not save instances
/// of this type. Instead, immediately copy out any data you need to hold onto
/// into standalone buffers.
public struct Message {
internal var _base: SocketDescriptor.AncillaryMessageBuffer
internal var _offset: Int
internal init(_base: SocketDescriptor.AncillaryMessageBuffer, offset: Int) {
self._base = _base
self._offset = offset
}
}
/// The index of the first message in the collection, or `endIndex` if
/// the collection contains no messages.
///
/// This roughly corresponds to the C macro `CMSG_FIRSTHDR`.
public var startIndex: Index { Index(_offset: 0) }
/// The index after the last message in the collection.
public var endIndex: Index { Index(_offset: _endOffset) }
/// True if the collection contains no elements.
public var isEmpty: Bool { _endOffset == 0 }
/// Return the length (in bytes) of the message at the specified index, or
/// nil if the index isn't valid, or it addresses a corrupt message.
internal func _length(at i: Index) -> Int? {
_withUnsafeBytes { buffer in
guard i._offset >= 0 && i._offset + _headerSize <= buffer.count else {
return nil
}
let p = (buffer.baseAddress! + i._offset)
.assumingMemoryBound(to: CInterop.CMsgHdr.self)
let length = Int(p.pointee.cmsg_len)
// Cut the list short at the first sign of corrupt data.
// Messages must not be shorter than their header, and they must fit
// entirely in the buffer.
if length < _headerSize || i._offset + length > buffer.count {
return nil
}
return length
}
}
/// Returns the index immediately following `i` in the collection.
///
/// This roughly corresponds to the C macro `CMSG_NXTHDR`.
///
/// - Complexity: O(1)
public func index(after i: Index) -> Index {
precondition(i._offset != _endOffset, "Can't advance past endIndex")
precondition(i._offset >= 0 && i._offset + _headerSize <= _endOffset,
"Invalid index")
guard let length = _length(at: i) else { return endIndex }
return Index(_offset: i._offset + length)
}
/// Returns the message at the given position, which must be a valid index
/// in this collection.
///
/// The returned value merely refers to a slice of the entire buffer, so
/// it contains a shared regerence to it.
///
/// To reduce memory use and to prevent unnecessary copy-on-write copying, do
/// not save `Message` values -- instead, copy out the data you need to hold
/// on to into standalone storage.
public subscript(position: Index) -> Message {
guard let _ = _length(at: position) else {
preconditionFailure("Invalid index")
}
return Element(_base: self, offset: position._offset)
}
}
@available(System 99, *)
extension SocketDescriptor.AncillaryMessageBuffer.Message {
internal var _header: CInterop.CMsgHdr {
_base._withUnsafeBytes { buffer in
assert(_offset + _base._headerSize <= buffer.count)
let p = buffer.baseAddress! + _offset
let header = p.assumingMemoryBound(to: CInterop.CMsgHdr.self)
return header.pointee
}
}
/// The protocol level of the message. Socket-level command messages
/// use the special protocol value `SocketDescriptor.ProtocolID.socketOption`.
public var level: SocketDescriptor.ProtocolID {
.init(rawValue: _header.cmsg_level)
}
/// The protocol-specific type of the message.
public var type: SocketDescriptor.Option {
.init(rawValue: _header.cmsg_type)
}
/// Calls `body` with an unsafe raw buffer pointer containing the
/// message payload.
///
/// This roughly corresponds to the C macro `CMSG_DATA`.
///
/// - Note: The buffer passed to `body` does not include storage reserved
/// for holding the message header, such as the `level` and `type` values.
/// To access header information, you have to use the corresponding
/// properties.
public func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
try _base._withUnsafeBytes { buffer in
let headerSize = _base._headerSize
assert(_offset + headerSize <= buffer.count)
let p = buffer.baseAddress! + _offset
let header = p.assumingMemoryBound(to: CInterop.CMsgHdr.self)
let data = p + headerSize
let count = Swift.min(Int(header.pointee.cmsg_len) - headerSize,
buffer.count)
return try body(UnsafeRawBufferPointer(start: data, count: count))
}
}
}
@@ -0,0 +1,389 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: - Socket Creation and Lifecycle
@available(System 99, *)
extension SocketDescriptor {
/// Creates an endpoint for communication.
///
/// - Parameters:
/// - domain: The protocol family for communication.
/// - type: The semantics of communication.
/// - protocol: The particular protocol to use. The default is `.default`,
/// which typically selects the appropriate protocol for the domain/type
/// combination (e.g., TCP for IPv4/stream).
/// - retryOnInterrupt: Whether to retry if interrupted. The default is `true`.
/// - Returns: A new socket descriptor.
///
/// The corresponding C function is `socket`.
@_alwaysEmitIntoClient
public static func open(
_ domain: Domain,
_ type: ConnectionType,
protocol: ProtocolID = .default,
retryOnInterrupt: Bool = true
) throws -> SocketDescriptor {
try _open(domain, type, protocol: `protocol`, retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal static func _open(
_ domain: Domain,
_ type: ConnectionType,
protocol: ProtocolID,
retryOnInterrupt: Bool
) -> Result<SocketDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_socket(domain.rawValue, type.rawValue, `protocol`.rawValue)
}.map(SocketDescriptor.init(rawValue:))
}
/// Closes the socket.
///
/// The corresponding C function is `close`.
@_alwaysEmitIntoClient
public func close() throws {
try _close().get()
}
@usableFromInline
internal func _close() -> Result<(), Errno> {
nothingOrErrno(retryOnInterrupt: false) {
system_close(self.rawValue)
}
}
/// Shuts down part of a full-duplex connection.
///
/// - Parameter how: Which parts of the connection to shut down.
///
/// The corresponding C function is `shutdown`.
@_alwaysEmitIntoClient
public func shutdown(_ how: ShutdownKind) throws {
try _shutdown(how).get()
}
@usableFromInline
internal func _shutdown(_ how: ShutdownKind) -> Result<(), Errno> {
nothingOrErrno(retryOnInterrupt: false) {
system_shutdown(self.rawValue, how.rawValue)
}
}
}
// MARK: - Connection Operations
@available(System 99, *)
extension SocketDescriptor {
/// Binds a socket to an address.
///
/// - Parameter address: The socket address to bind to.
///
/// The corresponding C function is `bind`.
@_alwaysEmitIntoClient
public func bind(to address: SocketAddress) throws {
try _bind(to: address).get()
}
@usableFromInline
internal func _bind(to address: SocketAddress) -> Result<(), Errno> {
address.withUnsafePointer { addr, len in
nothingOrErrno(retryOnInterrupt: false) {
system_bind(self.rawValue, addr, len)
}
}
}
/// Listens for connections on the socket.
///
/// Only applies to sockets of type `.stream`.
///
/// - Parameter backlog: The maximum length of the pending connections queue.
///
/// The corresponding C function is `listen`.
@_alwaysEmitIntoClient
public func listen(backlog: Int) throws {
try _listen(backlog: backlog).get()
}
@usableFromInline
internal func _listen(backlog: Int) -> Result<(), Errno> {
nothingOrErrno(retryOnInterrupt: false) {
system_listen(self.rawValue, CInt(backlog))
}
}
/// Accepts a connection on the socket.
///
/// - Parameter retryOnInterrupt: Whether to retry if interrupted.
/// - Returns: A new socket descriptor for the accepted connection.
///
/// The corresponding C function is `accept`.
@_alwaysEmitIntoClient
public func accept(retryOnInterrupt: Bool = true) throws -> SocketDescriptor {
try _accept(retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal func _accept(retryOnInterrupt: Bool) -> Result<SocketDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_accept(self.rawValue, nil, nil)
}.map(SocketDescriptor.init(rawValue:))
}
/// Accepts a connection and returns the client's address.
///
/// - Parameters:
/// - client: A socket address buffer to receive the client's address.
/// - retryOnInterrupt: Whether to retry if interrupted.
/// - Returns: A new socket descriptor for the accepted connection.
///
/// The corresponding C function is `accept`.
@_alwaysEmitIntoClient
public func accept(
client: inout SocketAddress,
retryOnInterrupt: Bool = true
) throws -> SocketDescriptor {
try _accept(client: &client, retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal func _accept(
client: inout SocketAddress,
retryOnInterrupt: Bool
) -> Result<SocketDescriptor, Errno> {
client._withUnsafeMutablePointer { addr, len in
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_accept(self.rawValue, addr, &len)
}.map(SocketDescriptor.init(rawValue:))
}
}
/// Initiates a connection on the socket.
///
/// - Parameter address: The address to connect to.
///
/// The corresponding C function is `connect`.
@_alwaysEmitIntoClient
public func connect(to address: SocketAddress) throws {
try _connect(to: address).get()
}
@usableFromInline
internal func _connect(to address: SocketAddress) -> Result<(), Errno> {
address.withUnsafePointer { addr, len in
nothingOrErrno(retryOnInterrupt: false) {
system_connect(self.rawValue, addr, len)
}
}
}
}
// MARK: - Send and Receive
@available(System 99, *)
extension SocketDescriptor {
/// Sends data on the socket.
///
/// - Parameters:
/// - buffer: The data to send.
/// - flags: Message flags.
/// - retryOnInterrupt: Whether to retry if interrupted.
/// - Returns: The number of bytes sent.
///
/// The corresponding C function is `send`.
@_alwaysEmitIntoClient
public func send(
_ buffer: UnsafeRawBufferPointer,
flags: MessageFlags = .none,
retryOnInterrupt: Bool = true
) throws -> Int {
try _send(buffer, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal func _send(
_ buffer: UnsafeRawBufferPointer,
flags: MessageFlags,
retryOnInterrupt: Bool
) -> Result<Int, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_send(self.rawValue, buffer.baseAddress, buffer.count, flags.rawValue)
}
}
/// Receives data from the socket.
///
/// - Parameters:
/// - buffer: The buffer to receive data into.
/// - flags: Message flags.
/// - retryOnInterrupt: Whether to retry if interrupted.
/// - Returns: The number of bytes received.
///
/// The corresponding C function is `recv`.
@_alwaysEmitIntoClient
public func receive(
into buffer: UnsafeMutableRawBufferPointer,
flags: MessageFlags = .none,
retryOnInterrupt: Bool = true
) throws -> Int {
try _receive(into: buffer, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal func _receive(
into buffer: UnsafeMutableRawBufferPointer,
flags: MessageFlags,
retryOnInterrupt: Bool
) -> Result<Int, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_recv(self.rawValue, buffer.baseAddress, buffer.count, flags.rawValue)
}
}
/// Sends data to a specific address.
///
/// - Parameters:
/// - buffer: The data to send.
/// - address: The destination address.
/// - flags: Message flags.
/// - retryOnInterrupt: Whether to retry if interrupted.
/// - Returns: The number of bytes sent.
///
/// The corresponding C function is `sendto`.
@_alwaysEmitIntoClient
public func send(
_ buffer: UnsafeRawBufferPointer,
to address: SocketAddress,
flags: MessageFlags = .none,
retryOnInterrupt: Bool = true
) throws -> Int {
try _send(buffer, to: address, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal func _send(
_ buffer: UnsafeRawBufferPointer,
to address: SocketAddress,
flags: MessageFlags,
retryOnInterrupt: Bool
) -> Result<Int, Errno> {
address.withUnsafePointer { addr, addrlen in
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_sendto(
self.rawValue,
buffer.baseAddress,
buffer.count,
flags.rawValue,
addr,
addrlen
)
}
}
}
/// Receives data and returns the sender's address.
///
/// - Parameters:
/// - buffer: The buffer to receive data into.
/// - sender: A buffer to receive the sender's address.
/// - flags: Message flags.
/// - retryOnInterrupt: Whether to retry if interrupted.
/// - Returns: The number of bytes received.
///
/// The corresponding C function is `recvfrom`.
@_alwaysEmitIntoClient
public func receive(
into buffer: UnsafeMutableRawBufferPointer,
sender: inout SocketAddress,
flags: MessageFlags = .none,
retryOnInterrupt: Bool = true
) throws -> Int {
try _receive(into: buffer, sender: &sender, flags: flags, retryOnInterrupt: retryOnInterrupt).get()
}
@usableFromInline
internal func _receive(
into buffer: UnsafeMutableRawBufferPointer,
sender: inout SocketAddress,
flags: MessageFlags,
retryOnInterrupt: Bool
) -> Result<Int, Errno> {
sender._withUnsafeMutablePointer { addr, len in
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_recvfrom(
self.rawValue,
buffer.baseAddress,
buffer.count,
flags.rawValue,
addr,
&len
)
}
}
}
}
// MARK: - Socket Information
@available(System 99, *)
extension SocketDescriptor {
/// Gets the local address of the socket.
///
/// - Parameter address: A buffer to receive the local address.
///
/// The corresponding C function is `getsockname`.
@_alwaysEmitIntoClient
public func getLocalAddress(into address: inout SocketAddress) throws {
try _getLocalAddress(into: &address).get()
}
@usableFromInline
internal func _getLocalAddress(into address: inout SocketAddress) -> Result<(), Errno> {
address._withUnsafeMutablePointer { addr, len in
nothingOrErrno(retryOnInterrupt: false) {
system_getsockname(self.rawValue, addr, &len)
}
}
}
/// Gets the remote address of the socket.
///
/// - Parameter address: A buffer to receive the peer address.
///
/// The corresponding C function is `getpeername`.
@_alwaysEmitIntoClient
public func getPeerAddress(into address: inout SocketAddress) throws {
try _getPeerAddress(into: &address).get()
}
@usableFromInline
internal func _getPeerAddress(into address: inout SocketAddress) -> Result<(), Errno> {
address._withUnsafeMutablePointer { addr, len in
nothingOrErrno(retryOnInterrupt: false) {
system_getpeername(self.rawValue, addr, &len)
}
}
}
}
@@ -0,0 +1,352 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import SystemPackage
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: - Option Level
@available(System 99, *)
extension SocketDescriptor {
/// Socket option levels.
@frozen
public struct OptionLevel: RawRepresentable, Hashable, Sendable {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
/// Socket-level options.
///
/// The corresponding C constant is `SOL_SOCKET`.
@_alwaysEmitIntoClient
public static var socket: OptionLevel { OptionLevel(rawValue: SOL_SOCKET) }
/// IPv4 protocol options.
///
/// The corresponding C constant is `IPPROTO_IP`.
@_alwaysEmitIntoClient
public static var ip: OptionLevel { OptionLevel(rawValue: IPPROTO_IP) }
/// IPv6 protocol options.
///
/// The corresponding C constant is `IPPROTO_IPV6`.
@_alwaysEmitIntoClient
public static var ipv6: OptionLevel { OptionLevel(rawValue: IPPROTO_IPV6) }
/// TCP protocol options.
///
/// The corresponding C constant is `IPPROTO_TCP`.
@_alwaysEmitIntoClient
public static var tcp: OptionLevel { OptionLevel(rawValue: IPPROTO_TCP) }
/// UDP protocol options.
///
/// The corresponding C constant is `IPPROTO_UDP`.
@_alwaysEmitIntoClient
public static var udp: OptionLevel { OptionLevel(rawValue: IPPROTO_UDP) }
}
}
// MARK: - Socket-Level Options
@available(System 99, *)
extension SocketDescriptor {
/// Socket-level options for use with `getOption` and `setOption`.
@frozen
public struct SocketOption: RawRepresentable, Hashable, Sendable {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
/// Enable debugging.
///
/// The corresponding C constant is `SO_DEBUG`.
@_alwaysEmitIntoClient
public static var debug: SocketOption { SocketOption(rawValue: SO_DEBUG) }
/// Allow local address reuse.
///
/// The corresponding C constant is `SO_REUSEADDR`.
@_alwaysEmitIntoClient
public static var reuseAddress: SocketOption { SocketOption(rawValue: SO_REUSEADDR) }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux)
/// Allow local port reuse.
///
/// The corresponding C constant is `SO_REUSEPORT`.
@_alwaysEmitIntoClient
public static var reusePort: SocketOption { SocketOption(rawValue: SO_REUSEPORT) }
#endif
/// Keep connections alive.
///
/// The corresponding C constant is `SO_KEEPALIVE`.
@_alwaysEmitIntoClient
public static var keepAlive: SocketOption { SocketOption(rawValue: SO_KEEPALIVE) }
/// Don't route, use direct interface.
///
/// The corresponding C constant is `SO_DONTROUTE`.
@_alwaysEmitIntoClient
public static var dontRoute: SocketOption { SocketOption(rawValue: SO_DONTROUTE) }
/// Linger on close if data present.
///
/// The corresponding C constant is `SO_LINGER`.
@_alwaysEmitIntoClient
public static var linger: SocketOption { SocketOption(rawValue: SO_LINGER) }
/// Permit sending of broadcast messages.
///
/// The corresponding C constant is `SO_BROADCAST`.
@_alwaysEmitIntoClient
public static var broadcast: SocketOption { SocketOption(rawValue: SO_BROADCAST) }
/// Send buffer size.
///
/// The corresponding C constant is `SO_SNDBUF`.
@_alwaysEmitIntoClient
public static var sendBufferSize: SocketOption { SocketOption(rawValue: SO_SNDBUF) }
/// Receive buffer size.
///
/// The corresponding C constant is `SO_RCVBUF`.
@_alwaysEmitIntoClient
public static var receiveBufferSize: SocketOption { SocketOption(rawValue: SO_RCVBUF) }
/// Send low water mark.
///
/// The corresponding C constant is `SO_SNDLOWAT`.
@_alwaysEmitIntoClient
public static var sendLowWaterMark: SocketOption { SocketOption(rawValue: SO_SNDLOWAT) }
/// Receive low water mark.
///
/// The corresponding C constant is `SO_RCVLOWAT`.
@_alwaysEmitIntoClient
public static var receiveLowWaterMark: SocketOption { SocketOption(rawValue: SO_RCVLOWAT) }
/// Get socket error.
///
/// The corresponding C constant is `SO_ERROR`.
@_alwaysEmitIntoClient
public static var error: SocketOption { SocketOption(rawValue: SO_ERROR) }
/// Get socket type.
///
/// The corresponding C constant is `SO_TYPE`.
@_alwaysEmitIntoClient
public static var type: SocketOption { SocketOption(rawValue: SO_TYPE) }
#if SYSTEM_PACKAGE_DARWIN
/// Don't generate SIGPIPE on broken pipe.
///
/// The corresponding C constant is `SO_NOSIGPIPE`.
@_alwaysEmitIntoClient
public static var noSigPipe: SocketOption { SocketOption(rawValue: SO_NOSIGPIPE) }
#endif
}
}
// MARK: - TCP Options
@available(System 99, *)
extension SocketDescriptor {
/// TCP-level options for use with `getOption` and `setOption`.
@frozen
public struct TCPOption: RawRepresentable, Hashable, Sendable {
@_alwaysEmitIntoClient
public var rawValue: CInt
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
/// Disable Nagle algorithm.
///
/// The corresponding C constant is `TCP_NODELAY`.
@_alwaysEmitIntoClient
public static var noDelay: TCPOption { TCPOption(rawValue: TCP_NODELAY) }
/// Maximum segment size.
///
/// The corresponding C constant is `TCP_MAXSEG`.
@_alwaysEmitIntoClient
public static var maxSegmentSize: TCPOption { TCPOption(rawValue: TCP_MAXSEG) }
#if SYSTEM_PACKAGE_DARWIN || os(Linux)
/// Keep alive idle time.
///
/// The corresponding C constant is `TCP_KEEPIDLE` on Linux
/// or `TCP_KEEPALIVE` on Darwin.
@_alwaysEmitIntoClient
public static var keepAliveIdle: TCPOption {
#if SYSTEM_PACKAGE_DARWIN
TCPOption(rawValue: TCP_KEEPALIVE)
#else
TCPOption(rawValue: TCP_KEEPIDLE)
#endif
}
#endif
#if os(Linux)
/// Keep alive interval.
///
/// The corresponding C constant is `TCP_KEEPINTVL`.
@_alwaysEmitIntoClient
public static var keepAliveInterval: TCPOption { TCPOption(rawValue: TCP_KEEPINTVL) }
/// Keep alive probe count.
///
/// The corresponding C constant is `TCP_KEEPCNT`.
@_alwaysEmitIntoClient
public static var keepAliveCount: TCPOption { TCPOption(rawValue: TCP_KEEPCNT) }
#endif
}
}
// MARK: - Get and Set Options
@available(System 99, *)
extension SocketDescriptor {
/// Gets a socket option value.
///
/// - Parameters:
/// - level: The protocol level.
/// - option: The option to get.
/// - Returns: The option value.
///
/// The corresponding C function is `getsockopt`.
@_alwaysEmitIntoClient
public func getOption<T>(
_ level: OptionLevel,
_ option: CInt
) throws -> T {
try _getOption(level, option).get()
}
@usableFromInline
internal func _getOption<T>(
_ level: OptionLevel,
_ option: CInt
) -> Result<T, Errno> {
// Allocate zeroed storage for the option value
var storage = [UInt8](repeating: 0, count: MemoryLayout<T>.size)
var length = socklen_t(MemoryLayout<T>.size)
let result = storage.withUnsafeMutableBytes { buffer in
nothingOrErrno(retryOnInterrupt: false) {
system_getsockopt(
self.rawValue,
level.rawValue,
option,
buffer.baseAddress,
&length
)
}
}
return result.map {
storage.withUnsafeBytes { buffer in
buffer.load(as: T.self)
}
}
}
/// Sets a socket option value.
///
/// - Parameters:
/// - level: The protocol level.
/// - option: The option to set.
/// - value: The value to set.
///
/// The corresponding C function is `setsockopt`.
@_alwaysEmitIntoClient
public func setOption<T>(
_ level: OptionLevel,
_ option: CInt,
to value: T
) throws {
try _setOption(level, option, to: value).get()
}
@usableFromInline
internal func _setOption<T>(
_ level: OptionLevel,
_ option: CInt,
to value: T
) -> Result<(), Errno> {
withUnsafePointer(to: value) { valuePtr in
nothingOrErrno(retryOnInterrupt: false) {
system_setsockopt(
self.rawValue,
level.rawValue,
option,
valuePtr,
socklen_t(MemoryLayout<T>.size)
)
}
}
}
}
// MARK: - Convenience Methods
@available(System 99, *)
extension SocketDescriptor {
/// Gets a socket-level option as an integer.
@_alwaysEmitIntoClient
public func getSocketOption(_ option: SocketOption) throws -> CInt {
try getOption(.socket, option.rawValue)
}
/// Sets a socket-level option as an integer.
@_alwaysEmitIntoClient
public func setSocketOption(_ option: SocketOption, to value: CInt) throws {
try setOption(.socket, option.rawValue, to: value)
}
/// Gets a TCP-level option as an integer.
@_alwaysEmitIntoClient
public func getTCPOption(_ option: TCPOption) throws -> CInt {
try getOption(.tcp, option.rawValue)
}
/// Sets a TCP-level option as an integer.
@_alwaysEmitIntoClient
public func setTCPOption(_ option: TCPOption, to value: CInt) throws {
try setOption(.tcp, option.rawValue, to: value)
}
/// Enables reuse of local addresses.
@_alwaysEmitIntoClient
public func setReuseAddress(_ enabled: Bool = true) throws {
try setSocketOption(.reuseAddress, to: enabled ? 1 : 0)
}
/// Disables the Nagle algorithm.
@_alwaysEmitIntoClient
public func setNoDelay(_ enabled: Bool = true) throws {
try setTCPOption(.noDelay, to: enabled ? 1 : 0)
}
}
+101
View File
@@ -0,0 +1,101 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Utility functions for socket operations
import SystemPackage
extension Errno {
internal static var current: Errno {
get { Errno(rawValue: system_errno) }
set { system_errno = newValue.rawValue }
}
}
// Results in errno if i == -1
@available(System 0.0.1, *)
private func valueOrErrno<I: FixedWidthInteger>(
_ i: I
) -> Result<I, Errno> {
i == -1 ? .failure(Errno.current) : .success(i)
}
@available(System 0.0.1, *)
private func nothingOrErrno<I: FixedWidthInteger>(
_ i: I
) -> Result<(), Errno> {
valueOrErrno(i).map { _ in () }
}
@available(System 0.0.1, *)
internal func valueOrErrno<I: FixedWidthInteger>(
retryOnInterrupt: Bool, _ f: () -> I
) -> Result<I, Errno> {
repeat {
switch valueOrErrno(f()) {
case .success(let r): return .success(r)
case .failure(let err):
guard retryOnInterrupt && err == .interrupted else { return .failure(err) }
break
}
} while true
}
@available(System 0.0.1, *)
internal func nothingOrErrno<I: FixedWidthInteger>(
retryOnInterrupt: Bool, _ f: () -> I
) -> Result<(), Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () }
}
// Run a precondition for debug client builds
internal func _debugPrecondition(
_ condition: @autoclosure () -> Bool,
_ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
if _slowPath(_isDebugAssertConfiguration()) {
precondition(
condition(), String(describing: message), file: file, line: line)
}
}
extension OptionSet {
@inline(never)
internal func _buildDescription(
_ descriptions: [(Element, StaticString)]
) -> String {
var copy = self
var result = "["
for (option, name) in descriptions {
if _slowPath(copy.contains(option)) {
result += name.description
copy.remove(option)
if !copy.isEmpty { result += ", " }
}
}
if _slowPath(!copy.isEmpty) {
result += "\(Self.self)(rawValue: \(copy.rawValue))"
}
result += "]"
return result
}
}
internal func _withOptionalUnsafePointerOrNull<T, R>(
to value: T?,
_ body: (UnsafePointer<T>?) throws -> R
) rethrows -> R {
guard let value = value else {
return try body(nil)
}
return try withUnsafePointer(to: value, body)
}
-45
View File
@@ -1,45 +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
*/
// Compile-only canary for MemberImportVisibility regressions: this file fails
// to build if a C member of a type SystemPackage vends is attributed to the
// private CSystem module.
//
// For new type wrappers introduced to System, access their C members here:
// - Import the platform overlay (Glibc/Musl), as consumers do.
// - Access raw C members of vended types (e.g. CInterop.Stat) as a downstream
// consumer would. Don't go through the Swift (e.g. Stat) wrapper since its
// accesses happen inside System, where importing CSystem is fine.
// - Touch every direct member the public API exposes. One field is not always
// a safe proxy for the rest.
#if canImport(Glibc) || canImport(Musl)
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif
import SystemPackage
func _mivProbe(_ s: CInterop.Stat) {
_ = s.st_dev
_ = s.st_ino
_ = s.st_mode
_ = s.st_nlink
_ = s.st_uid
_ = s.st_gid
_ = s.st_rdev
_ = s.st_size
_ = s.st_blksize
_ = s.st_blocks
_ = s.st_atim
_ = s.st_mtim
_ = s.st_ctim
}
#endif
@@ -0,0 +1,45 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import Testing
import SystemPackage
@testable import SystemSockets
@Suite("Ancillary Message Buffer")
struct AncillaryMessageBufferTests {
@available(System 99, *)
@Test("Append and iterate messages")
func testAppend() {
// Create a buffer of 100 messages, with varying payload lengths.
var buffer = SocketDescriptor.AncillaryMessageBuffer(minimumCapacity: 0)
for i in 0 ..< 100 {
let bytes = UnsafeMutableRawBufferPointer.allocate(byteCount: i, alignment: 1)
defer { bytes.deallocate() }
system_memset(bytes, to: UInt8(i))
buffer.appendMessage(level: .init(rawValue: CInt(100 * i)),
type: .init(rawValue: CInt(1000 * i)),
bytes: UnsafeRawBufferPointer(bytes))
}
// Check that we can access appended messages.
var i = 0
for message in buffer {
#expect(Int(message.level.rawValue) == 100 * i)
#expect(Int(message.type.rawValue) == 1000 * i)
message.withUnsafeBytes { buffer in
#expect(buffer.count == i)
for idx in buffer.indices {
#expect(buffer[idx] == UInt8(i), "byte #\(idx)")
}
}
i += 1
}
#expect(i == 100, "Too many messages in buffer")
}
}
@@ -0,0 +1,194 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if !os(Windows)
import Testing
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
@testable import SystemSockets
import SystemPackage
@Suite("Socket Addresses")
private struct SocketAddressTests {
// MARK: - IPv4 Address Tests
@available(System 99, *)
@Test func ipv4BasicCreation() {
let addr = IPv4Address("127.0.0.1", port: 8080)
#expect(addr != nil)
#expect(addr?.port == 8080)
#expect(addr?.addressString == "127.0.0.1")
}
@available(System 99, *)
@Test func ipv4InvalidAddress() {
let addr = IPv4Address("not.an.ip.address", port: 8080)
#expect(addr == nil)
}
@available(System 99, *)
@Test func ipv4Any() {
let addr = IPv4Address.any(port: 0)
#expect(addr.port == 0)
#expect(addr.addressString == "0.0.0.0")
}
@available(System 99, *)
@Test func ipv4Loopback() {
let addr = IPv4Address.loopback(port: 80)
#expect(addr.port == 80)
#expect(addr.addressString == "127.0.0.1")
}
@available(System 99, *)
@Test func ipv4StringLiteral() {
let addr: IPv4Address = "192.168.1.1:443"
#expect(addr.port == 443)
#expect(addr.addressString == "192.168.1.1")
}
@available(System 99, *)
@Test func ipv4Equality() {
let addr1 = IPv4Address("10.0.0.1", port: 8080)!
let addr2 = IPv4Address("10.0.0.1", port: 8080)!
let addr3 = IPv4Address("10.0.0.2", port: 8080)!
let addr4 = IPv4Address("10.0.0.1", port: 9090)!
#expect(addr1 == addr2)
#expect(addr1 != addr3)
#expect(addr1 != addr4)
}
@available(System 99, *)
@Test func ipv4Description() {
let addr = IPv4Address("8.8.8.8", port: 53)!
#expect(addr.description == "8.8.8.8:53")
}
// MARK: - IPv6 Address Tests
@available(System 99, *)
@Test func ipv6BasicCreation() {
let addr = IPv6Address("::1", port: 8080)
#expect(addr != nil)
#expect(addr?.port == 8080)
#expect(addr?.addressString == "::1")
}
@available(System 99, *)
@Test func ipv6InvalidAddress() {
let addr = IPv6Address("not:an:ipv6:address", port: 8080)
#expect(addr == nil)
}
@available(System 99, *)
@Test func ipv6Any() {
let addr = IPv6Address.any(port: 0)
#expect(addr.port == 0)
#expect(addr.addressString == "::")
}
@available(System 99, *)
@Test func ipv6Loopback() {
let addr = IPv6Address.loopback(port: 80)
#expect(addr.port == 80)
#expect(addr.addressString == "::1")
}
@available(System 99, *)
@Test func ipv6Description() {
let addr = IPv6Address("2001:db8::1", port: 443)!
#expect(addr.description == "[2001:db8::1]:443")
}
@available(System 99, *)
@Test func ipv6StringLiteral() {
let addr: IPv6Address = "[::1]:8080"
#expect(addr.port == 8080)
#expect(addr.addressString == "::1")
}
// MARK: - Unix Address Tests
@available(System 99, *)
@Test func unixBasicCreation() {
let addr = UnixAddress("/tmp/test.sock")
#expect(addr != nil)
#expect(addr?.path == "/tmp/test.sock")
}
@available(System 99, *)
@Test func unixDescription() {
let addr = UnixAddress("/var/run/daemon.sock")!
#expect(addr.description == "/var/run/daemon.sock")
}
@available(System 99, *)
@Test func unixEquality() {
let addr1 = UnixAddress("/tmp/a.sock")!
let addr2 = UnixAddress("/tmp/a.sock")!
let addr3 = UnixAddress("/tmp/b.sock")!
#expect(addr1 == addr2)
#expect(addr1 != addr3)
}
// MARK: - SocketAddress Container Tests
@available(System 99, *)
@Test func socketAddressFromIPv4() {
let ipv4 = IPv4Address.loopback(port: 8080)
let sockAddr = SocketAddress(ipv4: ipv4)
#expect(sockAddr.family == SocketDescriptor.Domain.ipv4)
#expect(sockAddr.ipv4 != nil)
#expect(sockAddr.ipv4?.port == 8080)
#expect(sockAddr.ipv6 == nil)
#expect(sockAddr.unix == nil)
}
@available(System 99, *)
@Test func socketAddressFromIPv6() {
let ipv6 = IPv6Address.loopback(port: 443)
let sockAddr = SocketAddress(ipv6: ipv6)
#expect(sockAddr.family == SocketDescriptor.Domain.ipv6)
#expect(sockAddr.ipv6 != nil)
#expect(sockAddr.ipv6?.port == 443)
#expect(sockAddr.ipv4 == nil)
#expect(sockAddr.unix == nil)
}
@available(System 99, *)
@Test func socketAddressFromUnix() {
let unix = UnixAddress("/tmp/test.sock")!
let sockAddr = SocketAddress(unix: unix)
#expect(sockAddr.family == SocketDescriptor.Domain.local)
#expect(sockAddr.unix != nil)
#expect(sockAddr.unix?.path == "/tmp/test.sock")
#expect(sockAddr.ipv4 == nil)
#expect(sockAddr.ipv6 == nil)
}
}
#endif
@@ -0,0 +1,93 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if !os(Windows)
import Testing
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
@testable import SystemSockets
import SystemPackage
@Suite("Socket Descriptor")
private struct SocketDescriptorTests {
// MARK: - Type Tests
@available(System 99, *)
@Test func domainValues() {
#expect(SocketDescriptor.Domain.ipv4.rawValue == AF_INET)
#expect(SocketDescriptor.Domain.ipv6.rawValue == AF_INET6)
#expect(SocketDescriptor.Domain.local.rawValue == AF_UNIX)
}
@available(System 99, *)
@Test func connectionTypeValues() {
#expect(SocketDescriptor.ConnectionType.stream.rawValue == SOCK_STREAM)
#expect(SocketDescriptor.ConnectionType.datagram.rawValue == SOCK_DGRAM)
}
@available(System 99, *)
@Test func protocolValues() {
#expect(SocketDescriptor.ProtocolID.tcp.rawValue == CInt(IPPROTO_TCP))
#expect(SocketDescriptor.ProtocolID.udp.rawValue == CInt(IPPROTO_UDP))
}
// MARK: - Socket Creation Tests
@available(System 99, *)
@Test func createTCPSocket() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
#expect(socket.rawValue >= 0)
try socket.close()
}
@available(System 99, *)
@Test func createUDPSocket() throws {
let socket = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
#expect(socket.rawValue >= 0)
try socket.close()
}
@available(System 99, *)
@Test func createIPv6TCPSocket() throws {
let socket = try SocketDescriptor.open(.ipv6, .stream, protocol: .tcp)
#expect(socket.rawValue >= 0)
try socket.close()
}
@available(System 99, *)
@Test func createUnixSocket() throws {
let socket = try SocketDescriptor.open(.local, .stream)
#expect(socket.rawValue >= 0)
try socket.close()
}
// MARK: - Shutdown Tests
@available(System 99, *)
@Test func shutdownKindValues() {
#expect(SocketDescriptor.ShutdownKind.read.rawValue == SHUT_RD)
#expect(SocketDescriptor.ShutdownKind.write.rawValue == SHUT_WR)
#expect(SocketDescriptor.ShutdownKind.readWrite.rawValue == SHUT_RDWR)
}
}
#endif
@@ -0,0 +1,225 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if !os(Windows)
import Testing
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
@testable import SystemSockets
import SystemPackage
@Suite("Socket Operations")
private struct SocketOperationsTests {
// MARK: - Bind Tests
@available(System 99, *)
@Test func bindToAnyPort() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? socket.close() }
let address = SocketAddress(ipv4: IPv4Address.any(port: 0))
try socket.bind(to: address)
// Verify we can get the local address after binding
var localAddr = SocketAddress()
try socket.getLocalAddress(into: &localAddr)
#expect(localAddr.family == SocketDescriptor.Domain.ipv4)
#expect(localAddr.ipv4?.port != 0) // Port should be assigned
}
@available(System 99, *)
@Test func bindToLoopback() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? socket.close() }
let address = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
try socket.bind(to: address)
var localAddr = SocketAddress()
try socket.getLocalAddress(into: &localAddr)
#expect(localAddr.ipv4?.addressString == "127.0.0.1")
}
// MARK: - Listen Tests
@available(System 99, *)
@Test func listenWithDefaultBacklog() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? socket.close() }
let address = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
try socket.bind(to: address)
try socket.listen(backlog: 5)
}
// MARK: - Connect and Accept Tests
@available(System 99, *)
@Test func tcpConnectAndAccept() throws {
// Create server socket
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? server.close() }
let serverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
try server.bind(to: serverAddr)
try server.listen(backlog: 1)
// Get the actual port
var boundAddr = SocketAddress()
try server.getLocalAddress(into: &boundAddr)
let port = boundAddr.ipv4!.port
// Create client socket and connect
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? client.close() }
let connectAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
try client.connect(to: connectAddr)
// Accept connection
var peerAddr = SocketAddress()
let acceptedSocket = try server.accept(client: &peerAddr)
defer { try? acceptedSocket.close() }
#expect(peerAddr.family == SocketDescriptor.Domain.ipv4)
#expect(peerAddr.ipv4?.addressString == "127.0.0.1")
}
// MARK: - Send and Receive Tests
@available(System 99, *)
@Test func tcpSendReceive() throws {
// Create server socket
let server = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? server.close() }
let serverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
try server.bind(to: serverAddr)
try server.listen(backlog: 1)
var boundAddr = SocketAddress()
try server.getLocalAddress(into: &boundAddr)
let port = boundAddr.ipv4!.port
// Create client socket and connect
let client = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? client.close() }
let connectAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
try client.connect(to: connectAddr)
// Accept connection
let acceptedSocket = try server.accept()
defer { try? acceptedSocket.close() }
// Send data from client
let message = "Hello, World!"
let messageBytes = Array(message.utf8)
let sent = try messageBytes.withUnsafeBytes { buffer in
try client.send(UnsafeRawBufferPointer(buffer))
}
#expect(sent == messageBytes.count)
// Receive data on server
var buffer = [UInt8](repeating: 0, count: 1024)
let received = try buffer.withUnsafeMutableBytes { buffer in
try acceptedSocket.receive(into: buffer)
}
#expect(received == messageBytes.count)
let receivedMessage = String(decoding: buffer.prefix(received), as: UTF8.self)
#expect(receivedMessage == message)
}
// MARK: - UDP Tests
@available(System 99, *)
@Test func udpSendReceive() throws {
// Create receiver socket
let receiver = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
defer { try? receiver.close() }
let receiverAddr = SocketAddress(ipv4: IPv4Address.loopback(port: 0))
try receiver.bind(to: receiverAddr)
var boundAddr = SocketAddress()
try receiver.getLocalAddress(into: &boundAddr)
let port = boundAddr.ipv4!.port
// Create sender socket
let sender = try SocketDescriptor.open(.ipv4, .datagram, protocol: .udp)
defer { try? sender.close() }
// Send datagram
let message = "UDP Message"
let messageBytes = Array(message.utf8)
let targetAddr = SocketAddress(ipv4: IPv4Address.loopback(port: port))
let sent = try messageBytes.withUnsafeBytes { buffer in
try sender.send(UnsafeRawBufferPointer(buffer), to: targetAddr)
}
#expect(sent == messageBytes.count)
// Receive datagram
var buffer = [UInt8](repeating: 0, count: 1024)
var fromAddr = SocketAddress()
let received = try buffer.withUnsafeMutableBytes { buffer in
try receiver.receive(into: buffer, sender: &fromAddr)
}
#expect(received == messageBytes.count)
#expect(fromAddr.family == SocketDescriptor.Domain.ipv4)
let receivedMessage = String(decoding: buffer.prefix(received), as: UTF8.self)
#expect(receivedMessage == message)
}
// MARK: - Socket Options Tests
@available(System 99, *)
@Test func setReuseAddress() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? socket.close() }
try socket.setReuseAddress(true)
let value = try socket.getSocketOption(SocketDescriptor.SocketOption.reuseAddress)
#expect(value != 0)
}
@available(System 99, *)
@Test func getSendBufferSize() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? socket.close() }
let size = try socket.getSocketOption(SocketDescriptor.SocketOption.sendBufferSize)
#expect(size > 0)
}
@available(System 99, *)
@Test func getReceiveBufferSize() throws {
let socket = try SocketDescriptor.open(.ipv4, .stream, protocol: .tcp)
defer { try? socket.close() }
let size = try socket.getSocketOption(SocketDescriptor.SocketOption.receiveBufferSize)
#expect(size > 0)
}
}
#endif
+1 -99
View File
@@ -176,105 +176,7 @@ final class FileOperationsTest: XCTestCase {
}
}
}
#if !SYSTEM_PACKAGE_DARWIN
func testAdHocPipeWithOptions() throws {
// Ad-hoc test testing `Pipe` functionality.
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
let options: FileDescriptor.PipeOptions = [.closeOnExec]
let pipe: (readEnd: FileDescriptor, writeEnd: FileDescriptor)
pipe = try FileDescriptor.pipe(options: options)
try pipe.readEnd.closeAfter {
try pipe.writeEnd.closeAfter {
var abc = "abc"
try abc.withUTF8 {
_ = try pipe.writeEnd.write(UnsafeRawBufferPointer($0))
}
let readLen = 3
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { buf, count in
count = try pipe.readEnd.read(into: UnsafeMutableRawBufferPointer(buf))
}
XCTAssertEqual(readBytes, Array(abc.utf8))
}
}
}
#endif // !SYSTEM_PACKAGE_DARWIN
#endif // !os(WASI)
#if !os(Windows)
func testAdHocDuplicate2() throws {
try withTemporaryFilePath(basename: "test") {
let path = $0.appending("foo2.txt")
let fd1 = try FileDescriptor.open(path, .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite)
let fd2 = FileDescriptor(rawValue: 731)
let fd3 = try fd1.duplicate(as: fd2)
XCTAssertEqual(fd2, fd3)
try fd2.close()
do {
try fd3.close()
XCTFail("Should be unreachable")
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .badFileDescriptor)
}
}
// dup2() accepts two equal parameters.
let fd4 = try fd1.duplicate(as: fd1)
XCTAssertEqual(fd4, fd1)
try fd1.close()
do {
try fd4.close()
XCTFail("Should be unreachable")
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .badFileDescriptor)
}
}
}
}
#endif // !os(Windows)
#if !SYSTEM_PACKAGE_DARWIN && !os(Windows)
func testAdHocDuplicate3() throws {
try withTemporaryFilePath(basename: "test") {
let path = $0.appending("foo3.txt")
let fd1 = try FileDescriptor.open(path, .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite)
let fd2 = FileDescriptor(rawValue: 731)
let fd3 = try fd1.duplicate(as: fd2, options: [.closeOnExec])
XCTAssertEqual(fd2, fd3)
try fd2.close()
do {
try fd3.close()
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .badFileDescriptor)
}
}
// dup3() does not accept two equal parameters.
do {
_ = try fd1.duplicate(as: fd1, options: [])
XCTFail("Should be unreachable")
} catch {
if let error = try? XCTUnwrap(error as? Errno) {
XCTAssertEqual(error, .invalidArgument)
}
}
}
}
#endif // !SYSTEM_PACKAGE_DARWIN && !os(Windows)
#endif
func testAdHocOpen() {
// Ad-hoc test touching a file system.
@@ -19,10 +19,6 @@ import XCTest
import WinSDK
private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA)
private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE)
private let FILE_READ_ATTRIBUTES = DWORD(WinSDK.FILE_READ_ATTRIBUTES)
@available(iOS 8, *)
final class FileOperationsTestWindows: XCTestCase {
private let r = ACCESS_MASK(
@@ -47,8 +43,6 @@ final class FileOperationsTestWindows: XCTestCase {
| SYNCHRONIZE
)
private let none = ACCESS_MASK(0)
private struct Test {
var permissions: CModeT
var ownerAccess: ACCESS_MASK
@@ -78,7 +72,7 @@ final class FileOperationsTestWindows: XCTestCase {
var psidEveryone: PSID? = nil
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
DWORD(SECURITY_WORLD_RID),
0, 0, 0, 0, 0, 0, 0,
&psidEveryone))
defer {
@@ -112,7 +106,7 @@ final class FileOperationsTestWindows: XCTestCase {
&psidGroup,
&pDacl,
nil,
&pSD), ERROR_SUCCESS)
&pSD), DWORD(ERROR_SUCCESS))
defer {
LocalFree(pSD)
}
@@ -141,15 +135,15 @@ final class FileOperationsTestWindows: XCTestCase {
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&owner,
&ownerAccess), ERROR_SUCCESS)
&ownerAccess), DWORD(ERROR_SUCCESS))
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&group,
&groupAccess), ERROR_SUCCESS)
&groupAccess), DWORD(ERROR_SUCCESS))
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&everyone,
&otherAccess), ERROR_SUCCESS)
&otherAccess), DWORD(ERROR_SUCCESS))
return (ownerAccess, groupAccess, otherAccess)
}
@@ -188,9 +182,9 @@ final class FileOperationsTestWindows: XCTestCase {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|x, none),
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|x, 0),
Test(0o777, r|w|x, r|x, r|x)
]
@@ -201,9 +195,9 @@ final class FileOperationsTestWindows: XCTestCase {
.otherWrite, .otherExecute]) {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r, none),
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r, 0),
Test(0o777, r|w|x, r, r)
]
@@ -220,81 +214,34 @@ final class FileOperationsTestWindows: XCTestCase {
try FilePermissions.withCreationMask([]) {
try withTemporaryFilePath(basename: "testPermissions") { path in
let tests = [
Test(0o000, none, none, none),
Test(0o000, 0, 0, 0),
Test(0o400, r, none, none),
Test(0o200, w, none, none),
Test(0o100, x, none, none),
Test(0o040, none, r, none),
Test(0o020, none, w, none),
Test(0o010, none, x, none),
Test(0o004, none, none, r),
Test(0o002, none, none, w),
Test(0o001, none, none, x),
Test(0o400, r, 0, 0),
Test(0o200, w, 0, 0),
Test(0o100, x, 0, 0),
Test(0o040, 0, r, 0),
Test(0o020, 0, w, 0),
Test(0o010, 0, x, 0),
Test(0o004, 0, 0, r),
Test(0o002, 0, 0, w),
Test(0o001, 0, 0, x),
Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|w|x, none),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|w|x, 0),
Test(0o777, r|w|x, r|w|x, r|w|x),
Test(0o755, r|w|x, r|x, r|x),
Test(0o644, r|w, r, r),
Test(0o007, none, none, r|w|x),
Test(0o070, none, r|w|x, none),
Test(0o077, none, r|w|x, r|w|x),
Test(0o007, 0, 0, r|w|x),
Test(0o070, 0, r|w|x, 0),
Test(0o077, 0, r|w|x, r|w|x),
]
try runTests(tests, at: path)
}
}
}
/// Test that buffer sizes exceeding DWORD.max (4GB) are properly rejected
func testBufferSizeLimit() throws {
try withTemporaryFilePath(basename: "testBufferSizeLimit") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"),
.readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
defer { try? fd.close() }
// Write some data first
try fd.writeAll("test data".utf8)
// Allocate a small buffer for testing
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 1)
defer { buffer.deallocate() }
// Test that a count exceeding DWORD.max (UInt32.max = 4,294,967,295) returns EINVAL
// We use a buffer pointer but pass a count > DWORD.max
let oversizedCount = Int(DWORD.max) + 1
let oversizedBuffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress,
count: oversizedCount
)
// pread should fail with EINVAL
do {
_ = try fd.read(fromAbsoluteOffset: 0, into: oversizedBuffer)
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// pwrite should also fail with EINVAL
do {
_ = try fd.write(toAbsoluteOffset: 0, UnsafeRawBufferPointer(oversizedBuffer))
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// Verify that exactly DWORD.max works (if we had a buffer that large)
// We can't easily test this without allocating 4GB, but the boundary is correct
}
}
}
#endif // os(Windows)
+1 -2
View File
@@ -22,8 +22,7 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
// which are known to work correctly.
final class IORequestTests: XCTestCase {
func testNop() {
let req = IORing.Request.nop().makeRawRequest(
pathBuffers: PendingPathBuffers(reservedCapacity: 0))
let req = IORing.Request.nop().makeRawRequest()
let sourceBytes = requestBytes(req)
// convenient property of nop: it's all zeros!
// for some unknown reason, liburing sets the fd field to -1.
-75
View File
@@ -127,81 +127,6 @@ final class IORingTests: XCTestCase {
efdBuf.deallocate()
rawBuffer.deallocate()
}
// Prior to the fix this is testing, prepare() escaped a pointer obtained
// inside `path.withPlatformString { ... }` into the SQE and dropped the
// owning FilePath before submit, so io_uring_enter handed the kernel a
// dangling pointer. Here we deliberately let the FilePath go out of scope
// between prepare and submit, then churn the heap to make UAFs observable.
func testPathBufferLifetimeAcrossPrepareSubmit() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
var ring = try IORing(queueDepth: 6)
func enqueueOpen() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly))
XCTAssertTrue(ok)
}
enqueueOpen()
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
}
for buf in churn { buf.deallocate() }
churn.removeAll()
try ring.submitPreparedRequests()
let completion = try ring.blockingConsumeCompletion()
XCTAssertGreaterThanOrEqual(
completion.result, 0,
"open should succeed; got \(completion.result)")
if completion.result >= 0 {
let fd = FileDescriptor(rawValue: Int32(completion.result))
try fd.close()
}
try cleanUpHelloWorldFile(parent)
}
func testPathBufferLifetimeAcrossLinkedRequests() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
func enqueueLinkedReadback() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly),
.read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]),
.close(ring.registeredFileSlots[0]))
XCTAssertTrue(ok)
}
enqueueLinkedReadback()
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
}
for buf in churn { buf.deallocate() }
try ring.submitPreparedRequests()
_ = try ring.blockingConsumeCompletion() // open
_ = try ring.blockingConsumeCompletion() // read
_ = try ring.blockingConsumeCompletion() // close
let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result, "Hello, World!")
try cleanUpHelloWorldFile(parent)
rawBuffer.deallocate()
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+467
View File
@@ -0,0 +1,467 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2)
import Testing
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
@Suite("Span-based File I/O")
private struct SpanFileIOTests {
// MARK: - Basic Functionality
@available(SystemWithSpan 0.0.1, *)
@Test func basicReadWriteOperations() async throws {
try withTemporaryFilePath(basename: "basicReadWriteOperations") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
// Test write(_:)
let data1: [UInt8] = [0x61, 0x62, 0x63] // "abc"
let written1 = try data1.withUnsafeBytes { bytes in
try fd.write(RawSpan(_unsafeBytes: bytes))
}
#expect(written1 == 3)
// Test write(toAbsoluteOffset:_:)
let data2: [UInt8] = [0x64, 0x65, 0x66] // "def"
let written2 = try data2.withUnsafeBytes { bytes in
try fd.write(toAbsoluteOffset: 3, RawSpan(_unsafeBytes: bytes))
}
#expect(written2 == 3)
// Test writeAll(_:)
try fd.seek(offset: 6, from: .start)
let data3: [UInt8] = [0x67, 0x68, 0x69] // "ghi"
let written3 = try data3.withUnsafeBytes { bytes in
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
}
#expect(written3 == 3)
// Test writeAll(toAbsoluteOffset:_:)
let data4: [UInt8] = [0x6A, 0x6B, 0x6C] // "jkl"
let written4 = try data4.withUnsafeBytes { bytes in
try fd.writeAll(toAbsoluteOffset: 9, RawSpan(_unsafeBytes: bytes))
}
#expect(written4 == 3)
// Test read(into:)
try fd.seek(offset: 0, from: .start)
let result1 = try [UInt8](unsafeUninitializedCapacity: 12) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
_ = try fd.read(into: &output)
count = output.byteCount
}
#expect(result1.count <= 12) // May be partial
// Test read(filling:)
try fd.seek(offset: 0, from: .start)
let result2 = try [UInt8](unsafeUninitializedCapacity: 12) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(filling: &output)
}
#expect(result2 == data1 + data2 + data3 + data4)
// Test read(fromAbsoluteOffset:into:)
let result3 = try [UInt8](unsafeUninitializedCapacity: 3) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
_ = try fd.read(fromAbsoluteOffset: 3, into: &output)
count = output.byteCount
}
#expect(result3.count <= 3) // May be partial
// Test read(fromAbsoluteOffset:filling:)
let result4 = try [UInt8](unsafeUninitializedCapacity: 3) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(fromAbsoluteOffset: 6, filling: &output)
}
#expect(result4 == data3)
}
}
}
@available(SystemWithSpan 0.0.1, *)
@Test func writeOperations() async throws {
try withTemporaryFilePath(basename: "writeOperations") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
// Small write
let small: [UInt8] = [0x61, 0x62, 0x63]
_ = try small.withUnsafeBytes { bytes in
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
}
// Large write
let large: [UInt8] = Array((0..<1024).map { UInt8($0 % 256) })
_ = try large.withUnsafeBytes { bytes in
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
}
// Verify size
let size = try fd.seek(offset: 0, from: .end)
#expect(size == 3 + 1024)
// Verify content
try fd.seek(offset: 0, from: .start)
let readBack = try [UInt8](unsafeUninitializedCapacity: 3 + 1024) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(filling: &output)
}
#expect(readBack == small + large)
}
}
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1, *)
@Test func readOperations() async throws {
try withTemporaryFilePath(basename: "readOperations") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
let data: [UInt8] = Array((0..<1024).map { UInt8($0 % 256) })
try fd.writeAll(data)
try fd.seek(offset: 0, from: .start)
// Small read
let small = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(filling: &output)
}
#expect(small == Array(0..<10))
// Large read
try fd.seek(offset: 0, from: .start)
let large = try [UInt8](unsafeUninitializedCapacity: 1024) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(filling: &output)
}
#expect(large == data)
}
}
}
@available(SystemWithSpan 0.0.1, *)
@Test func absoluteOffsetOperations() async throws {
try withTemporaryFilePath(basename: "absoluteOffsetOperations") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
let data: [UInt8] = Array(0..<100)
try fd.writeAll(data)
// Write at absolute offset should not change file position
let initialOffset = try fd.seek(offset: 0, from: .current)
let patchData: [UInt8] = [0xFF, 0xFE]
_ = try patchData.withUnsafeBytes { bytes in
try fd.writeAll(toAbsoluteOffset: 50, RawSpan(_unsafeBytes: bytes))
}
let afterWriteOffset = try fd.seek(offset: 0, from: .current)
#expect(initialOffset == afterWriteOffset)
// Read at absolute offset should not change file position
try fd.seek(offset: 10, from: .start)
let readAtOffset = try [UInt8](unsafeUninitializedCapacity: 2) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(fromAbsoluteOffset: 50, filling: &output)
}
#expect(readAtOffset == patchData)
let afterReadOffset = try fd.seek(offset: 0, from: .current)
#expect(afterReadOffset == 10) // Should still be at 10
}
}
}
// MARK: - Semantic Behavior
@available(SystemWithSpan 0.0.1, *)
@Test func partialReadBehavior() async throws {
try withTemporaryFilePath(basename: "partialReadBehavior") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
let data: [UInt8] = Array(0..<100)
try fd.writeAll(data)
try fd.seek(offset: 0, from: .start)
// read(into:) may return partial data - this is valid behavior
let output = UnsafeMutableRawBufferPointer.allocate(byteCount: 100, alignment: 1)
defer { output.deallocate() }
var span = OutputRawSpan(buffer: output, initializedCount: 0)
var totalRead = 0
while span.freeCapacity > 0 {
let bytesRead = try fd.read(into: &span)
if bytesRead == 0 { break } // EOF
totalRead += bytesRead
#expect(bytesRead > 0)
#expect(bytesRead <= span.freeCapacity + bytesRead) // Can't read more than capacity
}
// Should eventually get all data with multiple reads
#expect(totalRead == 100)
#expect(span.byteCount == 100)
}
}
}
@available(SystemWithSpan 0.0.1, *)
@Test func readFillingBehavior() async throws {
try withTemporaryFilePath(basename: "readFillingBehavior") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
// Test 1: read(filling:) fills buffer completely when data available
let fullData: [UInt8] = Array(0..<100)
try fd.writeAll(fullData)
try fd.seek(offset: 0, from: .start)
let result1 = try [UInt8](unsafeUninitializedCapacity: 100) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
let bytesRead = try fd.read(filling: &output)
#expect(bytesRead == 100)
#expect(output.freeCapacity == 0) // Should be completely full
count = output.byteCount
}
#expect(result1 == fullData)
// Test 2: read(filling:) stops at EOF even if buffer not full
try fd.seek(offset: 0, from: .start)
let result2 = try [UInt8](unsafeUninitializedCapacity: 200) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
let bytesRead = try fd.read(filling: &output)
#expect(bytesRead == 100) // Only 100 bytes available
#expect(output.freeCapacity == 100) // 100 bytes unfilled
count = output.byteCount
}
#expect(result2 == fullData)
}
}
}
// MARK: - Edge Cases
@available(SystemWithSpan 0.0.1, *)
@Test func emptyIO() async throws {
try withTemporaryFilePath(basename: "emptyIO") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
// Empty write
let empty: [UInt8] = []
let written = try empty.withUnsafeBytes { bytes in
try fd.writeAll(RawSpan(_unsafeBytes: bytes))
}
#expect(written == 0)
// Empty read (from empty file)
let result1 = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(into: &output)
}
#expect(result1.isEmpty)
// Zero-capacity buffer
let data: [UInt8] = [0x61, 0x62, 0x63]
try fd.writeAll(data)
try fd.seek(offset: 0, from: .start)
let result2 = try [UInt8](unsafeUninitializedCapacity: 0) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(into: &output)
}
#expect(result2.isEmpty)
}
}
}
@available(SystemWithSpan 0.0.1, *)
@Test func eofBehavior() async throws {
try withTemporaryFilePath(basename: "eofBehavior") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
let data: [UInt8] = [0x61, 0x62, 0x63]
try fd.writeAll(data)
try fd.seek(offset: 0, from: .start)
// Read all data
let result1 = try [UInt8](unsafeUninitializedCapacity: 3) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(filling: &output)
}
#expect(result1 == data)
// Read at EOF returns 0
let result2 = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(into: &output)
}
#expect(result2.isEmpty)
// read(filling:) with buffer larger than file stops at EOF
try fd.seek(offset: 0, from: .start)
let result3 = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
let bytesRead = try fd.read(filling: &output)
#expect(bytesRead == 3) // Only 3 bytes available
count = bytesRead
}
#expect(result3 == data)
}
}
}
@available(SystemWithSpan 0.0.1, *)
@Test func preInitializedSpan() async throws {
try withTemporaryFilePath(basename: "preInitializedSpan") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
let fileData: [UInt8] = [0x61, 0x62, 0x63] // "abc"
try fd.writeAll(fileData)
try fd.seek(offset: 0, from: .start)
// Create buffer with pre-existing initialized data
let result = try [UInt8](unsafeUninitializedCapacity: 10) { buffer, count in
// Pre-initialize first 2 bytes
buffer[0] = 0xFF
buffer[1] = 0xFE
// Create OutputRawSpan that knows about pre-initialized portion
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 2)
// Read more data - should append after pre-initialized data
let bytesRead = try fd.read(filling: &output)
#expect(bytesRead == 3) // Read "abc"
#expect(output.byteCount == 5) // 2 pre-initialized + 3 read = 5 total
count = output.byteCount
}
// Verify: first 2 bytes are pre-initialized, next 3 are from file
#expect(result == [0xFF, 0xFE, 0x61, 0x62, 0x63])
}
}
}
@available(SystemWithSpan 0.0.1, *)
@Test func errorHandling() throws {
// Test 1: Reading from closed FD
let fd1 = try FileDescriptor.open(FilePath("/dev/null"), .readOnly)
try fd1.close()
#expect(throws: Errno.badFileDescriptor) {
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 10, alignment: 1)
defer { buffer.deallocate() }
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
_ = try fd1.read(into: &output)
}
// Test 2: Writing to closed FD
let fd2 = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly)
try fd2.close()
let data: [UInt8] = [0x61, 0x62, 0x63]
#expect(throws: Errno.badFileDescriptor) {
try data.withUnsafeBytes { bytes in
try fd2.write(RawSpan(_unsafeBytes: bytes))
}
}
// Test 3: Writing to read-only FD
try withTemporaryFilePath(basename: "errorHandling") { path in
// Create file first
let fdWrite = try FileDescriptor.open(
path.appending("test.txt"), .writeOnly,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
_ = try fdWrite.closeAfter {
try fdWrite.writeAll(data)
}
// Open read-only and try to write
let fdRead = try FileDescriptor.open(
path.appending("test.txt"), .readOnly
)
_ = try fdRead.closeAfter {
#expect(throws: Errno.badFileDescriptor) {
try data.withUnsafeBytes { bytes in
try fdRead.write(RawSpan(_unsafeBytes: bytes))
}
}
}
}
}
// MARK: - Regression/Examples
@available(SystemWithSpan 0.0.1, *)
@Test func proposalExample() async throws {
// Example from the proposal
try withTemporaryFilePath(basename: "proposalExample") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"), .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
try fd.closeAfter {
let writeData: [UInt8] = Array(repeating: 42, count: 4096)
try fd.writeAll(writeData)
try fd.seek(offset: 0, from: .start)
let chunk = try [UInt8](unsafeUninitializedCapacity: 4096) { buffer, count in
var output = OutputRawSpan(buffer: UnsafeMutableRawBufferPointer(buffer), initializedCount: 0)
count = try fd.read(filling: &output, retryOnInterrupt: true)
}
#expect(chunk.count == 4096)
#expect(chunk == writeData)
}
}
}
}
#endif // compiler(>=6.2)
+11 -10
View File
@@ -118,7 +118,7 @@ private struct StatTests {
#expect(targetStat.type == .regular)
#expect(symlinkStat.type == .symbolicLink)
#expect(symlinkStat.size < targetStat.size)
#expect(symlinkStat.sizeAllocated <= targetStat.sizeAllocated)
#expect(symlinkStat.sizeAllocated < targetStat.sizeAllocated)
// Set each .st_atim back to its original value for comparison
@@ -368,11 +368,14 @@ private struct StatTests {
]
#elseif os(FreeBSD)
let userSettableFlags: FileFlags = [
.noDump, .hidden, .offline,
.readOnly, .sparse, .system
// The following flags throw EPERM on ZFS.
// .userImmutable, .userAppend, .opaque,
// .userNoUnlink, .reparse,
.noDump, .userImmutable, .userAppend,
.opaque, .tracked, .hidden,
.userNoUnlink,
.offline,
.readOnly,
.reparse,
.sparse,
.system
]
#else // os(OpenBSD)
let userSettableFlags: FileFlags = [
@@ -381,15 +384,13 @@ private struct StatTests {
#endif
flags.insert(userSettableFlags)
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
try #require(fchflags(fd.rawValue, flags.rawValue) == 0, "\(Errno.current)")
stat = try fd.stat()
#expect(stat.flags == flags)
flags.remove(userSettableFlags)
// On FreeBSD, the second argument of `fchflags` requires `UInt` instead of`UInt32`.
try #require(fchflags(fd.rawValue, .init(flags.rawValue)) == 0, "\(Errno.current)")
try #require(fchflags(fd.rawValue, flags.rawValue) == 0, "\(Errno.current)")
stat = try fd.stat()
#expect(stat.flags == flags)