Compare commits

..
Author SHA1 Message Date
Rauhul Varma 0ff423fe26 update method name 2023-06-16 22:23:25 -07:00
Rauhul Varma 7661e95acf Flesh out and better organize stat.h 2023-06-16 22:14:28 -07:00
Rauhul Varma 3b62b88701 move things around 2023-06-10 23:44:01 -07:00
Rauhul Varma 3536697660 WIP: Ideas for stat.h interface 2023-06-10 22:17:07 -07:00
Rauhul Varma ffc90f58de Signal definitions 2023-06-10 22:16:19 -07:00
Rauhul Varma 55d9da0dcd Add protocol conformances 2023-06-10 22:16:19 -07:00
Rauhul Varma 539134c24b WIP: time.h and sys/time.h coverage 2023-06-10 22:16:19 -07:00
97 changed files with 3937 additions and 5493 deletions

No files matched your search

-13
View File
@@ -1,13 +0,0 @@
# Lines starting with '#' are comments.
# Each line is a case-sensitive file pattern followed by one or more owners.
# Order is important. The last matching pattern has the most precedence.
# More information: https://docs.github.com/en/articles/about-code-owners
#
# Please mirror the repository's file hierarchy in case-sensitive lexicographic
# order.
# Default owners
* @glessard @lorentey @milseman
# Swift CI configuration files
.swiftci/ @shahmishal
-54
View File
@@ -1,54 +0,0 @@
name: Pull request
on:
pull_request:
types: [opened, reopened, synchronize]
jobs:
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
linux_os_versions: '["jammy", "focal"]'
enable_macos_checks: true
# FIXME: https://github.com/swiftlang/github-workflows/pull/140
# Xcode 16.0 and 16.1 are not actually available
macos_exclude_xcode_versions: |
[
{"xcode_version": "16.0"},
{"xcode_version": "16.1"},
]
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
enable_linux_static_sdk_build: true
enable_wasm_sdk_build: true
build-abi-stable:
name: Build ABI Stable
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
enable_linux_checks: false
enable_macos_checks: true
enable_windows_checks: false
# Only build
macos_build_command: "xcrun swift build --build-tests"
# FIXME: https://github.com/swiftlang/github-workflows/pull/140
# Xcode 16.0 and 16.1 are not actually available
macos_exclude_xcode_versions: |
[
{"xcode_version": "16.0"},
{"xcode_version": "16.1"},
]
# Enable availability to match ABI stable verion of system.
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE"
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
with:
license_header_check_project_name: "Swift.org"
# https://github.com/apple/swift-system/issues/224
docs_check_enabled: false
unacceptable_language_check_enabled: false
license_header_check_enabled: false
format_check_enabled: false
python_lint_check_enabled: false
+2 -3
View File
@@ -2,8 +2,7 @@
/.swiftpm
/.build
/Packages
/*.xcodeproj
swift-system.xcodeproj
xcuserdata/
.*.sw?
/.swiftpm
.docc-build
.docc-build
-4
View File
@@ -1,4 +0,0 @@
version: 1
builder:
configs:
- documentation_targets: [SystemPackage]
-5
View File
@@ -1,5 +0,0 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.10-jammy"
repo = "swift-system"
branch = "main"
}
-5
View File
@@ -1,5 +0,0 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.9-jammy"
repo = "swift-system"
branch = "main"
}
-5
View File
@@ -1,5 +0,0 @@
macOSSwiftPackageJob {
swift_version = "6.0"
repo = "swift-system"
branch = "main"
}
-5
View File
@@ -1,5 +0,0 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-6.0-jammy"
repo = "swift-system"
branch = "main"
}
-5
View File
@@ -1,5 +0,0 @@
macOSSwiftPackageJob {
swift_version = "main"
repo = "swift-system"
branch = "main"
}
-5
View File
@@ -1,5 +0,0 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-jammy"
repo = "swift-system"
branch = "main"
}
-7
View File
@@ -1,7 +0,0 @@
WindowsSwiftPackageWithDockerImageJob {
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
repo = "swift-system"
branch = "main"
sub_dir = "swift-system"
label = "windows-server-2019"
}
-2
View File
@@ -11,8 +11,6 @@ cmake_minimum_required(VERSION 3.16.0)
project(SwiftSystem
LANGUAGES C Swift)
include(GNUInstallDirs)
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
-38
View File
@@ -1,38 +0,0 @@
# Code of Conduct
To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.
To give clarity of what is expected of our members, this code of conduct is based on [contributor-covenant.org](http://contributor-covenant.org). This document is used across many open source communities, and we think it articulates our values well.
### Contributor Code of Conduct v1.4
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language (e.g., prefer non-gendered words like “folks” to “guys”, non-ableist words like “soundness check” to “sanity check”, etc.)
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others’ private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
This Code of Conduct applies within all project spaces managed by Swift.org, including (but not limited to) source code repositories, bug trackers, web sites, documentation, and online forums. It also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a member of the [Swift Core Team](https://swift.org/community/#community-structure) or by flagging the behavior for moderation (e.g., in the Forums), whether you are the target of that behavior or not. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. The site of the disputed behavior is usually not an acceptable place to discuss moderation decisions, and moderators may move or remove any such discussion.
Project maintainers are held to a higher standard, and project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
If you disagree with a moderation action, you can appeal to the Core Team (or individual Core Team members) privately.
This policy is adapted from the Contributor Code of Conduct [version 1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/).
+39 -139
View File
@@ -1,143 +1,43 @@
// swift-tools-version:5.9
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import PackageDescription
struct Available {
var name: String
var version: String
var osAvailability: String
var sourceAvailability: String
init(
_ version: String,
_ osAvailability: String
) {
self.name = "System"
self.version = version
self.osAvailability = osAvailability
self.sourceAvailability = "macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0"
}
var swiftSetting: SwiftSetting {
#if SYSTEM_ABI_STABLE
// Use availability matching Darwin API.
let availability = self.osAvailability
#else
// Use availability matching SwiftPM default.
let availability = self.sourceAvailability
#endif
return .enableExperimentalFeature(
"AvailabilityMacro=\(self.name) \(version):\(availability)")
}
}
let availability: [Available] = [
Available("0.0.1", "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0"),
Available("0.0.2", "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0"),
Available("0.0.3", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
Available("1.1.0", "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4"),
Available("1.1.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.2.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.2.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.3.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4"),
Available("1.3.1", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("1.3.2", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
Available("1.4.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.4.2", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.5.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.6.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
Available("1.6.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
]
let swiftSettingsAvailability = availability.map(\.swiftSetting)
#if SYSTEM_CI
let swiftSettingsCI: [SwiftSetting] = [
.unsafeFlags(["-require-explicit-availability=error"]),
]
#else
let swiftSettingsCI: [SwiftSetting] = []
#endif
let swiftSettings = swiftSettingsAvailability + swiftSettingsCI + [
.define(
"SYSTEM_PACKAGE_DARWIN",
.when(platforms: [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS])),
.define("SYSTEM_PACKAGE"),
.define("ENABLE_MOCKING", .when(configuration: .debug)),
.enableExperimentalFeature("Lifetimes"),
]
let cSettings: [CSetting] = [
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])),
]
#if SYSTEM_ABI_STABLE
let platforms: [SupportedPlatform] = [
.macOS("26"),
.iOS("26"),
.watchOS("26"),
.tvOS("26"),
.visionOS("26"),
]
#else
let platforms: [SupportedPlatform]? = nil
#endif
#if os(Linux)
let filesToExclude = ["CMakeLists.txt"]
#else
let filesToExclude = ["CMakeLists.txt", "IORing"]
#endif
#if os(Linux)
let testsToExclude:[String] = []
#else
let testsToExclude = ["IORequestTests.swift", "IORingTests.swift"]
#endif
let package = Package(
name: "swift-system",
platforms: platforms,
products: [
.library(name: "SystemPackage", targets: ["SystemPackage"]),
],
dependencies: [],
targets: [
.target(
name: "CSystem",
dependencies: [],
exclude: ["CMakeLists.txt"],
cSettings: cSettings),
.target(
name: "SystemPackage",
dependencies: ["CSystem"],
path: "Sources/System",
exclude: filesToExclude,
cSettings: cSettings,
swiftSettings: swiftSettings),
.testTarget(
name: "SystemTests",
dependencies: ["SystemPackage"],
exclude: testsToExclude,
cSettings: cSettings,
swiftSettings: swiftSettings),
])
name: "swift-system",
products: [
.library(name: "SystemPackage", targets: ["SystemPackage"]),
],
dependencies: [],
targets: [
.target(
name: "CSystem",
dependencies: []),
.target(
name: "SystemPackage",
dependencies: ["CSystem"],
path: "Sources/System",
cSettings: [
.define("_CRT_SECURE_NO_WARNINGS")
],
swiftSettings: [
.define("SYSTEM_PACKAGE"),
.define("ENABLE_MOCKING", .when(configuration: .debug))
]),
.testTarget(
name: "SystemTests",
dependencies: ["SystemPackage"],
swiftSettings: [
.define("SYSTEM_PACKAGE")
]),
]
)
+9 -71
View File
@@ -2,13 +2,11 @@
Swift System provides idiomatic interfaces to system calls and low-level currency types. Our vision is for System to act as the single home for low-level system interfaces for all supported Swift platforms.
## No Cross-platform Abstractions
## Multi-platform not Cross-platform
Swift System is not a cross-platform library. It provides a separate set of APIs and behaviors on every supported platform, closely reflecting the underlying OS interfaces. A single import will pull in the native platform interfaces specific for the targeted OS.
System is a multi-platform library, not a cross-platform one. It provides a separate set of APIs and behaviors on every supported platform, closely reflecting the underlying OS interfaces. A single import will pull in the native platform interfaces specific for the targeted OS.
Our immediate goal is to simplify building cross-platform libraries and applications such as SwiftNIO and SwiftPM. It is not a design goal for System to eliminate the need for `#if os()` conditionals to implement cross-platform abstractions; rather, our goal is to make it safer and more expressive to fill out the platform-specific parts.
(That said, it is desirable to avoid unnecessary differences -- for example, when two operating systems share the same C name for a system call, ideally Swift System would expose them using the same Swift name. This is a particularly obvious expectation for system interfaces that implement an industry standard, such as POSIX.)
Our immediate goal is to simplify building cross-platform libraries and applications such as SwiftNIO and SwiftPM. System does not eliminate the need for `#if os()` conditionals to implement cross-platform abstractions, but it does make it safer and more expressive to fill out the platform-specific parts.
## Usage
@@ -24,15 +22,13 @@ try fd.closeAfter {
}
```
[API documentation](https://swiftpackageindex.com/apple/swift-system/documentation/SystemPackage)
## Adding `SystemPackage` as a Dependency
To use the `SystemPackage` library in a SwiftPM project,
add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-system", from: "1.6.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
```
Finally, include `"SystemPackage"` as a dependency for your executable target:
@@ -41,7 +37,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.6.1"),
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
// other dependencies
],
targets: [
@@ -55,72 +51,14 @@ let package = Package(
## Source Stability
At this time, the Swift System package supports three types of operating systems: Darwin-based, POSIX-like, and Windows. The source-stability status of the package differs according to the platform:
| Platform type | Source Stability |
| ----------------- | --------------- |
| Darwin (macOS, iOS, etc.) | Stable |
| POSIX (Linux, WASI, etc.) | Stable |
| Windows | Unstable |
The package version numbers follow [Semantic Versioning][semver] -- source breaking changes to source-stable public API can only land in a new major version. However, platforms for which support has not reached source stability may see source-breaking changes in a new minor version.
The Swift System package is source stable. The version numbers follow [Semantic Versioning][semver] -- source breaking changes to public API can only land in a new major version.
[semver]: https://semver.org
The public API of the swift-system package consists of non-underscored declarations that are marked `public` in the `SystemPackage` module.
By "underscored declarations" we mean declarations that have a leading underscore anywhere in their fully qualified name. For instance, here are some names that wouldn't be considered part of the public API, even if they were technically marked public:
- `FooModule.Bar._someMember(value:)` (underscored member)
- `FooModule._Bar.someMember` (underscored type)
- `_FooModule.Bar` (underscored module)
- `FooModule.Bar.init(_value:)` (underscored initializer)
Interfaces that aren't part of the public API may continue to change in any release, including patch releases. If you have a use case that requires using non-public APIs, please submit a Feature Request describing it! We'd like the public interface to be as useful as possible -- although preferably without compromising safety or limiting future evolution.
Future minor versions of the package may update these rules as needed.
## Toolchain Requirements
The following table maps existing package releases to their minimum required Swift toolchain release:
| Package version | Swift version | Xcode release |
| ----------------------- | --------------- | ------------- |
| swift-system 1.3.x | >= Swift 5.8 | >= Xcode 14.3 |
| swift-system 1.4.x through 1.6.x | >= Swift 5.9 | >= Xcode 15.0 |
We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, new versions of this package require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Patch (i.e., bugfix) releases will not increase the required toolchain version, but any minor (i.e., new feature) release may do so.
(Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.)
## Licensing
See [LICENSE](LICENSE.txt) for license information.
## Contributing
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
### Branching Strategy
## LICENSE
We maintain separate branches for each active minor version of the package:
| Package version | Branch |
| ----------------------- | ----------- |
| swift-system 1.3.x | release/1.3 |
| swift-system 1.4.x | release/1.4 |
| swift-system 1.5.x | release/1.5 |
| swift-system 1.6.x | release/1.6 |
| swift-system 1.7.x (unreleased) | main |
Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction:
`release/1.3` → `release/1.4` → `main`
For example, anything landing on `release/1.3` will eventually appear on `release/1.4` and then `main` too; there is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.)
### Code of Conduct
Like all Swift.org projects, we would like the Swift System project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc].
[coc]: CODE_OF_CONDUCT.md
See [LICENSE](LICENSE.txt) for license information.
+2 -2
View File
@@ -9,8 +9,8 @@ See https://swift.org/LICENSE.txt for license information
add_library(CSystem INTERFACE)
target_include_directories(CSystem INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
$<INSTALL_INTERFACE:include/CSystem>)
include)
install(FILES
include/CSystemLinux.h
-1
View File
@@ -21,6 +21,5 @@
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include "io_uring.h"
#endif
-66
View File
@@ -1,66 +0,0 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2024 - 2025 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#pragma once
#if __wasi__
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h> // For NAME_MAX
// wasi-libc defines the following constants in a way that Clang Importer can't
// understand, so we need to expose them manually.
static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; }
static inline int32_t _getConst_O_APPEND(void) { return O_APPEND; }
static inline int32_t _getConst_O_CREAT(void) { return O_CREAT; }
static inline int32_t _getConst_O_DIRECTORY(void) { return O_DIRECTORY; }
static inline int32_t _getConst_O_EXCL(void) { return O_EXCL; }
static inline int32_t _getConst_O_NONBLOCK(void) { return O_NONBLOCK; }
static inline int32_t _getConst_O_TRUNC(void) { return O_TRUNC; }
static inline int32_t _getConst_O_WRONLY(void) { return O_WRONLY; }
static inline int32_t _getConst_EWOULDBLOCK(void) { return EWOULDBLOCK; }
static inline int32_t _getConst_EOPNOTSUPP(void) { return EOPNOTSUPP; }
static inline uint8_t _getConst_DT_DIR(void) { return DT_DIR; }
// Modified dirent struct that can be imported to Swift
struct _system_dirent {
ino_t d_ino;
unsigned char d_type;
// char d_name[] cannot be imported to Swift
char d_name[NAME_MAX + 1];
};
// Convert WASI dirent with d_name[] to _system_dirent
static inline
struct _system_dirent *
_system_dirent_from_wasi_dirent(const struct dirent *wasi_dirent) {
// Match readdir behavior and use thread-local storage for the converted dirent
static __thread struct _system_dirent _converted_dirent;
if (wasi_dirent == NULL) {
return NULL;
}
memset(&_converted_dirent, 0, sizeof(struct _system_dirent));
_converted_dirent.d_ino = wasi_dirent->d_ino;
_converted_dirent.d_type = wasi_dirent->d_type;
strncpy(_converted_dirent.d_name, wasi_dirent->d_name, NAME_MAX);
_converted_dirent.d_name[NAME_MAX] = '\0';
return &_converted_dirent;
}
#endif
-245
View File
@@ -1,245 +0,0 @@
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <signal.h>
#define __SWIFT_IORING_SQE_FALLBACK_STRUCT { \
__u8 opcode; \
__u8 flags; \
__u16 ioprio; \
__s32 fd; \
union { \
__u64 off; \
__u64 addr2; \
struct { \
__u32 cmd_op; \
__u32 __pad1; \
}; \
}; \
union { \
__u64 addr; \
__u64 splice_off_in; \
struct { \
__u32 level; \
__u32 optname; \
}; \
}; \
__u32 len; \
union { \
__kernel_rwf_t rw_flags; \
__u32 fsync_flags; \
__u16 poll_events; \
__u32 poll32_events; \
__u32 sync_range_flags; \
__u32 msg_flags; \
__u32 timeout_flags; \
__u32 accept_flags; \
__u32 cancel_flags; \
__u32 open_flags; \
__u32 statx_flags; \
__u32 fadvise_advice; \
__u32 splice_flags; \
__u32 rename_flags; \
__u32 unlink_flags; \
__u32 hardlink_flags; \
__u32 xattr_flags; \
__u32 msg_ring_flags; \
__u32 uring_cmd_flags; \
__u32 waitid_flags; \
__u32 futex_flags; \
__u32 install_fd_flags; \
__u32 nop_flags; \
}; \
__u64 user_data; \
union { \
__u16 buf_index; \
__u16 buf_group; \
} __attribute__((packed)); \
__u16 personality; \
union { \
__s32 splice_fd_in; \
__u32 file_index; \
__u32 optlen; \
struct { \
__u16 addr_len; \
__u16 __pad3[1]; \
}; \
}; \
union { \
struct { \
__u64 addr3; \
__u64 __pad2[1]; \
}; \
__u64 optval; \
__u8 cmd[0]; \
}; \
}
#if __has_include(<linux/io_uring.h>)
#include <linux/io_uring.h>
#ifdef IORING_TIMEOUT_BOOTTIME
// Kernel version >= 5.15, io_uring_sqe has file_index
// and all current Swift operations are supported.
#define __SWIFT_IORING_SUPPORTED true
typedef struct io_uring_sqe swift_io_uring_sqe;
#else
// io_uring_sqe is missing properties that IORequest expects.
// This configuration is not supported for now.
//
// Define a fallback struct to avoid build errors, but IORing
// will throw ENOTSUP on initialization.
#define __SWIFT_IORING_SUPPORTED false
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
#endif
// We can define more specific availability later
#ifdef IORING_FEAT_RW_CUR_POS
// Kernel version >= 5.6, io_uring_sqe has open_flags
#endif
#ifdef IORING_FEAT_NODROP
// Kernel version >= 5.5, io_uring_sqe has cancel_flags
#endif
#else
// Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK)
#include <stdint.h>
#define __SWIFT_IORING_SUPPORTED false
#define IORING_OFF_SQ_RING 0ULL
#define IORING_OFF_CQ_RING 0x8000000ULL
#define IORING_OFF_SQES 0x10000000ULL
#define IORING_ENTER_GETEVENTS (1U << 0)
#define IORING_FEAT_SINGLE_MMAP (1U << 0)
#define IORING_FEAT_NODROP (1U << 1)
#define IORING_FEAT_SUBMIT_STABLE (1U << 2)
#define IORING_FEAT_RW_CUR_POS (1U << 3)
#define IORING_FEAT_CUR_PERSONALITY (1U << 4)
#define IORING_FEAT_FAST_POLL (1U << 5)
#define IORING_FEAT_POLL_32BITS (1U << 6)
#define IORING_FEAT_SQPOLL_NONFIXED (1U << 7)
#define IORING_FEAT_EXT_ARG (1U << 8)
#define IORING_FEAT_NATIVE_WORKERS (1U << 9)
#define IORING_FEAT_RSRC_TAGS (1U << 10)
#define IORING_FEAT_CQE_SKIP (1U << 11)
#define IORING_FEAT_LINKED_FILE (1U << 12)
#define IORING_FEAT_REG_REG_RING (1U << 13)
#define IORING_FEAT_RECVSEND_BUNDLE (1U << 14)
#define IORING_FEAT_MIN_TIMEOUT (1U << 15)
#define IORING_FEAT_RW_ATTR (1U << 16)
#define IORING_FEAT_NO_IOWAIT (1U << 17)
typedef uint8_t __u8;
typedef uint16_t __u16;
typedef uint32_t __u32;
typedef uint64_t __u64;
typedef int32_t __s32;
#ifndef __kernel_rwf_t
typedef int __kernel_rwf_t;
#endif
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
struct io_uring_cqe {
__u64 user_data;
__s32 res;
__u32 flags;
};
struct io_sqring_offsets {
__u32 head;
__u32 tail;
__u32 ring_mask;
__u32 ring_entries;
__u32 flags;
__u32 dropped;
__u32 array;
__u32 resv1;
__u64 user_addr;
};
struct io_cqring_offsets {
__u32 head;
__u32 tail;
__u32 ring_mask;
__u32 ring_entries;
__u32 overflow;
__u32 cqes;
__u32 flags;
__u32 resv1;
__u64 user_addr;
};
struct io_uring_params {
__u32 sq_entries;
__u32 cq_entries;
__u32 flags;
__u32 sq_thread_cpu;
__u32 sq_thread_idle;
__u32 features;
__u32 wq_fd;
__u32 resv[3];
struct io_sqring_offsets sq_off;
struct io_cqring_offsets cq_off;
};
#endif // __has_include(<linux/io_uring.h>)
#ifndef SWIFT_IORING_C_WRAPPER
#define SWIFT_IORING_C_WRAPPER
# ifndef __NR_io_uring_setup
# define __NR_io_uring_setup 425
# endif
# ifndef __NR_io_uring_enter
# define __NR_io_uring_enter 426
# endif
# ifndef __NR_io_uring_register
# define __NR_io_uring_register 427
# endif
/*
struct io_uring_getevents_arg {
__u64 sigmask;
__u32 sigmask_sz;
__u32 min_wait_usec; //used to be called `pad`. This compatibility wrapper avoids dealing with that.
__u64 ts;
};
*/
struct swift_io_uring_getevents_arg {
__u64 sigmask;
__u32 sigmask_sz;
__u32 min_wait_usec;
__u64 ts;
};
static inline int io_uring_register(int fd, unsigned int opcode, void *arg,
unsigned int nr_args)
{
return syscall(__NR_io_uring_register, fd, opcode, arg, nr_args);
}
static inline int io_uring_setup(unsigned int entries, struct io_uring_params *p)
{
return syscall(__NR_io_uring_setup, entries, p);
}
static inline int io_uring_enter2(int fd, unsigned int to_submit, unsigned int min_complete,
unsigned int flags, void *args, size_t sz)
{
return syscall(__NR_io_uring_enter, fd, to_submit, min_complete,
flags, args, _NSIG / 8);
}
static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete,
unsigned int flags, sigset_t *sig)
{
return io_uring_enter2(fd, to_submit, min_complete, flags, sig, _NSIG / 8);
}
#endif
-1
View File
@@ -1,6 +1,5 @@
module CSystem {
header "CSystemLinux.h"
header "CSystemWASI.h"
header "CSystemWindows.h"
export *
}
-4
View File
@@ -41,10 +41,6 @@ target_sources(SystemPackage PRIVATE
target_link_libraries(SystemPackage PUBLIC
CSystem)
set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS")
if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS)
target_compile_definitions(SystemPackage PRIVATE SYSTEM_PACKAGE_DARWIN)
endif()
_install_target(SystemPackage)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage)
+135 -193
View File
File diff suppressed because it is too large. Load diff
-20
View File
@@ -1,20 +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
extension Errno {
internal init(windowsError: DWORD) {
self.init(rawValue: _mapWindowsErrorToErrno(windowsError))
}
}
#endif
@@ -14,8 +14,8 @@
/// of `FileDescriptor` values,
/// in the same way as you manage a raw C file handle.
@frozen
@available(System 0.0.1, *)
public struct FileDescriptor: RawRepresentable, Hashable {
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
public struct FileDescriptor: RawRepresentable, Hashable, Codable {
/// The raw C file handle.
@_alwaysEmitIntoClient
public let rawValue: CInt
@@ -26,7 +26,7 @@ public struct FileDescriptor: RawRepresentable, Hashable {
}
// Standard file descriptors.
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor {
/// The standard input file descriptor, with a numeric value of 0.
@_alwaysEmitIntoClient
@@ -41,12 +41,11 @@ extension FileDescriptor {
public static var standardError: FileDescriptor { .init(rawValue: 2) }
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor {
/// The desired read and write access for a newly opened file.
@frozen
@available(System 0.0.1, *)
public struct AccessMode: RawRepresentable, Sendable, Hashable {
public struct AccessMode: RawRepresentable, Hashable, Codable {
/// The raw C access mode.
@_alwaysEmitIntoClient
public var rawValue: CInt
@@ -88,8 +87,7 @@ extension FileDescriptor {
/// Options that specify behavior for a newly-opened file.
@frozen
@available(System 0.0.1, *)
public struct OpenOptions: OptionSet, Sendable, Hashable {
public struct OpenOptions: OptionSet, Hashable, Codable {
/// The raw C options.
@_alwaysEmitIntoClient
public var rawValue: CInt
@@ -98,6 +96,9 @@ extension FileDescriptor {
@_alwaysEmitIntoClient
public init(rawValue: CInt) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInt) { self.init(rawValue: raw) }
#if !os(Windows)
/// Indicates that opening the file doesn't
/// wait for the file or device to become available.
@@ -114,7 +115,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_NONBLOCK`.
@_alwaysEmitIntoClient
public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) }
public static var nonBlocking: OpenOptions { OpenOptions(_O_NONBLOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "nonBlocking")
@@ -130,7 +131,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_APPEND`.
@_alwaysEmitIntoClient
public static var append: OpenOptions { .init(rawValue: _O_APPEND) }
public static var append: OpenOptions { OpenOptions(_O_APPEND) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "append")
@@ -140,7 +141,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_CREAT`.
@_alwaysEmitIntoClient
public static var create: OpenOptions { .init(rawValue: _O_CREAT) }
public static var create: OpenOptions { OpenOptions(_O_CREAT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "create")
@@ -154,7 +155,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_TRUNC`.
@_alwaysEmitIntoClient
public static var truncate: OpenOptions { .init(rawValue: _O_TRUNC) }
public static var truncate: OpenOptions { OpenOptions(_O_TRUNC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "truncate")
@@ -176,13 +177,13 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_EXCL`.
@_alwaysEmitIntoClient
public static var exclusiveCreate: OpenOptions { .init(rawValue: _O_EXCL) }
public static var exclusiveCreate: OpenOptions { OpenOptions(_O_EXCL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "exclusiveCreate")
public static var O_EXCL: OpenOptions { exclusiveCreate }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Indicates that opening the file
/// atomically obtains a shared lock on the file.
///
@@ -194,7 +195,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_SHLOCK`.
@_alwaysEmitIntoClient
public static var sharedLock: OpenOptions { .init(rawValue: _O_SHLOCK) }
public static var sharedLock: OpenOptions { OpenOptions(_O_SHLOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "sharedLock")
@@ -211,7 +212,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_EXLOCK`.
@_alwaysEmitIntoClient
public static var exclusiveLock: OpenOptions { .init(rawValue: _O_EXLOCK) }
public static var exclusiveLock: OpenOptions { OpenOptions(_O_EXLOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "exclusiveLock")
@@ -229,7 +230,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_NOFOLLOW`.
@_alwaysEmitIntoClient
public static var noFollow: OpenOptions { .init(rawValue: _O_NOFOLLOW) }
public static var noFollow: OpenOptions { OpenOptions(_O_NOFOLLOW) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "noFollow")
@@ -243,30 +244,14 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_DIRECTORY`.
@_alwaysEmitIntoClient
public static var directory: OpenOptions { .init(rawValue: _O_DIRECTORY) }
public static var directory: OpenOptions { OpenOptions(_O_DIRECTORY) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "directory")
public static var O_DIRECTORY: OpenOptions { directory }
#endif
#if os(FreeBSD)
/// Indicates that each write operation is synchronous.
///
/// If this option is specified,
/// each time you write to the file,
/// the new data is written immediately and synchronously to the disk.
///
/// The corresponding C constant is `O_SYNC`.
@_alwaysEmitIntoClient
public static var sync: OpenOptions { .init(rawValue: _O_SYNC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "sync")
public static var O_SYNC: OpenOptions { sync }
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Indicates that opening the file
/// opens symbolic links instead of following them.
///
@@ -278,7 +263,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_SYMLINK`.
@_alwaysEmitIntoClient
public static var symlink: OpenOptions { .init(rawValue: _O_SYMLINK) }
public static var symlink: OpenOptions { OpenOptions(_O_SYMLINK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "symlink")
@@ -294,7 +279,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_EVTONLY`.
@_alwaysEmitIntoClient
public static var eventOnly: OpenOptions { .init(rawValue: _O_EVTONLY) }
public static var eventOnly: OpenOptions { OpenOptions(_O_EVTONLY) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "eventOnly")
@@ -316,7 +301,7 @@ extension FileDescriptor {
///
/// The corresponding C constant is `O_CLOEXEC`.
@_alwaysEmitIntoClient
public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) }
public static var closeOnExec: OpenOptions { OpenOptions(_O_CLOEXEC) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "closeOnExec")
@@ -326,8 +311,7 @@ extension FileDescriptor {
/// Options for specifying what a file descriptor's offset is relative to.
@frozen
@available(System 0.0.1, *)
public struct SeekOrigin: RawRepresentable, Sendable, Hashable {
public struct SeekOrigin: RawRepresentable, Hashable, Codable {
/// The raw C value.
@_alwaysEmitIntoClient
public var rawValue: CInt
@@ -370,7 +354,7 @@ extension FileDescriptor {
// TODO: These are available on some versions of Linux with appropriate
// macro defines.
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Indicates that the offset should be set
/// to the next hole after the specified number of bytes.
///
@@ -402,23 +386,7 @@ extension FileDescriptor {
}
}
#if !$Embedded
@available(System 0.0.1, *)
extension FileDescriptor: Codable {}
@available(System 0.0.1, *)
extension FileDescriptor.AccessMode: Codable {}
@available(System 0.0.1, *)
extension FileDescriptor.OpenOptions: Codable {}
@available(System 0.0.1, *)
extension FileDescriptor.SeekOrigin: Codable {}
#endif // !$Embedded
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor.AccessMode
: CustomStringConvertible, CustomDebugStringConvertible
{
@@ -437,7 +405,7 @@ extension FileDescriptor.AccessMode
public var debugDescription: String { self.description }
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor.SeekOrigin
: CustomStringConvertible, CustomDebugStringConvertible
{
@@ -448,7 +416,7 @@ extension FileDescriptor.SeekOrigin
case .start: return "start"
case .current: return "current"
case .end: return "end"
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
case .nextHole: return "nextHole"
case .nextData: return "nextData"
#endif
@@ -460,14 +428,14 @@ extension FileDescriptor.SeekOrigin
public var debugDescription: String { self.description }
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor.OpenOptions
: CustomStringConvertible, CustomDebugStringConvertible
{
/// A textual representation of the open options.
@inline(never)
public var description: String {
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
let descriptions: [(Element, StaticString)] = [
(.nonBlocking, ".nonBlocking"),
(.append, ".append"),
@@ -488,19 +456,6 @@ extension FileDescriptor.OpenOptions
(.truncate, ".truncate"),
(.exclusiveCreate, ".exclusiveCreate"),
]
#elseif os(FreeBSD)
let descriptions: [(Element, StaticString)] = [
(.nonBlocking, ".nonBlocking"),
(.append, ".append"),
(.create, ".create"),
(.truncate, ".truncate"),
(.exclusiveCreate, ".exclusiveCreate"),
(.sharedLock, ".sharedLock"),
(.exclusiveLock, ".exclusiveLock"),
(.sync, ".sync"),
(.noFollow, ".noFollow"),
(.closeOnExec, ".closeOnExec")
]
#else
let descriptions: [(Element, StaticString)] = [
(.nonBlocking, ".nonBlocking"),
@@ -520,7 +475,13 @@ extension FileDescriptor.OpenOptions
public var debugDescription: String { self.description }
}
#if compiler(>=5.5) && canImport(_Concurrency)
// The decision on whether to make FileDescriptor Sendable or not
// is currently being discussed in https://github.com/apple/swift-system/pull/112
//@available(*, unavailable, message: "File descriptors are not completely thread-safe.")
//extension FileDescriptor: Sendable {}
extension FileDescriptor.AccessMode: Sendable {}
extension FileDescriptor.OpenOptions: Sendable {}
extension FileDescriptor.SeekOrigin: Sendable {}
#endif
@@ -7,7 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor {
/// Runs a closure and then closes the file descriptor, even if an error occurs.
///
@@ -1,13 +1,13 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FileDescriptor {
/// Opens or creates a file for reading or writing.
///
@@ -30,24 +30,24 @@ extension FileDescriptor {
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor {
) throws -> FileDescriptor {
#if !os(Windows)
return try path.withCString { (cString) throws(SystemError) in
return try path.withCString {
try FileDescriptor.open(
cString, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
}
#else
return try path.withPlatformString { (platformString) throws(SystemError) in
#else
return try path.withPlatformString {
try FileDescriptor.open(
platformString, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
}
#endif
}
#if !os(Windows)
// On Darwin, `CInterop.PlatformChar` is less available than
#if !os(Windows)
// On Darwin, `CInterop.PlatformChar` is less available than
// `FileDescriptor.open`, so we need to use `CChar` instead.
/// Opens or creates a file for reading or writing.
///
/// - Parameters:
@@ -69,7 +69,7 @@ extension FileDescriptor {
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor {
) throws -> FileDescriptor {
try FileDescriptor._open(
path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt
).get()
@@ -116,7 +116,7 @@ extension FileDescriptor {
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor {
) throws -> FileDescriptor {
try FileDescriptor._open(
path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt
).get()
@@ -135,6 +135,8 @@ extension FileDescriptor {
if let permissions = permissions {
return system_open(path, oFlag, permissions.rawValue)
}
precondition(!options.contains(.create),
"Create must be given permissions")
return system_open(path, oFlag)
}
return descOrError.map { FileDescriptor(rawValue: $0) }
@@ -149,14 +151,14 @@ extension FileDescriptor {
///
/// The corresponding C function is `close`.
@_alwaysEmitIntoClient
public func close() throws(SystemError) { try _close().get() }
public func close() throws { try _close().get() }
@usableFromInline
internal func _close() -> Result<(), Errno> {
nothingOrErrno(retryOnInterrupt: false) { system_close(self.rawValue) }
}
/// Repositions the offset for the given file descriptor.
/// Reposition the offset for the given file descriptor.
///
/// - Parameters:
/// - offset: The new offset for the file descriptor.
@@ -169,7 +171,7 @@ extension FileDescriptor {
@discardableResult
public func seek(
offset: Int64, from whence: FileDescriptor.SeekOrigin
) throws(SystemError) -> Int64 {
) throws -> Int64 {
try _seek(offset: offset, from: whence).get()
}
@@ -187,7 +189,7 @@ extension FileDescriptor {
@available(*, unavailable, renamed: "seek")
public func lseek(
offset: Int64, from whence: FileDescriptor.SeekOrigin
) throws(SystemError) -> Int64 {
) throws -> Int64 {
try seek(offset: offset, from: whence)
}
@@ -214,7 +216,7 @@ extension FileDescriptor {
public func read(
into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool = true
) throws(SystemError) -> Int {
) throws -> Int {
try _read(into: buffer, retryOnInterrupt: retryOnInterrupt).get()
}
@@ -222,7 +224,7 @@ extension FileDescriptor {
internal func _read(
into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool
) throws(SystemError) -> Result<Int, Errno> {
) throws -> Result<Int, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_read(self.rawValue, buffer.baseAddress, buffer.count)
}
@@ -251,7 +253,7 @@ extension FileDescriptor {
fromAbsoluteOffset offset: Int64,
into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool = true
) throws(SystemError) -> Int {
) throws -> Int {
try _read(
fromAbsoluteOffset: offset,
into: buffer,
@@ -276,7 +278,7 @@ extension FileDescriptor {
fromAbsoluteOffset offset: Int64,
into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool = true
) throws(SystemError) -> Int {
) throws -> Int {
try read(
fromAbsoluteOffset: offset,
into: buffer,
@@ -303,7 +305,7 @@ extension FileDescriptor {
public func write(
_ buffer: UnsafeRawBufferPointer,
retryOnInterrupt: Bool = true
) throws(SystemError) -> Int {
) throws -> Int {
try _write(buffer, retryOnInterrupt: retryOnInterrupt).get()
}
@@ -337,7 +339,7 @@ extension FileDescriptor {
toAbsoluteOffset offset: Int64,
_ buffer: UnsafeRawBufferPointer,
retryOnInterrupt: Bool = true
) throws(SystemError) -> Int {
) throws -> Int {
try _write(toAbsoluteOffset: offset, buffer, retryOnInterrupt: retryOnInterrupt).get()
}
@@ -359,7 +361,7 @@ extension FileDescriptor {
toAbsoluteOffset offset: Int64,
into buffer: UnsafeRawBufferPointer,
retryOnInterrupt: Bool = true
) throws(SystemError) -> Int {
) throws -> Int {
try write(
toAbsoluteOffset: offset,
buffer,
@@ -367,10 +369,9 @@ extension FileDescriptor {
}
}
#if !os(WASI)
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FileDescriptor {
/// Duplicates this file descriptor and return the newly created copy.
/// Duplicate this file descriptor and return the newly created copy.
///
/// - Parameters:
/// - `target`: The desired target file descriptor, or `nil`, in which case
@@ -398,20 +399,20 @@ extension FileDescriptor {
///
/// The corresponding C functions are `dup` and `dup2`.
@_alwaysEmitIntoClient
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
public func duplicate(
as target: FileDescriptor? = nil,
retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor {
) throws -> FileDescriptor {
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
@usableFromInline
internal func _duplicate(
as target: FileDescriptor?,
retryOnInterrupt: Bool
) throws(SystemError) -> Result<FileDescriptor, Errno> {
) throws -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
if let target = target {
return system_dup2(self.rawValue, target.rawValue)
@@ -422,33 +423,32 @@ extension FileDescriptor {
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "duplicate")
public func dup() throws(SystemError) -> FileDescriptor {
public func dup() throws -> FileDescriptor {
fatalError("Not implemented")
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "duplicate")
public func dup2() throws(SystemError) -> FileDescriptor {
public func dup2() throws -> FileDescriptor {
fatalError("Not implemented")
}
}
#endif
#if !os(WASI)
@available(System 1.1.0, *)
#if !os(Windows)
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
extension FileDescriptor {
/// Creates a unidirectional data channel, which can be used for interprocess communication.
/// Create a pipe, 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(SystemError) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe().get()
}
@available(System 1.1.0, *)
@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@usableFromInline
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
var fds: (Int32, Int32) = (-1, -1)
@@ -463,9 +463,10 @@ extension FileDescriptor {
}
#endif
@available(System 1.2.0, *)
#if !os(Windows)
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
extension FileDescriptor {
/// Truncates or extends the file referenced by this file descriptor.
/// Truncate or extend the file referenced by this file descriptor.
///
/// - Parameters:
/// - newSize: The length in bytes to resize the file to.
@@ -485,19 +486,19 @@ extension FileDescriptor {
/// associated with the file.
///
/// The corresponding C function is `ftruncate`.
@available(System 1.2.0, *)
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@_alwaysEmitIntoClient
public func resize(
to newSize: Int64,
retryOnInterrupt: Bool = true
) throws(SystemError) {
) throws {
try _resize(
to: newSize,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(System 1.2.0, *)
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@usableFromInline
internal func _resize(
to newSize: Int64,
@@ -508,46 +509,4 @@ extension FileDescriptor {
}
}
}
#if !os(WASI) // WASI has no umask
extension FilePermissions {
/// The file creation permission mask (aka "umask").
///
/// Permissions set in this mask will be cleared by functions that create
/// files or directories. Note that this mask is process-wide, and that
/// *getting* it is not thread safe.
internal static var creationMask: FilePermissions {
get {
let oldMask = _umask(0o22)
_ = _umask(oldMask)
return FilePermissions(rawValue: oldMask)
}
set {
_ = _umask(newValue.rawValue)
}
}
/// Change the file creation permission mask, run some code, then
/// restore it to its original value.
///
/// - Parameters:
/// - permissions: The new permission mask.
///
/// This is more efficient than reading `creationMask` and restoring it
/// afterwards, because of the way reading the creation mask works.
internal static func withCreationMask<R>(
_ permissions: FilePermissions,
body: () throws(SystemError) -> R
) rethrows -> R {
let oldMask = _umask(permissions.rawValue)
defer {
_ = _umask(oldMask)
}
return try body()
}
internal static func _umask(_ mode: CModeT) -> CModeT {
return system_umask(mode)
}
}
#endif
+8 -29
View File
@@ -37,8 +37,8 @@
/// However, the rules for path equivalence
/// are file-system–specific and have additional considerations
/// like case insensitivity, Unicode normalization, and symbolic links.
@available(System 0.0.1, *)
public struct FilePath: Sendable {
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
public struct FilePath {
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
// components, etc.
internal var _storage: SystemString
@@ -59,36 +59,15 @@ public struct FilePath: Sendable {
}
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
/// The length of the file path, excluding the null terminator.
public var length: Int { _storage.length }
}
@available(System 0.0.1, *)
extension FilePath: Hashable {}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath: Hashable, Codable {}
#if !$Embedded
@available(System 0.0.1, *)
extension FilePath: Codable {
// Encoder is synthesized; it probably should have been explicit and used
// a single-value container, but making that change now is somewhat risky.
// Decoder is written explicitly to ensure that we validate invariants on
// untrusted input.
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self._storage = try container.decode(SystemString.self, forKey: ._storage)
guard _invariantsSatisfied() else {
throw DecodingError.dataCorruptedError(
forKey: ._storage,
in: container,
debugDescription:
"Encoding does not satisfy the invariants of FilePath"
)
}
}
}
#endif // !$Embedded
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePath: Sendable {}
#endif
@@ -9,7 +9,7 @@
// MARK: - API
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// A bidirectional, range replaceable collection of the non-root components
/// that make up a file path.
@@ -28,8 +28,7 @@ extension FilePath {
///
/// path.components.removeAll { $0.kind == .currentDirectory }
/// // path is "/home/username/bin/scripts/tree"
@available(System 0.0.2, *)
public struct ComponentView: Sendable {
public struct ComponentView {
internal var _path: FilePath
internal var _start: SystemString.Index
@@ -40,6 +39,30 @@ extension FilePath {
}
}
#if SYSTEM_PACKAGE // Workaround for a __consuming getter bug in Swift 5.3.3
/// View the non-root components that make up this path.
public var components: ComponentView {
get { ComponentView(self) }
_modify {
// RRC's empty init means that we can't guarantee that the yielded
// view will restore our root. So copy it out first.
//
// TODO(perf): Small-form root (especially on Unix). Have Root
// always copy out (not worth ref counting). Make sure that we're
// not needlessly sliding values around or triggering a COW
let rootStr = self.root?._systemString ?? SystemString()
var comp = ComponentView(self)
self = FilePath()
defer {
self = comp._path
if root?._slice.elementsEqual(rootStr) != true {
self.root = Root(rootStr)
}
}
yield &comp
}
}
#else
/// View the non-root components that make up this path.
public var components: ComponentView {
__consuming get { ComponentView(self) }
@@ -62,14 +85,13 @@ extension FilePath {
yield &comp
}
}
#endif
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.ComponentView: BidirectionalCollection {
public typealias Element = FilePath.Component
@available(System 0.0.2, *)
public struct Index: Sendable, Comparable, Hashable {
public struct Index: Comparable, Hashable {
internal typealias Storage = SystemString.Index
internal var _storage: Storage
@@ -100,7 +122,7 @@ extension FilePath.ComponentView: BidirectionalCollection {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.ComponentView: RangeReplaceableCollection {
public init() {
self.init(FilePath())
@@ -150,7 +172,7 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Create a file path from a root and a collection of components.
public init<C: Collection>(
@@ -179,7 +201,7 @@ extension FilePath {
// MARK: - Internals
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.ComponentView: _PathSlice {
internal var _range: Range<SystemString.Index> {
_start ..< _path._storage.endIndex
@@ -192,7 +214,7 @@ extension FilePath.ComponentView: _PathSlice {
// MARK: - Invariants
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.ComponentView {
internal func _invariantCheck() {
#if DEBUG
@@ -217,3 +239,8 @@ extension FilePath.ComponentView {
#endif // DEBUG
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePath.ComponentView: Sendable {}
extension FilePath.ComponentView.Index: Sendable {}
#endif
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 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
@@ -9,7 +9,7 @@
// MARK: - API
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Represents a root of a file path.
///
@@ -28,8 +28,7 @@ extension FilePath {
/// * `\\server\share\`
/// * `\\?\UNC\server\share\`
/// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\`
@available(System 0.0.2, *)
public struct Root: Sendable {
public struct Root {
internal var _path: FilePath
internal var _rootEnd: SystemString.Index
@@ -55,8 +54,7 @@ extension FilePath {
/// file.kind == .regular // true
/// file.extension // "txt"
/// path.append(file) // path is "/tmp/foo.txt"
@available(System 0.0.2, *)
public struct Component: Sendable {
public struct Component {
internal var _path: FilePath
internal var _range: Range<SystemString.Index>
@@ -74,14 +72,13 @@ extension FilePath {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
/// Whether a component is a regular file or directory name, or a special
/// directory `.` or `..`
@frozen
@available(System 0.0.2, *)
public enum Kind: Sendable {
public enum Kind {
/// The special directory `.`, representing the current directory.
case currentDirectory
@@ -100,7 +97,7 @@ extension FilePath.Component {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
// TODO: Windows analysis APIs
}
@@ -128,8 +125,6 @@ extension SystemString {
}
}
#if !$Embedded
// Unifying protocol for common functionality between roots, components,
// and views onto SystemString and FilePath.
internal protocol _StrSlice: _PlatformStringable, Hashable, Codable {
@@ -140,20 +135,6 @@ internal protocol _StrSlice: _PlatformStringable, Hashable, Codable {
func _invariantCheck()
}
#else
internal protocol _StrSlice: _PlatformStringable, Hashable {
var _storage: SystemString { get }
var _range: Range<SystemString.Index> { get }
init?(_ str: SystemString)
func _invariantCheck()
}
#endif // !$Embedded
extension _StrSlice {
internal var _slice: Slice<SystemString> {
Slice(base: _storage, bounds: _range)
@@ -162,7 +143,7 @@ extension _StrSlice {
internal func _withSystemChars<T>(
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
) rethrows -> T {
try _storage.withNullTerminatedSystemChars {
try _storage.withSystemChars {
try f(UnsafeBufferPointer(rebasing: $0[_range]))
}
}
@@ -202,17 +183,17 @@ extension _PathSlice {
internal var _storage: SystemString { _path._storage }
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component: _PathSlice {
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root: _PathSlice {
internal var _range: Range<SystemString.Index> {
(..<_rootEnd).relative(to: _path._storage)
}
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath: _PlatformStringable {
func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
try _storage.withPlatformString(body)
@@ -224,7 +205,7 @@ extension FilePath: _PlatformStringable {
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
// The index of the `.` denoting an extension
internal func _extensionIndex() -> SystemString.Index? {
@@ -253,7 +234,7 @@ internal func _makeExtension(_ ext: String) -> SystemString {
return result
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
internal init?(_ str: SystemString) {
// FIXME: explicit null root? Or something else?
@@ -266,7 +247,7 @@ extension FilePath.Component {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
internal init?(_ str: SystemString) {
// FIXME: explicit null root? Or something else?
@@ -281,7 +262,7 @@ extension FilePath.Root {
// MARK: - Invariants
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
// TODO: ensure this all gets easily optimized away in release...
internal func _invariantCheck() {
@@ -294,7 +275,7 @@ extension FilePath.Component {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
internal func _invariantCheck() {
#if DEBUG
@@ -304,3 +285,9 @@ extension FilePath.Root {
#endif
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePath.Root: Sendable {}
extension FilePath.Component: Sendable {}
extension FilePath.Component.Kind: Sendable {}
#endif
+14 -27
View File
@@ -89,11 +89,6 @@ extension SystemString {
// `_prenormalizeWindowsRoots` and resume.
readIdx = _prenormalizeWindowsRoots()
writeIdx = readIdx
// Skip redundant separators
while readIdx < endIndex && isSeparator(self[readIdx]) {
self.formIndex(after: &readIdx)
}
} else {
assert(genericSeparator == platformSeparator)
}
@@ -116,7 +111,7 @@ extension SystemString {
}
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
internal mutating func _removeTrailingSeparator() {
_storage._removeTrailingSeparator()
@@ -197,7 +192,7 @@ extension SystemString {
}
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
internal var _relativeStart: SystemString.Index {
_storage._relativePathStart
@@ -209,7 +204,7 @@ extension FilePath {
// Parse separators
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
internal typealias _Index = SystemString.Index
@@ -273,7 +268,7 @@ extension FilePath {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.ComponentView {
// TODO: Store this...
internal var _relativeStart: SystemString.Index {
@@ -298,7 +293,7 @@ extension SystemString {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
// Asserting self is a root, returns whether this is an
// absolute root.
@@ -323,7 +318,7 @@ extension FilePath.Root {
}
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
internal var _portableDescription: String {
guard _windowsPaths else { return description }
@@ -335,17 +330,14 @@ extension FilePath {
// Whether we are providing Windows paths
@inline(__always)
internal var _windowsPaths: Bool {
if let forceWindowsPaths = forceWindowsPaths {
return forceWindowsPaths
}
#if os(Windows)
return true
#else
return false
return forceWindowsPaths
#endif
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
// Whether we should add a separator when doing an append
internal var _needsSeparatorForAppend: Bool {
@@ -373,20 +365,15 @@ extension FilePath {
}
// MARK: - Invariants
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
internal func _invariantsSatisfied() -> Bool {
var normal = self
normal._normalizeSeparators()
guard self == normal else { return false }
guard !self._storage._hasTrailingSeparator() else { return false }
guard _hasRoot == (self.root != nil) else { return false }
return true
}
internal func _invariantCheck() {
#if DEBUG
precondition(_invariantsSatisfied())
var normal = self
normal._normalizeSeparators()
precondition(self == normal)
precondition(!self._storage._hasTrailingSeparator())
precondition(_hasRoot == (self.root != nil))
#endif // DEBUG
}
}
+22 -22
View File
@@ -9,7 +9,7 @@
// MARK: - Platform string
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Creates a file path by copying bytes from a null-terminated platform
/// string.
@@ -64,7 +64,7 @@ extension FilePath {
}
#if !os(Windows)
// Note: This function should have been opaque, but it shipped as
// Note: This function should have been opaque, but it shipped as
// `@_alwaysEmitIntoClient` in macOS 12/iOS 15, and now it is stuck
// this way forever. (Or until the language provides a way for us
// to declare separate availability for a function's exported symbol
@@ -84,7 +84,7 @@ extension FilePath {
/// Don't try to store the pointer for later use.
@_alwaysEmitIntoClient
public func withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result {
return try withCString(body)
}
@@ -102,14 +102,14 @@ extension FilePath {
/// only during the execution of this method.
/// Don't try to store the pointer for later use.
public func withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result {
return try _withPlatformString(body)
}
#endif
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
/// Creates a file path component by copying bytes from a null-terminated
/// platform string.
@@ -198,7 +198,7 @@ extension FilePath.Component {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
/// Creates a file path root by copying bytes from a null-terminated platform
/// string.
@@ -287,7 +287,7 @@ extension FilePath.Root {
// MARK: - String literals
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath: ExpressibleByStringLiteral {
/// Creates a file path from a string literal.
///
@@ -306,7 +306,7 @@ extension FilePath: ExpressibleByStringLiteral {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component: ExpressibleByStringLiteral {
/// Create a file path component from a string literal.
///
@@ -331,7 +331,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root: ExpressibleByStringLiteral {
/// Create a file path root from a string literal.
///
@@ -356,7 +356,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
// MARK: - Printing and dumping
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the file path.
///
@@ -372,7 +372,7 @@ extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
public var debugDescription: String { description.debugDescription }
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the path component.
@@ -389,7 +389,7 @@ extension FilePath.Component: CustomStringConvertible, CustomDebugStringConverti
public var debugDescription: String { description.debugDescription }
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the path root.
@@ -409,7 +409,7 @@ extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Convenience helpers
// Convenience helpers
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Creates a string by interpreting the path’s content as UTF-8 on Unix
/// and UTF-16 on Windows.
@@ -420,7 +420,7 @@ extension FilePath {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
/// Creates a string by interpreting the component’s content as UTF-8 on Unix
/// and UTF-16 on Windows.
@@ -431,7 +431,7 @@ extension FilePath.Component {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
/// On Unix, this returns `"/"`.
///
@@ -445,7 +445,7 @@ extension FilePath.Root {
// MARK: - Decoding and validating
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension String {
/// Creates a string by interpreting the file path's content as UTF-8 on Unix
/// and UTF-16 on Windows.
@@ -475,7 +475,7 @@ extension String {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension String {
/// Creates a string by interpreting the path component's content as UTF-8 on
/// Unix and UTF-16 on Windows.
@@ -505,7 +505,7 @@ extension String {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension String {
/// On Unix, creates the string `"/"`
///
@@ -558,7 +558,7 @@ extension String {
// MARK: - Deprecations
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension String {
@available(*, deprecated, renamed: "init(decoding:)")
public init(_ path: FilePath) { self.init(decoding: path) }
@@ -568,7 +568,7 @@ extension String {
}
#if !os(Windows)
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath {
/// For backwards compatibility only. This initializer is equivalent to
/// the preferred `FilePath(platformString:)`.
@@ -595,8 +595,8 @@ extension FilePath {
/// For backwards compatibility only. This function is equivalent to
/// the preferred `withPlatformString`.
public func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws(SystemError) -> Result
) throws(SystemError) -> Result {
_ body: (UnsafePointer<CChar>) throws -> Result
) rethrows -> Result {
return try _withPlatformString(body)
}
}
+8 -8
View File
@@ -9,7 +9,7 @@
// MARK: - Query API
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Returns true if this path uniquely identifies the location of
/// a file without reference to an additional starting location.
@@ -99,7 +99,7 @@ extension FilePath {
}
// MARK: - Decompose a path
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Returns the root of a path if there is one, otherwise `nil`.
///
@@ -182,7 +182,7 @@ extension FilePath {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Returns the final component of the path.
/// Returns `nil` if the path is empty or only contains a root.
@@ -252,7 +252,7 @@ extension FilePath {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
/// The extension of this file or directory component.
///
@@ -283,7 +283,7 @@ extension FilePath.Component {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// The extension of the file or directory last component.
@@ -349,7 +349,7 @@ extension FilePath {
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Whether the path is in lexical-normal form, that is `.` and `..`
/// components have been collapsed lexically (i.e. without following
@@ -430,7 +430,7 @@ extension FilePath {
}
// Modification and concatenation API
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
// TODO(Windows docs): example with roots
/// If `prefix` is a prefix of `self`, removes it and returns `true`.
@@ -583,7 +583,7 @@ extension FilePath {
}
// MARK - Renamed
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
@available(*, unavailable, renamed: "removingLastComponent()")
public var dirname: FilePath { removingLastComponent() }
@@ -1,97 +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
*/
// MARK: - API
/// Create a temporary path for the duration of the closure.
///
/// - Parameters:
/// - basename: The base name for the temporary path.
/// - body: The closure to execute.
///
/// Creates a temporary directory with a name based on the given `basename`,
/// executes `body`, passing in the path of the created directory, then
/// deletes the directory and all of its contents before returning.
internal func withTemporaryFilePath<R>(
basename: FilePath.Component,
_ body: (FilePath) throws(SystemError) -> R
) throws(SystemError) -> R {
let temporaryDir = try createUniqueTemporaryDirectory(basename: basename)
defer {
try? _recursiveRemove(at: temporaryDir)
}
return try body(temporaryDir)
}
// MARK: - Internals
fileprivate let base64 = Array<UInt8>(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8
)
/// Create a directory that is only accessible to the current user.
///
/// - Parameters:
/// - path: The path of the directory to create.
/// - Returns: `true` if a new directory was created.
///
/// This function will throw if there is an error, except if the error
/// is that the directory exists, in which case it returns `false`.
fileprivate func makeLockedDownDirectory(at path: FilePath) throws(SystemError) -> Bool {
return try path.withPlatformString { (platformString) throws(SystemError) in
if system_mkdir(platformString, 0o700) == 0 {
return true
}
let err = system_errno
if err == Errno.fileExists.rawValue {
return false
} else {
throw Errno(rawValue: err)
}
}
}
/// Generate a random string of base64 filename safe characters.
///
/// - Parameters:
/// - length: The number of characters in the returned string.
/// - Returns: A random string of length `length`.
fileprivate func createRandomString(length: Int) -> String {
return String(
decoding: (0..<length).map{
_ in base64[Int.random(in: 0..<64)]
},
as: UTF8.self
)
}
/// Given a base name, create a uniquely named temporary directory.
///
/// - Parameters:
/// - basename: The base name for the new directory.
/// - Returns: The path to the new directory.
///
/// Creates a directory in the system temporary directory whose name
/// starts with `basename`, followed by a `.` and then a random
/// string of characters.
fileprivate func createUniqueTemporaryDirectory(
basename: FilePath.Component
) throws(SystemError) -> FilePath {
var tempDir = try _getTemporaryDirectory()
tempDir.append(basename)
while true {
tempDir.extension = createRandomString(length: 16)
if try makeLockedDownDirectory(at: tempDir) {
return tempDir
}
}
}
@@ -1,153 +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)
/// Get the path to the system temporary directory.
internal func _getTemporaryDirectory() throws(SystemError) -> FilePath {
guard let tmp = system_getenv("TMPDIR") else {
return "/tmp"
}
return FilePath(SystemString(platformString: tmp))
}
/// Delete the entire contents of a directory, including its subdirectories.
///
/// - Parameters:
/// - path: The directory to be deleted.
///
/// Removes a directory completely, including all of its contents.
internal func _recursiveRemove(
at path: FilePath
) throws(SystemError) {
let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory)
defer {
try? dirfd.close()
}
let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0)
try withUnsafeBytes(of: dot) { (bytes) throws(SystemError) in
try recursiveRemove(
in: dirfd.rawValue,
name: bytes.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress!
)
}
try path.withPlatformString { (platformString) throws(SystemError) in
if system_rmdir(platformString) != 0 {
throw Errno.current
}
}
}
/// Open a directory by reference to its parent and name.
///
/// - Parameters:
/// - dirfd: An open file descriptor for the parent directory.
/// - name: The name of the directory to open.
/// - Returns: A pointer to a `DIR` structure.
///
/// This is like `opendir()`, but instead of taking a path, it uses a
/// file descriptor pointing at the parent, thus avoiding path length
/// limits.
fileprivate func impl_opendirat(
_ dirfd: CInt,
_ name: UnsafePointer<CInterop.PlatformChar>
) -> system_DIRPtr? {
let fd = system_openat(dirfd, name,
FileDescriptor.AccessMode.readOnly.rawValue
| FileDescriptor.OpenOptions.directory.rawValue)
if fd < 0 {
return nil
}
return system_fdopendir(fd)
}
/// Invoke a closure for each file within a particular directory.
///
/// - Parameters:
/// - dirfd: The parent of the directory to be enumerated.
/// - subdir: The subdirectory to be enumerated.
/// - body: The closure that will be invoked.
///
/// We skip the `.` and `..` pseudo-entries.
fileprivate func forEachFile(
in dirfd: CInt,
subdir: UnsafePointer<CInterop.PlatformChar>,
_ body: (system_dirent) throws(SystemError) -> ()
) throws(SystemError) {
guard let dir = impl_opendirat(dirfd, subdir) else {
throw Errno.current
}
defer {
_ = system_closedir(dir)
}
while let dirent = system_readdir(dir) {
// Skip . and ..
if dirent.pointee.d_name.0 == 46
&& (dirent.pointee.d_name.1 == 0
|| (dirent.pointee.d_name.1 == 46
&& dirent.pointee.d_name.2 == 0)) {
continue
}
try body(dirent.pointee)
}
}
/// Delete the entire contents of a directory, including its subdirectories.
///
/// - Parameters:
/// - dirfd: The parent of the directory to be removed.
/// - name: The name of the directory to be removed.
///
/// Removes a directory completely, including all of its contents.
fileprivate func recursiveRemove(
in dirfd: CInt,
name: UnsafePointer<CInterop.PlatformChar>
) throws(SystemError) {
// First, deal with subdirectories
try forEachFile(in: dirfd, subdir: name) { dirent in
if dirent.d_type == SYSTEM_DT_DIR {
try withUnsafeBytes(of: dirent.d_name) {
try recursiveRemove(
in: dirfd,
name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self)
.baseAddress!
)
}
}
}
// Now delete the contents of this directory
try forEachFile(in: dirfd, subdir: name) { dirent in
let flag: CInt
if dirent.d_type == SYSTEM_DT_DIR {
flag = SYSTEM_AT_REMOVE_DIR
} else {
flag = 0
}
let result = withUnsafeBytes(of: dirent.d_name) {
system_unlinkat(dirfd,
$0.assumingMemoryBound(to: CInterop.PlatformChar.self)
.baseAddress!,
flag)
}
if result != 0 {
throw Errno.current
}
}
}
#endif // !os(Windows)
@@ -1,114 +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
/// Get the path to the system temporary directory.
internal func _getTemporaryDirectory() throws -> FilePath {
return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self,
capacity: Int(MAX_PATH) + 1) {
buffer in
guard GetTempPathW(DWORD(buffer.count), buffer.baseAddress) != 0 else {
throw Errno(windowsError: GetLastError())
}
return FilePath(SystemString(platformString: buffer.baseAddress!))
}
}
/// Invoke a closure for each file within a particular directory.
///
/// - Parameters:
/// - path: The path at which we should enumerate items.
/// - body: The closure that will be invoked.
///
/// We skip the `.` and `..` pseudo-entries.
fileprivate func forEachFile(
at path: FilePath,
_ body: (WIN32_FIND_DATAW) throws -> ()
) rethrows {
let searchPath = path.appending("\\*")
try searchPath.withPlatformString { szPath in
var findData = WIN32_FIND_DATAW()
let hFind = try szPath.withCanonicalPathRepresentation({ szPath in FindFirstFileW(szPath, &findData) })
if hFind == INVALID_HANDLE_VALUE {
throw Errno(windowsError: GetLastError())
}
defer {
FindClose(hFind)
}
repeat {
// Skip . and ..
if findData.cFileName.0 == 46
&& (findData.cFileName.1 == 0
|| (findData.cFileName.1 == 46
&& findData.cFileName.2 == 0)) {
continue
}
try body(findData)
} while FindNextFileW(hFind, &findData)
}
}
/// Delete the entire contents of a directory, including its subdirectories.
///
/// - Parameters:
/// - path: The directory to be deleted.
///
/// Removes a directory completely, including all of its contents.
internal func _recursiveRemove(
at path: FilePath
) throws {
// First, deal with subdirectories
try forEachFile(at: path) { findData in
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 {
let name = withUnsafeBytes(of: findData.cFileName) {
return SystemString(platformString: $0.assumingMemoryBound(
to: CInterop.PlatformChar.self).baseAddress!)
}
let component = FilePath.Component(name)!
let subpath = path.appending(component)
try _recursiveRemove(at: subpath)
}
}
// Now delete everything else
try forEachFile(at: path) { findData in
let name = withUnsafeBytes(of: findData.cFileName) {
return SystemString(platformString: $0.assumingMemoryBound(
to: CInterop.PlatformChar.self).baseAddress!)
}
let component = FilePath.Component(name)!
let subpath = path.appending(component)
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 {
try subpath.withPlatformString { subpath in
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
throw Errno(windowsError: GetLastError())
}
}
}
}
// Finally, delete the parent
try path.withPlatformString {
if try !$0.withCanonicalPathRepresentation({ RemoveDirectoryW($0) }) {
throw Errno(windowsError: GetLastError())
}
}
}
#endif // os(Windows)
@@ -461,78 +461,3 @@ extension SystemString {
return lexer.current
}
}
#if os(Windows)
import WinSDK
// FIXME: Rather than canonicalizing the path at every call site to a Win32 API,
// we should consider always storing absolute paths with the \\?\ prefix applied,
// for better performance.
extension UnsafePointer where Pointee == CInterop.PlatformChar {
/// Invokes `body` with a resolved and potentially `\\?\`-prefixed version of the pointee,
/// to ensure long paths greater than MAX_PATH (260) characters are handled correctly.
///
/// - seealso: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
internal func withCanonicalPathRepresentation<Result>(_ body: (Self) throws -> Result) throws -> Result {
// 1. Normalize the path first.
// Contrary to the documentation, this works on long paths independently
// of the registry or process setting to enable long paths (but it will also
// not add the \\?\ prefix required by other functions under these conditions).
let dwLength: DWORD = GetFullPathNameW(self, 0, nil, nil)
return try withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) { pwszFullPath in
guard (1..<dwLength).contains(GetFullPathNameW(self, DWORD(pwszFullPath.count), pwszFullPath.baseAddress, nil)) else {
throw Errno(rawValue: _mapWindowsErrorToErrno(GetLastError()))
}
// 1.5 Leave \\.\ prefixed paths alone since device paths are already an exact representation and PathCchCanonicalizeEx will mangle these.
if let base = pwszFullPath.baseAddress,
base[0] == UInt8(ascii: "\\"),
base[1] == UInt8(ascii: "\\"),
base[2] == UInt8(ascii: "."),
base[3] == UInt8(ascii: "\\") {
return try body(base)
}
// 2. Canonicalize the path.
// This will add the \\?\ prefix if needed based on the path's length.
var pwszCanonicalPath: LPWSTR?
let flags: ULONG = numericCast(PATHCCH_ALLOW_LONG_PATHS.rawValue)
let result = PathAllocCanonicalize(pwszFullPath.baseAddress, flags, &pwszCanonicalPath)
if let pwszCanonicalPath {
defer { LocalFree(pwszCanonicalPath) }
if result == S_OK {
// 3. Perform the operation on the normalized path.
return try body(pwszCanonicalPath)
}
}
throw Errno(rawValue: _mapWindowsErrorToErrno(WIN32_FROM_HRESULT(result)))
}
}
}
@inline(__always)
fileprivate func HRESULT_CODE(_ hr: HRESULT) -> DWORD {
DWORD(hr) & 0xffff
}
@inline(__always)
fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD {
DWORD(hr << 16) & 0x1fff
}
@inline(__always)
fileprivate func SUCCEEDED(_ hr: HRESULT) -> Bool {
hr >= 0
}
// This is a non-standard extension to the Windows SDK that allows us to convert
// an HRESULT to a Win32 error code.
@inline(__always)
fileprivate func WIN32_FROM_HRESULT(_ hr: HRESULT) -> DWORD {
if SUCCEEDED(hr) { return DWORD(ERROR_SUCCESS) }
if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
return HRESULT_CODE(hr)
}
return DWORD(hr)
}
#endif
-71
View File
@@ -1,71 +0,0 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
public extension IORing {
struct Completion: ~Copyable {
@inlinable init(rawValue inRawValue: io_uring_cqe) {
rawValue = inRawValue
}
@usableFromInline let rawValue: io_uring_cqe
}
}
public extension IORing.Completion {
struct Flags: OptionSet, Hashable, Codable {
public let rawValue: UInt32
@inlinable public init(rawValue: UInt32) {
self.rawValue = rawValue
}
///`IORING_CQE_F_BUFFER` Indicates the buffer ID is stored in the upper 16 bits
@inlinable public static var allocatedBuffer: Flags { Flags(rawValue: 1 << 0) }
///`IORING_CQE_F_MORE` Indicates more completions will be generated from the request that generated this
@inlinable public static var moreCompletions: Flags { Flags(rawValue: 1 << 1) }
//`IORING_CQE_F_SOCK_NONEMPTY`, but currently unused
//@inlinable public static var socketNotEmpty: Flags { Flags(rawValue: 1 << 2) }
//`IORING_CQE_F_NOTIF`, but currently unused
//@inlinable public static var isNotificationEvent: Flags { Flags(rawValue: 1 << 3) }
//IORING_CQE_F_BUF_MORE will eventually be (1U << 4) if we add IOU_PBUF_RING_INC support
}
}
public extension IORing.Completion {
@inlinable var context: UInt64 {
get {
rawValue.user_data
}
}
@inlinable var userPointer: UnsafeRawPointer? {
get {
UnsafeRawPointer(bitPattern: UInt(rawValue.user_data))
}
}
@inlinable var result: Int32 {
get {
rawValue.res
}
}
@inlinable var flags: IORing.Completion.Flags {
get {
Flags(rawValue: rawValue.flags & 0x0000FFFF)
}
}
@inlinable var bufferIndex: UInt16? {
get {
if self.flags.contains(.allocatedBuffer) {
return UInt16(rawValue.flags >> 16)
} else {
return nil
}
}
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
-497
View File
@@ -1,497 +0,0 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
@usableFromInline
internal enum IORequestCore {
case nop // nothing here
case openat(
atDirectory: FileDescriptor,
path: FilePath,
FileDescriptor.AccessMode,
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
context: UInt64 = 0
)
case openatSlot(
atDirectory: FileDescriptor,
path: FilePath,
FileDescriptor.AccessMode,
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
intoSlot: IORing.RegisteredFile,
context: UInt64 = 0
)
case read(
file: FileDescriptor,
buffer: IORing.RegisteredBuffer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case readUnregistered(
file: FileDescriptor,
buffer: UnsafeMutableRawBufferPointer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case readSlot(
file: IORing.RegisteredFile,
buffer: IORing.RegisteredBuffer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case readUnregisteredSlot(
file: IORing.RegisteredFile,
buffer: UnsafeMutableRawBufferPointer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case write(
file: FileDescriptor,
buffer: IORing.RegisteredBuffer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case writeUnregistered(
file: FileDescriptor,
buffer: UnsafeMutableRawBufferPointer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case writeSlot(
file: IORing.RegisteredFile,
buffer: IORing.RegisteredBuffer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case writeUnregisteredSlot(
file: IORing.RegisteredFile,
buffer: UnsafeMutableRawBufferPointer,
offset: UInt64 = 0,
context: UInt64 = 0
)
case close(
FileDescriptor,
context: UInt64 = 0
)
case closeSlot(
IORing.RegisteredFile,
context: UInt64 = 0
)
case unlinkAt(
atDirectory: FileDescriptor,
path: FilePath,
context: UInt64 = 0
)
case cancel(
flags:UInt32
)
case cancelContext(
flags: UInt32,
targetContext: UInt64
)
case cancelFD(
flags: UInt32,
targetFD: FileDescriptor
)
case cancelFDSlot(
flags: UInt32,
target: IORing.RegisteredFile
)
}
@inline(__always) @inlinable
internal func makeRawRequest_readWrite_registered(
file: FileDescriptor,
buffer: IORing.RegisteredBuffer,
offset: UInt64,
context: UInt64 = 0,
request: consuming RawIORequest
) -> RawIORequest {
request.fileDescriptor = file
request.buffer = buffer.unsafeBuffer
request.rawValue.buf_index = UInt16(exactly: buffer.index)!
request.offset = offset
request.rawValue.user_data = context
return request
}
@inline(__always) @inlinable
internal func makeRawRequest_readWrite_registered_slot(
file: IORing.RegisteredFile,
buffer: IORing.RegisteredBuffer,
offset: UInt64,
context: UInt64 = 0,
request: consuming RawIORequest
) -> RawIORequest {
request.rawValue.fd = Int32(exactly: file.index)!
request.flags = .fixedFile
request.buffer = buffer.unsafeBuffer
request.rawValue.buf_index = UInt16(exactly: buffer.index)!
request.offset = offset
request.rawValue.user_data = context
return request
}
@inline(__always) @inlinable
internal func makeRawRequest_readWrite_unregistered(
file: FileDescriptor,
buffer: UnsafeMutableRawBufferPointer,
offset: UInt64,
context: UInt64 = 0,
request: consuming RawIORequest
) -> RawIORequest {
request.fileDescriptor = file
request.buffer = buffer
request.offset = offset
request.rawValue.user_data = context
return request
}
@inline(__always) @inlinable
internal func makeRawRequest_readWrite_unregistered_slot(
file: IORing.RegisteredFile,
buffer: UnsafeMutableRawBufferPointer,
offset: UInt64,
context: UInt64 = 0,
request: consuming RawIORequest
) -> RawIORequest {
request.rawValue.fd = Int32(exactly: file.index)!
request.flags = .fixedFile
request.buffer = buffer
request.offset = offset
request.rawValue.user_data = context
return request
}
extension IORing {
public struct Request {
@usableFromInline var core: IORequestCore
@inlinable internal init(core inCore: IORequestCore) {
core = inCore
}
@inlinable internal consuming func extractCore() -> IORequestCore {
return core
}
}
}
extension IORing.Request {
@inlinable public static func nop(context: UInt64 = 0) -> IORing.Request {
.init(core: .nop)
}
@inlinable public static func read(
_ file: IORing.RegisteredFile,
into buffer: IORing.RegisteredBuffer,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func read(
_ file: FileDescriptor,
into buffer: IORing.RegisteredBuffer,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .read(file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func read(
_ file: IORing.RegisteredFile,
into buffer: UnsafeMutableRawBufferPointer,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func read(
_ file: FileDescriptor,
into buffer: UnsafeMutableRawBufferPointer,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func write(
_ buffer: IORing.RegisteredBuffer,
into file: IORing.RegisteredFile,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func write(
_ buffer: IORing.RegisteredBuffer,
into file: FileDescriptor,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .write(file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func write(
_ buffer: UnsafeMutableRawBufferPointer,
into file: IORing.RegisteredFile,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .writeUnregisteredSlot(
file: file, buffer: buffer, offset: offset, context: context))
}
@inlinable public static func write(
_ buffer: UnsafeMutableRawBufferPointer,
into file: FileDescriptor,
at offset: UInt64 = 0,
context: UInt64 = 0
) -> IORing.Request {
.init(
core: .writeUnregistered(file: file, buffer: buffer, offset: offset, context: context)
)
}
@inlinable public static func close(
_ file: FileDescriptor,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .close(file, context: context))
}
@inlinable public static func close(
_ file: IORing.RegisteredFile,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .closeSlot(file, context: context))
}
@inlinable public static func open(
_ path: FilePath,
in directory: FileDescriptor,
into slot: IORing.RegisteredFile,
mode: FileDescriptor.AccessMode,
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
context: UInt64 = 0
) -> IORing.Request {
.init(
core: .openatSlot(
atDirectory: directory, path: path, mode, options: options,
permissions: permissions, intoSlot: slot, context: context))
}
@inlinable public static func open(
_ path: FilePath,
in directory: FileDescriptor,
mode: FileDescriptor.AccessMode,
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil,
context: UInt64 = 0
) -> IORing.Request {
.init(
core: .openat(
atDirectory: directory, path: path, mode, options: options,
permissions: permissions, context: context
))
}
@inlinable public static func unlink(
_ path: FilePath,
in directory: FileDescriptor,
context: UInt64 = 0
) -> IORing.Request {
.init(core: .unlinkAt(atDirectory: directory, path: path, context: context))
}
// Cancel
/*
* ASYNC_CANCEL flags.
*
* IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key
* IORING_ASYNC_CANCEL_FD Key off 'fd' for cancellation rather than the
* request 'user_data'
* IORING_ASYNC_CANCEL_ANY Match any request
* IORING_ASYNC_CANCEL_FD_FIXED 'fd' passed in is a fixed descriptor
* IORING_ASYNC_CANCEL_USERDATA Match on user_data, default for no other key
* IORING_ASYNC_CANCEL_OP Match request based on opcode
*/
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 }
@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 }
public enum CancellationMatch {
case all
case first
}
@inlinable public static func cancel(
_ matchAll: CancellationMatch,
matchingContext: UInt64
) -> IORing.Request {
switch matchAll {
case .all:
.init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext))
case .first:
.init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext))
}
}
@inlinable public static func cancel(
_ matchAll: CancellationMatch,
matching: FileDescriptor
) -> IORing.Request {
switch matchAll {
case .all:
.init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching))
case .first:
.init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching))
}
}
@inlinable public static func cancel(
_ matchAll: CancellationMatch,
matching: IORing.RegisteredFile
) -> IORing.Request {
switch matchAll {
case .all:
.init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching))
case .first:
.init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching))
}
}
@inlinable public static func cancel(
_ matchAll: CancellationMatch,
) -> IORing.Request {
switch matchAll {
case .all:
.init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ALL))
case .first:
.init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ANY))
}
}
@inline(__always) @inlinable
internal consuming func makeRawRequest() -> RawIORequest {
var request = RawIORequest()
switch extractCore() {
case .nop:
request.operation = .nop
case .openatSlot(
let atDirectory, let path, let mode, let options, let permissions, let fileSlot,
let context):
// TODO: use rawValue less
request.operation = .openAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0
request.rawValue.file_index = UInt32(fileSlot.index + 1)
request.path = path
request.rawValue.user_data = context
case .openat(
let atDirectory, let path, let mode, let options, let permissions, let context):
request.operation = .openAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0
request.path = path
request.rawValue.user_data = context
case .write(let file, let buffer, let offset, let context):
request.operation = .writeFixed
return makeRawRequest_readWrite_registered(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .writeSlot(let file, let buffer, let offset, let context):
request.operation = .writeFixed
return makeRawRequest_readWrite_registered_slot(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .writeUnregistered(let file, let buffer, let offset, let context):
request.operation = .write
return makeRawRequest_readWrite_unregistered(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .writeUnregisteredSlot(let file, let buffer, let offset, let context):
request.operation = .write
return makeRawRequest_readWrite_unregistered_slot(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .read(let file, let buffer, let offset, let context):
request.operation = .readFixed
return makeRawRequest_readWrite_registered(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .readSlot(let file, let buffer, let offset, let context):
request.operation = .readFixed
return makeRawRequest_readWrite_registered_slot(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .readUnregistered(let file, let buffer, let offset, let context):
request.operation = .read
return makeRawRequest_readWrite_unregistered(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .readUnregisteredSlot(let file, let buffer, let offset, let context):
request.operation = .read
return makeRawRequest_readWrite_unregistered_slot(
file: file, buffer: buffer, offset: offset, context: context, request: request)
case .close(let file, let context):
request.operation = .close
request.fileDescriptor = file
request.rawValue.user_data = context
case .closeSlot(let file, let context):
request.operation = .close
request.rawValue.file_index = UInt32(file.index + 1)
request.rawValue.user_data = context
case .unlinkAt(let atDirectory, let path, let context):
request.operation = .unlinkAt
request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64(
UInt(
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
})
)
request.path = path
request.rawValue.user_data = context
case .cancelContext(let flags, let targetContext):
request.operation = .asyncCancel
request.cancel_flags = flags
request.addr = targetContext
case .cancelFD(let flags, let targetFD):
request.operation = .asyncCancel
request.cancel_flags = flags
request.fileDescriptor = targetFD
case .cancelFDSlot(let flags, let target):
request.operation = .asyncCancel
request.cancel_flags = flags
request.rawValue.fd = Int32(target.index)
case .cancel(let flags):
request.operation = .asyncCancel
request.cancel_flags = flags
}
return request
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
-904
View File
@@ -1,904 +0,0 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
// needed for mmap
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif
import Synchronization
private var ioringSupported: Bool {
__SWIFT_IORING_SUPPORTED != 0
}
//This was #defines in older headers, so we redeclare it to get a consistent import
internal enum RegistrationOps: UInt32 {
case registerBuffers = 0
case unregisterBuffers = 1
case registerFiles = 2
case unregisterFiles = 3
case registerEventFD = 4
case unregisterEventFD = 5
case registerFilesUpdate = 6
case registerEventFDAsync = 7
case registerProbe = 8
case registerPersonality = 9
case unregisterPersonality = 10
}
extension UnsafeMutableRawPointer {
func advanced(by offset: UInt32) -> UnsafeMutableRawPointer {
return advanced(by: Int(offset))
}
}
extension UnsafeMutableRawBufferPointer {
func to_iovec() -> iovec {
iovec(iov_base: baseAddress, iov_len: count)
}
}
// all pointers in this struct reference kernel-visible memory
@usableFromInline struct SQRing: ~Copyable {
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
@usableFromInline let kernelTail: UnsafePointer<Atomic<UInt32>>
@usableFromInline var userTail: UInt32
// from liburing: the kernel should never change these
// might change in the future with resizable rings?
@usableFromInline let ringMask: UInt32
// let ringEntries: UInt32 - absorbed into array.count
// ring flags bitfield
// currently used by the kernel only in SQPOLL mode to indicate
// when the polling thread needs to be woken up
@usableFromInline let flags: UnsafePointer<Atomic<UInt32>>
// ring array
// maps indexes between the actual ring and the submissionQueueEntries list,
// allowing the latter to be used as a kind of freelist with enough work?
// currently, just 1:1 mapping (0..<n)
@usableFromInline let array: UnsafeMutableBufferPointer<UInt32>
}
@usableFromInline struct CQRing: ~Copyable {
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
@usableFromInline let kernelTail: UnsafePointer<Atomic<UInt32>>
@usableFromInline let ringMask: UInt32
@usableFromInline let cqes: UnsafeBufferPointer<io_uring_cqe>
}
@inline(__always) @inlinable
internal func _tryWriteRequest(
_ request: __owned RawIORequest, ring: inout SQRing,
submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
)
-> Bool
{
if let entry = _getSubmissionEntry(
ring: &ring, submissionQueueEntries: submissionQueueEntries) {
entry.pointee = request.rawValue
return true
}
return false
}
//TODO: omitting signal mask for now
//Tell the kernel that we've submitted requests and/or are waiting for completions
@inlinable
internal func _enter(
ring: borrowing SQRing,
ringDescriptor: Int32,
numEvents: UInt32,
minCompletions: UInt32,
flags: UInt32
) throws(Errno) -> Int32 {
// Ring always needs enter right now;
// TODO: support SQPOLL here
while true {
let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil)
// error handling:
// EAGAIN / EINTR (try again),
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
// (failure in ring lifetime management, fatal),
// EINVAL (bad constant flag?, fatal),
// EFAULT (bad address for argument from library, fatal)
if ret == -EAGAIN || ret == -EINTR {
//TODO: should we wait a bit on AGAIN?
continue
} else if ret < 0 {
throw(Errno(rawValue: -ret))
} else if _getSubmissionQueueCount(ring: ring) > 0 {
// See https://github.com/axboe/liburing/issues/309, in some cases not all pending requests are submitted
continue
} else {
return ret
}
}
}
@inlinable
internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(Errno) {
let flushedEvents = _flushQueue(ring: ring)
_ = try _enter(
ring: ring, ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0)
}
@inlinable
internal func _getSubmissionQueueCount(ring: borrowing SQRing) -> UInt32 {
return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring)
}
@inlinable
internal func _getRemainingSubmissionQueueCapacity(ring: borrowing SQRing) -> UInt32 {
return UInt32(truncatingIfNeeded: ring.array.count) - _getSubmissionQueueCount(ring: ring)
}
@inlinable
internal func _getUnconsumedCompletionCount(ring: borrowing CQRing) -> UInt32 {
return ring.kernelTail.pointee.load(ordering: .acquiring)
- ring.kernelHead.pointee.load(ordering: .acquiring)
}
@inlinable
internal func _flushQueue(ring: borrowing SQRing) -> UInt32 {
ring.kernelTail.pointee.store(
ring.userTail, ordering: .releasing
)
return _getSubmissionQueueCount(ring: ring)
}
@inlinable
internal func _getSubmissionEntry(
ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
) -> UnsafeMutablePointer<
swift_io_uring_sqe
>? {
let next = ring.userTail &+ 1 //this is expected to wrap
let kernelHead: UInt32 = ring.kernelHead.pointee.load(ordering: .acquiring)
// FEAT: 128-bit event support (not in MVP)
if next - kernelHead <= ring.array.count {
// let sqe = &sq->sqes[(sq->sqe_tail & sq->ring_mask) << shift];
let sqeIndex = Int(
ring.userTail & ring.ringMask
)
let sqe = submissionQueueEntries
.baseAddress.unsafelyUnwrapped
.advanced(by: sqeIndex)
ring.userTail = next
return sqe
}
return nil
}
private func setUpRing(
queueDepth: UInt32, flags: IORing.SetupFlags
) throws(Errno) ->
(params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer?, ringSize: Int, submissionRingPtr: UnsafeMutableRawPointer?, submissionRingSize: Int, completionRingPtr: UnsafeMutableRawPointer?, completionRingSize: Int, sqes: UnsafeMutableRawPointer) {
var params = io_uring_params()
params.flags = flags.rawValue
var err: Errno? = nil
let ringDescriptor = withUnsafeMutablePointer(to: &params) {
let result = io_uring_setup(queueDepth, $0)
if result < 0 {
err = Errno.current
}
return result
}
if let err {
throw err
}
if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0
{
close(ringDescriptor)
throw Errno.invalidArgument
}
let submitRingSize =
params.sq_off.array
+ params.sq_entries * UInt32(MemoryLayout<UInt32>.size)
let completionRingSize =
params.cq_off.cqes
+ params.cq_entries * UInt32(MemoryLayout<io_uring_cqe>.size)
let ringSize = Int(max(submitRingSize, completionRingSize))
var ringPtr: UnsafeMutableRawPointer!
var sqPtr: UnsafeMutableRawPointer!
var cqPtr: UnsafeMutableRawPointer!
if params.features & IORING_FEAT_SINGLE_MMAP != 0{
ringPtr = mmap(
/* addr: */ nil,
/* len: */ ringSize,
/* prot: */ PROT_READ | PROT_WRITE,
/* flags: */ MAP_SHARED | MAP_POPULATE,
/* fd: */ ringDescriptor,
/* offset: */ off_t(IORING_OFF_SQ_RING)
)
if ringPtr == MAP_FAILED {
let errno = Errno.current
close(ringDescriptor)
throw errno
}
} else {
sqPtr = mmap(
/* addr: */ nil,
/* len: */ Int(submitRingSize),
/* prot: */ PROT_READ | PROT_WRITE,
/* flags: */ MAP_SHARED | MAP_POPULATE,
/* fd: */ ringDescriptor,
/* offset: */ off_t(IORING_OFF_SQ_RING)
)
if sqPtr == MAP_FAILED {
let errno = Errno.current
close(ringDescriptor)
throw errno
}
cqPtr = mmap(
/* addr: */ nil,
/* len: */ Int(completionRingSize),
/* prot: */ PROT_READ | PROT_WRITE,
/* flags: */ MAP_SHARED | MAP_POPULATE,
/* fd: */ ringDescriptor,
/* offset: */ off_t(IORING_OFF_CQ_RING)
)
if cqPtr == MAP_FAILED {
let errno: Errno = Errno.current
close(ringDescriptor)
throw errno
}
}
// map the submission queue
let sqes = mmap(
/* addr: */ nil,
/* len: */ Int(params.sq_entries) * MemoryLayout<swift_io_uring_sqe>.size,
/* prot: */ PROT_READ | PROT_WRITE,
/* flags: */ MAP_SHARED | MAP_POPULATE,
/* fd: */ ringDescriptor,
/* offset: */ off_t(IORING_OFF_SQES)
)
if sqes == MAP_FAILED {
let errno = Errno.current
if ringPtr != nil {
munmap(ringPtr, ringSize)
} else {
if sqPtr != nil {
munmap(sqPtr, Int(submitRingSize))
}
if cqPtr != nil {
munmap(cqPtr, Int(completionRingSize))
}
}
close(ringDescriptor)
throw errno
}
return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr, ringSize: ringSize, submissionRingPtr: sqPtr, submissionRingSize: Int(submitRingSize), completionRingPtr: cqPtr, completionRingSize: Int(completionRingSize), sqes: sqes!)
}
///IORing provides facilities for
/// * Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file IOdescriptors that improves their efficiency
/// * Registering and unregistering eventfds, which allow asynchronous waiting for completions
/// * Enqueueing IO requests
/// * Dequeueing IO completions
public struct IORing: ~Copyable {
let ringFlags: UInt32
@usableFromInline let ringDescriptor: Int32
@usableFromInline var submissionRing: SQRing
// FEAT: set this eventually
let submissionPolling: Bool = false
@usableFromInline let completionRing: CQRing
@usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer<swift_io_uring_sqe>
// kept around for unmap / cleanup. TODO: we can save a few words of memory by figuring out how to handle cleanup for non-IORING_FEAT_SINGLE_MMAP better
let ringSize: Int
let ringPtr: UnsafeMutableRawPointer?
let submissionRingSize: Int
let submissionRingPtr: UnsafeMutableRawPointer?
let completionRingSize: Int
let completionRingPtr: UnsafeMutableRawPointer?
@usableFromInline var _registeredFiles: [UInt32]
@usableFromInline var _registeredBuffers: [iovec]
var features = Features(rawValue: 0)
/// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them.
public struct RegisteredResource<T> {
public typealias Resource = T
@usableFromInline let resource: T
public let index: Int
@inlinable internal init(
resource: T,
index: Int
) {
self.resource = resource
self.index = index
}
}
public typealias RegisteredFile = RegisteredResource<UInt32>
public typealias RegisteredBuffer = RegisteredResource<iovec>
/// SetupFlags represents configuration options to an IORing as it's being created
public struct SetupFlags: OptionSet, RawRepresentable, Hashable {
public var rawValue: UInt32
@inlinable public init(rawValue: UInt32) {
self.rawValue = rawValue
}
@inlinable public static var pollCompletions: SetupFlags { .init(rawValue: UInt32(1) << 0) } //IORING_SETUP_IOPOLL
@inlinable public static var pollSubmissions: SetupFlags { .init(rawValue: UInt32(1) << 1) } //IORING_SETUP_SQPOLL
//TODO: figure out how to expose IORING_SETUP_SQ_AFF, IORING_SETUP_CQSIZE, IORING_SETUP_ATTACH_WQ
@inlinable public static var clampMaxEntries: SetupFlags { .init(rawValue: UInt32(1) << 4) } //IORING_SETUP_CLAMP
@inlinable public static var startDisabled: SetupFlags { .init(rawValue: UInt32(1) << 6) } //IORING_SETUP_R_DISABLED
@inlinable public static var continueSubmittingOnError: SetupFlags { .init(rawValue: UInt32(1) << 7) } //IORING_SETUP_SUBMIT_ALL
//TODO: do we want to expose IORING_SETUP_COOP_TASKRUN and IORING_SETUP_TASKRUN_FLAG?
//public static var runTasksCooperatively: SetupFlags { .init(rawValue: UInt32(1) << 8) } //IORING_SETUP_COOP_TASKRUN
//TODO: can we even do different size sqe/cqe? It requires a kernel feature, but how do we convince swift to let the types be different sizes?
//internal static var use128ByteSQEs: SetupFlags { .init(rawValue: UInt32(1) << 10) } //IORING_SETUP_SQE128
//internal static var use32ByteCQEs: SetupFlags { .init(rawValue: UInt32(1) << 11) } //IORING_SETUP_CQE32
@inlinable public static var singleSubmissionThread: SetupFlags { .init(rawValue: UInt32(1) << 12) } //IORING_SETUP_SINGLE_ISSUER
@inlinable public static var deferRunningTasks: SetupFlags { .init(rawValue: UInt32(1) << 13) } //IORING_SETUP_DEFER_TASKRUN
//pretty sure we don't want to expose IORING_SETUP_NO_MMAP or IORING_SETUP_REGISTERED_FD_ONLY currently
//TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it?
}
/// Initializes an IORing with enough space for `queueDepth` prepared requests and completed operations
public init(queueDepth: UInt32, flags: SetupFlags = []) throws(Errno) {
guard ioringSupported else {
throw Errno.notSupported
}
let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, tmpSQPtr, tmpSQSize, tmpCQPtr, tmpCQSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags)
// All throws need to be before initializing ivars here to avoid
// "error: conditional initialization or destruction of noncopyable types is not supported;
// this variable must be consistently in an initialized or uninitialized state through every code path"
// Pre-compute values to avoid accessing partially initialized state
let ringBasePtr = tmpRingPtr ?? tmpSQPtr!
let completionBasePtr = tmpRingPtr ?? tmpCQPtr!
let submissionRing = SQRing(
kernelHead: UnsafePointer<Atomic<UInt32>>(
ringBasePtr.advanced(by: params.sq_off.head)
.assumingMemoryBound(to: Atomic<UInt32>.self)
),
kernelTail: UnsafePointer<Atomic<UInt32>>(
ringBasePtr.advanced(by: params.sq_off.tail)
.assumingMemoryBound(to: Atomic<UInt32>.self)
),
userTail: 0, // no requests yet
ringMask: ringBasePtr.advanced(by: params.sq_off.ring_mask)
.assumingMemoryBound(to: UInt32.self).pointee,
flags: UnsafePointer<Atomic<UInt32>>(
ringBasePtr.advanced(by: params.sq_off.flags)
.assumingMemoryBound(to: Atomic<UInt32>.self)
),
array: UnsafeMutableBufferPointer(
start: ringBasePtr.advanced(by: params.sq_off.array)
.assumingMemoryBound(to: UInt32.self),
count: Int(
ringBasePtr.advanced(by: params.sq_off.ring_entries)
.assumingMemoryBound(to: UInt32.self).pointee)
)
)
let completionRing = CQRing(
kernelHead: UnsafePointer<Atomic<UInt32>>(
completionBasePtr.advanced(by: params.cq_off.head)
.assumingMemoryBound(to: Atomic<UInt32>.self)
),
kernelTail: UnsafePointer<Atomic<UInt32>>(
completionBasePtr.advanced(by: params.cq_off.tail)
.assumingMemoryBound(to: Atomic<UInt32>.self)
),
ringMask: completionBasePtr.advanced(by: params.cq_off.ring_mask)
.assumingMemoryBound(to: UInt32.self).pointee,
cqes: UnsafeBufferPointer(
start: completionBasePtr.advanced(by: params.cq_off.cqes)
.assumingMemoryBound(to: io_uring_cqe.self),
count: Int(
completionBasePtr.advanced(by: params.cq_off.ring_entries)
.assumingMemoryBound(to: UInt32.self).pointee)
)
)
let submissionQueueEntries = UnsafeMutableBufferPointer(
start: sqes.assumingMemoryBound(to: swift_io_uring_sqe.self),
count: Int(params.sq_entries)
)
// Now initialize all stored properties
self.features = Features(rawValue: params.features)
self.ringDescriptor = tmpRingDescriptor
self.ringPtr = tmpRingPtr
self.ringSize = tmpRingSize
self.submissionRingPtr = tmpSQPtr
self.submissionRingSize = tmpSQSize
self.completionRingPtr = tmpCQPtr
self.completionRingSize = tmpCQSize
self._registeredFiles = []
self._registeredBuffers = []
self.submissionRing = submissionRing
self.completionRing = completionRing
self.submissionQueueEntries = submissionQueueEntries
self.ringFlags = params.flags
// fill submission ring array with 1:1 map to underlying SQEs
// (happens after all properties are initialized)
for i in 0 ..< self.submissionRing.array.count {
self.submissionRing.array[i] = UInt32(i)
}
}
@inlinable
internal func _blockingConsumeCompletionGuts<Err: Error>(
minimumCount: UInt32,
maximumCount: UInt32,
extraArgs: UnsafeMutablePointer<swift_io_uring_getevents_arg>? = nil,
consumer: (consuming IORing.Completion?, Errno?, Bool) throws(Err) -> Void
) throws(Err) {
var count = 0
while let completion = _tryConsumeCompletion(ring: completionRing) {
count += 1
if completion.result < 0 {
try consumer(nil, Errno(rawValue: -completion.result), false)
} else {
try consumer(completion, nil, false)
}
if count == maximumCount {
try consumer(nil, nil, true)
return
}
}
if count < minimumCount {
while count < minimumCount {
var sz = 0
if extraArgs != nil {
sz = MemoryLayout<swift_io_uring_getevents_arg>.size
}
let res = io_uring_enter2(
ringDescriptor,
0,
minimumCount,
IORING_ENTER_GETEVENTS,
extraArgs,
sz
)
// error handling:
// EAGAIN / EINTR (try again),
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
// (failure in ring lifetime management, fatal),
// EINVAL (bad constant flag?, fatal),
// EFAULT (bad address for argument from library, fatal)
// EBUSY (not enough space for events; implies events filled
// by kernel between kernelTail load and now)
if res >= 0 || res == -EBUSY {
break
} else if res == -EAGAIN || res == -EINTR {
continue
}
fatalError(
"fatal error in receiving requests: "
+ Errno(rawValue: -res).debugDescription
)
}
var count = 0
while let completion = _tryConsumeCompletion(ring: completionRing) {
count += 1
if completion.result < 0 {
try consumer(nil, Errno(rawValue: -completion.result), false)
} else {
try consumer(completion, nil, false)
}
if count == maximumCount {
break
}
}
try consumer(nil, nil, true)
}
}
@inlinable
internal func _blockingConsumeOneCompletion(
extraArgs: UnsafeMutablePointer<swift_io_uring_getevents_arg>? = nil
) throws(Errno) -> Completion {
var result: Completion? = nil
try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) {
(completion: consuming Completion?, error, done) throws(Errno) in
if let error {
throw error
}
if let completion {
result = consume completion
}
}
return result.take()!
}
/// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified)
@inlinable
public func blockingConsumeCompletion(
timeout: Duration? = nil
) throws(Errno) -> Completion {
if let timeout {
var ts = timespec(
tv_sec: Int(timeout.components.seconds),
tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000)
)
return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> Completion in
var args = swift_io_uring_getevents_arg(
sigmask: 0,
sigmask_sz: 0,
min_wait_usec: 0,
ts: UInt64(UInt(bitPattern: tsPtr))
)
return try _blockingConsumeOneCompletion(extraArgs: &args)
}
} else {
return try _blockingConsumeOneCompletion()
}
}
/// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout` (or forever if not specified). For each completed operation found, `consumer` is called to handle processing it
@inlinable
public func blockingConsumeCompletions<Err: Error>(
minimumCount: UInt32 = 1,
timeout: Duration? = nil,
consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void
) throws(Err) {
if let timeout {
var ts = timespec(
tv_sec: Int(timeout.components.seconds),
tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000)
)
try withUnsafePointer(to: &ts) { (tsPtr) throws(Err) in
var args = swift_io_uring_getevents_arg(
sigmask: 0,
sigmask_sz: 0,
min_wait_usec: 0,
ts: UInt64(UInt(bitPattern: tsPtr))
)
try _blockingConsumeCompletionGuts(
minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args,
consumer: consumer)
}
} else {
try _blockingConsumeCompletionGuts(
minimumCount: minimumCount, maximumCount: UInt32.max, consumer: consumer)
}
}
// public func peekNextCompletion() -> IOCompletion {
// }
/// Takes a completed operation from the ring and returns it, if one is ready. Otherwise, returns nil.
@inlinable
public func tryConsumeCompletion() -> Completion? {
return _tryConsumeCompletion(ring: completionRing)
}
@inlinable
func _tryConsumeCompletion(ring: borrowing CQRing) -> Completion? {
let tail = ring.kernelTail.pointee.load(ordering: .acquiring)
let head = ring.kernelHead.pointee.load(ordering: .acquiring)
if tail != head {
// 32 byte copy - oh well
let res = ring.cqes[Int(head & ring.ringMask)]
ring.kernelHead.pointee.store(head &+ 1, ordering: .releasing)
return Completion(rawValue: res)
}
return nil
}
/// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information.
public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) {
var rawfd = descriptor.rawValue
let result = withUnsafePointer(to: &rawfd) { fdptr in
let result = io_uring_register(
ringDescriptor,
RegistrationOps.registerEventFD.rawValue,
UnsafeMutableRawPointer(mutating: fdptr),
1
)
return result >= 0 ? nil : Errno(rawValue: -result)
}
if let result {
throw result
}
}
/// Removes a registered event file descriptor from the ring
public mutating func unregisterEventFD() throws(Errno) {
let result = io_uring_register(
ringDescriptor,
RegistrationOps.unregisterEventFD.rawValue,
nil,
0
)
if result < 0 {
throw Errno(rawValue: -result)
}
}
/// Registers `count` files with the ring for later use in IO operations
public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources<RegisteredFile.Resource> {
precondition(_registeredFiles.isEmpty)
precondition(count < UInt32.max)
let files = [UInt32](repeating: UInt32.max, count: count)
let regResult = files.withUnsafeBufferPointer { bPtr in
let result = io_uring_register(
self.ringDescriptor,
RegistrationOps.registerFiles.rawValue,
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
UInt32(truncatingIfNeeded: count)
)
return result >= 0 ? nil : Errno(rawValue: -result)
}
if let regResult {
throw regResult
}
_registeredFiles = files
return registeredFileSlots
}
/// Removes registered files from the ring
public func unregisterFiles() throws {
let result = io_uring_register(
ringDescriptor,
RegistrationOps.unregisterFiles.rawValue,
nil,
0
)
if result < 0 {
throw Errno(rawValue: -result)
}
}
/// Allows access to registered files by index
@inlinable
public var registeredFileSlots: RegisteredResources<RegisteredFile.Resource> {
RegisteredResources(resources: _registeredFiles)
}
/// Registers buffers with the ring for later use in IO operations
public mutating func registerBuffers(_ buffers: some Collection<UnsafeMutableRawBufferPointer>) throws(Errno)
-> RegisteredResources<RegisteredBuffer.Resource>
{
precondition(buffers.count < UInt32.max)
precondition(_registeredBuffers.isEmpty)
let iovecs = buffers.map { $0.to_iovec() }
let regResult = iovecs.withUnsafeBufferPointer { bPtr in
let result = io_uring_register(
self.ringDescriptor,
RegistrationOps.registerBuffers.rawValue,
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
UInt32(truncatingIfNeeded: buffers.count)
)
return result >= 0 ? nil : Errno(rawValue: -result)
}
if let regResult {
throw regResult
}
_registeredBuffers = iovecs
return registeredBuffers
}
/// Registers buffers with the ring for later use in IO operations
@inlinable
public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno)
-> RegisteredResources<RegisteredBuffer.Resource>
{
try registerBuffers(buffers)
}
/// A view of the registered files or buffers in a ring
public struct RegisteredResources<T>: RandomAccessCollection {
@usableFromInline let resources: [T]
@inlinable public var startIndex: Int { 0 }
@inlinable public var endIndex: Int { resources.endIndex }
@inlinable init(resources: [T]) {
self.resources = resources
}
@inlinable public subscript(position: Int) -> RegisteredResource<T> {
RegisteredResource(resource: resources[position], index: position)
}
@inlinable public subscript(position: UInt16) -> RegisteredResource<T> {
RegisteredResource(resource: resources[Int(position)], index: Int(position))
}
}
/// Allows access to registered files by index
@inlinable
public var registeredBuffers: RegisteredResources<RegisteredBuffer.Resource> {
RegisteredResources(resources: _registeredBuffers)
}
public func unregisterBuffers() throws {
let result = io_uring_register(
self.ringDescriptor,
RegistrationOps.unregisterBuffers.rawValue,
nil,
0
)
guard result >= 0 else {
throw Errno(rawValue: -result)
}
}
/// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring.
@inlinable
public func submitPreparedRequests() throws(Errno) {
try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor)
}
/// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available.
@inlinable
public func submitPreparedRequestsAndConsumeCompletions<Err: Error>(
minimumCount: UInt32 = 1,
timeout: Duration? = nil,
consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void
) throws(Err) {
//TODO: optimize this to one uring_enter
do {
try submitPreparedRequests()
} catch (let e) {
try consumer(nil, e, true)
}
try blockingConsumeCompletions(
minimumCount: minimumCount,
timeout: timeout,
consumer: consumer
)
}
/// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request
@inlinable
public mutating func prepare(request: __owned Request) -> Bool {
var raw: RawIORequest? = request.makeRawRequest()
return _tryWriteRequest(
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
}
/// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order.
@inlinable
mutating func prepare(linkedRequests: some BidirectionalCollection<Request>) -> Bool {
guard linkedRequests.count > 0 else {
return true
}
let freeSQECount = _getRemainingSubmissionQueueCapacity(ring: submissionRing)
guard freeSQECount >= linkedRequests.count else {
return false
}
let last = linkedRequests.last!
for req in linkedRequests.dropLast() {
var raw = req.makeRawRequest()
raw.linkToNextRequest()
let successfullyAdded = _tryWriteRequest(
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
}
let successfullyAdded = _tryWriteRequest(
last.makeRawRequest(), ring: &submissionRing,
submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded)
return true
}
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
@inlinable
public mutating func prepare(linkedRequests: Request...) -> Bool {
prepare(linkedRequests: linkedRequests)
}
/// Prepares and submits a sequence of requests to the ring. Returns false if the submission queue doesn't have enough available space.
@inlinable
public mutating func submit(linkedRequests: Request...) throws(Errno) -> Bool {
if !prepare(linkedRequests: linkedRequests) {
return false
}
try submitPreparedRequests()
return true
}
/// Describes which io_uring features are supported by the kernel this program is running on
public struct Features: OptionSet, RawRepresentable, Hashable {
public let rawValue: UInt32
@inlinable public init(rawValue: UInt32) {
self.rawValue = rawValue
}
//IORING_FEAT_SINGLE_MMAP is handled internally
@inlinable public static var nonDroppingCompletions: Features { .init(rawValue: UInt32(1) << 1) } //IORING_FEAT_NODROP
@inlinable public static var stableSubmissions: Features { .init(rawValue: UInt32(1) << 2) } //IORING_FEAT_SUBMIT_STABLE
@inlinable public static var currentFilePosition: Features { .init(rawValue: UInt32(1) << 3) } //IORING_FEAT_RW_CUR_POS
@inlinable public static var assumingTaskCredentials: Features { .init(rawValue: UInt32(1) << 4) } //IORING_FEAT_CUR_PERSONALITY
@inlinable public static var fastPolling: Features { .init(rawValue: UInt32(1) << 5) } //IORING_FEAT_FAST_POLL
@inlinable public static var epoll32BitFlags: Features { .init(rawValue: UInt32(1) << 6) } //IORING_FEAT_POLL_32BITS
@inlinable public static var pollNonFixedFiles: Features { .init(rawValue: UInt32(1) << 7) } //IORING_FEAT_SQPOLL_NONFIXED
@inlinable public static var extendedArguments: Features { .init(rawValue: UInt32(1) << 8) } //IORING_FEAT_EXT_ARG
@inlinable public static var nativeWorkers: Features { .init(rawValue: UInt32(1) << 9) } //IORING_FEAT_NATIVE_WORKERS
@inlinable public static var resourceTags: Features { .init(rawValue: UInt32(1) << 10) } //IORING_FEAT_RSRC_TAGS
@inlinable public static var allowsSkippingSuccessfulCompletions: Features { .init(rawValue: UInt32(1) << 11) } //IORING_FEAT_CQE_SKIP
@inlinable public static var improvedLinkedFiles: Features { .init(rawValue: UInt32(1) << 12) } //IORING_FEAT_LINKED_FILE
@inlinable public static var registerRegisteredRings: Features { .init(rawValue: UInt32(1) << 13) } //IORING_FEAT_REG_REG_RING
@inlinable public static var minimumTimeout: Features { .init(rawValue: UInt32(1) << 15) } //IORING_FEAT_MIN_TIMEOUT
@inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE
}
/// Describes which io_uring features are supported by the kernel this program is running on
public var supportedFeatures: Features {
return features
}
deinit {
if let ringPtr {
munmap(ringPtr, ringSize)
} else if let submissionRingPtr, let completionRingPtr {
munmap(submissionRingPtr, submissionRingSize)
munmap(completionRingPtr, completionRingSize)
}
munmap(
UnsafeMutableRawPointer(submissionQueueEntries.baseAddress!),
submissionQueueEntries.count * MemoryLayout<swift_io_uring_sqe>.size
)
close(ringDescriptor)
}
}
extension IORing.RegisteredBuffer {
@unsafe @inlinable public var unsafeBuffer: UnsafeMutableRawBufferPointer {
return .init(start: resource.iov_base, count: resource.iov_len)
}
@inlinable public var mutableBytes: MutableRawSpan {
@_lifetime(&self)
mutating get {
let span = MutableRawSpan(_unsafeBytes: unsafeBuffer)
return unsafe _overrideLifetime(span, mutating: &self)
}
}
@inlinable public var bytes: RawSpan {
let span = RawSpan(_unsafeBytes: UnsafeRawBufferPointer(unsafeBuffer))
return unsafe _overrideLifetime(span, borrowing: self)
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
-205
View File
@@ -1,205 +0,0 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import CSystem
@usableFromInline
internal struct RawIORequest: ~Copyable {
// swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where
// IORing is supported (currently requires kernel version >= 5.15).
@usableFromInline var rawValue: swift_io_uring_sqe
@usableFromInline var path: FilePath? //buffer owner for the path pointer that the sqe may have
@inlinable public init() {
self.rawValue = swift_io_uring_sqe()
}
}
extension RawIORequest {
@usableFromInline
enum Operation: UInt8 {
case nop = 0
case readv = 1
case writev = 2
case fsync = 3
case readFixed = 4
case writeFixed = 5
case pollAdd = 6
case pollRemove = 7
case syncFileRange = 8
case sendMessage = 9
case receiveMessage = 10
// ...
case asyncCancel = 14
case link_timeout = 15
// ...
case openAt = 18
case close = 19
case filesUpdate = 20
case statx = 21
case read = 22
case write = 23
// ...
case openAt2 = 28
// ...
case unlinkAt = 36
}
public struct Flags: OptionSet, Hashable, Codable {
public let rawValue: UInt8
@inlinable public init(rawValue: UInt8) {
self.rawValue = rawValue
}
@inlinable public static var fixedFile: RawIORequest.Flags { Flags(rawValue: 1 << 0) }
@inlinable public static var drainQueue: RawIORequest.Flags { Flags(rawValue: 1 << 1) }
@inlinable public static var linkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 2) }
@inlinable public static var hardlinkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 3) }
@inlinable public static var asynchronous: RawIORequest.Flags { Flags(rawValue: 1 << 4) }
@inlinable public static var selectBuffer: RawIORequest.Flags { Flags(rawValue: 1 << 5) }
@inlinable public static var skipSuccess: RawIORequest.Flags { Flags(rawValue: 1 << 6) }
}
@inlinable var operation: Operation {
get { Operation(rawValue: rawValue.opcode)! }
set { rawValue.opcode = newValue.rawValue }
}
@inlinable var cancel_flags: UInt32 {
get { rawValue.cancel_flags }
set { rawValue.cancel_flags = newValue }
}
@inlinable var addr: UInt64 {
get { rawValue.addr }
set { rawValue.addr = newValue }
}
@inlinable public var flags: Flags {
get { Flags(rawValue: rawValue.flags) }
set { rawValue.flags = newValue.rawValue }
}
@inlinable public mutating func linkToNextRequest() {
flags = Flags(rawValue: flags.rawValue | Flags.linkRequest.rawValue)
}
@inlinable public var fileDescriptor: FileDescriptor {
get { FileDescriptor(rawValue: rawValue.fd) }
set { rawValue.fd = newValue.rawValue }
}
@inlinable public var offset: UInt64? {
get {
if (rawValue.off == UInt64.max) {
return nil
} else {
return rawValue.off
}
}
set {
if let val = newValue {
rawValue.off = val
} else {
rawValue.off = UInt64.max
}
}
}
@inlinable public var buffer: UnsafeMutableRawBufferPointer {
get {
let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!)
return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len))
}
set {
rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!))
rawValue.len = UInt32(exactly: newValue.count)!
}
}
public enum RequestFlags {
case readWriteFlags(ReadWriteFlags)
// case fsyncFlags(FsyncFlags?)
// poll_events
// poll32_events
// sync_range_flags
// msg_flags
case timeoutFlags(TimeOutFlags)
// accept_flags
// cancel_flags
case openFlags(FileDescriptor.OpenOptions)
// statx_flags
// fadvise_advice
// splice_flags
}
public struct ReadWriteFlags: OptionSet, Hashable, Codable {
public var rawValue: UInt32
@inlinable public init(rawValue: UInt32) {
self.rawValue = rawValue
}
@inlinable public static var highPriority: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 0) }
// sync with only data integrity
@inlinable public static var dataSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 1) }
// sync with full data + file integrity
@inlinable public static var fileSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 2) }
// return -EAGAIN if operation blocks
@inlinable public static var noWait: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 3) }
// append to end of the file
@inlinable public static var append: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 4) }
}
public struct TimeOutFlags: OptionSet, Hashable, Codable {
public var rawValue: UInt32
@inlinable public init(rawValue: UInt32) {
self.rawValue = rawValue
}
@inlinable public static var relativeTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 0) }
@inlinable public static var absoluteTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 1 << 0) }
}
}
extension RawIORequest {
@inlinable
static func nop() -> RawIORequest {
var req: RawIORequest = RawIORequest()
req.operation = .nop
return req
}
@inlinable
static func withTimeoutRequest<R>(
linkedTo opEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
in timeoutEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
duration: Duration,
flags: TimeOutFlags,
work: () throws -> R) rethrows -> R {
opEntry.pointee.flags |= Flags.linkRequest.rawValue
opEntry.pointee.off = 1
var ts = timespec(
tv_sec: Int(duration.components.seconds),
tv_nsec: Int(duration.components.attoseconds / 1_000_000_000)
)
return try withUnsafePointer(to: &ts) { tsPtr in
var req: RawIORequest = RawIORequest()
req.operation = .link_timeout
req.rawValue.timeout_flags = flags.rawValue
req.rawValue.len = 1
req.rawValue.addr = UInt64(UInt(bitPattern: tsPtr))
timeoutEntry.pointee = req.rawValue
return try work()
}
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+7 -21
View File
@@ -1,28 +1,20 @@
/*
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 - 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
@_implementationOnly import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Bionic)
@_implementationOnly import CSystem
import Bionic
#else
#error("Unsupported Platform")
#endif
@@ -37,19 +29,13 @@ import Bionic
public typealias CModeT = CInt
#else
/// The C `mode_t` type.
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
public typealias CModeT = mode_t
#endif
/// A namespace for C and platform types
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
public enum CInterop {
#if os(Windows)
public typealias Mode = CInt
#else
public typealias Mode = mode_t
#endif
/// The C `char` type
public typealias Char = CChar
+32 -139
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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
@@ -11,27 +11,19 @@
// they can be used anywhere without imports and without confusion to
// unavailable local decls.
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#elseif canImport(WASILibc)
import CSystem
import WASILibc
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: errno
#if SYSTEM_PACKAGE_DARWIN
// MARK: - errno
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _ERRNO_NOT_USED: CInt { 0 }
#endif
@@ -78,7 +70,7 @@ internal var _EACCES: CInt { EACCES }
@_alwaysEmitIntoClient
internal var _EFAULT: CInt { EFAULT }
#if !os(Windows) && !os(WASI)
#if !os(Windows)
@_alwaysEmitIntoClient
internal var _ENOTBLK: CInt { ENOTBLK }
#endif
@@ -146,13 +138,7 @@ internal var _ERANGE: CInt { ERANGE }
internal var _EAGAIN: CInt { EAGAIN }
@_alwaysEmitIntoClient
internal var _EWOULDBLOCK: CInt {
#if os(WASI)
_getConst_EWOULDBLOCK()
#else
EWOULDBLOCK
#endif
}
internal var _EWOULDBLOCK: CInt { EWOULDBLOCK }
@_alwaysEmitIntoClient
internal var _EINPROGRESS: CInt { EINPROGRESS }
@@ -178,7 +164,6 @@ internal var _ENOPROTOOPT: CInt { ENOPROTOOPT }
@_alwaysEmitIntoClient
internal var _EPROTONOSUPPORT: CInt { EPROTONOSUPPORT }
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _ESOCKTNOSUPPORT: CInt {
#if os(Windows)
@@ -187,7 +172,6 @@ internal var _ESOCKTNOSUPPORT: CInt {
return ESOCKTNOSUPPORT
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _ENOTSUP: CInt {
@@ -198,7 +182,6 @@ internal var _ENOTSUP: CInt {
#endif
}
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EPFNOSUPPORT: CInt {
#if os(Windows)
@@ -207,7 +190,6 @@ internal var _EPFNOSUPPORT: CInt {
return EPFNOSUPPORT
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT }
@@ -242,7 +224,6 @@ internal var _EISCONN: CInt { EISCONN }
@_alwaysEmitIntoClient
internal var _ENOTCONN: CInt { ENOTCONN }
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _ESHUTDOWN: CInt {
#if os(Windows)
@@ -260,7 +241,6 @@ internal var _ETOOMANYREFS: CInt {
return ETOOMANYREFS
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _ETIMEDOUT: CInt { ETIMEDOUT }
@@ -274,7 +254,6 @@ internal var _ELOOP: CInt { ELOOP }
@_alwaysEmitIntoClient
internal var _ENAMETOOLONG: CInt { ENAMETOOLONG }
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EHOSTDOWN: CInt {
#if os(Windows)
@@ -283,7 +262,6 @@ internal var _EHOSTDOWN: CInt {
return EHOSTDOWN
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
@@ -291,12 +269,11 @@ internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
@_alwaysEmitIntoClient
internal var _ENOTEMPTY: CInt { ENOTEMPTY }
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _EPROCLIM: CInt { EPROCLIM }
#endif
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EUSERS: CInt {
#if os(Windows)
@@ -305,7 +282,6 @@ internal var _EUSERS: CInt {
return EUSERS
#endif
}
#endif
@_alwaysEmitIntoClient
internal var _EDQUOT: CInt {
@@ -325,7 +301,6 @@ internal var _ESTALE: CInt {
#endif
}
#if !os(WASI)
@_alwaysEmitIntoClient
internal var _EREMOTE: CInt {
#if os(Windows)
@@ -334,9 +309,8 @@ internal var _EREMOTE: CInt {
return EREMOTE
#endif
}
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _EBADRPC: CInt { EBADRPC }
@@ -359,7 +333,7 @@ internal var _ENOLCK: CInt { ENOLCK }
@_alwaysEmitIntoClient
internal var _ENOSYS: CInt { ENOSYS }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _EFTYPE: CInt { EFTYPE }
@@ -368,9 +342,7 @@ internal var _EAUTH: CInt { EAUTH }
@_alwaysEmitIntoClient
internal var _ENEEDAUTH: CInt { ENEEDAUTH }
#endif
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EPWROFF: CInt { EPWROFF }
@@ -383,7 +355,7 @@ internal var _EDEVERR: CInt { EDEVERR }
internal var _EOVERFLOW: CInt { EOVERFLOW }
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _EBADEXEC: CInt { EBADEXEC }
@@ -411,7 +383,7 @@ internal var _ENOMSG: CInt { ENOMSG }
@_alwaysEmitIntoClient
internal var _EILSEQ: CInt { EILSEQ }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _ENOATTR: CInt { ENOATTR }
#endif
@@ -424,43 +396,32 @@ internal var _EBADMSG: CInt { EBADMSG }
@_alwaysEmitIntoClient
internal var _EMULTIHOP: CInt { EMULTIHOP }
#if !os(WASI) && !os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENODATA: CInt { ENODATA }
#endif
@_alwaysEmitIntoClient
internal var _ENOLINK: CInt { ENOLINK }
#if !os(WASI) && !os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENOSR: CInt { ENOSR }
@_alwaysEmitIntoClient
internal var _ENOSTR: CInt { ENOSTR }
#endif
#endif
@_alwaysEmitIntoClient
internal var _EPROTO: CInt { EPROTO }
#if !os(OpenBSD) && !os(WASI) && !os(FreeBSD)
#if !os(OpenBSD)
@_alwaysEmitIntoClient
internal var _ETIME: CInt { ETIME }
#endif
#endif
@_alwaysEmitIntoClient
internal var _EOPNOTSUPP: CInt {
#if os(WASI)
_getConst_EOPNOTSUPP()
#else
EOPNOTSUPP
#endif
}
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _ENOPOLICY: CInt { ENOPOLICY }
#endif
@@ -473,28 +434,15 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
#endif
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ENOTCAPABLE: CInt { ENOTCAPABLE }
@_alwaysEmitIntoClient
internal var _ECAPMODE: CInt { ECAPMODE }
@_alwaysEmitIntoClient
internal var _EINTEGRITY: CInt { EINTEGRITY }
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _EQFULL: CInt { EQFULL }
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@_alwaysEmitIntoClient
internal var _ELAST: CInt { ELAST }
#endif
// MARK: File Operations
// MARK: - File Operations
@_alwaysEmitIntoClient
internal var _O_RDONLY: CInt { O_RDONLY }
@@ -506,40 +454,18 @@ internal var _O_WRONLY: CInt { O_WRONLY }
internal var _O_RDWR: CInt { O_RDWR }
#if !os(Windows)
#if canImport(Musl)
internal var _O_ACCMODE: CInt { 0x03|O_SEARCH }
#else
// TODO: API?
@_alwaysEmitIntoClient
internal var _O_ACCMODE: CInt {
#if os(WASI)
_getConst_O_ACCMODE()
#else
O_ACCMODE
#endif
}
internal var _O_ACCMODE: CInt { O_ACCMODE }
@_alwaysEmitIntoClient
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
#endif
@_alwaysEmitIntoClient
internal var _O_NONBLOCK: CInt {
#if os(WASI)
_getConst_O_NONBLOCK()
#else
O_NONBLOCK
#endif
}
#endif
internal var _O_APPEND: CInt { O_APPEND }
@_alwaysEmitIntoClient
internal var _O_APPEND: CInt {
#if os(WASI)
_getConst_O_APPEND()
#else
O_APPEND
#endif
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _O_SHLOCK: CInt { O_SHLOCK }
@@ -548,52 +474,24 @@ internal var _O_EXLOCK: CInt { O_EXLOCK }
#endif
#if !os(Windows)
#if !os(WASI)
// TODO: API?
@_alwaysEmitIntoClient
internal var _O_ASYNC: CInt { O_ASYNC }
#endif
@_alwaysEmitIntoClient
internal var _O_NOFOLLOW: CInt { O_NOFOLLOW }
#endif
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _O_FSYNC: CInt { O_FSYNC }
internal var _O_CREAT: CInt { O_CREAT }
@_alwaysEmitIntoClient
internal var _O_SYNC: CInt { O_SYNC }
#endif
internal var _O_TRUNC: CInt { O_TRUNC }
@_alwaysEmitIntoClient
internal var _O_CREAT: CInt {
#if os(WASI)
_getConst_O_CREAT()
#else
O_CREAT
#endif
}
internal var _O_EXCL: CInt { O_EXCL }
@_alwaysEmitIntoClient
internal var _O_TRUNC: CInt {
#if os(WASI)
_getConst_O_TRUNC()
#else
O_TRUNC
#endif
}
@_alwaysEmitIntoClient
internal var _O_EXCL: CInt {
#if os(WASI)
_getConst_O_EXCL()
#else
O_EXCL
#endif
}
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _O_EVTONLY: CInt { O_EVTONLY }
#endif
@@ -604,16 +502,10 @@ internal var _O_EVTONLY: CInt { O_EVTONLY }
internal var _O_NOCTTY: CInt { O_NOCTTY }
@_alwaysEmitIntoClient
internal var _O_DIRECTORY: CInt {
#if os(WASI)
_getConst_O_DIRECTORY()
#else
O_DIRECTORY
#endif
}
internal var _O_DIRECTORY: CInt { O_DIRECTORY }
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _O_SYMLINK: CInt { O_SYMLINK }
#endif
@@ -632,10 +524,11 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
@_alwaysEmitIntoClient
internal var _SEEK_END: CInt { SEEK_END }
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
@_alwaysEmitIntoClient
internal var _SEEK_DATA: CInt { SEEK_DATA }
#endif
+10 -53
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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
@@ -12,22 +12,14 @@
// TODO: Should CSystem just include all the header files we need?
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
@_implementationOnly import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#elseif canImport(WASILibc)
import WASILibc
#elseif canImport(Android)
@_implementationOnly import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
@@ -36,7 +28,7 @@ internal typealias _COffT = off_t
// MARK: syscalls and variables
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
internal var system_errno: CInt {
get { Darwin.errno }
set { Darwin.errno = newValue }
@@ -53,26 +45,11 @@ internal var system_errno: CInt {
_ = ucrt._set_errno(newValue)
}
}
#elseif canImport(Glibc)
#else
internal var system_errno: CInt {
get { Glibc.errno }
set { Glibc.errno = newValue }
}
#elseif canImport(Musl)
internal var system_errno: CInt {
get { Musl.errno }
set { Musl.errno = newValue }
}
#elseif canImport(WASILibc)
internal var system_errno: CInt {
get { WASILibc.errno }
set { WASILibc.errno = newValue }
}
#elseif canImport(Android)
internal var system_errno: CInt {
get { Android.errno }
set { Android.errno = newValue }
}
#endif
// MARK: C stdlib decls
@@ -116,9 +93,9 @@ internal func system_memset(
// Interop between String and platfrom string
extension String {
internal func _withPlatformString<Success, Failure: Error>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(Failure) -> Success
) throws(Failure) -> Success {
internal func _withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result {
// Need to #if because CChar may be signed
#if os(Windows)
return try withCString(encodedAs: CInterop.PlatformUnicodeEncoding.self, body)
@@ -164,24 +141,6 @@ extension String {
// TLS
#if os(Windows)
internal typealias _PlatformTLSKey = DWORD
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
// Mock TLS storage for single-threaded WASI
internal final class _PlatformTLSKey {
fileprivate init() {}
}
private final class TLSStorage: @unchecked Sendable {
var storage = [ObjectIdentifier: UnsafeMutableRawPointer]()
}
private let sharedTLSStorage = TLSStorage()
func pthread_setspecific(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) -> Int {
sharedTLSStorage.storage[ObjectIdentifier(key)] = p
return 0
}
func pthread_getspecific(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
sharedTLSStorage.storage[ObjectIdentifier(key)]
}
#else
internal typealias _PlatformTLSKey = pthread_key_t
#endif
@@ -193,8 +152,6 @@ internal func makeTLSKey() -> _PlatformTLSKey {
fatalError("Unable to create key")
}
return raw
#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded))
return _PlatformTLSKey()
#else
var raw = pthread_key_t()
guard 0 == pthread_key_create(&raw, nil) else {
+26 -15
View File
@@ -17,7 +17,7 @@
// enabled in testing builds of System currently, to minimize runtime overhead of release builds.
//
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
internal struct Trace {
internal struct Entry {
@@ -63,7 +63,7 @@ internal class MockingDriver {
// Whether we should pretend to be Windows for syntactic operations
// inside FilePath
fileprivate var forceWindowsSyntaxForPaths: Bool? = nil
fileprivate var forceWindowsSyntaxForPaths = false
}
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
@@ -110,17 +110,17 @@ private var contextualMockingEnabled: Bool {
extension MockingDriver {
internal static var enabled: Bool { mockingEnabled }
internal static var forceWindowsPaths: Bool? {
currentMockingDriver?.forceWindowsSyntaxForPaths
internal static var forceWindowsPaths: Bool {
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
}
}
#endif // ENABLE_MOCKING && !$Embedded
#endif // ENABLE_MOCKING
@inline(__always)
internal var mockingEnabled: Bool {
// Fast constant-foldable check for release builds
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
return contextualMockingEnabled
#else
return false
@@ -128,16 +128,16 @@ internal var mockingEnabled: Bool {
}
@inline(__always)
internal var forceWindowsPaths: Bool? {
#if ENABLE_MOCKING && !$Embedded
return MockingDriver.forceWindowsPaths
internal var forceWindowsPaths: Bool {
#if !ENABLE_MOCKING
return false
#else
return nil
return MockingDriver.forceWindowsPaths
#endif
}
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
// Strip the mock_system prefix and the arg list suffix
private func originalSyscallName(_ function: String) -> String {
// `function` must be of format `system_<name>(<parameters>)`
@@ -193,14 +193,25 @@ internal func _mockOffT(
) -> _COffT {
_COffT(mockImpl(name: name, path: path, args))
}
#endif // ENABLE_MOCKING && !$Embedded
internal func _mockModeT(
name: String = #function, _ args: AnyHashable...
) -> CInterop.Mode {
CInterop.Mode(mockImpl(name: name, path: nil, args))
}
#endif // ENABLE_MOCKING
// Force paths to be treated as Windows syntactically if `enabled` is
// true, and as POSIX syntactically if not.
// true.
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
guard enabled else {
body()
return
}
MockingDriver.withMockingEnabled { driver in
driver.forceWindowsSyntaxForPaths = enabled
driver.forceWindowsSyntaxForPaths = true
body()
}
#else
+1 -7
View File
@@ -80,13 +80,7 @@ extension _RawBuffer {
internal static func create(minimumCapacity: Int) -> Storage {
Storage.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
#if os(OpenBSD)
minimumCapacity
#else
$0.capacity
#endif
}
makingHeaderWith: { $0.capacity }
) as! Storage
}
}
+17 -153
View File
@@ -1,25 +1,18 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif canImport(Glibc)
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(Android)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(WASILibc)
import CSystem
import WASILibc
#elseif os(Windows)
import ucrt
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
@@ -31,7 +24,7 @@ import Android
internal func system_open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
) -> CInt {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled {
return _mock(path: path, oflag)
}
@@ -43,7 +36,7 @@ internal func system_open(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ oflag: Int32, _ mode: CInterop.Mode
) -> CInt {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled {
return _mock(path: path, oflag, mode)
}
@@ -53,7 +46,7 @@ internal func system_open(
// close
internal func system_close(_ fd: Int32) -> Int32 {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd) }
#endif
return close(fd)
@@ -63,7 +56,7 @@ internal func system_close(_ fd: Int32) -> Int32 {
internal func system_read(
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int
) -> Int {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
#endif
return read(fd, buf, nbyte)
@@ -73,25 +66,17 @@ internal func system_read(
internal func system_pread(
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int, _ offset: off_t
) -> Int {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pread has a non-nullable `buf` pointer
pread(fd, buf ?? UnsafeMutableRawPointer($0), nbyte, offset)
}
#else
return pread(fd, buf, nbyte, offset)
#endif
}
// lseek
internal func system_lseek(
_ fd: Int32, _ off: off_t, _ whence: Int32
) -> off_t {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mockOffT(fd, off, whence) }
#endif
return lseek(fd, off, whence)
@@ -101,7 +86,7 @@ internal func system_lseek(
internal func system_write(
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int
) -> Int {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
#endif
return write(fd, buf, nbyte)
@@ -111,161 +96,40 @@ internal func system_write(
internal func system_pwrite(
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int, _ offset: off_t
) -> Int {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pwrite has a non-nullable `buf` pointer
pwrite(fd, buf ?? UnsafeRawPointer($0), nbyte, offset)
}
#else
return pwrite(fd, buf, nbyte, offset)
#endif
}
#if !os(WASI)
internal func system_dup(_ fd: Int32) -> Int32 {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd) }
#endif
return dup(fd)
}
internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, fd2) }
#endif
return dup2(fd, fd2)
}
#endif
#if !os(WASI)
#if !os(Windows)
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fds) }
#endif
return pipe(fds)
}
#endif
#if !os(Windows)
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
#if ENABLE_MOCKING && !$Embedded
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, length) }
#endif
return ftruncate(fd, length)
}
internal func system_mkdir(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> CInt {
#if ENABLE_MOCKING && !$Embedded
if mockingEnabled { return _mock(path: path, mode) }
#endif
return mkdir(path, mode)
}
internal func system_rmdir(
_ path: UnsafePointer<CInterop.PlatformChar>
) -> CInt {
#if ENABLE_MOCKING && !$Embedded
if mockingEnabled { return _mock(path: path) }
#endif
return rmdir(path)
}
#if SYSTEM_PACKAGE_DARWIN
internal let SYSTEM_CS_DARWIN_USER_TEMP_DIR = _CS_DARWIN_USER_TEMP_DIR
internal func system_confstr(
_ name: CInt,
_ buf: UnsafeMutablePointer<CInterop.PlatformChar>,
_ len: Int
) -> Int {
return confstr(name, buf, len)
}
#endif
#if !os(Windows)
internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR
#if os(WASI)
internal let SYSTEM_DT_DIR = _getConst_DT_DIR()
internal typealias system_dirent = _system_dirent
#else
internal let SYSTEM_DT_DIR = DT_DIR
internal typealias system_dirent = dirent
#endif
#if os(Linux) || os(Android) || os(FreeBSD) || os(OpenBSD) || os(WASI)
internal typealias system_DIRPtr = OpaquePointer
#else
internal typealias system_DIRPtr = UnsafeMutablePointer<DIR>
#endif
internal func system_unlinkat(
_ fd: CInt,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ flag: CInt
) -> CInt {
#if ENABLE_MOCKING && !$Embedded
if mockingEnabled { return _mock(fd, path, flag) }
#endif
return unlinkat(fd, path, flag)
}
internal func system_fdopendir(
_ fd: CInt
) -> system_DIRPtr? {
return fdopendir(fd)
}
internal func system_readdir(
_ dir: system_DIRPtr
) -> UnsafeMutablePointer<system_dirent>? {
#if os(WASI)
return _system_dirent_from_wasi_dirent(readdir(dir))
#else
return readdir(dir)
#endif
}
internal func system_rewinddir(
_ dir: system_DIRPtr
) {
return rewinddir(dir)
}
internal func system_closedir(
_ dir: system_DIRPtr
) -> CInt {
return closedir(dir)
}
internal func system_openat(
_ fd: CInt,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ oflag: Int32
) -> CInt {
#if ENABLE_MOCKING && !$Embedded
if mockingEnabled {
return _mock(fd, path, oflag)
}
#endif
return openat(fd, path, oflag)
}
#endif
#if !os(WASI) // WASI has no umask
internal func system_umask(
_ mode: CInterop.Mode
) -> CInterop.Mode {
return umask(mode)
}
#endif
internal func system_getenv(
_ name: UnsafePointer<CChar>
) -> UnsafeMutablePointer<CChar>? {
return getenv(name)
}
@@ -12,45 +12,13 @@
import ucrt
import WinSDK
fileprivate var _umask: CInterop.Mode = 0o22
@inline(__always)
func umask(
_ mode: CInterop.Mode
) -> CInterop.Mode {
let oldMask = _umask
_umask = mode
return oldMask
}
@inline(__always)
internal func open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
) -> CInt {
let decodedFlags = DecodedOpenFlags(oflag)
var saAttrs = SECURITY_ATTRIBUTES(
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
lpSecurityDescriptor: nil,
bInheritHandle: decodedFlags.bInheritHandle
)
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
nil)
}), hFile != INVALID_HANDLE_VALUE else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
var fh: CInt = -1
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
return fh
}
@inline(__always)
@@ -58,41 +26,10 @@ internal func open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
_ mode: CInterop.Mode
) -> CInt {
let actualMode = mode & ~_umask
guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
defer {
pSD.deallocate()
}
let decodedFlags = DecodedOpenFlags(oflag)
var saAttrs = SECURITY_ATTRIBUTES(
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
lpSecurityDescriptor: pSD,
bInheritHandle: decodedFlags.bInheritHandle
)
guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path,
decodedFlags.dwDesiredAccess,
DWORD(FILE_SHARE_DELETE
| FILE_SHARE_READ
| FILE_SHARE_WRITE),
&saAttrs,
decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes,
nil)
}), hFile != INVALID_HANDLE_VALUE else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
// TODO(compnerd): Apply read/write permissions
var fh: CInt = -1
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
return fh
}
@inline(__always)
@@ -143,7 +80,7 @@ internal func pread(
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
) -> Int {
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -154,7 +91,8 @@ internal func pread(
var nNumberOfBytesRead: DWORD = 0
if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
let _ = GetLastError()
// TODO(compnerd) map windows error to errno
return Int(-1)
}
return Int(nNumberOfBytesRead)
@@ -165,7 +103,7 @@ internal func pwrite(
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
) -> Int {
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -177,482 +115,11 @@ internal func pwrite(
var nNumberOfBytesWritten: DWORD = 0
if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten,
&ovlOverlapped) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
let _ = GetLastError()
// TODO(compnerd) map windows error to errno
return Int(-1)
}
return Int(nNumberOfBytesWritten)
}
@inline(__always)
internal func pipe(
_ fds: UnsafeMutablePointer<Int32>, bytesReserved: UInt32 = 4096
) -> CInt {
return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT);
}
@inline(__always)
internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)!
let liDesiredLength = LARGE_INTEGER(QuadPart: LONGLONG(length))
var liCurrentOffset = LARGE_INTEGER(QuadPart: 0)
// Save the current position and restore it when we're done
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
DWORD(FILE_CURRENT)) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
defer {
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN));
}
// Truncate (or extend) the file
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN))
|| !SetEndOfFile(hFile) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
return 0;
}
@inline(__always)
internal func mkdir(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> CInt {
let actualMode = mode & ~_umask
guard let pSD = _createSecurityDescriptor(from: actualMode,
for: .directory) else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
defer {
pSD.deallocate()
}
var saAttrs = SECURITY_ATTRIBUTES(
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
lpSecurityDescriptor: pSD,
bInheritHandle: false
)
guard (try? path.withCanonicalPathRepresentation({ path in CreateDirectoryW(path, &saAttrs) })) == true else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
return 0;
}
@inline(__always)
internal func rmdir(
_ path: UnsafePointer<CInterop.PlatformChar>
) -> CInt {
guard (try? path.withCanonicalPathRepresentation({ path in RemoveDirectoryW(path) })) == true else {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1
}
return 0;
}
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
switch Int32(errorCode) {
case ERROR_SUCCESS:
return 0
case ERROR_INVALID_FUNCTION,
ERROR_INVALID_ACCESS,
ERROR_INVALID_DATA,
ERROR_INVALID_PARAMETER,
ERROR_NEGATIVE_SEEK:
return EINVAL
case ERROR_FILE_NOT_FOUND,
ERROR_PATH_NOT_FOUND,
ERROR_INVALID_DRIVE,
ERROR_NO_MORE_FILES,
ERROR_BAD_NETPATH,
ERROR_BAD_NET_NAME,
ERROR_BAD_PATHNAME,
ERROR_FILENAME_EXCED_RANGE:
return ENOENT
case ERROR_TOO_MANY_OPEN_FILES:
return EMFILE
case ERROR_ACCESS_DENIED,
ERROR_CURRENT_DIRECTORY,
ERROR_LOCK_VIOLATION,
ERROR_NETWORK_ACCESS_DENIED,
ERROR_CANNOT_MAKE,
ERROR_FAIL_I24,
ERROR_DRIVE_LOCKED,
ERROR_SEEK_ON_DEVICE,
ERROR_NOT_LOCKED,
ERROR_LOCK_FAILED,
ERROR_WRITE_PROTECT...ERROR_SHARING_BUFFER_EXCEEDED:
return EACCES
case ERROR_INVALID_HANDLE,
ERROR_INVALID_TARGET_HANDLE,
ERROR_DIRECT_ACCESS_HANDLE:
return EBADF
case ERROR_ARENA_TRASHED,
ERROR_NOT_ENOUGH_MEMORY,
ERROR_INVALID_BLOCK,
ERROR_NOT_ENOUGH_QUOTA:
return ENOMEM
case ERROR_BAD_ENVIRONMENT:
return E2BIG
case ERROR_BAD_FORMAT,
ERROR_INVALID_STARTING_CODESEG...ERROR_INFLOOP_IN_RELOC_CHAIN:
return ENOEXEC
case ERROR_NOT_SAME_DEVICE:
return EXDEV
case ERROR_FILE_EXISTS,
ERROR_ALREADY_EXISTS:
return EEXIST
case ERROR_NO_PROC_SLOTS,
ERROR_MAX_THRDS_REACHED,
ERROR_NESTING_NOT_ALLOWED:
return EAGAIN
case ERROR_BROKEN_PIPE:
return EPIPE
case ERROR_DISK_FULL:
return ENOSPC
case ERROR_WAIT_NO_CHILDREN,
ERROR_CHILD_NOT_COMPLETE:
return ECHILD
case ERROR_DIR_NOT_EMPTY:
return ENOTEMPTY
case ERROR_NO_UNICODE_TRANSLATION:
return EILSEQ
default:
return EINVAL
}
}
fileprivate func rightsFromModeBits(
_ bits: Int,
sticky: Bool = false,
for fileOrDirectory: _FileOrDirectory
) -> DWORD {
var rights: DWORD = 0
if (bits & 0o4) != 0 {
rights |= DWORD(FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE)
}
if (bits & 0o2) != 0 {
rights |= DWORD(FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE)
if fileOrDirectory == .directory && !sticky {
rights |= DWORD(FILE_DELETE_CHILD)
}
}
if (bits & 0o1) != 0 {
rights |= DWORD(FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE)
}
return rights
}
fileprivate func getTokenInformation<T>(
of: T.Type,
hToken: HANDLE,
ticTokenClass: TOKEN_INFORMATION_CLASS
) -> UnsafePointer<T>? {
var capacity = 1024
for _ in 0..<2 {
let buffer = UnsafeMutableRawPointer.allocate(
byteCount: capacity,
alignment: MemoryLayout<T>.alignment
)
var dwLength = DWORD(0)
if GetTokenInformation(hToken,
ticTokenClass,
buffer,
DWORD(capacity),
&dwLength) {
return UnsafePointer(buffer.assumingMemoryBound(to: T.self))
}
buffer.deallocate()
capacity = Int(dwLength)
}
return nil
}
internal enum _FileOrDirectory {
case file
case directory
}
/// Build a SECURITY_DESCRIPTOR from UNIX-style "mode" bits. This only
/// takes account of the rwx and sticky bits; there's really nothing that
/// we can do about setuid/setgid.
internal func _createSecurityDescriptor(from mode: CInterop.Mode,
for fileOrDirectory: _FileOrDirectory)
-> PSECURITY_DESCRIPTOR? {
let ownerPerm = (Int(mode) >> 6) & 0o7
let groupPerm = (Int(mode) >> 3) & 0o7
let otherPerm = Int(mode) & 0o7
let ownerRights = rightsFromModeBits(ownerPerm, for: fileOrDirectory)
let groupRights = rightsFromModeBits(groupPerm,
sticky: (mode & 0o1000) != 0,
for: fileOrDirectory)
let otherRights = rightsFromModeBits(otherPerm,
sticky: (mode & 0o1000) != 0,
for: fileOrDirectory)
// If group or other permissions are *more* permissive, then we need
// some DENY ACEs as well to implement the expected semantics
let ownerDenyRights = ((ownerRights ^ groupRights) & groupRights) |
((ownerRights ^ otherRights) & otherRights)
let groupDenyRights = (groupRights ^ otherRights) & otherRights
var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1))
var everyone: PSID? = nil
guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
DWORD(SECURITY_WORLD_RID),
0, 0, 0, 0, 0, 0, 0,
&everyone) else {
return nil
}
guard let everyone = everyone else {
return nil
}
defer {
FreeSid(everyone)
}
let hToken = GetCurrentThreadEffectiveToken()!
guard let pTokenUser = getTokenInformation(of: TOKEN_USER.self,
hToken: hToken,
ticTokenClass: TokenUser) else {
return nil
}
defer {
pTokenUser.deallocate()
}
guard let pTokenPrimaryGroup = getTokenInformation(
of: TOKEN_PRIMARY_GROUP.self,
hToken: hToken,
ticTokenClass: TokenPrimaryGroup
) else {
return nil
}
defer {
pTokenPrimaryGroup.deallocate()
}
let user = pTokenUser.pointee.User.Sid!
let group = pTokenPrimaryGroup.pointee.PrimaryGroup!
var eas = [
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_USER,
ptstrName:
user.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
),
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
group.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
),
EXPLICIT_ACCESS_W(
grfAccessPermissions: otherRights,
grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
everyone.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
)
]
if ownerDenyRights != 0 {
eas.append(
EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_USER,
ptstrName:
user.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
)
)
}
if groupDenyRights != 0 {
eas.append(
EXPLICIT_ACCESS_W(
grfAccessPermissions: groupDenyRights,
grfAccessMode: DENY_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE),
Trustee: TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
group.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
)
)
}
var pACL: PACL? = nil
guard SetEntriesInAclW(ULONG(eas.count),
&eas,
nil,
&pACL) == ERROR_SUCCESS else {
return nil
}
defer {
LocalFree(pACL)
}
// Create the security descriptor, making sure that inherited ACEs don't
// take effect, since that wouldn't match the behaviour of mode bits.
var descriptor = SECURITY_DESCRIPTOR()
guard InitializeSecurityDescriptor(&descriptor,
DWORD(SECURITY_DESCRIPTOR_REVISION)) else {
return nil
}
guard SetSecurityDescriptorControl(&descriptor,
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED),
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED))
&& SetSecurityDescriptorOwner(&descriptor, user, false)
&& SetSecurityDescriptorGroup(&descriptor, group, false)
&& SetSecurityDescriptorDacl(&descriptor,
true,
pACL,
false) else {
return nil
}
// Make it self-contained (up to this point it uses pointers)
var dwRelativeSize = DWORD(0)
guard !MakeSelfRelativeSD(&descriptor, nil, &dwRelativeSize)
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER else {
return nil
}
let pDescriptor = UnsafeMutableRawPointer.allocate(
byteCount: Int(dwRelativeSize),
alignment: MemoryLayout<SECURITY_DESCRIPTOR>.alignment
).assumingMemoryBound(to: SECURITY_DESCRIPTOR.self)
guard MakeSelfRelativeSD(&descriptor, pDescriptor, &dwRelativeSize) else {
pDescriptor.deallocate()
return nil
}
return UnsafeMutableRawPointer(pDescriptor)
}
fileprivate struct DecodedOpenFlags {
var dwDesiredAccess: DWORD
var dwCreationDisposition: DWORD
var bInheritHandle: WindowsBool
var dwFlagsAndAttributes: DWORD
init(_ oflag: Int32) {
switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) {
case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC:
dwCreationDisposition = DWORD(CREATE_NEW)
case _O_CREAT:
dwCreationDisposition = DWORD(OPEN_ALWAYS)
case _O_CREAT | _O_TRUNC:
dwCreationDisposition = DWORD(CREATE_ALWAYS)
case _O_TRUNC:
dwCreationDisposition = DWORD(TRUNCATE_EXISTING)
default:
dwCreationDisposition = DWORD(OPEN_EXISTING)
}
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
// on Windows; in particular, _O_RDONLY is zero, which means we can't
// test for it by AND-ing.
dwDesiredAccess = 0
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
case _O_RDONLY:
dwDesiredAccess |= DWORD(GENERIC_READ)
case _O_WRONLY:
dwDesiredAccess |= DWORD(GENERIC_WRITE)
case _O_RDWR:
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE)
default:
break
}
bInheritHandle = WindowsBool((oflag & _O_NOINHERIT) == 0)
dwFlagsAndAttributes = 0
if (oflag & _O_SEQUENTIAL) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN)
}
if (oflag & _O_RANDOM) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS)
}
if (oflag & _O_TEMPORARY) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE)
}
if (oflag & _O_SHORT_LIVED) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY)
} else {
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL)
}
}
}
#endif
+47 -90
View File
@@ -1,20 +1,18 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2022 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2022 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
#if false && swift(>=5.8) && $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
import Darwin.Mach
@available(System 1.4.0, *)
public protocol MachPortRight {}
@available(System 1.4.0, *)
@inlinable
internal func _machPrecondition(
file: StaticString = #file,
@@ -26,10 +24,9 @@ internal func _machPrecondition(
precondition(kr == expected, file: file, line: line)
}
@available(System 1.4.0, *)
@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
@frozen
public enum Mach {
@available(System 1.4.0, *)
public struct Port<RightType: MachPortRight>: ~Copyable {
@usableFromInline
internal var _name: mach_port_name_t
@@ -51,15 +48,11 @@ public enum Mach {
///
/// This initializer makes a syscall to guard the right.
public init(name: mach_port_name_t) {
precondition(name != mach_port_name_t(MACH_PORT_NULL),
"Mach.Port cannot be initialized with MACH_PORT_NULL")
precondition(name != mach_port_name_t(MACH_PORT_NULL), "Mach.Port cannot be initialized with MACH_PORT_NULL")
self._name = name
if RightType.self == ReceiveRight.self {
precondition(
_name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */,
"Receive rights cannot be dead names"
)
precondition(name != 0xFFFFFFFF /* MACH_PORT_DEAD */, "Receive rights cannot be dead names")
let secret = mach_port_context_t(arc4random())
_machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0))
@@ -88,20 +81,17 @@ public enum Mach {
}
deinit {
if RightType.self == ReceiveRight.self {
precondition(
_name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */,
"Receive rights cannot be dead names"
)
_machPrecondition(
mach_port_destruct(mach_task_self_, _name, 0, _context)
)
if _name == 0xFFFFFFFF /* MACH_PORT_DEAD */ {
precondition(RightType.self != ReceiveRight.self, "Receive rights cannot be dead names")
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_DEAD_NAME, -1))
} else {
assert(
RightType.self == SendRight.self ||
RightType.self == SendOnceRight.self
)
_machPrecondition(mach_port_deallocate(mach_task_self_, _name))
if RightType.self == ReceiveRight.self {
_machPrecondition(mach_port_destruct(mach_task_self_, _name, -1, _context))
} else if RightType.self == SendRight.self {
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND, -1))
} else if RightType.self == SendOnceRight.self {
_machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND_ONCE, -1))
}
}
}
}
@@ -133,7 +123,6 @@ public enum Mach {
public struct SendOnceRight: MachPortRight {}
}
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.ReceiveRight {
/// Transfer ownership of an existing, unmanaged, but already guarded,
/// Mach port right into a Mach.Port by name.
@@ -146,8 +135,6 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// The underlying port right will be automatically deallocated when
/// the Mach.Port object is destroyed.
public init(name: mach_port_name_t, context: mach_port_context_t) {
precondition(name != mach_port_name_t(MACH_PORT_NULL),
"Mach.Port cannot be initialized with MACH_PORT_NULL")
self._name = name
self._context = context
}
@@ -158,12 +145,11 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// This initializer will abort if the right could not be created.
/// Callers may assert that a valid right is always returned.
@inlinable
@available(System 1.4.0, *)
public init() {
var storage: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
_machPrecondition(
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &storage)
)
withUnsafeMutablePointer(to: &storage) { storage in
_machPrecondition(mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage))
}
// name-only init will guard ReceiveRights
self.init(name: storage)
@@ -181,12 +167,9 @@ 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(
public __consuming func relinquish(
) -> (name: mach_port_name_t, context: mach_port_context_t) {
let destructured = (name: _name, context: _context)
discard self
return destructured
return (name: _name, context: _context)
}
/// Remove guard and transfer ownership of the underlying port right to
@@ -204,11 +187,9 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract
/// the context value along with the port name.
@inlinable
@available(System 1.4.0, *)
public consuming func unguardAndRelinquish() -> mach_port_name_t {
let (name, context) = self.relinquish()
_machPrecondition(mach_port_unguard(mach_task_self_, name, context))
return name
public __consuming func unguardAndRelinquish() -> mach_port_name_t {
_machPrecondition(mach_port_unguard(mach_task_self_, _name, _context))
return _name
}
/// Borrow access to the port name in a block that can perform
@@ -221,7 +202,6 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// The body block may optionally return something, which will then be
/// returned to the caller of withBorrowedName.
@inlinable
@available(System 1.4.0, *)
public func withBorrowedName<ReturnType>(
body: (mach_port_name_t, mach_port_context_t) -> ReturnType
) -> ReturnType {
@@ -235,21 +215,22 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// This function will abort if the right could not be created.
/// Callers may assert that a valid right is always returned.
@inlinable
@available(System 1.4.0, *)
public func makeSendOnceRight() -> Mach.Port<Mach.SendOnceRight> {
// send once rights do not coalesce
var newRight: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL)
var newRightType: mach_port_type_t = MACH_PORT_TYPE_NONE
_machPrecondition(
mach_port_extract_right(
mach_task_self_,
_name,
mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE),
&newRight,
&newRightType
)
)
withUnsafeMutablePointer(to: &newRight) { newRight in
withUnsafeMutablePointer(to: &newRightType) { newRightType in
_machPrecondition(
mach_port_extract_right(mach_task_self_,
_name,
mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE),
newRight,
newRightType)
)
}
}
// The value of newRight is validated by the Mach.Port initializer
precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE)
@@ -264,16 +245,11 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
/// This function will abort if the right could not be created.
/// Callers may assert that a valid right is always returned.
@inlinable
@available(System 1.4.0, *)
public func makeSendRight() -> Mach.Port<Mach.SendRight> {
let how = MACH_MSG_TYPE_MAKE_SEND
// name is the same because send and recv rights are coalesced
_machPrecondition(
mach_port_insert_right(
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
)
)
_machPrecondition(mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how)))
return Mach.Port(name: _name)
}
@@ -282,24 +258,14 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
///
/// Each get/set of this property makes a syscall.
@inlinable
@available(System 1.4.0, *)
public var makeSendCount: mach_port_mscount_t {
get {
var status: mach_port_status = mach_port_status()
var size = mach_msg_type_number_t(
MemoryLayout<mach_port_status>.size / MemoryLayout<natural_t>.size
)
withUnsafeMutablePointer(to: &status) {
[ _name = self._name ] in
let status = UnsafeMutableBufferPointer(start: $0, count: 1)
status.withMemoryRebound(to: integer_t.self) {
let info = $0.baseAddress
_machPrecondition(
mach_port_get_attributes(
mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, &size
)
)
var size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout<mach_port_status>.size / MemoryLayout<natural_t>.size)
withUnsafeMutablePointer(to: &size) { size in
withUnsafeMutablePointer(to: &status) { status in
let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1)
_machPrecondition(mach_port_get_attributes(mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, size))
}
}
return status.mps_mscount
@@ -311,7 +277,6 @@ extension Mach.Port where RightType == Mach.ReceiveRight {
}
}
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.SendRight {
/// Transfer ownership of the underlying port right to the caller.
///
@@ -323,10 +288,8 @@ extension Mach.Port where RightType == Mach.SendRight {
/// After this function completes, the Mach.Port is destroyed and no longer
/// usable.
@inlinable
public consuming func relinquish() -> mach_port_name_t {
let name = _name
discard self
return name
public __consuming func relinquish() -> mach_port_name_t {
return _name
}
/// Create another send right from a given send right.
@@ -337,15 +300,12 @@ extension Mach.Port where RightType == Mach.SendRight {
/// receiving side has been deallocated, then copySendRight() will throw
/// a Mach.PortRightError.deadName error.
@inlinable
@available(System 1.4.0, *)
public func copySendRight() throws -> Mach.Port<Mach.SendRight> {
let how = MACH_MSG_TYPE_COPY_SEND
// name is the same because send rights are coalesced
let kr = mach_port_insert_right(
mach_task_self_, _name, _name, mach_msg_type_name_t(how)
)
if kr == KERN_INVALID_NAME || kr == KERN_INVALID_CAPABILITY {
let kr = mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how))
if kr == KERN_INVALID_CAPABILITY {
throw Mach.PortRightError.deadName
}
_machPrecondition(kr)
@@ -354,7 +314,7 @@ extension Mach.Port where RightType == Mach.SendRight {
}
}
@available(System 1.4.0, *)
extension Mach.Port where RightType == Mach.SendOnceRight {
/// Transfer ownership of the underlying port right to the caller.
///
@@ -366,11 +326,8 @@ 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
discard self
return name
public __consuming func relinquish() -> mach_port_name_t {
return _name
}
}
+7 -8
View File
@@ -7,7 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension String {
/// Creates a string by interpreting the null-terminated platform string as
/// UTF-8 on Unix and UTF-16 on Windows.
@@ -20,7 +20,6 @@ extension String {
/// This means that, depending on the semantics of the specific platform,
/// conversion to a string and back might result in a value that's different
/// from the original platform string.
@_disfavoredOverload
public init(platformString: UnsafePointer<CInterop.PlatformChar>) {
self.init(_errorCorrectingPlatformString: platformString)
}
@@ -158,14 +157,14 @@ extension String {
/// only during the execution of this method.
/// Don't try to store the pointer for later use.
public func withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result
) throws(SystemError) -> Result {
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result {
try _withPlatformString(body)
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension CInterop.PlatformChar {
internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
#if os(Windows)
@@ -176,7 +175,7 @@ extension CInterop.PlatformChar {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension CInterop.PlatformUnicodeEncoding.CodeUnit {
internal var _platformChar: CInterop.PlatformChar {
#if os(Windows)
@@ -189,8 +188,8 @@ extension CInterop.PlatformUnicodeEncoding.CodeUnit {
internal protocol _PlatformStringable {
func _withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result
) throws(SystemError) -> Result
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result
init?(_platformString: UnsafePointer<CInterop.PlatformChar>)
}
@@ -0,0 +1,19 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
extension CInterop {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The C `int` type
public typealias Signal = CInt
#endif
}
@@ -0,0 +1,114 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// hangup
@_alwaysEmitIntoClient
internal var _SIGHUP: CInterop.Signal { SIGHUP }
/// interrupt
@_alwaysEmitIntoClient
internal var _SIGINT: CInterop.Signal { SIGINT }
/// quit
@_alwaysEmitIntoClient
internal var _SIGQUIT: CInterop.Signal { SIGQUIT }
/// illegal instruction (not reset when caught)
@_alwaysEmitIntoClient
internal var _SIGILL: CInterop.Signal { SIGILL }
/// trace trap (not reset when caught)
@_alwaysEmitIntoClient
internal var _SIGTRAP: CInterop.Signal { SIGTRAP }
/// abort()
@_alwaysEmitIntoClient
internal var _SIGABRT: CInterop.Signal { SIGABRT }
#if false
/// pollable event
@_alwaysEmitIntoClient
internal var _SIGPOLL: CInterop.Signal { SIGPOLL }
#endif
/// compatibility
@_alwaysEmitIntoClient
internal var _SIGIOT: CInterop.Signal { SIGIOT }
/// EMT instruction
@_alwaysEmitIntoClient
internal var _SIGEMT: CInterop.Signal { SIGEMT }
/// floating point exception
@_alwaysEmitIntoClient
internal var _SIGFPE: CInterop.Signal { SIGFPE }
/// kill (cannot be caught or ignored)
@_alwaysEmitIntoClient
internal var _SIGKILL: CInterop.Signal { SIGKILL }
/// bus error
@_alwaysEmitIntoClient
internal var _SIGBUS: CInterop.Signal { SIGBUS }
/// segmentation violation
@_alwaysEmitIntoClient
internal var _SIGSEGV: CInterop.Signal { SIGSEGV }
/// bad argument to system call
@_alwaysEmitIntoClient
internal var _SIGSYS: CInterop.Signal { SIGSYS }
/// write on a pipe with no one to read it
@_alwaysEmitIntoClient
internal var _SIGPIPE: CInterop.Signal { SIGPIPE }
/// alarm clock
@_alwaysEmitIntoClient
internal var _SIGALRM: CInterop.Signal { SIGALRM }
/// software termination signal from kill
@_alwaysEmitIntoClient
internal var _SIGTERM: CInterop.Signal { SIGTERM }
/// urgent condition on IO channel
@_alwaysEmitIntoClient
internal var _SIGURG: CInterop.Signal { SIGURG }
/// sendable stop signal not from tty
@_alwaysEmitIntoClient
internal var _SIGSTOP: CInterop.Signal { SIGSTOP }
/// stop signal from tty
@_alwaysEmitIntoClient
internal var _SIGTSTP: CInterop.Signal { SIGTSTP }
/// continue a stopped process
@_alwaysEmitIntoClient
internal var _SIGCONT: CInterop.Signal { SIGCONT }
/// to parent on child stop or exit
@_alwaysEmitIntoClient
internal var _SIGCHLD: CInterop.Signal { SIGCHLD }
/// to readers pgrp upon background tty read
@_alwaysEmitIntoClient
internal var _SIGTTIN: CInterop.Signal { SIGTTIN }
/// like TTIN for output if (tp->t_local&LTOSTOP)
@_alwaysEmitIntoClient
internal var _SIGTTOU: CInterop.Signal { SIGTTOU }
/// input/output possible signal
@_alwaysEmitIntoClient
internal var _SIGIO: CInterop.Signal { SIGIO }
/// exceeded CPU time limit
@_alwaysEmitIntoClient
internal var _SIGXCPU: CInterop.Signal { SIGXCPU }
/// exceeded file size limit
@_alwaysEmitIntoClient
internal var _SIGXFSZ: CInterop.Signal { SIGXFSZ }
/// virtual time alarm
@_alwaysEmitIntoClient
internal var _SIGVTALRM: CInterop.Signal { SIGVTALRM }
/// profiling time alarm
@_alwaysEmitIntoClient
internal var _SIGPROF: CInterop.Signal { SIGPROF }
/// window size changes
@_alwaysEmitIntoClient
internal var _SIGWINCH: CInterop.Signal { SIGWINCH }
/// information request
@_alwaysEmitIntoClient
internal var _SIGINFO: CInterop.Signal { SIGINFO }
/// user defined signal 1
@_alwaysEmitIntoClient
internal var _SIGUSR1: CInterop.Signal { SIGUSR1 }
/// user defined signal 2
@_alwaysEmitIntoClient
internal var _SIGUSR2: CInterop.Signal { SIGUSR2 }
#endif
+296
View File
@@ -0,0 +1,296 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public struct Signal: RawRepresentable {
/// The raw C signal value.
@_alwaysEmitIntoClient
public let rawValue: CInterop.Signal
/// Creates a strongly typed signal from a raw C signal value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Signal) { self.rawValue = rawValue }
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
extension Signal {
/// The corresponding C signal is `SIGHUP`.
@_alwaysEmitIntoClient
internal static var hangup: Self { Self(rawValue: _SIGHUP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "hangup")
internal static var SIGHUP: Self { hangup }
/// The corresponding C signal is `SIGINT`.
@_alwaysEmitIntoClient
internal static var interrupt: Self { Self(rawValue: _SIGINT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "interrupt")
internal static var SIGINT: Self { interrupt }
/// The corresponding C signal is `SIGQUIT`.
@_alwaysEmitIntoClient
internal static var quit: Self { Self(rawValue: _SIGQUIT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "quit")
internal static var SIGQUIT: Self { quit }
/// The corresponding C signal is `SIGILL`.
@_alwaysEmitIntoClient
internal static var illegalInstruction: Self { Self(rawValue: _SIGILL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "illegalInstruction")
internal static var SIGILL: Self { illegalInstruction }
/// The corresponding C signal is `SIGTRAP`.
@_alwaysEmitIntoClient
internal static var trap: Self { Self(rawValue: _SIGTRAP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "trap")
internal static var SIGTRAP: Self { trap }
/// The corresponding C signal is `SIGABRT`.
@_alwaysEmitIntoClient
internal static var abort: Self { Self(rawValue: _SIGABRT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "abort")
internal static var SIGABRT: Self { abort }
#if false
/// The corresponding C signal is `SIGPOLL`.
@_alwaysEmitIntoClient
internal static var pollableEvent: Self { Self(rawValue: _SIGPOLL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "pollableEvent")
internal static var SIGPOLL: Self { pollableEvent }
#endif
/// The corresponding C signal is `SIGIOT`.
@_alwaysEmitIntoClient
@available(*, deprecated, renamed: "abort")
internal static var inputOutputTrap: Self { Self(rawValue: _SIGIOT) }
@_alwaysEmitIntoClient
@available(*, deprecated)
@available(*, unavailable, renamed: "inputOutputTrap")
internal static var SIGIOT: Self { inputOutputTrap }
/// The corresponding C signal is `SIGEMT`.
@_alwaysEmitIntoClient
internal static var emulatorTrap: Self { Self(rawValue: _SIGEMT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "emulatorTrap")
internal static var SIGEMT: Self { emulatorTrap }
/// The corresponding C signal is `SIGFPE`.
@_alwaysEmitIntoClient
internal static var floatingPointException: Self { Self(rawValue: _SIGFPE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "floatingPointException")
internal static var SIGFPE: Self { floatingPointException }
/// The corresponding C signal is `SIGKILL`.
@_alwaysEmitIntoClient
internal static var kill: Self { Self(rawValue: _SIGKILL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "kill")
internal static var SIGKILL: Self { kill }
/// The corresponding C signal is `SIGBUS`.
@_alwaysEmitIntoClient
internal static var busError: Self { Self(rawValue: _SIGBUS) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "busError")
internal static var SIGBUS: Self { busError }
/// The corresponding C signal is `SIGSEGV`.
@_alwaysEmitIntoClient
internal static var segmentationViolation: Self { Self(rawValue: _SIGSEGV) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "segmentationViolation")
internal static var SIGSEGV: Self { segmentationViolation }
/// The corresponding C signal is `SIGSYS`.
@_alwaysEmitIntoClient
internal static var badSystemCall: Self { Self(rawValue: _SIGSYS) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "badSystemCall")
internal static var SIGSYS: Self { badSystemCall }
/// The corresponding C signal is `SIGPIPE`.
@_alwaysEmitIntoClient
internal static var brokenPipe: Self { Self(rawValue: _SIGPIPE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "brokenPipe")
internal static var SIGPIPE: Self { brokenPipe }
/// The corresponding C signal is `SIGALRM`.
@_alwaysEmitIntoClient
internal static var alarm: Self { Self(rawValue: _SIGALRM) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "alarm")
internal static var SIGALRM: Self { alarm }
/// The corresponding C signal is `SIGTERM`.
@_alwaysEmitIntoClient
internal static var terminationRequest: Self { Self(rawValue: _SIGTERM) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "terminationRequest")
internal static var SIGTERM: Self { terminationRequest }
/// The corresponding C signal is `SIGURG`.
@_alwaysEmitIntoClient
internal static var urgentInputOutput: Self { Self(rawValue: _SIGURG) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "urgentInputOutput")
internal static var SIGURG: Self { urgentInputOutput }
/// The corresponding C signal is `SIGSTOP`.
@_alwaysEmitIntoClient
internal static var stop: Self { Self(rawValue: _SIGSTOP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "stop")
internal static var SIGSTOP: Self { stop }
/// The corresponding C signal is `SIGTSTP`.
@_alwaysEmitIntoClient
internal static var interactiveStop: Self { Self(rawValue: _SIGTSTP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "interactiveStop")
internal static var SIGTSTP: Self { interactiveStop }
/// The corresponding C signal is `SIGCONT`.
@_alwaysEmitIntoClient
internal static var `continue`: Self { Self(rawValue: _SIGCONT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "continue")
internal static var SIGCONT: Self { `continue` }
/// The corresponding C signal is `SIGCHLD`.
@_alwaysEmitIntoClient
internal static var childStopOrExit: Self { Self(rawValue: _SIGCHLD) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "childStopOrExit")
internal static var SIGCHLD: Self { childStopOrExit }
/// The corresponding C signal is `SIGTTIN`.
@_alwaysEmitIntoClient
internal static var backgroundRead: Self { Self(rawValue: _SIGTTIN) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "backgroundRead")
internal static var SIGTTIN: Self { backgroundRead }
/// The corresponding C signal is `SIGTTOU`.
@_alwaysEmitIntoClient
internal static var backgroundWrite: Self { Self(rawValue: _SIGTTOU) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "backgroundWrite")
internal static var SIGTTOU: Self { backgroundWrite }
/// The corresponding C signal is `SIGIO`.
@_alwaysEmitIntoClient
internal static var possibleInputOutput: Self { Self(rawValue: _SIGIO) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "possibleInputOutput")
internal static var SIGIO: Self { possibleInputOutput }
/// The corresponding C signal is `SIGXCPU`.
@_alwaysEmitIntoClient
internal static var exceededCPUTimeLimit: Self { Self(rawValue: _SIGXCPU) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "exceededCPUTimeLimit")
internal static var SIGXCPU: Self { exceededCPUTimeLimit }
/// The corresponding C signal is `SIGXFSZ`.
@_alwaysEmitIntoClient
internal static var exceededFileSizeLimit: Self { Self(rawValue: _SIGXFSZ) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "exceededFileSizeLimit")
internal static var SIGXFSZ: Self { exceededFileSizeLimit }
/// The corresponding C signal is `SIGVTALRM`.
@_alwaysEmitIntoClient
internal static var virtualAlarm: Self { Self(rawValue: _SIGVTALRM) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "virtualAlarm")
internal static var SIGVTALRM: Self { virtualAlarm }
/// The corresponding C signal is `SIGPROF`.
@_alwaysEmitIntoClient
internal static var profilingAlarm: Self { Self(rawValue: _SIGPROF) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "profilingAlarm")
internal static var SIGPROF: Self { profilingAlarm }
/// The corresponding C signal is `SIGWINCH`.
@_alwaysEmitIntoClient
internal static var windowSizeChange: Self { Self(rawValue: _SIGWINCH) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "windowSizeChange")
internal static var SIGWINCH: Self { windowSizeChange }
/// The corresponding C signal is `SIGINFO`.
@_alwaysEmitIntoClient
internal static var informationRequest: Self { Self(rawValue: _SIGINFO) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "informationRequest")
internal static var SIGINFO: Self { informationRequest }
/// The corresponding C signal is `SIGUSR1`.
@_alwaysEmitIntoClient
internal static var userDefined1: Self { Self(rawValue: _SIGUSR1) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "userDefined1")
internal static var SIGUSR1: Self { userDefined1 }
/// The corresponding C signal is `SIGUSR2`.
@_alwaysEmitIntoClient
internal static var userDefined2: Self { Self(rawValue: _SIGUSR2) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "userDefined2")
internal static var SIGUSR2: Self { userDefined2 }
}
#endif
+18
View File
@@ -0,0 +1,18 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public struct SignalSet {
}
#endif
+20
View File
@@ -0,0 +1,20 @@
//
// File.swift
//
//
// Created by Rauhul Varma on 6/16/23.
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: this is wrong and should be done with wrapping fcntrl
// FIXME: go through and figure out the right way to express `at` methods
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
public struct ControlFlags {
let rawValue: Int32
// Test stub
public static var none: ControlFlags = ControlFlags(rawValue: 0)
// Out of scope of this sketch
}
}
#endif
+234
View File
@@ -0,0 +1,234 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: Document
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileFlags: OptionSet, Hashable, Codable {
/// The raw C file flags.
@_alwaysEmitIntoClient
public let rawValue: CInterop.FileFlags
/// Create a strongly-typed file flags from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.FileFlags) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInterop.FileFlags) { self.init(rawValue: raw) }
/// Do not dump the file. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_NODUMP`
@_alwaysEmitIntoClient
public static var noDump: FileFlags { FileFlags(_UF_NODUMP) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "noDump")
public static var UF_NODUMP: FileFlags { noDump }
/// The file may not be changed. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_IMMUTABLE`
@_alwaysEmitIntoClient
public static var immutable: FileFlags { FileFlags(_UF_IMMUTABLE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "immutable")
public static var UF_IMMUTABLE: FileFlags { immutable }
/// The file may only be appended to. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_APPEND`
@_alwaysEmitIntoClient
public static var appendOnly: FileFlags { FileFlags(_UF_APPEND) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "appendOnly")
public static var UF_APPEND: FileFlags { appendOnly }
/// The directory is opaque when viewed through a union stack. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_OPAQUE`
@_alwaysEmitIntoClient
public static var opaque: FileFlags { FileFlags(_UF_OPAQUE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "opaque")
public static var UF_OPAQUE: FileFlags { opaque }
// #if os(FreeBSD)
// /// The file may not be removed or renamed. Modifiable by file owner or super-user.
// ///
// /// The corresponding C constant is `UF_NOUNLINK`
// @_alwaysEmitIntoClient
// public static var noUnlink: FileFlags { FileFlags(_UF_NOUNLINK) }
//
// @_alwaysEmitIntoClient
// @available(*, unavailable, renamed: "noUnlink")
// public static var UF_NOUNLINK: FileFlags { noUnlink }
// #endif
/// The file is compressed (some file-systems). Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_COMPRESSED`
@_alwaysEmitIntoClient
public static var compressed: FileFlags { FileFlags(_UF_COMPRESSED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "compressed")
public static var UF_COMPRESSED: FileFlags { compressed }
/// No notifications will be issued for deletes or renames. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_TRACKED`
@_alwaysEmitIntoClient
public static var tracked: FileFlags { FileFlags(_UF_TRACKED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "tracked")
public static var UF_TRACKED: FileFlags { tracked }
/// The file requires entitlement required for reading and writing. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_DATAVAULT`
@_alwaysEmitIntoClient
public static var dataVault: FileFlags { FileFlags(_UF_DATAVAULT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "dataVault")
public static var UF_DATAVAULT: FileFlags { dataVault }
/// The file or directory is not intended to be displayed to the user. Modifiable by file owner or super-user.
///
/// The corresponding C constant is `UF_HIDDEN`
@_alwaysEmitIntoClient
public static var hidden: FileFlags { FileFlags(_UF_HIDDEN) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "hidden")
public static var UF_HIDDEN: FileFlags { hidden }
/// The file has been archived. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_ARCHIVED`
@_alwaysEmitIntoClient
public static var superUserArchived: FileFlags { FileFlags(_SF_ARCHIVED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserArchived")
public static var SF_ARCHIVED: FileFlags { superUserArchived }
/// The file may not be changed. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_IMMUTABLE`
@_alwaysEmitIntoClient
public static var superUserImmutable: FileFlags { FileFlags(_SF_IMMUTABLE) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserImmutable")
public static var SF_IMMUTABLE: FileFlags { superUserImmutable }
/// The file may only be appended to. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_APPEND`
@_alwaysEmitIntoClient
public static var superUserAppend: FileFlags { FileFlags(_SF_APPEND) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserAppend")
public static var SF_APPEND: FileFlags { superUserAppend }
/// The file requires entitlement required for reading and writing. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_RESTRICTED`
@_alwaysEmitIntoClient
public static var superUserRestricted: FileFlags { FileFlags(_SF_RESTRICTED) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserRestricted")
public static var SF_RESTRICTED: FileFlags { superUserRestricted }
/// The file may not be removed, renamed or mounted on. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_NOUNLINK`
@_alwaysEmitIntoClient
public static var superUserNoUnlink: FileFlags { FileFlags(_SF_NOUNLINK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserNoUnlink")
public static var SF_NOUNLINK: FileFlags { superUserNoUnlink }
// #if os(FreeBSD)
// /// The file is a snapshot file. Only modifiable by the super-user.
// ///
// /// The corresponding C constant is `SF_SNAPSHOT`
// @_alwaysEmitIntoClient
// public static var superUserSnapshot: FileFlags { FileFlags(_SF_SNAPSHOT) }
//
// @_alwaysEmitIntoClient
// @available(*, unavailable, renamed: "superUserSnapshot")
// public static var SF_SNAPSHOT: FileFlags { superUserSnapshot }
// #endif
/// The file is a firmlink. Only modifiable by the super-user.
///
/// The corresponding C constant is `SF_FIRMLINK`
@_alwaysEmitIntoClient
public static var superUserFirmlink: FileFlags { FileFlags(_SF_FIRMLINK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "superUserFirmlink")
public static var SF_FIRMLINK: FileFlags { superUserFirmlink }
/// The file is a dataless placeholder. The system will attempt to materialize it when accessed according to the dataless file materialization policy of the accessing thread or process. Cannot be modified in user-space.
///
/// The corresponding C constant is `SF_DATALESS`
@_alwaysEmitIntoClient
public static var kernelDataless: FileFlags { FileFlags(_SF_DATALESS) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "kernelDataless")
public static var SF_DATALESS: FileFlags { kernelDataless }
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileFlags
: CustomStringConvertible, CustomDebugStringConvertible
{
/// A textual representation of the file permissions.
@inline(never)
public var description: String {
let descriptions: [(Element, StaticString)] = [
(.noDump, ".noDump"),
(.immutable, ".immutable"),
(.appendOnly, ".appendOnly"),
(.opaque, ".opaque"),
(.compressed, ".compressed"),
(.tracked, ".tracked"),
(.dataVault, ".dataVault"),
(.hidden, ".hidden"),
(.superUserArchived, ".superUserArchived"),
(.superUserImmutable, ".superUserImmutable"),
(.superUserAppend, ".superUserAppend"),
(.superUserRestricted, ".superUserRestricted"),
(.superUserNoUnlink, ".superUserNoUnlink"),
(.superUserFirmlink, ".superUserFirmlink"),
(.kernelDataless, ".kernelDataless"),
]
return _buildDescription(descriptions)
}
/// A textual representation of the file permissions, suitable for debugging.
public var debugDescription: String { self.description }
}
#endif
+47
View File
@@ -0,0 +1,47 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: should the subtypes of Mode mask their rawValues to only allow their bits to be changed?
/// The superset of access permissions and type for a file.
///
/// The following example creates an instance of the `FileMode` structure
/// from a raw octal literal and reads the file type from it:
///
/// let mode = FileMode(rawValue: 0o140000)
/// mode.type == .socket // true
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileMode: RawRepresentable {
/// The raw C file mode.
@_alwaysEmitIntoClient
public var rawValue: CInterop.Mode
/// Create a strongly-typed file mode from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
/// Subset of mode for accessing and modifying file permissions.
@_alwaysEmitIntoClient
public var permissions: FilePermissions {
get { FilePermissions(rawValue: rawValue & _MODE_PERMISSIONS) }
set { rawValue = (rawValue & ~_MODE_PERMISSIONS) | (newValue.rawValue & _MODE_PERMISSIONS ) }
}
/// Subset of mode for accessing and modifying file type.
@_alwaysEmitIntoClient
public var type: FileType {
get { FileType(rawValue: rawValue & _MODE_TYPE) }
set { rawValue = (rawValue & ~_MODE_TYPE) | (newValue.rawValue & _MODE_TYPE ) }
}
}
#endif
@@ -17,8 +17,8 @@
/// let perms = FilePermissions(rawValue: 0o644)
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
@frozen
@available(System 0.0.1, *)
public struct FilePermissions: OptionSet, Sendable, Hashable {
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
public struct FilePermissions: OptionSet, Hashable, Codable {
/// The raw C file permissions.
@_alwaysEmitIntoClient
public let rawValue: CModeT
@@ -27,101 +27,104 @@ public struct FilePermissions: OptionSet, Sendable, Hashable {
@_alwaysEmitIntoClient
public init(rawValue: CModeT) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CModeT) { self.init(rawValue: raw) }
/// Indicates that other users have read-only permission.
@_alwaysEmitIntoClient
public static var otherRead: FilePermissions { .init(rawValue: 0o4) }
public static var otherRead: FilePermissions { FilePermissions(0o4) }
/// Indicates that other users have write-only permission.
@_alwaysEmitIntoClient
public static var otherWrite: FilePermissions { .init(rawValue: 0o2) }
public static var otherWrite: FilePermissions { FilePermissions(0o2) }
/// Indicates that other users have execute-only permission.
@_alwaysEmitIntoClient
public static var otherExecute: FilePermissions { .init(rawValue: 0o1) }
public static var otherExecute: FilePermissions { FilePermissions(0o1) }
/// Indicates that other users have read-write permission.
@_alwaysEmitIntoClient
public static var otherReadWrite: FilePermissions { .init(rawValue: 0o6) }
public static var otherReadWrite: FilePermissions { FilePermissions(0o6) }
/// Indicates that other users have read-execute permission.
@_alwaysEmitIntoClient
public static var otherReadExecute: FilePermissions { .init(rawValue: 0o5) }
public static var otherReadExecute: FilePermissions { FilePermissions(0o5) }
/// Indicates that other users have write-execute permission.
@_alwaysEmitIntoClient
public static var otherWriteExecute: FilePermissions { .init(rawValue: 0o3) }
public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) }
/// Indicates that other users have read, write, and execute permission.
@_alwaysEmitIntoClient
public static var otherReadWriteExecute: FilePermissions { .init(rawValue: 0o7) }
public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) }
/// Indicates that the group has read-only permission.
@_alwaysEmitIntoClient
public static var groupRead: FilePermissions { .init(rawValue: 0o40) }
public static var groupRead: FilePermissions { FilePermissions(0o40) }
/// Indicates that the group has write-only permission.
@_alwaysEmitIntoClient
public static var groupWrite: FilePermissions { .init(rawValue: 0o20) }
public static var groupWrite: FilePermissions { FilePermissions(0o20) }
/// Indicates that the group has execute-only permission.
@_alwaysEmitIntoClient
public static var groupExecute: FilePermissions { .init(rawValue: 0o10) }
public static var groupExecute: FilePermissions { FilePermissions(0o10) }
/// Indicates that the group has read-write permission.
@_alwaysEmitIntoClient
public static var groupReadWrite: FilePermissions { .init(rawValue: 0o60) }
public static var groupReadWrite: FilePermissions { FilePermissions(0o60) }
/// Indicates that the group has read-execute permission.
@_alwaysEmitIntoClient
public static var groupReadExecute: FilePermissions { .init(rawValue: 0o50) }
public static var groupReadExecute: FilePermissions { FilePermissions(0o50) }
/// Indicates that the group has write-execute permission.
@_alwaysEmitIntoClient
public static var groupWriteExecute: FilePermissions { .init(rawValue: 0o30) }
public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) }
/// Indicates that the group has read, write, and execute permission.
@_alwaysEmitIntoClient
public static var groupReadWriteExecute: FilePermissions { .init(rawValue: 0o70) }
public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) }
/// Indicates that the owner has read-only permission.
@_alwaysEmitIntoClient
public static var ownerRead: FilePermissions { .init(rawValue: 0o400) }
public static var ownerRead: FilePermissions { FilePermissions(0o400) }
/// Indicates that the owner has write-only permission.
@_alwaysEmitIntoClient
public static var ownerWrite: FilePermissions { .init(rawValue: 0o200) }
public static var ownerWrite: FilePermissions { FilePermissions(0o200) }
/// Indicates that the owner has execute-only permission.
@_alwaysEmitIntoClient
public static var ownerExecute: FilePermissions { .init(rawValue: 0o100) }
public static var ownerExecute: FilePermissions { FilePermissions(0o100) }
/// Indicates that the owner has read-write permission.
@_alwaysEmitIntoClient
public static var ownerReadWrite: FilePermissions { .init(rawValue: 0o600) }
public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) }
/// Indicates that the owner has read-execute permission.
@_alwaysEmitIntoClient
public static var ownerReadExecute: FilePermissions { .init(rawValue: 0o500) }
public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) }
/// Indicates that the owner has write-execute permission.
@_alwaysEmitIntoClient
public static var ownerWriteExecute: FilePermissions { .init(rawValue: 0o300) }
public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) }
/// Indicates that the owner has read, write, and execute permission.
@_alwaysEmitIntoClient
public static var ownerReadWriteExecute: FilePermissions { .init(rawValue: 0o700) }
public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) }
/// Indicates that the file is executed as the owner.
///
/// For more information, see the `setuid(2)` man page.
@_alwaysEmitIntoClient
public static var setUserID: FilePermissions { .init(rawValue: 0o4000) }
public static var setUserID: FilePermissions { FilePermissions(0o4000) }
/// Indicates that the file is executed as the group.
///
/// For more information, see the `setgid(2)` man page.
@_alwaysEmitIntoClient
public static var setGroupID: FilePermissions { .init(rawValue: 0o2000) }
public static var setGroupID: FilePermissions { FilePermissions(0o2000) }
/// Indicates that executable's text segment
/// should be kept in swap space even after it exits.
@@ -129,10 +132,10 @@ public struct FilePermissions: OptionSet, Sendable, Hashable {
/// For more information, see the `chmod(2)` man page's
/// discussion of `S_ISVTX` (the sticky bit).
@_alwaysEmitIntoClient
public static var saveText: FilePermissions { .init(rawValue: 0o1000) }
public static var saveText: FilePermissions { FilePermissions(0o1000) }
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePermissions
: CustomStringConvertible, CustomDebugStringConvertible
{
@@ -173,7 +176,6 @@ extension FilePermissions
public var debugDescription: String { self.description }
}
#if !$Embedded
@available(System 0.0.1, *)
extension FilePermissions: Codable {}
#if compiler(>=5.5) && canImport(_Concurrency)
extension FilePermissions: Sendable {}
#endif
+90
View File
@@ -0,0 +1,90 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
// FIXME: Document
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileStatus: RawRepresentable {
/// The raw C file status.
@_alwaysEmitIntoClient
public let rawValue: CInterop.Stat
/// Create a strongly-typed file status from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Stat) { self.rawValue = rawValue }
// FIXME: replace with swift type DeviceID that splits out major/minor
/// ID of device containing file.
@_alwaysEmitIntoClient
public var deviceID: CInterop.DeviceID { rawValue.st_dev }
/// Mode of file.
@_alwaysEmitIntoClient
public var mode: FileMode { FileMode(rawValue: rawValue.st_mode) }
/// Number of hard links.
@_alwaysEmitIntoClient
public var hardLinkCount: CInterop.NumberOfLinks { rawValue.st_nlink }
/// File serial number.
@_alwaysEmitIntoClient
public var inodeNumber: CInterop.INodeNumber { rawValue.st_ino }
/// User ID of the file.
@_alwaysEmitIntoClient
public var userID: CInterop.UserID { rawValue.st_uid }
/// Group ID of the file.
@_alwaysEmitIntoClient
public var groupID: CInterop.GroupID { rawValue.st_gid }
/// Device ID.
@_alwaysEmitIntoClient
public var rDeviceID: CInterop.DeviceID { rawValue.st_rdev }
/// Time of last access.
@_alwaysEmitIntoClient
public var accessTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_atimespec) }
/// Time of last data modification.
@_alwaysEmitIntoClient
public var modifyTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_mtimespec) }
/// Time of last status change.
@_alwaysEmitIntoClient
public var statusChangeTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_ctimespec) }
/// Time of file creation.
@_alwaysEmitIntoClient
public var creationTime: TimeSpecification { TimeSpecification(rawValue: rawValue.st_birthtimespec) }
/// File size, in bytes.
@_alwaysEmitIntoClient
public var fileSize: CInterop.Offset { rawValue.st_size }
/// Blocks allocated for file.
@_alwaysEmitIntoClient
public var blockCount: CInterop.BlockCount { rawValue.st_blocks }
/// Optimal block size for I/O.
@_alwaysEmitIntoClient
public var blockSize: CInterop.BlockSize { rawValue.st_blksize }
/// User defined flags for file.
@_alwaysEmitIntoClient
public var fileFlags: FileFlags { FileFlags(rawValue: rawValue.st_flags) }
/// File generation number.
@_alwaysEmitIntoClient
public var generationID: CInterop.GenerationID { rawValue.st_gen }
}
#endif
+109
View File
@@ -0,0 +1,109 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: Document
@frozen
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
public struct FileType: RawRepresentable {
/// The raw C file type.
@_alwaysEmitIntoClient
public var rawValue: CInterop.Mode
/// Create a strongly-typed file type from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
/// Named pipe (fifo)
///
/// The corresponding C constant is `S_IFIFO`
@_alwaysEmitIntoClient
public static var fifo: FileType { FileType(_S_IFIFO) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "fifo")
public static var S_IFIFO: FileType { fifo }
/// Character special
///
/// The corresponding C constant is `S_IFCHR`
@_alwaysEmitIntoClient
public static var characterDevice: FileType { FileType(_S_IFCHR) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "characterDevice")
public static var S_IFCHR: FileType { characterDevice }
/// Directory
///
/// The corresponding C constant is `S_IFDIR`
@_alwaysEmitIntoClient
public static var directory: FileType { FileType(_S_IFDIR) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "directory")
public static var S_IFDIR: FileType { directory }
/// Block special
///
/// The corresponding C constant is `S_IFBLK`
@_alwaysEmitIntoClient
public static var blockDevice: FileType { FileType(_S_IFBLK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "blockDevice")
public static var S_IFBLK: FileType { blockDevice }
/// Regular
///
/// The corresponding C constant is `S_IFREG`
@_alwaysEmitIntoClient
public static var regular: FileType { FileType(_S_IFREG) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "regular")
public static var S_IFREG: FileType { regular }
/// Symbolic link
///
/// The corresponding C constant is `S_IFLNK`
@_alwaysEmitIntoClient
public static var symbolicLink: FileType { FileType(_S_IFLNK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "symbolicLink")
public static var S_IFLNK: FileType { symbolicLink }
/// Socket
///
/// The corresponding C constant is `S_IFSOCK`
@_alwaysEmitIntoClient
public static var socket: FileType { FileType(_S_IFSOCK) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "socket")
public static var S_IFSOCK: FileType { socket }
/// Whiteout
///
/// The corresponding C constant is `S_IFWHT`
@_alwaysEmitIntoClient
// FIXME: rename with inclusive language
public static var whiteout: FileType { FileType(_S_IFWHT) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "whiteout")
public static var S_IFWHT: FileType { whiteout }
}
#endif
@@ -0,0 +1,162 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - stat
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
/// Obtain information about the file pointed to by the FileDescriptor.
///
/// - Parameters:
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: A `FileStatus` for the file pointed to by `self`.
///
/// The corresponding C function is `fstat`.
@_alwaysEmitIntoClient
public func getFileStatus(
retryOnInterrupt: Bool = true
) throws -> FileStatus {
try _getFileStatus(
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _getFileStatus(
retryOnInterrupt: Bool = true
) -> Result<FileStatus, Errno> {
var result = CInterop.Stat()
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fstat(self.rawValue, &result)
}.map { FileStatus(rawValue: result) }
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chmod
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
public func changeFileMode(
to mode: FileMode,
retryOnInterrupt: Bool = true
) throws {
try _changeFileMode(
to: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileMode(
to mode: FileMode,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchmod(self.rawValue, mode.rawValue)
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chown
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
public func changeFileOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
retryOnInterrupt: Bool = true
) throws {
try _changeFileOwner(
to: owner,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchown(self.rawValue, owner.userID, owner.groupID)
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chflags
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
internal func changeFileFlags(
to flags: FileFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileFlags(
to: flags,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileFlags(
to flags: FileFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchflags(self.rawValue, flags.rawValue)
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - utimens
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileDescriptor {
@_alwaysEmitIntoClient
public func changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
retryOnInterrupt: Bool = true
) throws {
try _changeFileTimes(
to: times,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
if let times = times {
return withUnsafePointer(to: times) { tuplePtr in
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
timespecPtr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_futimens(self.rawValue, timespecPtr)
}
}
}
} else {
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_futimens(self.rawValue, nil)
}
}
}
}
#endif
@@ -0,0 +1,24 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - umask
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FileMode {
@_alwaysEmitIntoClient
func updateProcessMask() -> Self {
_updateProcessMask()
}
@usableFromInline
func _updateProcessMask() -> Self {
Self(rawValue: system_umask(self.rawValue))
}
}
#endif
@@ -0,0 +1,544 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - stat
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
/// Obtain information about the file pointed to by the FilePath.
///
/// - Parameters:
/// - followSymlinks: Whether to follow symlinks.
/// The default is `true`.
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: A `FileStatus` for the file pointed to by `self`.
///
/// Read, write or execute permission of the pointed to file is not required,
/// but all intermediate directories must be searchable.
///
/// The corresponding C functions are `stat` and `lstat`.
@_alwaysEmitIntoClient
public func getFileStatus(
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws -> FileStatus {
try _getFileStatus(
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _getFileStatus(
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<FileStatus, Errno> {
var result = CInterop.Stat()
let fn = followSymlinks ? system_lstat : system_stat
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, &result)
}.map { FileStatus(rawValue: result) }
}
}
/// Obtain information about the file pointed to by the FilePath relative to
/// the provided FileDescriptor.
///
/// - Parameters:
/// - relativeTo: if `self` is relative, treat it as relative to this file descriptor
/// rather than relative to the current working directory.
/// - followSymlinks: Whether to follow symlinks.
/// The default is `true`.
/// - retryOnInterrupt: Whether to retry the read operation
/// if it throws ``Errno/interrupted``.
/// The default is `true`.
/// Pass `false` to try only once and throw an error upon interruption.
/// - Returns: A `FileStatus` for the file pointed to by `self`.
///
/// Read, write or execute permission of the pointed to file is not required,
/// but all intermediate directories must be searchable.
///
/// The corresponding C function is `fstatat`.
@_alwaysEmitIntoClient
public func getFileStatus(
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws -> FileStatus {
try _getFileStatus(
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _getFileStatus(
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<FileStatus, Errno> {
var result = CInterop.Stat()
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fstatat(fd.rawValue, ptr, &result, fcntrl.rawValue)
}.map { FileStatus(rawValue: result) }
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chmod
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func changeFileMode(
to mode: FileMode,
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeFileMode(
to: mode,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileMode(
to mode: FileMode,
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_lchmod : system_chmod
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, mode.rawValue)
}
}
}
// valid flags: AT_SYMLINK_NOFOLLOW | AT_REALDEV | AT_FDONLY
@_alwaysEmitIntoClient
public func changeFileMode(
to mode: FileMode,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileMode(
to: mode,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileMode(
to mode: FileMode,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
self.withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchmodat(fd.rawValue, ptr, mode.rawValue, fcntrl.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chown
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeOwner(
to: owner,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_lchown : system_chown
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, owner.userID, owner.groupID)
}
}
}
@_alwaysEmitIntoClient
public func changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeOwner(
to: owner,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeOwner(
to owner: (userID: CInterop.UserID, groupID: CInterop.GroupID),
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
self.withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fchownat(
fd.rawValue, ptr, owner.userID, owner.groupID, fcntrl.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - chflags
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func changeFileFlags(
to flags: FileFlags,
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeFileFlags(
to: flags,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileFlags(
to flags: FileFlags,
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_lchflags : system_chflags
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, flags.rawValue)
}
}
}
#if os(FreeBSD)
@_alwaysEmitIntoClient
public func changeFileFlags(
to flags: FileFlags,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileFlags(
to: flags,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileFlags(
to flags: FileFlags,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
return withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_chflagsat(fd.rawValue, ptr, flags.rawValue, fcntrl.rawValue)
}
}
}
#endif
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mkfifo
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func makeFIFO(
withMode mode: FileMode,
retryOnInterrupt: Bool = true) throws {
try _makeFIFO(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _makeFIFO(
withMode mode: FileMode,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkfifo(ptr, mode.rawValue)
}
}
}
@available(macOS 13.0, *)
@_alwaysEmitIntoClient
public func makeFIFO(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool = true) throws {
try _makeFIFO(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(macOS 13.0, *)
@usableFromInline
internal func _makeFIFO(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkfifoat(fd.rawValue, ptr, mode.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mknod
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
retryOnInterrupt: Bool = true) throws {
try _makeNode(
withMode: mode,
andDeviceID: deviceID,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mknod(ptr, mode.rawValue, deviceID)
}
}
}
@available(macOS 13.0, *)
@_alwaysEmitIntoClient
public func makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool = true) throws {
try _makeNode(
withMode: mode,
andDeviceID: deviceID,
relativeTo: fd,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(macOS 13.0, *)
@usableFromInline
internal func _makeNode(
withMode mode: FileMode,
andDeviceID deviceID: CInterop.DeviceID,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mknodat(fd.rawValue, ptr, mode.rawValue, deviceID)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mkdir
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
@_alwaysEmitIntoClient
public func makeDirectory(
withMode mode: FileMode,
retryOnInterrupt: Bool = true) throws {
try _makeDirectory(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _makeDirectory(
withMode mode: FileMode,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkdir(ptr, mode.rawValue)
}
}
}
@available(macOS 13.0, *)
@_alwaysEmitIntoClient
public func makeDirectory(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool = true) throws {
try _makeDirectory(
withMode: mode,
retryOnInterrupt: retryOnInterrupt
).get()
}
@available(macOS 13.0, *)
@usableFromInline
internal func _makeDirectory(
withMode mode: FileMode,
relativeTo fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
withPlatformString { ptr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_mkdirat(fd.rawValue, ptr, mode.rawValue)
}
}
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// MARK: - mkdir
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
extension FilePath {
#if os(FreeBSD)
@_alwaysEmitIntoClient
public func changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
followSymlinks: Bool = true,
retryOnInterrupt: Bool = true
) throws {
try _changeFileTimes(
to: times,
followSymlinks: followSymlinks,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
followSymlinks: Bool,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
let fn = followSymlinks ? system_utimens : system_lutimens
return withPlatformString { ptr in
if let times = times {
return withUnsafePointer(to: times) { tuplePtr in
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
timespecPtr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, timespecPtr)
}
}
}
} else {
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
fn(ptr, nil)
}
}
}
}
#endif
@_alwaysEmitIntoClient
public func changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool = true
) throws {
try _changeFileTimes(
to: times,
relativeTo: fd,
fcntrl: fcntrl,
retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal func _changeFileTimes(
to times: (access: TimeSpecification, modification: TimeSpecification)?,
relativeTo fd: FileDescriptor,
fcntrl: FileDescriptor.ControlFlags,
retryOnInterrupt: Bool
) -> Result<Void, Errno> {
self.withPlatformString { ptr in
if let times = times {
return withUnsafePointer(to: times) { tuplePtr in
tuplePtr.withMemoryRebound(to: CInterop.TimeSpec.self, capacity: 2) {
timespecPtr in
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_utimensat(fd.rawValue, ptr, timespecPtr, fcntrl.rawValue)
}
}
}
} else {
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_utimensat(fd.rawValue, ptr, nil, fcntrl.rawValue)
}
}
}
}
}
#endif
+52
View File
@@ -0,0 +1,52 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(Windows)
import CSystem
import ucrt
#endif
extension CInterop {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The C `stat` type.
public typealias Stat = stat
/// The C `mode_t` type.
public typealias Mode = mode_t
/// The C `uid_t` type.
public typealias UserID = uid_t
/// The C `gid_t` type.
public typealias GroupID = gid_t
/// The C `dev_t` type.
public typealias DeviceID = dev_t
/// The C `nlink_t` type.
public typealias NumberOfLinks = nlink_t
/// The C `ino_t` type.
public typealias INodeNumber = ino_t
/// The C `timespec` type.
public typealias TimeSpec = timespec
/// The C `off_t` type.
public typealias Offset = off_t
/// The C `blkcnt_t` type.
public typealias BlockCount = blkcnt_t
/// The C `blksize_t` type.
public typealias BlockSize = blksize_t
/// The C `UInt32` type.
public typealias GenerationID = UInt32
/// The C `UInt32` type.
public typealias FileFlags = UInt32
#endif
#if os(Windows)
public typealias Mode = CInt
#endif
}
+116
View File
@@ -0,0 +1,116 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
// MARK: - Mode Masks
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// mode_t: type ugs rwx rwx rwx
@_alwaysEmitIntoClient
internal var _MODE_PERMISSIONS: CInterop.Mode { 0b0000_111_111_111_111 }
@_alwaysEmitIntoClient
internal var _MODE_TYPE: CInterop.Mode { 0b1111_000_000_000_000 }
#endif
// MARK: - File Type
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _S_IFIFO: CInterop.Mode { S_IFIFO }
@_alwaysEmitIntoClient
internal var _S_IFCHR: CInterop.Mode { S_IFCHR }
@_alwaysEmitIntoClient
internal var _S_IFDIR: CInterop.Mode { S_IFDIR }
@_alwaysEmitIntoClient
internal var _S_IFBLK: CInterop.Mode { S_IFBLK }
@_alwaysEmitIntoClient
internal var _S_IFREG: CInterop.Mode { S_IFREG }
@_alwaysEmitIntoClient
internal var _S_IFLNK: CInterop.Mode { S_IFLNK }
@_alwaysEmitIntoClient
internal var _S_IFSOCK: CInterop.Mode { S_IFSOCK }
@_alwaysEmitIntoClient
internal var _S_IFWHT: CInterop.Mode { S_IFWHT }
#endif
// MARK: - File Flags
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _UF_NODUMP: CInterop.FileFlags { UInt32(bitPattern: UF_NODUMP) }
@_alwaysEmitIntoClient
internal var _UF_IMMUTABLE: CInterop.FileFlags { UInt32(bitPattern: UF_IMMUTABLE) }
@_alwaysEmitIntoClient
internal var _UF_APPEND: CInterop.FileFlags { UInt32(bitPattern: UF_APPEND) }
@_alwaysEmitIntoClient
internal var _UF_OPAQUE: CInterop.FileFlags { UInt32(bitPattern: UF_OPAQUE) }
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _UF_NOUNLINK: CInterop.FileFlags { UInt32(bitPattern: UF_NOUNLINK) }
#endif
@_alwaysEmitIntoClient
internal var _UF_COMPRESSED: CInterop.FileFlags { UInt32(bitPattern: UF_COMPRESSED) }
@_alwaysEmitIntoClient
internal var _UF_TRACKED: CInterop.FileFlags { UInt32(bitPattern: UF_TRACKED) }
@_alwaysEmitIntoClient
internal var _UF_DATAVAULT: CInterop.FileFlags { UInt32(bitPattern: UF_DATAVAULT) }
@_alwaysEmitIntoClient
internal var _UF_HIDDEN: CInterop.FileFlags { UInt32(bitPattern: UF_HIDDEN) }
@_alwaysEmitIntoClient
internal var _SF_ARCHIVED: CInterop.FileFlags { UInt32(bitPattern: SF_ARCHIVED) }
@_alwaysEmitIntoClient
internal var _SF_IMMUTABLE: CInterop.FileFlags { UInt32(bitPattern: SF_IMMUTABLE) }
@_alwaysEmitIntoClient
internal var _SF_APPEND: CInterop.FileFlags { UInt32(bitPattern: SF_APPEND) }
@_alwaysEmitIntoClient
internal var _SF_RESTRICTED: CInterop.FileFlags { UInt32(bitPattern: SF_RESTRICTED) }
@_alwaysEmitIntoClient
internal var _SF_NOUNLINK: CInterop.FileFlags { UInt32(bitPattern: SF_NOUNLINK) }
#if os(FreeBSD)
@_alwaysEmitIntoClient
internal var _SF_SNAPSHOT: CInterop.FileFlags { UInt32(bitPattern: SF_SNAPSHOT) }
#endif
@_alwaysEmitIntoClient
internal var _SF_FIRMLINK: CInterop.FileFlags { UInt32(bitPattern: SF_FIRMLINK) }
@_alwaysEmitIntoClient
internal var _SF_DATALESS: CInterop.FileFlags { UInt32(bitPattern: SF_DATALESS) }
#endif
// MARK: - Time Specification
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _UTIME_NOW: Int { Int(UTIME_NOW) }
@_alwaysEmitIntoClient
internal var _UTIME_OMIT: Int { Int(UTIME_OMIT) }
#endif
+296
View File
@@ -0,0 +1,296 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
internal func system_stat(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ buf: UnsafeMutablePointer<stat>
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, buf) }
#endif
return stat(path, buf)
}
internal func system_lstat(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ buf: UnsafeMutablePointer<stat>
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, buf) }
#endif
return lstat(path, buf)
}
internal func system_fstat(
_ fd: Int32,
_ buf: UnsafeMutablePointer<stat>
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, buf) }
#endif
return fstat(fd, buf)
}
internal func system_fstatat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ buf: UnsafeMutablePointer<stat>,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, buf, flag) }
#endif
return fstatat(fd, path, buf, flag)
}
internal func system_chmod(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return chmod(path, mode)
}
internal func system_lchmod(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return lchmod(path, mode)
}
internal func system_fchmod(
_ fd: Int32,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, mode) }
#endif
return fchmod(fd, mode)
}
internal func system_fchmodat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, mode, flag) }
#endif
return fchmodat(fd, path, mode, flag)
}
internal func system_chown(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, userID, groupID) }
#endif
return chown(path, userID, groupID)
}
internal func system_lchown(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, userID, groupID) }
#endif
return lchown(path, userID, groupID)
}
internal func system_fchown(
_ fd: Int32,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, userID, groupID) }
#endif
return fchown(fd, userID, groupID)
}
internal func system_fchownat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ userID: CInterop.UserID,
_ groupID: CInterop.GroupID,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, userID, groupID, flag) }
#endif
return fchownat(fd, path, userID, groupID, flag)
}
internal func system_chflags(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ flag: UInt32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, flag) }
#endif
return chflags(path, flag)
}
internal func system_lchflags(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ flag: UInt32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, flag) }
#endif
return lchflags(path, flag)
}
internal func system_fchflags(
_ fd: Int32,
_ flag: UInt32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, flag) }
#endif
return fchflags(fd, flag)
}
internal func system_umask(
_ cmask: CInterop.Mode
) -> CInterop.Mode {
#if ENABLE_MOCKING
if mockingEnabled { return _mockModeT(cmask) }
#endif
return umask(cmask)
}
internal func system_mkfifo(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return mkfifo(path, mode)
}
@available(macOS 13.0, *)
internal func system_mkfifoat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return mkfifoat(fd, path, mode)
}
internal func system_mknod(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode,
_ deviceID: CInterop.DeviceID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode, deviceID) }
#endif
return mknod(path, mode, deviceID)
}
@available(macOS 13.0, *)
internal func system_mknodat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode,
_ deviceID: CInterop.DeviceID
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode, deviceID) }
#endif
return mknodat(fd, path, mode, deviceID)
}
internal func system_mkdir(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, mode) }
#endif
return mkdir(path, mode)
}
internal func system_mkdirat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, mode) }
#endif
return mkdirat(fd, path, mode)
}
#if os(FreeBSD)
internal func system_utimens(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ times: UnsafePointer<timespec>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, times) }
#endif
return utimens(path, times)
}
#endif
#if os(FreeBSD)
internal func system_lutimens(
_ path: UnsafePointer<CInterop.PlatformChar>,
_ times: UnsafePointer<timespec>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(path, times) }
#endif
return lutimens(path, times)
}
#endif
internal func system_utimensat(
_ fd: Int32,
_ path: UnsafePointer<CInterop.PlatformChar>,
_ times: UnsafePointer<timespec>?,
_ flag: Int32
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, times, flag) }
#endif
return utimensat(fd, path, times, flag)
}
internal func system_futimens(
_ fd: Int32,
_ times: UnsafePointer<timespec>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, times) }
#endif
return futimens(fd, times)
}
#endif
+96
View File
@@ -0,0 +1,96 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// MARK: - stat
// int stat(const char *, struct stat *)
// int lstat(const char *, struct stat *)
// FilePath.getFileStatus(followSymlinks:) throws Errno -> FileStatus
// int fstatat(int, const char *, struct stat *, int)
// FilePath.getFileStatus(relativeTo:controlFlags:) throws Errno -> FileStatus
// int fstat(int, struct stat *)
// FileDescriptor.getFileStatus() throws Errno -> FileStatus
// MARK: - chmod
// int chmod(const char *, mode_t)
// int lchmod(const char *, mode_t)
// FilePath.changeFileMode(to:followSymlinks) throws Errno -> Void
// int fchmodat(int, const char *, mode_t, int)
// FilePath.changeFileMode(to:relativeTo:controlFlags:) throws Errno -> Void
// int fchmod(int, mode_t)
// FileDescriptor.changeFileMode(to:) throws Errno -> Void
// MARK: - chown
// int chown(const char *, uid_t, gid_t)
// int lchown(const char *, uid_t, gid_t)
// FilePath.changeFileOwner(to:followSymlinks:) throws Errno -> Void
// int fchownat(int, const char *, uid_t, gid_t, int)
// FilePath.changeFileOwner(to:relativeTo:controlFlags:) throws Errno -> Void
// int fchown(int, uid_t, gid_t)
// FileDescriptor.changeFileOwner(to:) throws Errno -> Void
// MARK: - chflags
// int chflags(const char *, uint32_t)
// int lchflags(const char *, uint32_t)
// FilePath.changeFileFlags(to:followSymlinks:) throws Errno -> Void
// int chflagsat(int, const char *, uint32_t, int) (FreeBSD)
// FilePath.changeFileFlags(to:relativeTo:controlFlags:) throws Errno -> Void
// int fchflags(int, uint32_t)
// FileDescriptor.changeFileFlags(to:) throws Errno -> Void
// MARK: - umask
// mode_t umask(mode_t)
// FileMode.updateProcessMask() -> FileMode
// MARK: - mkfifo
// int mkfifo(const char *, mode_t)
// FilePath.makeFIFO(withMode:) throws Errno -> Void
// int mkfifoat(int, const char *, mode_t)
// FilePath.makeFIFO(withMode:relativeTo:) throws Errno -> Void
// MARK: - mknod
// int mknod(const char *, mode_t, dev_t)
// FilePath.makeNode(withMode:andDeviceID:) throws Errno -> Void
// int mknodat(int, const char *, mode_t, dev_t)
// FilePath.makeNode(withMode:andDeviceID:relativeTo:) throws Errno -> Void
// MARK: - mkdir
// int mkdir(const char *, mode_t)
// FilePath.makeDirectory(withMode:) throws Errno -> Void
// int mkdirat(int, const char *, mode_t)
// FilePath.makeDirectory(withMode:relativeTo:) throws Errno -> Void
// MARK: - utimens
// int utimens(const char *, const struct timespec[2])
// int lutimens(const char *, const struct timespec[2])
// FilePath.changeFileTimes(to:followSymlinks:) throws Errno -> Void
// int utimensat(int, const char *, const struct timespec[2], int)
// FilePath.changeFileTimes(to:relativeTo:controlFlags:) throws Errno -> Void
// int futimens(int, const struct timespec[2])
// FileDescriptor.changeFileTimes(to:) throws Errno -> Void
+29 -74
View File
@@ -1,15 +1,14 @@
/*
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 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// A platform-native character representation, currently used for file paths
internal struct SystemChar:
RawRepresentable, Sendable, Comparable, Hashable {
internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable {
internal typealias RawValue = CInterop.PlatformChar
internal var rawValue: RawValue
@@ -23,12 +22,6 @@ internal struct SystemChar:
}
}
#if !$Embedded
extension SystemChar: Codable {}
#endif // !$Embedded
extension SystemChar {
internal init(ascii: Unicode.Scalar) {
self.init(rawValue: numericCast(UInt8(ascii: ascii)))
@@ -68,7 +61,7 @@ extension SystemChar {
// A platform-native string representation, currently for file paths
//
// Always null-terminated.
internal struct SystemString: Sendable {
internal struct SystemString {
internal typealias Storage = [SystemChar]
internal var nullTerminatedStorage: Storage
}
@@ -102,18 +95,10 @@ extension SystemString {
}
extension SystemString {
fileprivate func _invariantsSatisfied() -> Bool {
guard !nullTerminatedStorage.isEmpty else { return false }
guard nullTerminatedStorage.last! == .null else { return false }
guard nullTerminatedStorage.firstIndex(of: .null) == length else {
return false
}
return true
}
fileprivate func _invariantCheck() {
#if DEBUG
precondition(_invariantsSatisfied())
precondition(nullTerminatedStorage.last! == .null)
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
#endif // DEBUG
}
}
@@ -156,73 +141,44 @@ extension SystemString: RangeReplaceableCollection {
nullTerminatedStorage.reserveCapacity(1 + n)
}
// TODO: Below include null terminator, is this desired?
internal func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
// Do not include the null terminator, it is outside the Collection
try nullTerminatedStorage.withContiguousStorageIfAvailable {
try body(.init(start: $0.baseAddress, count: $0.count-1))
}
try nullTerminatedStorage.withContiguousStorageIfAvailable(body)
}
internal mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
defer { _invariantCheck() }
// Do not include the null terminator, it is outside the Collection
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable {
var buffer = UnsafeMutableBufferPointer<SystemChar>(
start: $0.baseAddress, count: $0.count-1
)
return try body(&buffer)
}
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
}
}
extension SystemString: Hashable {}
#if !$Embedded
extension SystemString: Codable {
// Encoder is synthesized; it probably should have been explicit and used
// a single-value container, but making that change now is somewhat risky.
// Decoder is written explicitly to ensure that we validate invariants on
// untrusted input.
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.nullTerminatedStorage = try container.decode(
Storage.self, forKey: .nullTerminatedStorage
)
guard _invariantsSatisfied() else {
throw DecodingError.dataCorruptedError(
forKey: .nullTerminatedStorage,
in: container,
debugDescription:
"Encoding does not satisfy the invariants of SystemString"
)
}
}
}
#endif // !$Embedded
extension SystemString: Hashable, Codable {}
extension SystemString {
// TODO: Below include null terminator, is this desired?
internal func withNullTerminatedSystemChars<T>(
internal func withSystemChars<T>(
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
) rethrows -> T {
try nullTerminatedStorage.withUnsafeBufferPointer(f)
try withContiguousStorageIfAvailable(f)!
}
// withCodeUnits does not include the null terminator
internal func withCodeUnits<T>(
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
) rethrows -> T {
try withNullTerminatedSystemChars {
try $0.withMemoryRebound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self) {
assert($0.last == .zero)
return try f(.init(start: $0.baseAddress, count: $0.count&-1))
try withSystemChars { chars in
let length = chars.count * MemoryLayout<SystemChar>.stride
let count = length / MemoryLayout<CInterop.PlatformUnicodeEncoding.CodeUnit>.stride
return try chars.baseAddress!.withMemoryRebound(
to: CInterop.PlatformUnicodeEncoding.CodeUnit.self,
capacity: count
) { pointer in
try f(UnsafeBufferPointer(start: pointer, count: count))
}
}
}
@@ -238,9 +194,7 @@ extension Slice where Base == SystemString {
}
internal var string: String {
withCodeUnits {
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
}
withCodeUnits { String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) }
}
internal func withPlatformString<T>(
@@ -282,11 +236,7 @@ extension SystemString: ExpressibleByStringLiteral {
}
extension SystemString: CustomStringConvertible, CustomDebugStringConvertible {
internal var string: String {
self.withCodeUnits {
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
}
}
internal var string: String { String(decoding: self) }
internal var description: String { string }
internal var debugDescription: String { description.debugDescription }
@@ -325,7 +275,7 @@ extension SystemString {
internal func withPlatformString<T>(
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
) rethrows -> T {
try withNullTerminatedSystemChars { chars in
try withSystemChars { chars in
let length = chars.count * MemoryLayout<SystemChar>.stride
return try chars.baseAddress!.withMemoryRebound(
to: CInterop.PlatformChar.self,
@@ -338,6 +288,11 @@ extension SystemString {
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
extension SystemChar: Sendable {}
extension SystemString: Sendable {}
#endif
// TODO: SystemString should use a COW-interchangable storage form rather
// than array, so you could "borrow" the storage from a non-bridged String
// or Data or whatever
+140
View File
@@ -0,0 +1,140 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// sys/time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// A system provided timer which can be configured to run after an initial
/// delay and subsequent interval.
///
/// The corresponding C type is `int`.
@frozen
public struct IntervalTimer: RawRepresentable {
public typealias RawValue = CInterop.IntervalTimer
/// The raw C ITIMER value.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed interval timer from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension IntervalTimer {
/// A timer which decrements in real time.
///
/// A `SIGALRM` signal is delivered when this timer expires.
///
/// The corresponding C timer is `ITIMER_REAL`.
@_alwaysEmitIntoClient
public static var real: Self { Self(rawValue: _ITIMER_REAL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "real")
public static var ITIMER_REAL: Self { real }
/// A timer which decrements in process virtual time.
///
/// The timer runs only while the process is executing. A `SIGVTALRM` signal
/// is delivered when this timer expires.
///
/// The corresponding C timer is `ITIMER_VIRTUAL`.
@_alwaysEmitIntoClient
public static var virtual: Self { Self(rawValue: _ITIMER_VIRTUAL) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "virtual")
public static var ITIMER_VIRTUAL: Self { virtual }
/// A timer which decrements both in process virtual time and when the system
/// is running on behalf of the process.
///
/// This timer is designed to be used by interpreters when statistically
/// profiling the execution of interpreted programs. A `SIGPROF` signal
/// is delivered when this timer expires. Because this signal may interrupt
/// in-progress system calls, programs using this timer must be prepared to
/// restart interrupted system calls.
///
/// The corresponding C timer is `ITIMER_PROF`.
@_alwaysEmitIntoClient
public static var profile: Self { Self(rawValue: _ITIMER_PROF) }
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "profile")
public static var ITIMER_PROF: Self { profile }
}
extension IntervalTimer {
/// Returns the current value for the timer.
///
/// - Returns: The current value of the timer.
///
/// The corresponding C function is `getitimer`.
@_alwaysEmitIntoClient
public func get() throws -> IntervalTimerValue {
try _get().get()
}
@usableFromInline
internal func _get() -> Result<IntervalTimerValue, Errno> {
var currentValue = itimerval()
return nothingOrErrno(retryOnInterrupt: false) {
system_getitimer(self.rawValue, &currentValue)
}
.map {
IntervalTimerValue(rawValue: currentValue)
}
}
/// Sets a timer to run on specified value.
///
/// If the initial delay is non-zero, it indicates the time to the next timer
/// expiration. If the interval is non-zero, it specifies a value to be used
/// in reloading initial delay when the timer expires.
///
/// Setting the initial delay to `0` disables the timer.
/// Setting the interval to `0` causes a timer to be disabled after its next
/// expiration, assuming initial delay is non-zero.
///
/// - Parameters:
/// - newValue: The new interval to run the timer.
/// - Returns: The previous value of the timer.
///
/// The corresponding C function is `setitimer`.
@_alwaysEmitIntoClient
@discardableResult
public func set(newValue: IntervalTimerValue) throws -> IntervalTimerValue {
try _set(newValue: newValue).get()
}
@usableFromInline
internal func _set(
newValue: IntervalTimerValue
) -> Result<IntervalTimerValue, Errno> {
var newValue = newValue.rawValue
var oldValue = itimerval()
return nothingOrErrno(retryOnInterrupt: false) {
system_setitimer(self.rawValue, &newValue, &oldValue)
}
.map {
IntervalTimerValue(rawValue: oldValue)
}
}
}
#endif
@@ -0,0 +1,70 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// sys/time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The value an interval timer is configured to run on.
///
/// The corresponding C type is `itimerval`.
@frozen
public struct IntervalTimerValue: RawRepresentable {
public typealias RawValue = CInterop.IntervalTimerValue
/// The raw C itimerval type.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed internal timer value from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension IntervalTimerValue {
/// The initial delay before running the timer.
///
/// Setting the initial delay to `0` disables the timer.
///
/// The corresponding C property is `it_value`.
@_alwaysEmitIntoClient
public var initialDelay: TimeValue {
get { TimeValue(rawValue: rawValue.it_value) }
set { rawValue.it_value = newValue.rawValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "initialDelay")
public var it_value: TimeValue { initialDelay }
/// The subsequent delay after the initial delay before running the timer.
///
/// Setting the interval to `0` causes a timer to be disabled after its next
/// expiration, assuming initial delay is non-zero.
///
/// The corresponding C property is `it_interval`.
@_alwaysEmitIntoClient
public var interval: TimeValue {
get { TimeValue(rawValue: rawValue.it_interval) }
set { rawValue.it_interval = newValue.rawValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "interval")
public var it_interval: TimeValue { interval }
}
#endif
+31
View File
@@ -0,0 +1,31 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
extension CInterop {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// The C `time_t` type
public typealias Time = time_t
/// The C `suseconds_t` type
public typealias Microseconds = suseconds_t
/// The C `long` type
public typealias Nanoseconds = CLong
/// The C `timeval` type
public typealias TimeValue = timeval
/// The C `timespec` type
public typealias TimeSpecification = timespec
/// The C `itimerval` type
public typealias IntervalTimerValue = itimerval
/// The C type of `ITIMER` values
public typealias IntervalTimer = CInt
#endif
}
+21
View File
@@ -0,0 +1,21 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_alwaysEmitIntoClient
internal var _ITIMER_REAL: CInterop.IntervalTimer { ITIMER_REAL }
@_alwaysEmitIntoClient
internal var _ITIMER_VIRTUAL: CInterop.IntervalTimer { ITIMER_VIRTUAL }
@_alwaysEmitIntoClient
internal var _ITIMER_PROF: CInterop.IntervalTimer { ITIMER_PROF }
#endif
+37
View File
@@ -0,0 +1,37 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// getitimer
internal func system_getitimer(
_ timer: CInt,
_ currentValue: UnsafeMutablePointer<itimerval>
) -> CInt {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(timer, currentValue) }
#endif
return getitimer(timer, currentValue)
}
// setitimer
internal func system_setitimer(
_ timer: CInt,
_ newValue: UnsafePointer<itimerval>,
_ oldValue: UnsafeMutablePointer<itimerval>?
) -> Int32 {
#if ENABLE_MOCKING
if mockingEnabled { return _mock(timer, newValue, oldValue) }
#endif
return setitimer(timer, newValue, oldValue)
}
#endif
+164
View File
@@ -0,0 +1,164 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Represents an elapsed time since a reference point.
///
/// The corresponding C type is `timeval`.
@frozen
public struct TimeSpecification: RawRepresentable {
public typealias RawValue = CInterop.TimeSpecification
/// The raw C timeval type.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed time value from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension TimeSpecification {
/// The elapsed time in seconds.
///
/// The corresponding C property is `tv_sec`.
@_alwaysEmitIntoClient
public var seconds: CInterop.Time {
get { rawValue.tv_sec }
set { rawValue.tv_sec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "seconds")
public var tv_sec: CInterop.Time { seconds }
/// The remaining elapsed time in nanoseconds.
///
/// This value must always be in the range [0, 999999999].
///
/// The corresponding C property is `tv_nsec`.
@_alwaysEmitIntoClient
public var nanoseconds: CInterop.Nanoseconds {
get { rawValue.tv_nsec }
set { rawValue.tv_nsec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "nanoseconds")
public var tv_nsec: CInterop.Nanoseconds { nanoseconds }
}
extension TimeSpecification {
@_alwaysEmitIntoClient
@inline(__always)
private static let attosecondsPerNanoseconds: Int64 = 1_000_000_000
/// Creates a new value, rounded to the closest possible representation.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init(_ duration: Duration) {
let (seconds, attoseconds) = duration.components
let nanoseconds = attoseconds / Self.attosecondsPerNanoseconds
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_nsec: CInterop.Nanoseconds(nanoseconds))
}
/// Creates a new value, if the given duration can be represented exactly.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init?(exactly duration: Duration) {
let (seconds, attoseconds) = duration.components
guard
let seconds = CInterop.Time(exactly: seconds),
attoseconds.isMultiple(of: Self.attosecondsPerNanoseconds)
else {
return nil
}
let nanoseconds = attoseconds / Self.attosecondsPerNanoseconds
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_nsec: CInterop.Nanoseconds(nanoseconds))
}
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public var duration: Duration {
let seconds = Int64(self.seconds)
let attoseconds = Int64(self.nanoseconds) *
Self.attosecondsPerNanoseconds
return .init(
secondsComponent: seconds,
attosecondsComponent: attoseconds)
}
}
extension TimeSpecification: AdditiveArithmetic {
@_alwaysEmitIntoClient
@inline(__always)
private static let nanosecondsPerSecond: CInterop.Nanoseconds = 1_000_000_000
@_alwaysEmitIntoClient
public static var zero: Self {
Self(rawValue: .init(tv_sec: 0, tv_nsec: 0))
}
@_alwaysEmitIntoClient
public static func + (lhs: Self, rhs: Self) -> Self {
var newValue = TimeSpecification.zero
newValue.seconds = lhs.seconds + rhs.seconds
newValue.nanoseconds = lhs.nanoseconds + rhs.nanoseconds
if (newValue.nanoseconds >= Self.nanosecondsPerSecond) {
newValue.seconds += 1
newValue.nanoseconds -= Self.nanosecondsPerSecond
}
return newValue
}
@_alwaysEmitIntoClient
public static func - (lhs: Self, rhs: Self) -> Self {
var newValue = TimeSpecification.zero
newValue.seconds = lhs.seconds - rhs.seconds;
newValue.nanoseconds = lhs.nanoseconds - rhs.nanoseconds
if (newValue.nanoseconds < 0) {
newValue.seconds -= 1
newValue.nanoseconds += Self.nanosecondsPerSecond
}
return newValue
}
}
extension TimeSpecification: Comparable {
@_alwaysEmitIntoClient
public static func < (lhs: Self, rhs: Self) -> Bool {
guard lhs.seconds == rhs.seconds else {
return lhs.seconds < rhs.seconds
}
return lhs.nanoseconds < rhs.nanoseconds
}
}
extension TimeSpecification: Equatable {
@_alwaysEmitIntoClient
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.seconds == rhs.seconds && lhs.nanoseconds == rhs.nanoseconds
}
}
#endif
+164
View File
@@ -0,0 +1,164 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Specification:
// - POSIX.1-2017
// - IEEE Std 1003.1™-2017
// - The Open Group Technical Standard Base Specifications, Issue 7
// Reference: https://pubs.opengroup.org/onlinepubs/9699919799
// sys/time.h
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// Represents an elapsed time since a reference point.
///
/// The corresponding C type is `timeval`.
@frozen
public struct TimeValue: RawRepresentable {
public typealias RawValue = CInterop.TimeValue
/// The raw C timeval type.
@_alwaysEmitIntoClient
public var rawValue: RawValue
/// Create a strongly-typed time value from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: RawValue) { self.rawValue = rawValue }
}
extension TimeValue {
/// The elapsed time in seconds.
///
/// The corresponding C property is `tv_sec`.
@_alwaysEmitIntoClient
public var seconds: CInterop.Time {
get { rawValue.tv_sec }
set { rawValue.tv_sec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "seconds")
public var tv_sec: CInterop.Time { seconds }
/// The remaining elapsed time in microseconds.
///
/// This value must always be in the range [0, 999999].
///
/// The corresponding C property is `tv_usec`.
@_alwaysEmitIntoClient
public var microseconds: CInterop.Microseconds {
get { rawValue.tv_usec }
set { rawValue.tv_usec = newValue }
}
@_alwaysEmitIntoClient
@available(*, unavailable, renamed: "microseconds")
public var tv_usec: CInterop.Microseconds { microseconds }
}
extension TimeValue {
@_alwaysEmitIntoClient
@inline(__always)
private static let attosecondsPerMicrosecond: Int64 = 1_000_000_000_000
/// Creates a new value, rounded to the closest possible representation.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init(_ duration: Duration) {
let (seconds, attoseconds) = duration.components
let microseconds = attoseconds / Self.attosecondsPerMicrosecond
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_usec: CInterop.Microseconds(microseconds))
}
/// Creates a new value, if the given duration can be represented exactly.
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public init?(exactly duration: Duration) {
let (seconds, attoseconds) = duration.components
guard
let seconds = CInterop.Time(exactly: seconds),
attoseconds.isMultiple(of: Self.attosecondsPerMicrosecond)
else {
return nil
}
let microseconds = attoseconds / Self.attosecondsPerMicrosecond
self.rawValue = .init(
tv_sec: CInterop.Time(truncatingIfNeeded: seconds),
tv_usec: CInterop.Microseconds(microseconds))
}
@_alwaysEmitIntoClient
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public var duration: Duration {
let seconds = Int64(self.seconds)
let attoseconds = Int64(self.microseconds) *
Self.attosecondsPerMicrosecond
return .init(
secondsComponent: seconds,
attosecondsComponent: attoseconds)
}
}
extension TimeValue: AdditiveArithmetic {
@_alwaysEmitIntoClient
@inline(__always)
private static let microsecondsPerSecond: CInterop.Microseconds = 1_000_000
@_alwaysEmitIntoClient
public static var zero: TimeValue {
Self(rawValue: .init(tv_sec: 0, tv_usec: 0))
}
@_alwaysEmitIntoClient
public static func + (lhs: Self, rhs: Self) -> Self {
var newValue = TimeValue.zero
newValue.seconds = lhs.seconds + rhs.seconds
newValue.microseconds = lhs.microseconds + rhs.microseconds
if (newValue.microseconds >= Self.microsecondsPerSecond) {
newValue.seconds += 1
newValue.microseconds -= Self.microsecondsPerSecond
}
return newValue
}
@_alwaysEmitIntoClient
public static func - (lhs: Self, rhs: Self) -> Self {
var newValue = TimeValue.zero
newValue.seconds = lhs.seconds - rhs.seconds;
newValue.microseconds = lhs.microseconds - rhs.microseconds
if (newValue.microseconds < 0) {
newValue.seconds -= 1
newValue.microseconds += Self.microsecondsPerSecond
}
return newValue
}
}
extension TimeValue: Comparable {
@_alwaysEmitIntoClient
public static func < (lhs: Self, rhs: Self) -> Bool {
guard lhs.seconds == rhs.seconds else {
return lhs.seconds < rhs.seconds
}
return lhs.microseconds < rhs.microseconds
}
}
extension TimeValue: Equatable {
@_alwaysEmitIntoClient
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.seconds == rhs.seconds && lhs.microseconds == rhs.microseconds
}
}
#endif
+4 -8
View File
@@ -8,21 +8,21 @@
*/
// Results in errno if i == -1
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
private func valueOrErrno<I: FixedWidthInteger>(
_ i: I
) -> Result<I, Errno> {
i == -1 ? .failure(Errno.current) : .success(i)
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
private func nothingOrErrno<I: FixedWidthInteger>(
_ i: I
) -> Result<(), Errno> {
valueOrErrno(i).map { _ in () }
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
internal func valueOrErrno<I: FixedWidthInteger>(
retryOnInterrupt: Bool, _ f: () -> I
) -> Result<I, Errno> {
@@ -36,15 +36,13 @@ internal func valueOrErrno<I: FixedWidthInteger>(
} while true
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
internal func nothingOrErrno<I: FixedWidthInteger>(
retryOnInterrupt: Bool, _ f: () -> I
) -> Result<(), Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () }
}
#if !$Embedded
// Run a precondition for debug client builds
internal func _debugPrecondition(
_ condition: @autoclosure () -> Bool,
@@ -58,8 +56,6 @@ internal func _debugPrecondition(
}
}
#endif // !$Embedded
extension OpaquePointer {
internal var _isNULL: Bool {
OpaquePointer(bitPattern: Int(bitPattern: self)) == nil
+2 -2
View File
@@ -52,13 +52,13 @@ extension Slice where Element: Equatable {
return self[...idx]
}
// If `e` is present, eat up to first occurrence of `e`
// If `e` is present, eat up to first occurence of `e`
internal mutating func _eatUntil(_ e: Element) -> Slice? {
guard let idx = self.firstIndex(of: e) else { return nil }
return _eatUntil(idx)
}
// If `e` is present, eat up to and through first occurrence of `e`
// If `e` is present, eat up to and through first occurence of `e`
internal mutating func _eatThrough(_ e: Element) -> Slice? {
guard let idx = self.firstIndex(of: e) else { return nil }
return _eatThrough(idx)
+8
View File
@@ -0,0 +1,8 @@
import XCTest
import SystemTests
var tests = [XCTestCaseEntry]()
tests += SystemTests.__allTests()
XCTMain(tests)
+16 -35
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -19,7 +19,7 @@ import System
import WinSDK
#endif
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
final class ErrnoTest: XCTestCase {
func testConstants() {
XCTAssert(EPERM == Errno.notPermitted.rawValue)
@@ -36,7 +36,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOMEM == Errno.noMemory.rawValue)
XCTAssert(EACCES == Errno.permissionDenied.rawValue)
XCTAssert(EFAULT == Errno.badAddress.rawValue)
#if !os(Windows) && !os(WASI)
#if !os(Windows)
XCTAssert(ENOTBLK == Errno.notBlockDevice.rawValue)
#endif
XCTAssert(EBUSY == Errno.resourceBusy.rawValue)
@@ -74,11 +74,9 @@ final class ErrnoTest: XCTestCase {
XCTAssert(WSAEOPNOTSUPP == Errno.notSupported.rawValue)
XCTAssert(WSAEPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
#else
XCTAssert(ENOTSUP == Errno.notSupported.rawValue)
#if !os(WASI)
XCTAssert(ESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
XCTAssert(ENOTSUP == Errno.notSupported.rawValue)
XCTAssert(EPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
#endif
#endif
XCTAssert(EAFNOSUPPORT == Errno.addressFamilyNotSupported.rawValue)
XCTAssert(EADDRINUSE == Errno.addressInUse.rawValue)
@@ -93,7 +91,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOTCONN == Errno.socketNotConnected.rawValue)
#if os(Windows)
XCTAssert(WSAESHUTDOWN == Errno.socketShutdown.rawValue)
#elseif !os(WASI)
#else
XCTAssert(ESHUTDOWN == Errno.socketShutdown.rawValue)
#endif
XCTAssert(ETIMEDOUT == Errno.timedOut.rawValue)
@@ -102,13 +100,13 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENAMETOOLONG == Errno.fileNameTooLong.rawValue)
#if os(Windows)
XCTAssert(WSAEHOSTDOWN == Errno.hostIsDown.rawValue)
#elseif !os(WASI)
#else
XCTAssert(EHOSTDOWN == Errno.hostIsDown.rawValue)
#endif
XCTAssert(EHOSTUNREACH == Errno.noRouteToHost.rawValue)
XCTAssert(ENOTEMPTY == Errno.directoryNotEmpty.rawValue)
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(EPROCLIM == Errno.tooManyProcesses.rawValue)
#endif
@@ -117,14 +115,12 @@ final class ErrnoTest: XCTestCase {
XCTAssert(WSAEDQUOT == Errno.diskQuotaExceeded.rawValue)
XCTAssert(WSAESTALE == Errno.staleNFSFileHandle.rawValue)
#else
#if !os(WASI)
XCTAssert(EUSERS == Errno.tooManyUsers.rawValue)
#endif
XCTAssert(EDQUOT == Errno.diskQuotaExceeded.rawValue)
XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(EBADRPC == Errno.rpcUnsuccessful.rawValue)
XCTAssert(ERPCMISMATCH == Errno.rpcVersionMismatch.rawValue)
XCTAssert(EPROGUNAVAIL == Errno.rpcProgramUnavailable.rawValue)
@@ -135,13 +131,10 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOLCK == Errno.noLocks.rawValue)
XCTAssert(ENOSYS == Errno.noFunction.rawValue)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(EFTYPE == Errno.badFileTypeOrFormat.rawValue)
XCTAssert(EAUTH == Errno.authenticationError.rawValue)
XCTAssert(ENEEDAUTH == Errno.needAuthenticator.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EPWROFF == Errno.devicePowerIsOff.rawValue)
XCTAssert(EDEVERR == Errno.deviceError.rawValue)
#endif
@@ -150,7 +143,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(EOVERFLOW == Errno.overflow.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(EBADEXEC == Errno.badExecutable.rawValue)
XCTAssert(EBADARCH == Errno.badCPUType.rawValue)
XCTAssert(ESHLIBVERS == Errno.sharedLibraryVersionMismatch.rawValue)
@@ -164,39 +157,33 @@ final class ErrnoTest: XCTestCase {
#endif
XCTAssert(EILSEQ == Errno.illegalByteSequence.rawValue)
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(ENOATTR == Errno.attributeNotFound.rawValue)
#endif
#if !os(Windows)
XCTAssert(EBADMSG == Errno.badMessage.rawValue)
XCTAssert(EMULTIHOP == Errno.multiHop.rawValue)
XCTAssert(ENOLINK == Errno.noLink.rawValue)
XCTAssert(EPROTO == Errno.protocolError.rawValue)
#endif
#if !os(Windows) && !os(FreeBSD) && !os(WASI)
XCTAssert(ENODATA == Errno.noData.rawValue)
XCTAssert(ENOLINK == Errno.noLink.rawValue)
XCTAssert(ENOSR == Errno.noStreamResources.rawValue)
XCTAssert(ENOSTR == Errno.notStream.rawValue)
XCTAssert(EPROTO == Errno.protocolError.rawValue)
XCTAssert(ETIME == Errno.timeout.rawValue)
#endif
XCTAssert(EOPNOTSUPP == Errno.notSupportedOnSocket.rawValue)
// From headers but not man page
#if !os(WASI) // Would need to use _getConst func from CSystem
XCTAssert(EWOULDBLOCK == Errno.wouldBlock.rawValue)
#endif
#if os(Windows)
XCTAssert(WSAETOOMANYREFS == Errno.tooManyReferences.rawValue)
XCTAssert(WSAEREMOTE == Errno.tooManyRemoteLevels.rawValue)
#elseif !os(WASI)
#else
XCTAssert(ETOOMANYREFS == Errno.tooManyReferences.rawValue)
XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(ENOPOLICY == Errno.noSuchPolicy.rawValue)
#endif
@@ -205,13 +192,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue)
#endif
#if os(FreeBSD)
XCTAssert(ENOTCAPABLE == Errno.notCapable.rawValue)
XCTAssert(ECAPMODE == Errno.capabilityMode.rawValue)
XCTAssert(EINTEGRITY == Errno.integrityCheckFailed.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssert(EQFULL == Errno.outputQueueFull.rawValue)
XCTAssert(ELAST == Errno.lastErrnoValue.rawValue)
#endif
+114 -145
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -10,19 +10,13 @@
import XCTest
#if SYSTEM_PACKAGE
@testable import SystemPackage
import SystemPackage
#else
@testable import System
#endif
#if canImport(Android)
import Android
#elseif os(WASI)
import CSystem
import System
#endif
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
final class FileOperationsTest: XCTestCase {
#if ENABLE_MOCKING && !os(WASI) // Would need to use _getConst funcs from CSystem
func testSyscalls() {
let fd = FileDescriptor(rawValue: 1)
@@ -34,7 +28,8 @@ final class FileOperationsTest: XCTestCase {
let writeBuf = UnsafeRawBufferPointer(rawBuf)
let writeBufAddr = writeBuf.baseAddress
let syscallTestCases: Array<MockTestCase> = [
var syscallTestCases: Array<MockTestCase> = []
syscallTestCases += [
MockTestCase(name: "open", .interruptable, "a path", O_RDWR | O_APPEND) {
retryOnInterrupt in
_ = try FileDescriptor.open(
@@ -89,75 +84,57 @@ final class FileOperationsTest: XCTestCase {
},
]
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
let fp = FilePath("/")
let rawFP = fp.withPlatformString { strdup($0) }
defer { free(rawFP) }
let stat = UnsafeMutablePointer<stat>.allocate(capacity: 1)
defer { stat.deallocate() }
syscallTestCases += [
// MockTestCase(name: "stat", .interruptable, rawFP) { retryOnInterrupt in
// _ = try fp.stat(followSymlinks: false, retryOnInterrupt: retryOnInterrupt)
// },
// MockTestCase(name: "lstat", .interruptable, rawFP) { retryOnInterrupt in
// _ = try fp.stat(followSymlinks: true, retryOnInterrupt: retryOnInterrupt)
// },
// MockTestCase(name: "fstat", .interruptable, rawFP) { retryOnInterrupt in
// _ = try fd.stat(retryOnInterrupt: retryOnInterrupt)
// },
// MockTestCase(name: "fstatat", .interruptable, rawFP) { retryOnInterrupt in
// _ = try fp.stat(relativeTo: fd, fcntrl: .none, retryOnInterrupt: retryOnInterrupt)
// },
// fstatat
// chmod
// lchmod
// fchmod
// fchmodat
// chown
// lchown
// fchown
// fchownat
// chflags
// lchflags
// fchflags
// umask
// mkfifo
// mknod
// mkdir
// mkdirat
// futimens
// utimensat
]
#endif
for test in syscallTestCases { test.runAllTests() }
}
#endif // ENABLE_MOCKING && !os(WASI)
func testWriteFromEmptyBuffer() throws {
#if os(Windows)
let fd = try FileDescriptor.open(FilePath("NUL"), .writeOnly)
#else
let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly)
#endif
let written1 = try fd.write(toAbsoluteOffset: 0, .init(start: nil, count: 0))
XCTAssertEqual(written1, 0)
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
defer { pointer.deallocate() }
let empty = UnsafeRawBufferPointer(start: pointer, count: 0)
let written2 = try fd.write(toAbsoluteOffset: 0, empty)
XCTAssertEqual(written2, 0)
}
#if os(Windows)
// Generate a file containing random bytes; this should not be used
// for cryptography, it's just for testing.
func generateRandomData(at path: FilePath, count: Int) throws {
let fd = try FileDescriptor.open(path, .readWrite,
options: [.create, .truncate])
defer {
try! fd.close()
}
let data = [UInt8](
sequence(first: 0,
next: {
_ in UInt8.random(in: UInt8.min...UInt8.max)
}).dropFirst().prefix(count)
)
try data.withUnsafeBytes {
_ = try fd.write($0)
}
}
#endif
func testReadToEmptyBuffer() throws {
try withTemporaryFilePath(basename: "testReadToEmptyBuffer") { path in
#if os(Windows)
// Windows doesn't have an equivalent to /dev/random, so generate
// some random bytes and write them to a file for the next step.
let randomPath = path.appending("random.txt")
try generateRandomData(at: randomPath, count: 16)
let fd = try FileDescriptor.open(randomPath, .readOnly)
#else // !os(Windows)
let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly)
#endif
let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0))
XCTAssertEqual(read1, 0)
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
defer { pointer.deallocate() }
let empty = UnsafeMutableRawBufferPointer(start: pointer, count: 0)
let read2 = try fd.read(fromAbsoluteOffset: 0, into: empty)
XCTAssertEqual(read2, 0)
}
}
func testHelpers() {
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
}
#if !os(WASI) // WASI has no pipe
#if !os(Windows)
func testAdHocPipe() throws {
// Ad-hoc test testing `Pipe` functionality.
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
@@ -176,35 +153,33 @@ final class FileOperationsTest: XCTestCase {
}
}
}
#endif
#endif
func testAdHocOpen() {
// Ad-hoc test touching a file system.
do {
// TODO: Test this against a virtual in-memory file system
try withTemporaryFilePath(basename: "testAdhocOpen") { path in
let fd = try FileDescriptor.open(path.appending("b.txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
try fd.closeAfter {
try fd.writeAll("abc".utf8)
var def = "def"
try def.withUTF8 {
_ = try fd.write(UnsafeRawBufferPointer($0))
}
try fd.seek(offset: 1, from: .start)
let readLen = 3
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
}
let preadBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf))
}
XCTAssertEqual(readBytes.first!, "b".utf8.first!)
XCTAssertEqual(readBytes, preadBytes)
// TODO: seek
let fd = try FileDescriptor.open("/tmp/b.txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
try fd.closeAfter {
try fd.writeAll("abc".utf8)
var def = "def"
try def.withUTF8 {
_ = try fd.write(UnsafeRawBufferPointer($0))
}
try fd.seek(offset: 1, from: .start)
let readLen = 3
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
}
let preadBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf))
}
XCTAssertEqual(readBytes.first!, "b".utf8.first!)
XCTAssertEqual(readBytes, preadBytes)
// TODO: seek
}
} catch let err as Errno {
print("caught \(err))")
@@ -215,16 +190,10 @@ final class FileOperationsTest: XCTestCase {
}
}
#if ENABLE_MOCKING
func testGithubIssues() {
// https://github.com/apple/swift-system/issues/26
#if os(WASI)
let openOptions = _getConst_O_WRONLY() | _getConst_O_CREAT()
#else
let openOptions = O_WRONLY | O_CREAT
#endif
let issue26 = MockTestCase(
name: "open", .interruptable, "a path", openOptions, 0o020
name: "open", .interruptable, "a path", O_WRONLY | O_CREAT, 0o020
) {
retryOnInterrupt in
_ = try FileDescriptor.open(
@@ -233,51 +202,51 @@ final class FileOperationsTest: XCTestCase {
retryOnInterrupt: retryOnInterrupt)
}
issue26.runAllTests()
}
#endif // ENABLE_MOCKING
}
#if !os(Windows)
func testResizeFile() throws {
try withTemporaryFilePath(basename: "testResizeFile") { path in
let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
try fd.closeAfter {
// File should be empty initially.
XCTAssertEqual(try fd.fileSize(), 0)
// Write 3 bytes.
try fd.writeAll("abc".utf8)
// File should now be 3 bytes.
XCTAssertEqual(try fd.fileSize(), 3)
// Resize to 6 bytes.
try fd.resize(to: 6)
// File should now be 6 bytes.
XCTAssertEqual(try fd.fileSize(), 6)
// Read in the 6 bytes.
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
try fd.seek(offset: 0, from: .start)
// Should have read all 6 bytes.
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
XCTAssertEqual(count, 6)
}
// First 3 bytes should be unaffected by resize.
XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8))
// Extension should be padded with zeros.
XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3))
// File should still be 6 bytes.
XCTAssertEqual(try fd.fileSize(), 6)
// Resize to 2 bytes.
try fd.resize(to: 2)
// File should now be 2 bytes.
XCTAssertEqual(try fd.fileSize(), 2)
// Read in file with a buffer big enough for 6 bytes.
let readBytesAfterTruncation = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
try fd.seek(offset: 0, from: .start)
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
// Should only have read 2 bytes.
XCTAssertEqual(count, 2)
}
// Written content was trunctated.
XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8))
let fd = try FileDescriptor.open("/tmp/\(UUID().uuidString).txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
try fd.closeAfter {
// File should be empty initially.
XCTAssertEqual(try fd.fileSize(), 0)
// Write 3 bytes.
try fd.writeAll("abc".utf8)
// File should now be 3 bytes.
XCTAssertEqual(try fd.fileSize(), 3)
// Resize to 6 bytes.
try fd.resize(to: 6)
// File should now be 6 bytes.
XCTAssertEqual(try fd.fileSize(), 6)
// Read in the 6 bytes.
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
try fd.seek(offset: 0, from: .start)
// Should have read all 6 bytes.
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
XCTAssertEqual(count, 6)
}
// First 3 bytes should be unaffected by resize.
XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8))
// Extension should be padded with zeros.
XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3))
// File should still be 6 bytes.
XCTAssertEqual(try fd.fileSize(), 6)
// Resize to 2 bytes.
try fd.resize(to: 2)
// File should now be 2 bytes.
XCTAssertEqual(try fd.fileSize(), 2)
// Read in file with a buffer big enough for 6 bytes.
let readBytesAfterTruncation = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
try fd.seek(offset: 0, from: .start)
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
// Should only have read 2 bytes.
XCTAssertEqual(count, 2)
}
// Written content was trunctated.
XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8))
}
}
#endif
}
@@ -1,247 +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
*/
import XCTest
#if os(Windows)
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
import WinSDK
@available(iOS 8, *)
final class FileOperationsTestWindows: XCTestCase {
private let r = ACCESS_MASK(
FILE_READ_ATTRIBUTES
| FILE_READ_DATA
| FILE_READ_EA
| STANDARD_RIGHTS_READ
| SYNCHRONIZE
)
private let w = ACCESS_MASK(
FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA
| FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE
| SYNCHRONIZE
)
private let x = ACCESS_MASK(
FILE_EXECUTE
| FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE
)
private struct Test {
var permissions: CModeT
var ownerAccess: ACCESS_MASK
var groupAccess: ACCESS_MASK
var otherAccess: ACCESS_MASK
init(_ permissions: CModeT,
_ ownerAccess: ACCESS_MASK,
_ groupAccess: ACCESS_MASK,
_ otherAccess: ACCESS_MASK) {
self.permissions = permissions
self.ownerAccess = ownerAccess
self.groupAccess = groupAccess
self.otherAccess = otherAccess
}
}
/// Retrieve the owner, group and other access masks for a given file.
///
/// - Parameters:
/// - path: The path to the file to inspect
/// - Returns: A tuple of ACCESS_MASK values.
func getAccessMasks(
path: FilePath
) -> (ACCESS_MASK, ACCESS_MASK, ACCESS_MASK) {
var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1))
var psidEveryone: PSID? = nil
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
DWORD(SECURITY_WORLD_RID),
0, 0, 0, 0, 0, 0, 0,
&psidEveryone))
defer {
FreeSid(psidEveryone)
}
var everyone = TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
psidEveryone!.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
return path.withPlatformString { objectName in
var psidOwner: PSID? = nil
var psidGroup: PSID? = nil
var pDacl: PACL? = nil
var pSD: PSECURITY_DESCRIPTOR? = nil
XCTAssertEqual(GetNamedSecurityInfoW(
objectName,
SE_FILE_OBJECT,
SECURITY_INFORMATION(
DACL_SECURITY_INFORMATION
| GROUP_SECURITY_INFORMATION
| OWNER_SECURITY_INFORMATION
),
&psidOwner,
&psidGroup,
&pDacl,
nil,
&pSD), DWORD(ERROR_SUCCESS))
defer {
LocalFree(pSD)
}
var owner = TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_USER,
ptstrName:
psidOwner!.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
var group = TRUSTEE_W(
pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_GROUP,
ptstrName:
psidGroup!.assumingMemoryBound(to: CInterop.PlatformChar.self)
)
var ownerAccess = ACCESS_MASK(0)
var groupAccess = ACCESS_MASK(0)
var otherAccess = ACCESS_MASK(0)
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&owner,
&ownerAccess), DWORD(ERROR_SUCCESS))
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&group,
&groupAccess), DWORD(ERROR_SUCCESS))
XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl,
&everyone,
&otherAccess), DWORD(ERROR_SUCCESS))
return (ownerAccess, groupAccess, otherAccess)
}
}
private func runTests(_ tests: [Test], at path: FilePath) throws {
for test in tests {
let octal = String(test.permissions, radix: 8)
let testPath = path.appending("test-\(octal).txt")
let fd = try FileDescriptor.open(
testPath,
.readWrite,
options: [.create, .truncate],
permissions: FilePermissions(rawValue: test.permissions)
)
_ = try fd.closeAfter {
try fd.writeAll("Hello World".utf8)
}
let (ownerAccess, groupAccess, otherAccess)
= getAccessMasks(path: testPath)
XCTAssertEqual(ownerAccess, test.ownerAccess)
XCTAssertEqual(groupAccess, test.groupAccess)
XCTAssertEqual(otherAccess, test.otherAccess)
}
}
/// Test that the umask works properly
func testUmask() throws {
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
// Default mask should be 0o022
XCTAssertEqual(FilePermissions.creationMask, [.groupWrite, .otherWrite])
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r|x, 0),
Test(0o777, r|w|x, r|x, r|x)
]
try runTests(tests, at: path)
}
try FilePermissions.withCreationMask([.groupWrite, .groupExecute,
.otherWrite, .otherExecute]) {
try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [
Test(0o000, 0, 0, 0),
Test(0o700, r|w|x, 0, 0),
Test(0o770, r|w|x, r, 0),
Test(0o777, r|w|x, r, r)
]
try runTests(tests, at: path)
}
}
}
/// Test that setting permissions on a file works as expected
func testPermissions() throws {
// See https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/persistent-storage#permissions
try XCTSkipIf(NSUserName() == "ContainerAdministrator", "containers use a different permission model")
try FilePermissions.withCreationMask([]) {
try withTemporaryFilePath(basename: "testPermissions") { path in
let tests = [
Test(0o000, 0, 0, 0),
Test(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, 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, 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)
}
}
}
}
#endif // os(Windows)
@@ -15,7 +15,7 @@ import XCTest
@testable import System
#endif
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
struct TestPathComponents: TestCase {
var path: FilePath
var expectedRoot: FilePath.Root?
@@ -100,7 +100,7 @@ struct TestPathComponents: TestCase {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
final class FilePathComponentsTest: XCTestCase {
func testAdHocRRC() {
var path: FilePath = "/usr/local/bin"
@@ -231,7 +231,7 @@ final class FilePathComponentsTest: XCTestCase {
}
func testCases() {
var testPaths: Array<TestPathComponents> = [
let testPaths: Array<TestPathComponents> = [
TestPathComponents("", root: nil, []),
TestPathComponents("/", root: "/", []),
TestPathComponents("foo", root: nil, ["foo"]),
@@ -240,28 +240,16 @@ final class FilePathComponentsTest: XCTestCase {
TestPathComponents("foo/bar", root: nil, ["foo", "bar"]),
TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]),
TestPathComponents("/foo/bar", root: "/", ["foo", "bar"]),
TestPathComponents("///foo//", root: "/", ["foo"]),
TestPathComponents("/foo///bar", root: "/", ["foo", "bar"]),
TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]),
TestPathComponents("foo///bar/baz/", root: nil, ["foo", "bar", "baz"]),
TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"]),
TestPathComponents("./", root: nil, ["."]),
TestPathComponents("./..", root: nil, [".", ".."]),
TestPathComponents("/./..//", root: "/", [".", ".."]),
]
#if !os(Windows)
testPaths.append(contentsOf:[
TestPathComponents("///foo//", root: "/", ["foo"]),
TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"])
])
#else
// On Windows, these are UNC paths
testPaths.append(contentsOf:[
TestPathComponents("///foo//", root: "///foo//", []),
TestPathComponents("//foo///bar/baz/", root: "//foo//", ["bar", "baz"])
])
#endif
testPaths.forEach {
$0.runAllTests()
}
testPaths.forEach { $0.runAllTests() }
}
func testSeparatorNormalization() {
@@ -1,129 +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
*/
import XCTest
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
@available(System 0.0.1, *)
final class FilePathDecodableTest: XCTestCase {
func testInvalidFilePath() {
// _storage is a valid SystemString, but the invariants of FilePath are
// violated (specifically, _storage is not normal).
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 49, 48, 57, 44, 45, 55, 54, 44, 53, 53, 44, 55, 49, 44, 49, 52,
44, 53, 57, 44, 45, 49, 49, 50, 44, 45, 56, 52, 44, 52, 50, 44, 45, 55,
48, 44, 45, 49, 48, 52, 44, 55, 51, 44, 45, 54, 44, 50, 44, 53, 55, 44,
54, 50, 44, 45, 56, 55, 44, 45, 53, 44, 45, 54, 53, 44, 45, 51, 57, 44,
45, 49, 48, 57, 44, 45, 55, 54, 44, 51, 48, 44, 53, 50, 44, 45, 56, 50,
44, 45, 54, 48, 44, 45, 50, 44, 56, 53, 44, 49, 50, 51, 44, 45, 56, 52,
44, 45, 53, 56, 44, 49, 49, 52, 44, 49, 44, 45, 49, 49, 54, 44, 56, 48,
44, 49, 48, 52, 44, 45, 55, 56, 44, 45, 52, 53, 44, 49, 54, 44, 45, 52,
54, 44, 55, 44, 49, 49, 56, 44, 45, 50, 52, 44, 54, 50, 44, 54, 52, 44,
45, 52, 49, 44, 45, 49, 48, 51, 44, 53, 44, 45, 55, 53, 44, 50, 50, 44,
45, 49, 48, 53, 44, 45, 49, 54, 44, 52, 55, 44, 52, 55, 44, 49, 50, 52,
44, 45, 53, 55, 44, 53, 51, 44, 49, 49, 49, 44, 49, 53, 44, 45, 50, 55,
44, 54, 54, 44, 45, 49, 54, 44, 49, 48, 50, 44, 49, 48, 54, 44, 49, 51,
44, 49, 48, 53, 44, 45, 49, 49, 50, 44, 55, 56, 44, 45, 53, 48, 44, 50,
48, 44, 56, 44, 45, 50, 55, 44, 52, 52, 44, 52, 44, 56, 44, 54, 53, 44,
50, 51, 44, 57, 55, 44, 45, 50, 56, 44, 56, 56, 44, 52, 50, 44, 45, 51,
54, 44, 45, 50, 51, 44, 49, 48, 51, 44, 57, 57, 44, 45, 53, 56, 44, 45,
49, 49, 48, 44, 45, 53, 52, 44, 45, 49, 49, 55, 44, 45, 57, 52, 44, 45,
55, 50, 44, 50, 57, 44, 45, 50, 52, 44, 45, 56, 52, 44, 53, 55, 44, 45,
49, 50, 54, 44, 52, 52, 44, 55, 53, 44, 55, 54, 44, 52, 57, 44, 45, 52,
49, 44, 45, 50, 53, 44, 50, 52, 44, 45, 49, 50, 54, 44, 55, 44, 50, 56,
44, 45, 52, 56, 44, 56, 55, 44, 51, 49, 44, 45, 49, 49, 53, 44, 55, 44,
45, 54, 48, 44, 53, 57, 44, 49, 51, 44, 55, 57, 44, 53, 48, 44, 45, 57,
54, 44, 45, 50, 44, 45, 50, 52, 44, 45, 57, 49, 44, 55, 49, 44, 45, 49,
50, 53, 44, 52, 50, 44, 45, 56, 52, 44, 52, 44, 53, 57, 44, 49, 50, 53,
44, 49, 50, 49, 44, 45, 50, 54, 44, 45, 49, 50, 44, 45, 49, 48, 53, 44,
53, 54, 44, 49, 49, 48, 44, 49, 52, 44, 45, 49, 48, 52, 44, 45, 53, 50,
44, 45, 53, 56, 44, 45, 54, 44, 45, 50, 54, 44, 45, 52, 55, 44, 53, 57,
44, 52, 50, 44, 49, 50, 51, 44, 52, 52, 44, 45, 57, 50, 44, 45, 50, 57,
44, 45, 51, 54, 44, 45, 54, 50, 44, 50, 54, 44, 45, 49, 55, 44, 45, 49,
48, 44, 45, 56, 49, 44, 54, 49, 44, 52, 55, 44, 45, 57, 52, 44, 45, 49,
48, 54, 44, 49, 53, 44, 49, 48, 48, 44, 45, 49, 50, 49, 44, 45, 49, 49,
49, 44, 51, 44, 45, 57, 44, 52, 54, 44, 45, 55, 48, 44, 45, 49, 57, 44,
52, 56, 44, 45, 49, 50, 44, 45, 57, 49, 44, 45, 50, 48, 44, 49, 51, 44,
54, 53, 44, 45, 55, 48, 44, 52, 49, 44, 45, 57, 53, 44, 49, 48, 52, 44,
45, 55, 53, 44, 45, 49, 49, 53, 44, 49, 48, 49, 44, 45, 57, 52, 44, 45,
49, 50, 51, 44, 45, 51, 53, 44, 45, 50, 49, 44, 45, 52, 50, 44, 45, 51,
48, 44, 45, 55, 49, 44, 45, 49, 49, 57, 44, 52, 52, 44, 49, 49, 49, 44,
49, 48, 53, 44, 54, 54, 44, 45, 49, 50, 54, 44, 55, 50, 44, 45, 52, 48,
44, 49, 50, 49, 44, 45, 50, 49, 44, 52, 50, 44, 45, 55, 56, 44, 49, 50,
54, 44, 56, 49, 44, 45, 57, 52, 44, 55, 52, 44, 49, 49, 50, 44, 45, 56,
54, 44, 51, 50, 44, 55, 54, 44, 49, 49, 55, 44, 45, 56, 44, 56, 54, 44,
49, 48, 51, 44, 54, 50, 44, 49, 49, 55, 44, 54, 55, 44, 45, 56, 54, 44,
45, 49, 48, 48, 44, 45, 49, 48, 57, 44, 45, 53, 52, 44, 45, 51, 49, 44,
45, 56, 57, 44, 48, 93,125,125,
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
func testInvalidSystemString() {
// _storage is a SystemString whose invariants are violated; it contains
// a non-terminating null byte.
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 49, 49, 49, 44, 48, 44, 45, 49, 54, 44, 57, 49, 44, 52, 54, 44,
45, 49, 48, 50, 44, 49, 49, 53, 44, 45, 50, 49, 44, 45, 49, 49, 56, 44,
52, 57, 44, 57, 50, 44, 45, 49, 48, 44, 53, 56, 44, 45, 55, 48, 44, 57,
55, 44, 56, 44, 57, 57, 44, 48, 93,125, 125
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
func testInvalidExample() {
// Another misformed example from Johannes that violates FilePath's
// invariants by virtue of not being normalized.
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 56, 55, 44, 50, 52, 44, 45, 49, 49, 53, 44, 45, 49, 57, 44, 49,
50, 50, 44, 45, 54, 56, 44, 57, 49, 44, 45, 49, 48, 54, 44, 45, 49, 48,
48, 44, 45, 49, 49, 52, 44, 53, 54, 44, 45, 54, 53, 44, 49, 49, 56, 44,
45, 54, 48, 44, 54, 54, 44, 45, 52, 50, 44, 55, 55, 44, 45, 54, 44, 45,
52, 50, 44, 45, 56, 56, 44, 52, 55, 44, 48, 93,125, 125
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
func testEmptyString() {
// FilePath with an empty (and hence not null-terminated) SystemString.
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 93,125,125
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
}
@@ -6,7 +6,7 @@
#endif
// Why can't I write this extension on `FilePath.ComponentView.SubSequence`?
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension Slice where Base == FilePath.ComponentView {
internal var _storageSlice: SystemString.SubSequence {
base._path._storage[self.startIndex._storage ..< self.endIndex._storage]
@@ -15,7 +15,7 @@ extension Slice where Base == FilePath.ComponentView {
// Proposed API that didn't make the cut, but we stil want to keep our testing for
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Returns `self` relative to `base`.
/// This does not cosult the file system or resolve symlinks.
@@ -7,7 +7,6 @@
See https://swift.org/LICENSE.txt for license information
*/
#if ENABLE_MOCKING
import XCTest
#if SYSTEM_PACKAGE
@@ -69,7 +68,7 @@ extension ParsingTestCase {
@testable import System
#endif
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
final class FilePathParsingTest: XCTestCase {
func testNormalization() {
let unixPaths: Array<ParsingTestCase> = [
@@ -106,4 +105,3 @@ final class FilePathParsingTest: XCTestCase {
}
}
}
#endif // ENABLE_MOCKING
@@ -7,7 +7,6 @@
See https://swift.org/LICENSE.txt for license information
*/
#if ENABLE_MOCKING
import XCTest
#if SYSTEM_PACKAGE
@@ -147,7 +146,7 @@ extension SyntaxTestCase {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension SyntaxTestCase {
func testComponents(_ path: FilePath, expected: [String]) {
let expectedComponents = expected.map { FilePath.Component($0)! }
@@ -343,7 +342,7 @@ private struct WindowsRootTestCase: TestCase {
var line: UInt
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension WindowsRootTestCase {
func runAllTests() {
withWindowsPaths(enabled: true) {
@@ -358,7 +357,7 @@ extension WindowsRootTestCase {
}
}
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
final class FilePathSyntaxTest: XCTestCase {
func testPathSyntax() {
let unixPaths: Array<SyntaxTestCase> = [
@@ -1065,10 +1064,7 @@ final class FilePathSyntaxTest: XCTestCase {
XCTAssert(path.lexicallyContains("usr"))
XCTAssert(path.lexicallyContains("/usr"))
XCTAssert(path.lexicallyContains("local/bin"))
#if !os(Windows)
// On Windows, this is a relative path and is still contained
XCTAssert(!path.lexicallyContains("/local/bin"))
#endif
path.append("..")
XCTAssert(!path.lexicallyContains("local/bin"))
XCTAssert(path.lexicallyContains("local/bin/.."))
@@ -1239,4 +1235,3 @@ final class FilePathSyntaxTest: XCTestCase {
}
}
#endif // ENABLE_MOCKING
@@ -1,58 +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
*/
import XCTest
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
final class TemporaryPathTest: XCTestCase {
#if SYSTEM_PACKAGE_DARWIN
func testNotInSlashTmp() throws {
try withTemporaryFilePath(basename: "NotInSlashTmp") { path in
// We shouldn't be using "/tmp" on Darwin
XCTAssertNotEqual(path.components.first!, "tmp")
}
}
#endif
func testUnique() throws {
try withTemporaryFilePath(basename: "test") { path in
let strPath = String(decoding: path)
XCTAssert(strPath.contains("test"))
try withTemporaryFilePath(basename: "test") { path2 in
let strPath2 = String(decoding: path2)
XCTAssertNotEqual(strPath, strPath2)
}
}
}
func testCleanup() throws {
var thePath: FilePath? = nil
try withTemporaryFilePath(basename: "test") { path in
thePath = path.appending("foo.txt")
let fd = try FileDescriptor.open(thePath!, .readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite)
_ = try fd.closeAfter {
try fd.writeAll("Hello World".utf8)
}
}
XCTAssertThrowsError(try FileDescriptor.open(thePath!, .readOnly)) {
error in
XCTAssertEqual(error as! Errno, Errno.noSuchFileOrDirectory)
}
}
}
@@ -15,63 +15,40 @@ import SystemPackage
import System
#endif
@available(System 0.0.1, *)
func filePathFromInvalidCodePointSequence<S: Sequence>(_ bytes: S) -> FilePath where S.Element == CInterop.PlatformUnicodeEncoding.CodeUnit {
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
func filePathFromUnterminatedBytes<S: Sequence>(_ bytes: S) -> FilePath where S.Element == UInt8 {
var array = Array(bytes)
assert(array.last != 0, "already null terminated")
array += [0]
return array.withUnsafeBufferPointer {
$0.withMemoryRebound(to: CInterop.PlatformChar.self) {
$0.withMemoryRebound(to: CChar.self) {
FilePath(platformString: $0.baseAddress!)
}
}
}
let invalidBytes: [UInt8] = [0x2F, 0x61, 0x2F, 0x62, 0x2F, 0x83]
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
final class FilePathTest: XCTestCase {
struct TestPath {
let filePath: FilePath
let string: String
let validString: Bool
init(filePath: FilePath, string: String, validString: Bool) {
self.filePath = filePath
#if os(Windows)
self.string = string.replacingOccurrences(of: "/", with: "\\")
#else
self.string = string
#endif
self.validString = validString
}
let validUTF8: Bool
}
#if os(Windows)
static let invalidSequence: [UTF16.CodeUnit] = [0xd800, 0x0020]
static let invalidSequenceTest =
TestPath(filePath: filePathFromInvalidCodePointSequence(invalidSequence),
string: String(decoding: invalidSequence, as: UTF16.self),
validString: false)
#else
static let invalidSequence: [UTF8.CodeUnit] = [0x2F, 0x61, 0x2F, 0x62, 0x2F, 0x83]
static let invalidSequenceTest =
TestPath(filePath: filePathFromInvalidCodePointSequence(invalidSequence),
string: String(decoding: invalidSequence, as: UTF8.self),
validString: false)
#endif
var testPaths: [TestPath] = [
let testPaths: [TestPath] = [
// empty
TestPath(filePath: FilePath(), string: String(), validString: true),
TestPath(filePath: FilePath(), string: String(), validUTF8: true),
// valid ascii
TestPath(filePath: "/a/b/c", string: "/a/b/c", validString: true),
TestPath(filePath: "/a/b/c", string: "/a/b/c", validUTF8: true),
// valid utf8
TestPath(filePath: "/あ/🧟‍♀️", string: "/あ/🧟‍♀️", validString: true),
TestPath(filePath: "/あ/🧟‍♀️", string: "/あ/🧟‍♀️", validUTF8: true),
// invalid sequence
invalidSequenceTest,
// invalid utf8
TestPath(filePath: filePathFromUnterminatedBytes(invalidBytes), string: String(decoding: invalidBytes, as: UTF8.self), validUTF8: false),
]
func testFilePath() {
@@ -82,8 +59,8 @@ final class FilePathTest: XCTestCase {
XCTAssertEqual(testPath.string, String(decoding: testPath.filePath))
// TODO: test component CodeUnit representation validation
if testPath.validString {
// TODO: test component UTF8 validation
if testPath.validUTF8 {
XCTAssertEqual(testPath.filePath, FilePath(testPath.string))
XCTAssertEqual(testPath.string, String(validating: testPath.filePath))
} else {
+5 -17
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 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
@@ -14,11 +14,8 @@ import SystemPackage
#else
import System
#endif
#if canImport(Android)
import Android
#endif
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
final class FileDescriptorTest: XCTestCase {
func testStandardDescriptors() {
XCTAssertEqual(FileDescriptor.standardInput.rawValue, 0)
@@ -32,7 +29,6 @@ final class FileDescriptorTest: XCTestCase {
XCTAssertEqual(O_WRONLY, FileDescriptor.AccessMode.writeOnly.rawValue)
XCTAssertEqual(O_RDWR, FileDescriptor.AccessMode.readWrite.rawValue)
#if !os(WASI) // Would need to use _getConst funcs from CSystem
#if !os(Windows)
XCTAssertEqual(O_NONBLOCK, FileDescriptor.OpenOptions.nonBlocking.rawValue)
#endif
@@ -40,32 +36,24 @@ final class FileDescriptorTest: XCTestCase {
XCTAssertEqual(O_CREAT, FileDescriptor.OpenOptions.create.rawValue)
XCTAssertEqual(O_TRUNC, FileDescriptor.OpenOptions.truncate.rawValue)
XCTAssertEqual(O_EXCL, FileDescriptor.OpenOptions.exclusiveCreate.rawValue)
#endif // !os(WASI
#if !os(Windows)
XCTAssertEqual(O_NOFOLLOW, FileDescriptor.OpenOptions.noFollow.rawValue)
XCTAssertEqual(O_CLOEXEC, FileDescriptor.OpenOptions.closeOnExec.rawValue)
#endif
// BSD only
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue)
XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue)
#endif
#if SYSTEM_PACKAGE_DARWIN
XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue)
XCTAssertEqual(O_EVTONLY, FileDescriptor.OpenOptions.eventOnly.rawValue)
#endif
#if os(FreeBSD)
XCTAssertEqual(O_SYNC, FileDescriptor.OpenOptions.sync.rawValue)
#endif
XCTAssertEqual(SEEK_SET, FileDescriptor.SeekOrigin.start.rawValue)
XCTAssertEqual(SEEK_CUR, FileDescriptor.SeekOrigin.current.rawValue)
XCTAssertEqual(SEEK_END, FileDescriptor.SeekOrigin.end.rawValue)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssertEqual(SEEK_HOLE, FileDescriptor.SeekOrigin.nextHole.rawValue)
XCTAssertEqual(SEEK_DATA, FileDescriptor.SeekOrigin.nextData.rawValue)
#endif
@@ -76,7 +64,7 @@ final class FileDescriptorTest: XCTestCase {
}
@available(System 0.0.1, *)
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
final class FilePermissionsTest: XCTestCase {
func testPermissions() {
-34
View File
@@ -1,34 +0,0 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import XCTest
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
import System
#endif
func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
return withUnsafePointer(to: request.rawValue) {
let requestBuf = UnsafeBufferPointer(start: $0, count: 1)
let rawBytes = UnsafeRawBufferPointer(requestBuf)
return .init(rawBytes)
}
}
// This test suite compares various IORequests bit-for-bit to IORequests
// that were generated with liburing or manually written out,
// which are known to work correctly.
final class IORequestTests: XCTestCase {
func testNop() {
let req = IORing.Request.nop().makeRawRequest()
let sourceBytes = requestBytes(req)
// convenient property of nop: it's all zeros!
// for some unknown reason, liburing sets the fd field to -1.
// we're not trying to be bug-compatible with it, so 0 *should* work.
XCTAssertEqual(sourceBytes, .init(repeating: 0, count: 64))
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
-132
View File
@@ -1,132 +0,0 @@
#if compiler(>=6.2) && $Lifetimes
#if os(Linux)
import XCTest
import CSystem //for eventfd
#if SYSTEM_PACKAGE
import SystemPackage
#else
import System
#endif
func uringEnabled() throws -> Bool {
do {
let procPath = FilePath("/proc/sys/kernel/io_uring_disabled")
let fd = try FileDescriptor.open(procPath, .readOnly)
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0)
_ = try fd.read(into: buffer)
if buffer.load(fromByteOffset: 0, as: Int.self) == 0 {
return true
}
} catch (_) {
return false
}
return false
}
final class IORingTests: XCTestCase {
func testInit() throws {
guard try uringEnabled() else { return }
_ = try IORing(queueDepth: 32, flags: [])
}
func testNop() throws {
guard try uringEnabled() else { return }
var ring = try IORing(queueDepth: 32, flags: [])
_ = try ring.submit(linkedRequests: .nop())
let completion = try ring.blockingConsumeCompletion()
XCTAssertEqual(completion.result, 0)
}
func makeHelloWorldFile() throws -> (dir: FileDescriptor, file: FilePath) {
mkdir("/tmp/IORingTests/", 0o777)
let path: FilePath = "/tmp/IORingTests/test.txt"
let fd = try FileDescriptor.open(
path,
.readWrite,
options: .create,
permissions: .ownerReadWrite
)
try fd.writeAll("Hello, World!".utf8)
try fd.close()
let parent = try FileDescriptor.open("/tmp/IORingTests/", .readOnly)
return (parent, path)
}
func cleanUpHelloWorldFile(_ parent: FileDescriptor) throws {
try parent.close()
rmdir("/tmp/IORingTests/")
}
func setupTestRing(depth: Int, fileSlots: Int, buffers: [UnsafeMutableRawBufferPointer]) throws -> IORing {
var ring: IORing = try IORing(queueDepth: UInt32(depth))
_ = try ring.registerFileSlots(count: 1)
_ = try ring.registerBuffers(buffers)
return ring
}
func testUndersizedSubmissionQueue() throws {
guard try uringEnabled() else { return }
var ring: IORing = try IORing(queueDepth: 1)
let enqueued = ring.prepare(linkedRequests: .nop(), .nop())
XCTAssertFalse(enqueued)
}
// Exercises opening, reading, closing, registered files, registered buffers, and eventfd
func testOpenReadAndWriteFixedFile() throws {
guard try uringEnabled() else { return }
let (parent, path) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
let eventFD = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE)))
try ring.registerEventFD(eventFD)
//Part 1: read the file we just created, and make sure the eventfd fires
let enqueued = try ring.submit(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly),
.read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]),
.close(ring.registeredFileSlots[0]))
XCTAssert(enqueued)
let efdBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 0)
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //open
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //read
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //close
let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result, "Hello, World!")
//Part 2: delete that file, then use the ring to write out a new one
let rmResult = path.withPlatformString {
remove($0)
}
XCTAssertEqual(rmResult, 0)
let enqueued2 = try ring.submit(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readWrite, options: .create, permissions: .ownerReadWrite),
.write(ring.registeredBuffers[0], into: ring.registeredFileSlots[0]),
.close(ring.registeredFileSlots[0]))
XCTAssert(enqueued2)
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //open
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //write
_ = try eventFD.read(into: efdBuf)
_ = try ring.blockingConsumeCompletion() //close
memset(rawBuffer.baseAddress!, 0, rawBuffer.count)
//Verify using a non-ring IO method that what we wrote matches our expectations
print("about to open")
let nonRingFD = try FileDescriptor.open(path, .readOnly)
let bytesRead = try nonRingFD.read(into: rawBuffer)
XCTAssert(bytesRead == 13)
let result2 = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result2, "Hello, World!")
try cleanUpHelloWorldFile(parent)
efdBuf.deallocate()
rawBuffer.deallocate()
}
}
#endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes
+34 -132
View File
@@ -1,13 +1,13 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2022 - 2025 Apple Inc. and the Swift System project authors
Copyright (c) 2022 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
#if false && swift(>=5.8) && $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
import XCTest
import Darwin.Mach
@@ -18,40 +18,35 @@ import SystemPackage
import System
#endif
@available(System 1.4.0, *)
final class MachPortTests: XCTestCase {
func refCountForMachPortName(name:mach_port_name_t, kind:mach_port_right_t) -> mach_port_urefs_t {
var refCount:mach_port_urefs_t = .max
let kr = mach_port_get_refs(mach_task_self_, name, kind, &refCount)
if kr == KERN_INVALID_NAME {
refCount = 0
} else {
XCTAssertEqual(kr, KERN_SUCCESS)
var refCount:mach_port_urefs_t = 0
withUnsafeMutablePointer(to: &refCount) { refCount in
let kr = mach_port_get_refs(mach_task_self_, name, kind, refCount)
assert(kr == KERN_SUCCESS)
}
return refCount
}
func scopedReceiveRight(name:mach_port_name_t) -> mach_port_urefs_t {
let right = Mach.Port<Mach.ReceiveRight>(name:name) // this should automatically deallocate when going out of scope
defer { _ = right }
_ = Mach.Port<Mach.ReceiveRight>(name:name) // this should automatically deallocate when going out of scope
return refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_RECEIVE)
}
func testReceiveRightDeallocation() throws {
var name: mach_port_name_t = 0xFFFFFFFF
let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &name)
XCTAssertEqual(kr, KERN_SUCCESS)
func testRecieveRightDeallocation() throws {
var name:mach_port_name_t = 0 // Never read
withUnsafeMutablePointer(to:&name) { name in
let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, name)
assert(kr == KERN_SUCCESS)
}
XCTAssertNotEqual(name, 0xFFFFFFFF)
XCTAssert(name != 0xFFFFFFFF)
let originalCount = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_RECEIVE)
XCTAssertEqual(originalCount, 1)
let one = scopedReceiveRight(name:name)
let zero = refCountForMachPortName(name:name, kind: MACH_PORT_RIGHT_RECEIVE)
let incrementedCount = scopedReceiveRight(name:name)
XCTAssertEqual(incrementedCount, 1);
let deallocated = refCountForMachPortName(name:name, kind: MACH_PORT_RIGHT_RECEIVE)
XCTAssertEqual(deallocated, 0);
XCTAssert(one == 1);
XCTAssert(zero == 0);
}
func consumeSendRightAutomatically(name:mach_port_name_t) -> mach_port_urefs_t {
@@ -66,11 +61,11 @@ final class MachPortTests: XCTestCase {
let recv = Mach.Port<Mach.ReceiveRight>()
recv.withBorrowedName { name in
let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND))
XCTAssertEqual(kr, KERN_SUCCESS)
XCTAssert(kr == KERN_SUCCESS)
let one = consumeSendRightAutomatically(name:name)
XCTAssertEqual(one, 1);
XCTAssert(one == 1);
let zero = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND)
XCTAssertEqual(zero, 0);
XCTAssert(zero == 0);
}
}
@@ -82,70 +77,29 @@ final class MachPortTests: XCTestCase {
let one = send.withBorrowedName { name in
return self.refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND)
}
XCTAssertEqual(one, 1)
XCTAssert(one == 1)
return send.relinquish()
})()
let stillOne = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND)
XCTAssertEqual(stillOne, 1)
recv.withBorrowedName {
let alsoOne = refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE)
XCTAssertEqual(alsoOne, 1)
}
}
func testSendOnceRightRelinquishment() throws {
let recv = Mach.Port<Mach.ReceiveRight>()
let name = ({
let send = recv.makeSendOnceRight()
let one = send.withBorrowedName { name in
return self.refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_SEND_ONCE)
}
XCTAssertEqual(one, 1)
return send.relinquish()
})()
let stillOne = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_SEND_ONCE)
XCTAssertEqual(stillOne, 1)
recv.withBorrowedName {
let alsoOne = refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE)
XCTAssertEqual(alsoOne, 1)
}
}
func testReceiveRightRelinquishment() throws {
let recv = Mach.Port<Mach.ReceiveRight>()
let one = recv.withBorrowedName {
self.refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE)
}
XCTAssertEqual(one, 1)
let name = recv.unguardAndRelinquish()
let stillOne = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_RECEIVE)
XCTAssertEqual(stillOne, 1)
XCTAssert(stillOne == 1)
}
func testMakeSendCountSettable() throws {
var recv = Mach.Port<Mach.ReceiveRight>()
XCTAssertEqual(recv.makeSendCount, 0)
XCTAssert(recv.makeSendCount == 0)
recv.makeSendCount = 7
XCTAssertEqual(recv.makeSendCount, 7)
XCTAssert(recv.makeSendCount == 7)
}
func makeSendRight() throws -> Mach.Port<Mach.SendRight> {
let recv = Mach.Port<Mach.ReceiveRight>()
let zero = recv.makeSendCount
XCTAssertEqual(zero, 0)
XCTAssert(zero == 0)
let send = recv.makeSendRight()
let one = recv.makeSendCount
XCTAssertEqual(one, 1)
XCTAssert(one == 1)
return send
}
@@ -156,10 +110,10 @@ final class MachPortTests: XCTestCase {
func testMakeSendOnceDoesntIncrementMakeSendCount() throws {
let recv = Mach.Port<Mach.ReceiveRight>()
let zero = recv.makeSendCount
XCTAssertEqual(zero, 0)
XCTAssert(zero == 0)
_ = recv.makeSendOnceRight()
let same = recv.makeSendCount
XCTAssertEqual(same, zero)
XCTAssert(same == zero)
}
func testMakeSendOnceIsUnique() throws {
@@ -167,7 +121,8 @@ final class MachPortTests: XCTestCase {
let once = recv.makeSendOnceRight()
recv.withBorrowedName { rname in
once.withBorrowedName { oname in
XCTAssertNotEqual(oname, rname)
print(oname, rname)
XCTAssert(oname != rname)
}
}
}
@@ -175,68 +130,15 @@ final class MachPortTests: XCTestCase {
func testCopySend() throws {
let recv = Mach.Port<Mach.ReceiveRight>()
let zero = recv.makeSendCount
XCTAssertEqual(zero, 0)
XCTAssert(zero == 0)
let send = recv.makeSendRight()
let one = recv.makeSendCount
XCTAssertEqual(one, 1)
XCTAssert(one == 1)
_ = try send.copySendRight()
let same = recv.makeSendCount
XCTAssertEqual(same, one)
XCTAssert(same == one)
}
func testCopyDeadName() throws {
let recv = Mach.Port<Mach.ReceiveRight>()
let send = recv.makeSendRight()
_ = consume recv // and turn `send` into a dead name
XCTAssertThrowsError(
_ = try send.copySendRight(),
"Copying a dead name should throw"
) { error in
XCTAssertEqual(
error as! Mach.PortRightError, Mach.PortRightError.deadName
)
}
}
func testCopyDeadName2() throws {
let send = Mach.Port<Mach.SendRight>(name: 0xffffffff)
XCTAssertThrowsError(
_ = try send.copySendRight(),
"Copying a dead name should throw"
) { error in
XCTAssertEqual(
error as! Mach.PortRightError, Mach.PortRightError.deadName
)
}
}
func testMakeReceiveRightFromExistingName() throws {
var name = mach_port_name_t(MACH_PORT_NULL)
var kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &name)
XCTAssertEqual(kr, KERN_SUCCESS)
XCTAssertNotEqual(name, mach_port_name_t(MACH_PORT_NULL))
let context = mach_port_context_t(arc4random())
kr = mach_port_guard(mach_task_self_, name, context, 0)
XCTAssertEqual(kr, KERN_SUCCESS)
let right = Mach.Port<Mach.ReceiveRight>(name: name, context: context)
right.withBorrowedName {
XCTAssertEqual(name, $0)
XCTAssertEqual(context, $1)
}
}
func testDeinitDeadSendRights() throws {
let recv = Mach.Port<Mach.ReceiveRight>()
let send = recv.makeSendRight()
let send1 = recv.makeSendOnceRight()
_ = consume recv
// `send` and `send1` have become dead names
_ = consume send
_ = consume send1
}
}
#endif
+1 -3
View File
@@ -7,7 +7,6 @@
See https://swift.org/LICENSE.txt for license information
*/
#if ENABLE_MOCKING
import XCTest
#if SYSTEM_PACKAGE
@@ -16,7 +15,7 @@ import XCTest
@testable import System
#endif
@available(System 0.0.2, *)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
final class MockingTest: XCTestCase {
func testMocking() {
XCTAssertFalse(mockingEnabled)
@@ -49,4 +48,3 @@ final class MockingTest: XCTestCase {
XCTAssertFalse(mockingEnabled)
}
}
#endif // ENABLE_MOCKING
+2 -7
View File
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
Copyright (c) 2020 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
@@ -101,7 +101,7 @@ struct StringTest: TestCase {
// Test null insertion
let rawChars = raw.lazy.map { SystemChar($0) }
expectEqual(sysRaw, SystemString(rawChars.dropLast()))
sysRaw.withNullTerminatedSystemChars {
sysRaw.withSystemChars { // TODO: assuming we want null in withSysChars
expectEqualSequence(rawChars, $0, "rawChars")
}
@@ -254,11 +254,6 @@ final class SystemStringTest: XCTestCase {
XCTAssert(str == "abcd")
}
func testStringProperty() {
let source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
let str = SystemString(platformString: source)
XCTAssertEqual(str.string, str[...].string)
}
}
extension SystemStringTest {
@@ -17,7 +17,6 @@ import XCTest
internal struct Wildcard: Hashable {}
#if ENABLE_MOCKING
extension Trace.Entry {
/// This implements `==` with wildcard matching.
/// (`Entry` cannot conform to `Equatable`/`Hashable` this way because
@@ -34,7 +33,6 @@ extension Trace.Entry {
return true
}
}
#endif // ENABLE_MOCKING
// To aid debugging, force failures to fatal error
internal var forceFatalFailures = false
@@ -83,7 +81,6 @@ extension TestCase {
fail(message)
}
}
#if ENABLE_MOCKING
func expectMatch(
_ expected: Trace.Entry?, _ actual: Trace.Entry?,
_ message: String? = nil
@@ -105,7 +102,6 @@ extension TestCase {
fail(message)
}
}
#endif // ENABLE_MOCKING
func expectNil<T>(
_ actual: T?,
_ message: String? = nil
@@ -146,7 +142,6 @@ extension TestCase {
}
#if ENABLE_MOCKING
internal struct MockTestCase: TestCase {
var file: StaticString
var line: UInt
@@ -246,7 +241,6 @@ internal struct MockTestCase: TestCase {
}
}
}
#endif // ENABLE_MOCKING
internal func withWindowsPaths(enabled: Bool, _ body: () -> ()) {
_withWindowsPaths(enabled: enabled, body)
+132
View File
@@ -0,0 +1,132 @@
#if !canImport(ObjectiveC) && swift(<5.5)
import XCTest
extension ErrnoTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__ErrnoTest = [
("testConstants", testConstants),
("testPatternMatching", testPatternMatching),
]
}
extension FileDescriptorTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FileDescriptorTest = [
("testConstants", testConstants),
("testStandardDescriptors", testStandardDescriptors),
]
}
extension FileOperationsTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FileOperationsTest = [
("testAdHocOpen", testAdHocOpen),
("testAdHocPipe", testAdHocPipe),
("testGithubIssues", testGithubIssues),
("testHelpers", testHelpers),
("testSyscalls", testSyscalls),
]
}
extension FilePathComponentsTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FilePathComponentsTest = [
("testAdHocRRC", testAdHocRRC),
("testCases", testCases),
("testSeparatorNormalization", testSeparatorNormalization),
]
}
extension FilePathParsingTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FilePathParsingTest = [
("testNormalization", testNormalization),
]
}
extension FilePathSyntaxTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FilePathSyntaxTest = [
("testAdHocMutations", testAdHocMutations),
("testFailableStringInitializers", testFailableStringInitializers),
("testLexicallyRelative", testLexicallyRelative),
("testPartialWindowsRoots", testPartialWindowsRoots),
("testPathSyntax", testPathSyntax),
("testPrefixSuffix", testPrefixSuffix),
]
}
extension FilePathTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FilePathTest = [
("testFilePath", testFilePath),
]
}
extension FilePermissionsTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FilePermissionsTest = [
("testPermissions", testPermissions),
]
}
extension MockingTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__MockingTest = [
("testMocking", testMocking),
]
}
extension SystemCharTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__SystemCharTest = [
("testIsLetter", testIsLetter),
]
}
extension SystemStringTest {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__SystemStringTest = [
("testAdHoc", testAdHoc),
("testPlatformString", testPlatformString),
]
}
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(ErrnoTest.__allTests__ErrnoTest),
testCase(FileDescriptorTest.__allTests__FileDescriptorTest),
testCase(FileOperationsTest.__allTests__FileOperationsTest),
testCase(FilePathComponentsTest.__allTests__FilePathComponentsTest),
testCase(FilePathParsingTest.__allTests__FilePathParsingTest),
testCase(FilePathSyntaxTest.__allTests__FilePathSyntaxTest),
testCase(FilePathTest.__allTests__FilePathTest),
testCase(FilePermissionsTest.__allTests__FilePermissionsTest),
testCase(MockingTest.__allTests__MockingTest),
testCase(SystemCharTest.__allTests__SystemCharTest),
testCase(SystemStringTest.__allTests__SystemStringTest),
]
}
#endif
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
# This script can be used to automatically add/remove `@available` attributes to
# declarations in Swift sources in this package.
#
# In order for this to work, ABI-impacting declarations need to be annotated
# with special comments in the following format:
#
# @available(/*System 0.0.2*/iOS 8, *)
# public func greeting() -> String {
# "Hello"
# }
#
# (The iOS 8 availability is a dummy no-op declaration -- it only has to be
# there because `@available(*)` isn't valid syntax, and commenting out the
# entire `@available` attribute would interfere with parser tools for doc
# comments. `iOS 8` is the shortest version string that matches the minimum
# possible deployment target for Swift code, so we use that as our dummy
# availability version. `@available(iOS 8, *)` is functionally equivalent to not
# having an `@available` attribute at all.)
#
# The script adds full availability incantations to these comments. It can run
# in one of two modes:
#
# By default, `expand-availability.py` expands availability macros within the
# comments. This is useful during package development to cross-reference
# availability across `SystemPackage` and the ABI-stable `System` module that
# ships in Apple's OS releases:
#
# @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
# public func greeting() -> String {
# "Hello"
# }
#
# `expand-availability.py --attributes` adds actual availability declarations.
# This is used by maintainers to build ABI stable releases of System on Apple's
# platforms:
#
# @available(/*System 0.0.2: */macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
# public func greeting() -> String {
# "Hello"
# }
#
# The script recognizes all three forms of these annotations and updates them on
# every run, so we can run the script to enable/disable attributes as needed.
import os
import os.path
import fileinput
import re
import sys
import argparse
versions = {
"System 0.0.1": "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0",
"System 0.0.2": "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0",
"System 1.1.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
"System 1.2.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
"System 1.3.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
}
parser = argparse.ArgumentParser(description="Expand availability macros.")
parser.add_argument("--attributes", help="Add @available attributes",
action="store_true")
args = parser.parse_args()
def swift_sources_in(path):
result = []
for (dir, _, files) in os.walk(path):
for file in files:
extension = os.path.splitext(file)[1]
if extension == ".swift":
result.append(os.path.join(dir, file))
return result
# Old-style syntax:
# /*System 0.0.2*/
# /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
# /*System 0.0.2*/@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
old_macro_pattern = re.compile(
r"/\*(System [^ *]+)(, @available\([^)]*\))?\*/(@available\([^)]*\))?")
# New-style comments:
# @available(/*SwiftSystem 0.0.2*/macOS 10, *)
# @available(/*SwiftSystem 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
# @available(/*SwiftSystem 0.0.2*/macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
#
# These do not interfere with our tools' ability to find doc comments.
macro_pattern = re.compile(
r"@available\(/\*(System [^ *:]+)[^*/)]*\*/([^)]*)\*\)")
def available_attribute(filename, lineno, symbolic_version):
expansion = versions[symbolic_version]
if expansion is None:
raise ValueError("{0}:{1}: error: Unknown System version '{0}'"
.format(fileinput.filename(), fileinput.lineno(), symbolic_version))
if args.attributes:
attribute = "@available(/*{0}*/{1}, *)".format(symbolic_version, expansion)
else:
# Sadly `@available(*)` is not valid syntax, so we have to mention at
# least one actual platform here.
attribute = "@available(/*{0}: {1}*/iOS 8, *)".format(symbolic_version, expansion)
return attribute
sources = swift_sources_in("Sources") + swift_sources_in("Tests")
for line in fileinput.input(files=sources, inplace=True):
match = re.search(macro_pattern, line)
if match is None:
match = re.search(old_macro_pattern, line)
if match:
symbolic_version = match.group(1)
replacement = available_attribute(
fileinput.filename(), fileinput.lineno(), symbolic_version)
line = line[:match.start()] + replacement + line[match.end():]
print(line, end="")
+10 -30
View File
@@ -36,7 +36,7 @@ function(get_swift_host_arch result_var_name)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
set("${result_var_name}" "armv7" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "amd64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
set("${result_var_name}" "amd64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
@@ -45,8 +45,6 @@ function(get_swift_host_arch result_var_name)
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
set("${result_var_name}" "i686" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "riscv64")
set("${result_var_name}" "riscv64" PARENT_SCOPE)
else()
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
endif()
@@ -69,28 +67,6 @@ function(get_swift_host_os result_var_name)
endif()
endfunction()
if(NOT Swift_MODULE_TRIPLE)
# Attempt to get the module triple from the Swift compiler.
set(module_triple_command "${CMAKE_Swift_COMPILER}" -print-target-info)
if(CMAKE_Swift_COMPILER_TARGET)
list(APPEND module_triple_command -target ${CMAKE_Swift_COMPILER_TARGET})
endif()
execute_process(COMMAND ${module_triple_command}
OUTPUT_VARIABLE target_info_json)
string(JSON module_triple GET "${target_info_json}" "target" "moduleTriple")
# Exit now if we failed to infer the triple.
if(NOT module_triple)
message(FATAL_ERROR
"Failed to get module triple from Swift compiler. "
"Compiler output: ${target_info_json}")
endif()
# Cache the module triple for future use.
set(Swift_MODULE_TRIPLE "${module_triple}" CACHE STRING "swift module triple used for installed swiftmodule and swiftinterface files")
mark_as_advanced(Swift_MODULE_TRIPLE)
endif()
function(_install_target module)
get_swift_host_os(swift_os)
get_target_property(type ${module} TYPE)
@@ -101,20 +77,24 @@ function(_install_target module)
set(swift swift)
endif()
install(TARGETS ${module})
install(TARGETS ${module}
ARCHIVE DESTINATION lib/${swift}/${swift_os}
LIBRARY DESTINATION lib/${swift}/${swift_os}
RUNTIME DESTINATION bin)
if(type STREQUAL EXECUTABLE)
return()
endif()
get_swift_host_arch(swift_arch)
get_target_property(module_name ${module} Swift_MODULE_NAME)
if(NOT module_name)
set(module_name ${module})
endif()
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftdoc
DESTINATION ${CMAKE_INSTALL_LIBDIR}/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${Swift_MODULE_TRIPLE}.swiftdoc)
DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${swift_arch}.swiftdoc)
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftmodule
DESTINATION ${CMAKE_INSTALL_LIBDIR}/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${Swift_MODULE_TRIPLE}.swiftmodule)
DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
RENAME ${swift_arch}.swiftmodule)
endfunction()