mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8a44d836f | ||
|
|
b80d743dab | ||
|
|
eeeb81d0cd | ||
|
|
234e15320e | ||
|
|
154cbf7c95 | ||
|
|
3f4e7cb45c | ||
|
|
11d481252d | ||
|
|
2e8f58ac41 | ||
|
|
5cd7eade6d | ||
|
|
b2d4917ebe | ||
|
|
d96435c72b | ||
|
|
95784d018f | ||
|
|
448bef7c38 | ||
|
|
69e737de3d | ||
|
|
afeecb6c28 | ||
|
|
69eee996ac | ||
|
|
209dfeacb8 | ||
|
|
b2b60a6b94 | ||
|
|
e11703d915 | ||
|
|
8df901cb24 | ||
|
|
938fda53e2 | ||
|
|
e7ffa45882 | ||
|
|
607542a559 | ||
|
|
b9e4d2b2ba | ||
|
|
473b493ab0 | ||
|
|
9eb1f34cbf | ||
|
|
6c64372b85 | ||
|
|
3a4e2f8071 | ||
|
|
53471ce33b | ||
|
|
f1d7eb52c6 | ||
|
|
cf7530848e | ||
|
|
5ae5d5a3af | ||
|
|
bcc7f6d569 | ||
|
|
e293300430 | ||
|
|
4cafcc96f6 | ||
|
|
85de4e51e2 | ||
|
|
d4e2b09c37 | ||
|
|
5ea5b2e89a | ||
|
|
8564f96d1f | ||
|
|
b85a788897 | ||
|
|
88a60e08b3 | ||
|
|
4c612a1e29 | ||
|
|
603c451818 | ||
|
|
d2ba781702 | ||
|
|
a1f77d0e1a | ||
|
|
6a9e38e7bd | ||
|
|
848a927122 | ||
|
|
2b30f8820c | ||
|
|
1a8d472f35 | ||
|
|
f9d6b48027 | ||
|
|
d82bccbb17 | ||
|
|
f9266c8518 | ||
|
|
b7dc8e8e41 | ||
|
|
7d45e0dd46 | ||
|
|
62e62b3a7c | ||
|
|
ab09f04cfe | ||
|
|
0cf079efea | ||
|
|
52f603c6b3 | ||
|
|
d18980c960 | ||
|
|
08800445eb | ||
|
|
de1f8bce5e | ||
|
|
0368ce547b | ||
|
|
7b14e48d0d | ||
|
|
c456f4186e | ||
|
|
ec395a7aa2 | ||
|
|
f1f59e148f | ||
|
|
37a5bbb965 | ||
|
|
f07d14ddb1 | ||
|
|
9620c1d30e | ||
|
|
c7259554b5 | ||
|
|
c3a7235bf7 | ||
|
|
e5a56da50e | ||
|
|
73baf1113d | ||
|
|
dd45c80062 | ||
|
|
dae787c199 | ||
|
|
5ca37e7d39 | ||
|
|
14597334dc | ||
|
|
403776dc2a | ||
|
|
f59a0b73ce | ||
|
|
8441d4a310 | ||
|
|
adca1f70b1 | ||
|
|
cc1962b882 | ||
|
|
6b15689813 | ||
|
|
51f6be041f | ||
|
|
e49d2b9bd2 | ||
|
|
c6b2119c81 | ||
|
|
c2e8f24c7c | ||
|
|
5c3617b9e9 | ||
|
|
9a812b5fef | ||
|
|
882466a730 | ||
|
|
11f1c6da5a | ||
|
|
b92be8a02a | ||
|
|
c81d5f35e1 | ||
|
|
fb0efe832c | ||
|
|
495f729347 | ||
|
|
7654f14f8c | ||
|
|
0e060b7a7a | ||
|
|
1ccaee141c | ||
|
|
8a8552f617 | ||
|
|
ad407249fe | ||
|
|
faffb9a15a | ||
|
|
547b2a5828 | ||
|
|
87e68fca36 | ||
|
|
f32faad415 | ||
|
|
a3aff2f913 | ||
|
|
8730f2cf25 | ||
|
|
65693b8b80 | ||
|
|
f5edd720bd | ||
|
|
6189c1f553 | ||
|
|
e4d06ae3ea | ||
|
|
d259ef476e | ||
|
|
5e03246e4e | ||
|
|
40b5b3068b | ||
|
|
e8bb779909 | ||
|
|
6ee96ffdb5 | ||
|
|
0539daa364 | ||
|
|
669dcf2c25 | ||
|
|
9123120c08 | ||
|
|
bf16d3da30 | ||
|
|
2df5b0b031 | ||
|
|
af4544c869 | ||
|
|
164fe8ce93 | ||
|
|
e1ab868059 | ||
|
|
022a7fe638 | ||
|
|
32026456ba | ||
|
|
0062c82c90 | ||
|
|
4116b8cbfb | ||
|
|
adbf8d2856 | ||
|
|
a87eaf71f6 | ||
|
|
1d1bef36c9 | ||
|
|
a74751c99c | ||
|
|
1cbb2cbcc6 | ||
|
|
7bcc01f0bf | ||
|
|
6bbed6b199 | ||
|
|
2d6c6a82b3 | ||
|
|
5b1b4cab56 | ||
|
|
7c6609eaca | ||
|
|
aabb8d0019 | ||
|
|
f059b4bfb3 | ||
|
|
64486e7d26 | ||
|
|
9674a9fee8 | ||
|
|
bb6ab43e44 | ||
|
|
e86702b34a | ||
|
|
cee9335aeb | ||
|
|
f572e4becb | ||
|
|
e708e4adda | ||
|
|
cc96d40bee | ||
|
|
9cdaaa356e | ||
|
|
16c7885387 | ||
|
|
08e9abe4e6 | ||
|
|
0fb71dd6ad | ||
|
|
16a2775645 | ||
|
|
7c11f19259 | ||
|
|
13bf719c29 | ||
|
|
3750b96b2e | ||
|
|
12baba9706 | ||
|
|
2c2a831f66 | ||
|
|
deb56e1ad2 | ||
|
|
a2bf0d5708 | ||
|
|
b5e330163a | ||
|
|
3f66dfbaf8 | ||
|
|
ccea4eed1a | ||
|
|
700b8f867e | ||
|
|
d129f62ce9 | ||
|
|
ae6b1f24a9 | ||
|
|
47feb93a38 | ||
|
|
6a9ebce259 | ||
|
|
7f4560f022 | ||
|
|
6dd57fe3a9 | ||
|
|
551d7b897f | ||
|
|
296374ecef | ||
|
|
213165ab72 | ||
|
|
bd036acda6 | ||
|
|
4536c47763 | ||
|
|
bdc776bd3e | ||
|
|
c2d940ecf3 | ||
|
|
304ccc3abb | ||
|
|
77d9ca18c1 | ||
|
|
18cceda484 | ||
|
|
252c0f0905 | ||
|
|
e1f6974ba6 | ||
|
|
015e9baf40 | ||
|
|
036f567f23 | ||
|
|
348b4de820 | ||
|
|
e378fb2f0d | ||
|
|
e9886bf251 | ||
|
|
63cdebeff6 | ||
|
|
97a03f97c8 | ||
|
|
0a7e8e121b | ||
|
|
a102156af3 | ||
|
|
dc5a3107c0 | ||
|
|
bcba321273 | ||
|
|
a5c43b17a9 | ||
|
|
429f64259f | ||
|
|
18c5f7a54b | ||
|
|
f9a514897e | ||
|
|
8e247d927e | ||
|
|
59ddf00c8e | ||
|
|
6d8abddbc8 | ||
|
|
025bcb1165 | ||
|
|
f5e4aac51b | ||
|
|
94fa6bd2ff | ||
|
|
a552fda216 | ||
|
|
bdb13a5a80 | ||
|
|
3920df78d9 | ||
|
|
469ede0fa2 | ||
|
|
afe2d35d0b | ||
|
|
25380a1bea | ||
|
|
74eb6f4ef8 | ||
|
|
6db5a4a43b | ||
|
|
5ba9e8fa77 | ||
|
|
914c782b96 | ||
|
|
82a6704912 | ||
|
|
bd5a7bb703 | ||
|
|
147ebc053a | ||
|
|
5c18991f29 | ||
|
|
7bb5279b57 | ||
|
|
865fd70605 | ||
|
|
ca6e888455 | ||
|
|
fea7d5030d | ||
|
|
d90bf8529a | ||
|
|
02daf4b6a7 | ||
|
|
7fab65f340 | ||
|
|
5d3519dcef | ||
|
|
23ac190631 | ||
|
|
a77a331dc7 | ||
|
|
ca700460b1 | ||
|
|
81d78be499 | ||
|
|
915070e006 | ||
|
|
6469433909 | ||
|
|
c0e8ef346b | ||
|
|
1d5e35a460 | ||
|
|
fd82b5a0ce | ||
|
|
0c24d31e08 | ||
|
|
1daa0c9677 | ||
|
|
836bc4557b | ||
|
|
5d68cf0eca | ||
|
|
5703dc2b4d | ||
|
|
2fa26782e1 | ||
|
|
0c291a65c2 | ||
|
|
0ac080ea56 | ||
|
|
d2c4e4507a | ||
|
|
78847afcd4 | ||
|
|
689390f50f | ||
|
|
ce8b491073 | ||
|
|
39774ef16a | ||
|
|
58a2725013 | ||
|
|
e520e61616 | ||
|
|
4f36710d0b | ||
|
|
591ff41944 |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# 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
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
.DS_Store
|
||||
/.swiftpm
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
swift-system.xcodeproj
|
||||
xcuserdata/
|
||||
.*.sw?
|
||||
.docc-build
|
||||
@@ -0,0 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [SystemPackage]
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.10-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
swift_version_tag = "5.9-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
macOSSwiftPackageJob {
|
||||
swift_version = "6.0"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
nightly_docker_tag = "nightly-6.0-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
macOSSwiftPackageJob {
|
||||
swift_version = "main"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
LinuxSwiftPackageJob {
|
||||
nightly_docker_tag = "nightly-jammy"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
WindowsSwiftPackageWithDockerImageJob {
|
||||
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
|
||||
repo = "swift-system"
|
||||
branch = "release/1.4.0"
|
||||
sub_dir = "swift-system"
|
||||
label = "windows-server-2019"
|
||||
}
|
||||
+2
-7
@@ -8,7 +8,7 @@ See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16.0)
|
||||
project(swift-system
|
||||
project(SwiftSystem
|
||||
LANGUAGES C Swift)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
@@ -21,9 +21,4 @@ set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||
include(SwiftSupport)
|
||||
|
||||
add_subdirectory(Sources)
|
||||
|
||||
get_property(SWIFT_SYSTEM_EXPORTS GLOBAL PROPERTY SWIFT_SYSTEM_EXPORTS)
|
||||
export(TARGETS ${SWIFT_SYSTEM_EXPORTS}
|
||||
NAMESPACE SwiftSystem::
|
||||
FILE swift-system-config.cmake
|
||||
EXPORT_LINK_INTERFACE_LIBRARIES)
|
||||
add_subdirectory(cmake/modules)
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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/).
|
||||
+45
-36
@@ -1,42 +1,51 @@
|
||||
// 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
|
||||
*/
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let targets: [PackageDescription.Target] = [
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: ["CSystem"],
|
||||
path: "Sources/System",
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug))
|
||||
]),
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: []),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE")
|
||||
]),
|
||||
let cSettings: [CSetting] = [
|
||||
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])),
|
||||
]
|
||||
|
||||
let swiftSettings: [SwiftSetting] = [
|
||||
.define(
|
||||
"SYSTEM_PACKAGE_DARWIN",
|
||||
.when(platforms: [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS])),
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug)),
|
||||
]
|
||||
|
||||
let package = Package(
|
||||
name: "swift-system",
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: targets
|
||||
)
|
||||
name: "swift-system",
|
||||
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: ["CMakeLists.txt"],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
])
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
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.
|
||||
|
||||
## Multi-platform not Cross-platform
|
||||
## No Cross-platform Abstractions
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
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.)
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -22,22 +24,15 @@ try fd.closeAfter {
|
||||
}
|
||||
```
|
||||
|
||||
[API documentation](https://swiftpackageindex.com/apple/swift-system/main/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: "0.0.1"),
|
||||
```
|
||||
|
||||
Because `SystemPackage` is under active development,
|
||||
source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`).
|
||||
If you don't want potentially source-breaking package updates,
|
||||
use this dependency specification instead:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-system", .upToNextMinor(from: "0.0.1")),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
|
||||
```
|
||||
|
||||
Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
@@ -46,7 +41,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-system", from: "0.0.1"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
@@ -58,10 +53,72 @@ let package = Package(
|
||||
)
|
||||
```
|
||||
|
||||
## Contributing
|
||||
## Source Stability
|
||||
|
||||
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
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:
|
||||
|
||||
## LICENSE
|
||||
| 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.
|
||||
|
||||
[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 | >= 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).
|
||||
|
||||
### Branching Strategy
|
||||
|
||||
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 (unreleased) | release/1.4 |
|
||||
| swift-system 1.5.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
|
||||
@@ -12,4 +12,9 @@ target_include_directories(CSystem INTERFACE
|
||||
include)
|
||||
|
||||
|
||||
install(FILES
|
||||
include/CSystemLinux.h
|
||||
include/CSystemWindows.h
|
||||
include/module.modulemap
|
||||
DESTINATION include/CSystem)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#if __wasi__
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
// 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; }
|
||||
|
||||
#endif
|
||||
@@ -1,5 +1,6 @@
|
||||
module CSystem {
|
||||
header "CSystemLinux.h"
|
||||
header "CSystemWASI.h"
|
||||
header "CSystemWindows.h"
|
||||
export *
|
||||
}
|
||||
@@ -7,17 +7,21 @@ Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(System
|
||||
add_library(SystemPackage
|
||||
Errno.swift
|
||||
FileDescriptor.swift
|
||||
FileHelpers.swift
|
||||
FileOperations.swift
|
||||
FilePermissions.swift
|
||||
MachPort.swift
|
||||
PlatformString.swift
|
||||
SystemString.swift
|
||||
Util.swift
|
||||
Util+StringArray.swift
|
||||
UtilConsumers.swift)
|
||||
target_sources(System PRIVATE
|
||||
set_target_properties(SystemPackage PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePath.swift
|
||||
FilePath/FilePathComponents.swift
|
||||
FilePath/FilePathComponentView.swift
|
||||
@@ -25,16 +29,22 @@ target_sources(System PRIVATE
|
||||
FilePath/FilePathString.swift
|
||||
FilePath/FilePathSyntax.swift
|
||||
FilePath/FilePathWindows.swift)
|
||||
target_sources(System PRIVATE
|
||||
target_sources(SystemPackage PRIVATE
|
||||
Internals/Backcompat.swift
|
||||
Internals/CInterop.swift
|
||||
Internals/Constants.swift
|
||||
Internals/Exports.swift
|
||||
Internals/Mocking.swift
|
||||
Internals/RawBuffer.swift
|
||||
Internals/Syscalls.swift
|
||||
Internals/WindowsSyscallAdapters.swift)
|
||||
target_link_libraries(System 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(System)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS System)
|
||||
_install_target(SystemPackage)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage)
|
||||
+149
-133
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
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,7 +14,7 @@
|
||||
/// of `FileDescriptor` values,
|
||||
/// in the same way as you manage a raw C file handle.
|
||||
@frozen
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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
|
||||
@@ -25,7 +25,8 @@ public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
// Standard file descriptors
|
||||
// Standard file descriptors.
|
||||
@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
|
||||
@@ -40,11 +41,12 @@ extension FileDescriptor {
|
||||
public static var standardError: FileDescriptor { .init(rawValue: 2) }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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
|
||||
public struct AccessMode: RawRepresentable, Hashable, Codable {
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct AccessMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C access mode.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -86,7 +88,8 @@ extension FileDescriptor {
|
||||
|
||||
/// Options that specify behavior for a newly-opened file.
|
||||
@frozen
|
||||
public struct OpenOptions: OptionSet, Hashable, Codable {
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct OpenOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -95,9 +98,6 @@ 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.
|
||||
@@ -106,7 +106,7 @@ extension FileDescriptor {
|
||||
/// the system doesn't wait for the device or file
|
||||
/// to be ready or available.
|
||||
/// If the
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// call would result in the process being blocked for some reason,
|
||||
/// that method returns immediately.
|
||||
/// This flag also has the effect of making all
|
||||
@@ -114,7 +114,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_NONBLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var nonBlocking: OpenOptions { OpenOptions(_O_NONBLOCK) }
|
||||
public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "nonBlocking")
|
||||
@@ -130,7 +130,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_APPEND`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var append: OpenOptions { OpenOptions(_O_APPEND) }
|
||||
public static var append: OpenOptions { .init(rawValue: _O_APPEND) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "append")
|
||||
@@ -140,7 +140,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_CREAT`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var create: OpenOptions { OpenOptions(_O_CREAT) }
|
||||
public static var create: OpenOptions { .init(rawValue: _O_CREAT) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "create")
|
||||
@@ -154,7 +154,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_TRUNC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var truncate: OpenOptions { OpenOptions(_O_TRUNC) }
|
||||
public static var truncate: OpenOptions { .init(rawValue: _O_TRUNC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "truncate")
|
||||
@@ -164,25 +164,25 @@ extension FileDescriptor {
|
||||
/// expecting that it doesn't exist.
|
||||
///
|
||||
/// If this option and ``create`` are both specified and the file exists,
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// returns an error instead of creating the file.
|
||||
/// You can use this, for example,
|
||||
/// to implement a simple exclusive-access locking mechanism.
|
||||
///
|
||||
/// If this option and ``create`` are both specified
|
||||
/// and the last component of the file's path is a symbolic link,
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// fails even if the symbolic link points to a nonexistent name.
|
||||
///
|
||||
/// The corresponding C constant is `O_EXCL`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exclusiveCreate: OpenOptions { OpenOptions(_O_EXCL) }
|
||||
public static var exclusiveCreate: OpenOptions { .init(rawValue: _O_EXCL) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exclusiveCreate")
|
||||
public static var O_EXCL: OpenOptions { exclusiveCreate }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Indicates that opening the file
|
||||
/// atomically obtains a shared lock on the file.
|
||||
///
|
||||
@@ -194,7 +194,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_SHLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var sharedLock: OpenOptions { OpenOptions(_O_SHLOCK) }
|
||||
public static var sharedLock: OpenOptions { .init(rawValue: _O_SHLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "sharedLock")
|
||||
@@ -211,7 +211,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EXLOCK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var exclusiveLock: OpenOptions { OpenOptions(_O_EXLOCK) }
|
||||
public static var exclusiveLock: OpenOptions { .init(rawValue: _O_EXLOCK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "exclusiveLock")
|
||||
@@ -223,32 +223,46 @@ extension FileDescriptor {
|
||||
///
|
||||
/// If you specify this option
|
||||
/// and the file path you pass to
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// is a symbolic link,
|
||||
/// then that open operation fails.
|
||||
///
|
||||
/// The corresponding C constant is `O_NOFOLLOW`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var noFollow: OpenOptions { OpenOptions(_O_NOFOLLOW) }
|
||||
public static var noFollow: OpenOptions { .init(rawValue: _O_NOFOLLOW) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "noFollow")
|
||||
public static var O_NOFOLLOW: OpenOptions { noFollow }
|
||||
|
||||
/// Indicates that opening the file only succeeds if the file is a directory.
|
||||
///
|
||||
/// If you specify this option and the file path you pass to
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// is a not a directory, then that open operation fails.
|
||||
///
|
||||
/// The corresponding C constant is `O_DIRECTORY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: OpenOptions { .init(rawValue: _O_DIRECTORY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "directory")
|
||||
public static var O_DIRECTORY: OpenOptions { directory }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Indicates that opening the file
|
||||
/// opens symbolic links instead of following them.
|
||||
///
|
||||
/// If you specify this option
|
||||
/// and the file path you pass to
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// is a symbolic link,
|
||||
/// then the link itself is opened instead of what it links to.
|
||||
///
|
||||
/// The corresponding C constant is `O_SYMLINK`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var symlink: OpenOptions { OpenOptions(_O_SYMLINK) }
|
||||
public static var symlink: OpenOptions { .init(rawValue: _O_SYMLINK) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "symlink")
|
||||
@@ -264,7 +278,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_EVTONLY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var eventOnly: OpenOptions { OpenOptions(_O_EVTONLY) }
|
||||
public static var eventOnly: OpenOptions { .init(rawValue: _O_EVTONLY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "eventOnly")
|
||||
@@ -286,7 +300,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C constant is `O_CLOEXEC`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var closeOnExec: OpenOptions { OpenOptions(_O_CLOEXEC) }
|
||||
public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
@@ -296,7 +310,8 @@ extension FileDescriptor {
|
||||
|
||||
/// Options for specifying what a file descriptor's offset is relative to.
|
||||
@frozen
|
||||
public struct SeekOrigin: RawRepresentable, Hashable, Codable {
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct SeekOrigin: RawRepresentable, Sendable, Hashable, Codable {
|
||||
/// The raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public var rawValue: CInt
|
||||
@@ -339,7 +354,7 @@ extension FileDescriptor {
|
||||
|
||||
// TODO: These are available on some versions of Linux with appropriate
|
||||
// macro defines.
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
/// Indicates that the offset should be set
|
||||
/// to the next hole after the specified number of bytes.
|
||||
///
|
||||
@@ -371,7 +386,7 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FileDescriptor.AccessMode
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -390,7 +405,7 @@ extension FileDescriptor.AccessMode
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FileDescriptor.SeekOrigin
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -401,7 +416,7 @@ extension FileDescriptor.SeekOrigin
|
||||
case .start: return "start"
|
||||
case .current: return "current"
|
||||
case .end: return "end"
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
case .nextHole: return "nextHole"
|
||||
case .nextData: return "nextData"
|
||||
#endif
|
||||
@@ -413,14 +428,14 @@ extension FileDescriptor.SeekOrigin
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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 os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
(.append, ".append"),
|
||||
@@ -459,3 +474,8 @@ extension FileDescriptor.OpenOptions
|
||||
/// A textual representation of the open options, suitable for debugging.
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// 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 {}
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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.
|
||||
///
|
||||
@@ -46,9 +46,6 @@ extension FileDescriptor {
|
||||
/// increments that position by the number of bytes written.
|
||||
/// See also ``seek(offset:from:)``.
|
||||
///
|
||||
/// This method either writes the entire contents of `sequence`,
|
||||
/// or throws an error if only part of the content was written.
|
||||
///
|
||||
/// If `sequence` doesn't implement
|
||||
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
|
||||
/// temporary space will be allocated as needed.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
*/
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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.
|
||||
///
|
||||
@@ -31,12 +31,70 @@ extension FileDescriptor {
|
||||
permissions: FilePermissions? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileDescriptor {
|
||||
try path.withPlatformString {
|
||||
#if !os(Windows)
|
||||
return try path.withCString {
|
||||
try FileDescriptor.open(
|
||||
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
#else
|
||||
return try path.withPlatformString {
|
||||
try FileDescriptor.open(
|
||||
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#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:
|
||||
/// - path: The location of the file to open.
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: A file descriptor for the open file
|
||||
///
|
||||
/// The corresponding C function is `open`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileDescriptor {
|
||||
try FileDescriptor._open(
|
||||
path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
let oFlag = mode.rawValue | options.rawValue
|
||||
let descOrError: Result<CInt, Errno> = valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
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) }
|
||||
}
|
||||
#else
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -77,12 +135,11 @@ 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) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Deletes a file descriptor.
|
||||
///
|
||||
@@ -99,7 +156,7 @@ extension FileDescriptor {
|
||||
nothingOrErrno(retryOnInterrupt: false) { system_close(self.rawValue) }
|
||||
}
|
||||
|
||||
/// Reposition the offset for the given file descriptor.
|
||||
/// Repositions the offset for the given file descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The new offset for the file descriptor.
|
||||
@@ -144,7 +201,7 @@ extension FileDescriptor {
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/3019191-count> property of `buffer`
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/count-95usp> property of `buffer`
|
||||
/// determines the maximum number of bytes that are read into that buffer.
|
||||
///
|
||||
/// After reading,
|
||||
@@ -182,10 +239,10 @@ extension FileDescriptor {
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The number of bytes that were read.
|
||||
///
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/3019191-count> property of `buffer`
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/count-95usp> property of `buffer`
|
||||
/// determines the maximum number of bytes that are read into that buffer.
|
||||
///
|
||||
/// Unlike <doc:System/FileDescriptor/read(into:retryOnInterrupt:)>,
|
||||
/// Unlike <doc:FileDescriptor/read(into:retryOnInterrupt:)>,
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pread`.
|
||||
@@ -308,8 +365,12 @@ extension FileDescriptor {
|
||||
buffer,
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
}
|
||||
|
||||
/// Duplicate this file descriptor and return the newly created copy.
|
||||
#if !os(WASI)
|
||||
@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.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
@@ -337,7 +398,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C functions are `dup` and `dup2`.
|
||||
@_alwaysEmitIntoClient
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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
|
||||
@@ -345,7 +406,7 @@ extension FileDescriptor {
|
||||
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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?,
|
||||
@@ -371,3 +432,120 @@ extension FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(WASI)
|
||||
@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *)
|
||||
extension FileDescriptor {
|
||||
/// Creates a unidirectional data channel, which can be used for interprocess communication.
|
||||
///
|
||||
/// - Returns: The pair of file descriptors.
|
||||
///
|
||||
/// The corresponding C function is `pipe`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *)
|
||||
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
try _pipe().get()
|
||||
}
|
||||
|
||||
@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *)
|
||||
@usableFromInline
|
||||
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
|
||||
var fds: (Int32, Int32) = (-1, -1)
|
||||
return withUnsafeMutablePointer(to: &fds) { pointer in
|
||||
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
system_pipe(fds)
|
||||
}.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@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.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newSize: The length in bytes to resize the file to.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
///
|
||||
/// The file referenced by this file descriptor will by truncated (or extended) to `newSize`.
|
||||
///
|
||||
/// If the current size of the file exceeds `newSize`, any extra data is discarded. If the current
|
||||
/// size of the file is smaller than `newSize`, the file is extended and filled with zeros to the
|
||||
/// provided size.
|
||||
///
|
||||
/// This function requires that the file has been opened for writing.
|
||||
///
|
||||
/// - Note: This function does not modify the current offset for any open file descriptors
|
||||
/// associated with the file.
|
||||
///
|
||||
/// The corresponding C function is `ftruncate`.
|
||||
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@_alwaysEmitIntoClient
|
||||
public func resize(
|
||||
to newSize: Int64,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _resize(
|
||||
to: newSize,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
@available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@usableFromInline
|
||||
internal func _resize(
|
||||
to newSize: Int64,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_ftruncate(self.rawValue, _COffT(newSize))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 -> 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)
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
/// encoding.
|
||||
///
|
||||
/// On construction, `FilePath` will normalize separators by removing
|
||||
/// reduncant intermediary separators and stripping any trailing separators.
|
||||
/// redundant intermediary separators and stripping any trailing separators.
|
||||
/// On Windows, `FilePath` will also normalize forward slashes `/` into
|
||||
/// backslashes `\`, as preferred by the platform.
|
||||
///
|
||||
@@ -28,11 +28,8 @@
|
||||
/// let fd = try FileDescriptor.open(path, .writeOnly, options: .append)
|
||||
/// try fd.closeAfter { try fd.writeAll(message.utf8) }
|
||||
///
|
||||
/// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
|
||||
/// components, etc.
|
||||
///
|
||||
/// File paths conform to the
|
||||
/// and <doc://com.apple.documentation/documentation/swift/equatable>
|
||||
/// <doc://com.apple.documentation/documentation/swift/equatable>
|
||||
/// and <doc://com.apple.documentation/documentation/swift/hashable> protocols
|
||||
/// by performing the protocols' operations on their raw byte contents.
|
||||
/// This conformance allows file paths to be used,
|
||||
@@ -40,8 +37,10 @@
|
||||
/// However, the rules for path equivalence
|
||||
/// are file-system–specific and have additional considerations
|
||||
/// like case insensitivity, Unicode normalization, and symbolic links.
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
public struct FilePath {
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct FilePath: Sendable {
|
||||
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
|
||||
// components, etc.
|
||||
internal var _storage: SystemString
|
||||
|
||||
/// Creates an empty, null-terminated path.
|
||||
@@ -60,12 +59,32 @@ public struct FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath: Hashable, Codable {}
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FilePath: Hashable {}
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
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"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - API
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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,8 @@ extension FilePath {
|
||||
///
|
||||
/// path.components.removeAll { $0.kind == .currentDirectory }
|
||||
/// // path is "/home/username/bin/scripts/tree"
|
||||
///
|
||||
public struct ComponentView {
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
public struct ComponentView: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _start: SystemString.Index
|
||||
|
||||
@@ -40,30 +40,6 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
/// 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) }
|
||||
@@ -86,13 +62,14 @@ extension FilePath {
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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
|
||||
public struct Index: Comparable, Hashable {
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
public struct Index: Sendable, Comparable, Hashable {
|
||||
internal typealias Storage = SystemString.Index
|
||||
|
||||
internal var _storage: Storage
|
||||
@@ -123,7 +100,7 @@ extension FilePath.ComponentView: BidirectionalCollection {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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())
|
||||
@@ -173,7 +150,7 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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>(
|
||||
@@ -202,6 +179,7 @@ extension FilePath {
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
extension FilePath.ComponentView: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
_start ..< _path._storage.endIndex
|
||||
@@ -214,6 +192,7 @@ extension FilePath.ComponentView: _PathSlice {
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
extension FilePath.ComponentView {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - API
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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,7 +28,8 @@ extension FilePath {
|
||||
/// * `\\server\share\`
|
||||
/// * `\\?\UNC\server\share\`
|
||||
/// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\`
|
||||
public struct Root {
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
public struct Root: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _rootEnd: SystemString.Index
|
||||
|
||||
@@ -54,8 +55,8 @@ extension FilePath {
|
||||
/// file.kind == .regular // true
|
||||
/// file.extension // "txt"
|
||||
/// path.append(file) // path is "/tmp/foo.txt"
|
||||
///
|
||||
public struct Component {
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
public struct Component: Sendable {
|
||||
internal var _path: FilePath
|
||||
internal var _range: Range<SystemString.Index>
|
||||
|
||||
@@ -73,13 +74,14 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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
|
||||
public enum Kind {
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
public enum Kind: Sendable {
|
||||
/// The special directory `.`, representing the current directory.
|
||||
case currentDirectory
|
||||
|
||||
@@ -98,6 +100,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
}
|
||||
@@ -143,7 +146,7 @@ extension _StrSlice {
|
||||
internal func _withSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try _storage.withSystemChars {
|
||||
try _storage.withNullTerminatedSystemChars {
|
||||
try f(UnsafeBufferPointer(rebasing: $0[_range]))
|
||||
}
|
||||
}
|
||||
@@ -183,15 +186,18 @@ extension _PathSlice {
|
||||
internal var _storage: SystemString { _path._storage }
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
extension FilePath.Component: _PathSlice {
|
||||
}
|
||||
@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: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FilePath: _PlatformStringable {
|
||||
@usableFromInline
|
||||
func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
|
||||
try _storage.withPlatformString(body)
|
||||
}
|
||||
@@ -202,6 +208,7 @@ extension FilePath: _PlatformStringable {
|
||||
|
||||
}
|
||||
|
||||
@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? {
|
||||
@@ -230,6 +237,7 @@ internal func _makeExtension(_ ext: String) -> SystemString {
|
||||
return result
|
||||
}
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
extension FilePath.Component {
|
||||
internal init?(_ str: SystemString) {
|
||||
// FIXME: explicit null root? Or something else?
|
||||
@@ -242,6 +250,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
@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?
|
||||
@@ -256,6 +265,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
extension FilePath.Component {
|
||||
// TODO: ensure this all gets easily optimized away in release...
|
||||
internal func _invariantCheck() {
|
||||
@@ -267,6 +277,8 @@ extension FilePath.Component {
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
@@ -89,6 +89,11 @@ 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)
|
||||
}
|
||||
@@ -111,6 +116,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@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()
|
||||
@@ -191,6 +197,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
@@ -202,6 +209,7 @@ extension FilePath {
|
||||
|
||||
// Parse separators
|
||||
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FilePath {
|
||||
internal typealias _Index = SystemString.Index
|
||||
|
||||
@@ -265,6 +273,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
@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 {
|
||||
@@ -289,6 +298,7 @@ extension SystemString {
|
||||
}
|
||||
}
|
||||
|
||||
@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.
|
||||
@@ -313,6 +323,7 @@ extension FilePath.Root {
|
||||
}
|
||||
}
|
||||
|
||||
@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 }
|
||||
@@ -324,13 +335,17 @@ 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 forceWindowsPaths
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
@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 {
|
||||
@@ -358,14 +373,20 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK: - Invariants
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FilePath {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
internal func _invariantsSatisfied() -> Bool {
|
||||
var normal = self
|
||||
normal._normalizeSeparators()
|
||||
precondition(self == normal)
|
||||
precondition(!self._storage._hasTrailingSeparator())
|
||||
precondition(_hasRoot == (self.root != nil))
|
||||
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())
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - Platform string
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -20,6 +20,56 @@ extension FilePath {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a file path by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// - Parameter platformString: A null-terminated platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of FilePath.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = platformString.withUnsafeBufferPointer {
|
||||
FilePath(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.init(_ scalar: Unicode.Scalar)")
|
||||
public init(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of FilePath.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = FilePath()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath(_: String) to create a path from a String")
|
||||
public init(platformString: String) {
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
self = FilePath(String(platformString[..<nullLoc]))
|
||||
} else {
|
||||
self = FilePath(platformString)
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
// 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
|
||||
// and its inlinable body.)
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
@@ -36,16 +86,30 @@ extension FilePath {
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
// For backwards deployment, call withCString if available.
|
||||
#if !os(Windows)
|
||||
return try withCString(body)
|
||||
#else
|
||||
return try _withPlatformString(body)
|
||||
#endif
|
||||
}
|
||||
#else
|
||||
/// Calls the given closure with a pointer to the contents of the file path,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// 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 -> Result
|
||||
) rethrows -> Result {
|
||||
return try _withPlatformString(body)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -55,11 +119,63 @@ extension FilePath.Component {
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
public init?(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a file path component by copying bytes from a null-terminated
|
||||
/// platform string. It is a precondition that a null byte indicates the end of
|
||||
/// the string. The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// Returns `nil` if `platformString` is empty, is a root, or has more than
|
||||
/// one component in it.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// - Parameter platformString: A null-terminated platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of FilePath.Component.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
guard let component = platformString.withUnsafeBufferPointer({
|
||||
FilePath.Component(platformString: $0.baseAddress!)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
self = component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Component.init(_ scalar: Unicode.Scalar)")
|
||||
public init?(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of FilePath.Component.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Component.init(_: String)")
|
||||
public init?(platformString: String) {
|
||||
let string: String
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
string = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
string = platformString
|
||||
}
|
||||
guard let component = FilePath.Component(string) else { return nil }
|
||||
self = component
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path
|
||||
/// component, represented as a null-terminated platform string.
|
||||
///
|
||||
@@ -82,7 +198,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -91,11 +207,62 @@ extension FilePath.Root {
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
public init?(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a file path root by copying bytes from a null-terminated platform
|
||||
/// string. It is a precondition that a null byte indicates the end of
|
||||
/// the string. The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// Returns `nil` if `platformString` is empty or is not a root.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// - Parameter platformString: A null-terminated platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of FilePath.Root.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
guard let component = platformString.withUnsafeBufferPointer({
|
||||
FilePath.Root(platformString: $0.baseAddress!)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
self = component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Root.init(_ scalar: Unicode.Scalar)")
|
||||
public init?(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of FilePath.Root.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Root.init(_: String)")
|
||||
public init?(platformString: String) {
|
||||
let string: String
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
string = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
string = platformString
|
||||
}
|
||||
guard let root = FilePath.Root(string) else { return nil }
|
||||
self = root
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path
|
||||
/// root, represented as a null-terminated platform string.
|
||||
///
|
||||
@@ -120,7 +287,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - String literals
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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.
|
||||
///
|
||||
@@ -139,7 +306,7 @@ extension FilePath: ExpressibleByStringLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
///
|
||||
@@ -148,7 +315,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral: String) {
|
||||
guard let s = FilePath.Component(stringLiteral) else {
|
||||
// TODO: static assert
|
||||
preconditionFailure("""
|
||||
fatalError("""
|
||||
FilePath.Component must be created from exactly one non-root component
|
||||
""")
|
||||
}
|
||||
@@ -164,7 +331,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
///
|
||||
@@ -172,7 +339,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral: String) {
|
||||
guard let s = FilePath.Root(stringLiteral) else {
|
||||
// TODO: static assert
|
||||
preconditionFailure("""
|
||||
fatalError("""
|
||||
FilePath.Root must be created from a root
|
||||
""")
|
||||
}
|
||||
@@ -189,7 +356,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
|
||||
// MARK: - Printing and dumping
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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.
|
||||
///
|
||||
@@ -205,7 +372,7 @@ extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -222,7 +389,7 @@ extension FilePath.Component: CustomStringConvertible, CustomDebugStringConverti
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -242,7 +409,7 @@ extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
// MARK: - Convenience helpers
|
||||
|
||||
// Convenience helpers
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -253,7 +420,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -264,7 +431,7 @@ extension FilePath.Component {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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 `"/"`.
|
||||
///
|
||||
@@ -278,7 +445,7 @@ extension FilePath.Root {
|
||||
|
||||
// MARK: - Decoding and validating
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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.
|
||||
@@ -308,7 +475,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -338,7 +505,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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 `"/"`
|
||||
///
|
||||
@@ -391,7 +558,7 @@ extension String {
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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) }
|
||||
@@ -401,14 +568,30 @@ extension String {
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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:)`.
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: UnsafePointer<CChar>) {
|
||||
self.init(platformString: cString)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: [CChar]) {
|
||||
self.init(platformString: cString)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: inout CChar) {
|
||||
self.init(platformString: &cString)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: String) {
|
||||
self.init(platformString: cString)
|
||||
}
|
||||
|
||||
/// For backwards compatibility only. This function is equivalent to
|
||||
/// the preferred `withPlatformString`.
|
||||
public func withCString<Result>(
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
// MARK: - Query API
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -52,6 +52,8 @@ extension FilePath {
|
||||
/// * `\Users`
|
||||
public var isRelative: Bool { !isAbsolute }
|
||||
|
||||
// TODO(Windows docs): examples with roots, such as whether `\foo\bar`
|
||||
// starts with `C:\foo`
|
||||
/// Returns whether `other` is a prefix of `self`, only considering
|
||||
/// whole path components.
|
||||
///
|
||||
@@ -63,16 +65,14 @@ extension FilePath {
|
||||
/// path.starts(with: "/usr/bin/ls") // true
|
||||
/// path.starts(with: "/usr/bin/ls///") // true
|
||||
/// path.starts(with: "/us") // false
|
||||
///
|
||||
/// TODO(Windows docs): examples with roots, such as whether `\foo\bar`
|
||||
/// starts with `C:\foo`
|
||||
///
|
||||
public func starts(with other: FilePath) -> Bool {
|
||||
guard !other.isEmpty else { return true }
|
||||
return self.root == other.root && components.starts(
|
||||
with: other.components)
|
||||
}
|
||||
|
||||
// TODO(Windows docs): examples with roots, such as whether `C:\foo\bar`
|
||||
// ends with `C:bar`
|
||||
/// Returns whether `other` is a suffix of `self`, only considering
|
||||
/// whole path components.
|
||||
///
|
||||
@@ -84,10 +84,6 @@ extension FilePath {
|
||||
/// path.ends(with: "usr/bin/ls") // true
|
||||
/// path.ends(with: "/usr/bin/ls///") // true
|
||||
/// path.ends(with: "/ls") // false
|
||||
///
|
||||
/// TODO(Windows docs): examples with roots, such as whether `C:\foo\bar`
|
||||
/// ends with `C:bar`
|
||||
///
|
||||
public func ends(with other: FilePath) -> Bool {
|
||||
if other.root != nil {
|
||||
// TODO: anything tricky here for Windows?
|
||||
@@ -103,7 +99,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK: - Decompose a path
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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`.
|
||||
///
|
||||
@@ -147,7 +143,6 @@ extension FilePath {
|
||||
/// path.root = nil // path is #"foo\bar"#
|
||||
/// path.root = "C:" // path is #"C:foo\bar"#
|
||||
/// path.root = #"C:\"# // path is #"C:\foo\bar"#
|
||||
///
|
||||
public var root: FilePath.Root? {
|
||||
get {
|
||||
guard _hasRoot else { return nil }
|
||||
@@ -180,7 +175,6 @@ extension FilePath {
|
||||
/// * `\\?\device\folder\file.exe => folder\file.exe`
|
||||
/// * `\\server\share\file => file`
|
||||
/// * `\ => ""`
|
||||
///
|
||||
public __consuming func removingRoot() -> FilePath {
|
||||
var copy = self
|
||||
copy.root = nil
|
||||
@@ -188,7 +182,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -211,7 +205,6 @@ extension FilePath {
|
||||
/// * `\\?\UNC\server\share\bar.exe => bar.exe`
|
||||
/// * `\\server\share => nil`
|
||||
/// * `\\?\UNC\server\share\ => nil`
|
||||
///
|
||||
public var lastComponent: Component? { components.last }
|
||||
|
||||
/// Creates a new path with everything up to but not including
|
||||
@@ -249,7 +242,6 @@ extension FilePath {
|
||||
/// path.removeLastComponent() == true // path is "/usr"
|
||||
/// path.removeLastComponent() == true // path is "/"
|
||||
/// path.removeLastComponent() == false // path is "/"
|
||||
///
|
||||
@discardableResult
|
||||
public mutating func removeLastComponent() -> Bool {
|
||||
defer { _invariantCheck() }
|
||||
@@ -260,7 +252,7 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
///
|
||||
@@ -273,7 +265,6 @@ extension FilePath.Component {
|
||||
/// * `Foo.app => app`
|
||||
/// * `.hidden => nil`
|
||||
/// * `.. => nil`
|
||||
///
|
||||
public var `extension`: String? {
|
||||
guard let range = _extensionRange() else { return nil }
|
||||
return _slice[range].string
|
||||
@@ -287,13 +278,12 @@ extension FilePath.Component {
|
||||
/// * `Foo.app => Foo`
|
||||
/// * `.hidden => .hidden`
|
||||
/// * `.. => ..`
|
||||
///
|
||||
public var stem: String {
|
||||
_slice[_stemRange()].string
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -324,7 +314,6 @@ extension FilePath {
|
||||
/// path.extension = "o" // path is "/tmp/file.o"
|
||||
/// path.extension = nil // path is "/tmp/file"
|
||||
/// path.extension = "" // path is "/tmp/file."
|
||||
///
|
||||
public var `extension`: String? {
|
||||
get { lastComponent?.extension }
|
||||
set {
|
||||
@@ -351,8 +340,8 @@ extension FilePath {
|
||||
/// Returns `nil` if `lastComponent` is `nil`
|
||||
///
|
||||
/// * `/tmp/foo.txt => foo`
|
||||
/// * `/Appliations/Foo.app/ => Foo`
|
||||
/// * `/Appliations/Foo.app/bar.txt => bar`
|
||||
/// * `/Applications/Foo.app/ => Foo`
|
||||
/// * `/Applications/Foo.app/bar.txt => bar`
|
||||
/// * `/tmp/.hidden => .hidden`
|
||||
/// * `/tmp/.. => ..`
|
||||
/// * `/ => nil`
|
||||
@@ -360,7 +349,7 @@ extension FilePath {
|
||||
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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
|
||||
@@ -441,10 +430,11 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// Modification and concatenation API
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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`.
|
||||
/// Otherwise returns `false`.
|
||||
/// Otherwise returns `false`.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
@@ -452,9 +442,6 @@ extension FilePath {
|
||||
/// path.removePrefix("/usr/bin") // false
|
||||
/// path.removePrefix("/us") // false
|
||||
/// path.removePrefix("/usr/local") // true, path is "bin"
|
||||
///
|
||||
/// TODO(Windows docs): example with roots
|
||||
///
|
||||
public mutating func removePrefix(_ prefix: FilePath) -> Bool {
|
||||
defer { _invariantCheck() }
|
||||
// FIXME: Should Windows have more nuanced semantics?
|
||||
@@ -465,6 +452,7 @@ extension FilePath {
|
||||
return true
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Append a `component` on to the end of this path.
|
||||
///
|
||||
/// Example:
|
||||
@@ -475,14 +463,12 @@ extension FilePath {
|
||||
/// path.append(comp)
|
||||
/// }
|
||||
/// // path is "/tmp/foo/bar/../baz"
|
||||
///
|
||||
/// TODO(Windows docs): example with roots
|
||||
///
|
||||
public mutating func append(_ component: __owned FilePath.Component) {
|
||||
defer { _invariantCheck() }
|
||||
_append(unchecked: component._slice)
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Append `components` on to the end of this path.
|
||||
///
|
||||
/// Example:
|
||||
@@ -491,9 +477,6 @@ extension FilePath {
|
||||
/// path.append(["usr", "local"]) // path is "/usr/local"
|
||||
/// let otherPath: FilePath = "/bin/ls"
|
||||
/// path.append(otherPath.components) // path is "/usr/local/bin/ls"
|
||||
///
|
||||
/// TODO(Windows docs): example with roots
|
||||
///
|
||||
public mutating func append<C: Collection>(
|
||||
_ components: __owned C
|
||||
) where C.Element == FilePath.Component {
|
||||
@@ -503,19 +486,18 @@ extension FilePath {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots, should we rephrase this "spurious
|
||||
// roots"?
|
||||
/// Append the contents of `other`, ignoring any spurious leading separators.
|
||||
///
|
||||
/// A leading separator is spurious if `self` is non-empty.
|
||||
///
|
||||
/// Example:
|
||||
/// var path: FilePath = ""
|
||||
/// path.append("/var/www/website") // "/var/www/website"
|
||||
/// path.append("static/assets") // "/var/www/website/static/assets"
|
||||
/// path.append("/main.css") // "/var/www/website/static/assets/main.css"
|
||||
///
|
||||
/// TODO(Windows docs): example with roots, should we rephrase this "spurious
|
||||
/// roots"?
|
||||
///
|
||||
/// var path: FilePath = ""
|
||||
/// path.append("/var/www/website") // "/var/www/website"
|
||||
/// path.append("static/assets") // "/var/www/website/static/assets"
|
||||
/// path.append("/main.css") // "/var/www/website/static/assets/main.css"
|
||||
public mutating func append(_ other: __owned String) {
|
||||
defer { _invariantCheck() }
|
||||
guard !other.utf8.isEmpty else { return }
|
||||
@@ -527,20 +509,16 @@ extension FilePath {
|
||||
_append(unchecked: otherPath._storage[otherPath._relativeStart...])
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Non-mutating version of `append(_:Component)`.
|
||||
///
|
||||
/// TODO(Windows docs): example with roots
|
||||
///
|
||||
public __consuming func appending(_ other: __owned Component) -> FilePath {
|
||||
var copy = self
|
||||
copy.append(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Non-mutating version of `append(_:C)`.
|
||||
///
|
||||
/// TODO(Windows docs): example with roots
|
||||
///
|
||||
public __consuming func appending<C: Collection>(
|
||||
_ components: __owned C
|
||||
) -> FilePath where C.Element == FilePath.Component {
|
||||
@@ -549,16 +527,16 @@ extension FilePath {
|
||||
return copy
|
||||
}
|
||||
|
||||
// TODO(Windows docs): example with roots
|
||||
/// Non-mutating version of `append(_:String)`.
|
||||
///
|
||||
/// TODO(Windows docs): example with roots
|
||||
///
|
||||
public __consuming func appending(_ other: __owned String) -> FilePath {
|
||||
var copy = self
|
||||
copy.append(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
// TODO(Windows docs): examples and docs with roots, update/generalize doc
|
||||
// comment
|
||||
/// If `other` does not have a root, append each component of `other`. If
|
||||
/// `other` has a root, replaces `self` with other.
|
||||
///
|
||||
@@ -572,24 +550,18 @@ extension FilePath {
|
||||
/// var path: FilePath = "/tmp"
|
||||
/// path.push("dir/file.txt") // path is "/tmp/dir/file.txt"
|
||||
/// path.push("/bin") // path is "/bin"
|
||||
///
|
||||
/// TODO(Windows docs): examples and docs with roots, update/generalize doc
|
||||
/// comment
|
||||
///
|
||||
public mutating func push(_ other: __owned FilePath) {
|
||||
defer { _invariantCheck() }
|
||||
guard other.root == nil else {
|
||||
self = other
|
||||
return
|
||||
}
|
||||
/// FIXME: Windows drive-relative roots, etc?
|
||||
// FIXME: Windows drive-relative roots, etc?
|
||||
_append(unchecked: other._storage[...])
|
||||
}
|
||||
|
||||
/// Non-mutating version of `push()`
|
||||
///
|
||||
/// TODO(Windows docs): examples and docs with roots
|
||||
///
|
||||
// TODO(Windows docs): examples and docs with roots
|
||||
/// Non-mutating version of `push()`.
|
||||
public __consuming func pushing(_ other: __owned FilePath) -> FilePath {
|
||||
var copy = self
|
||||
copy.push(other)
|
||||
@@ -611,7 +583,7 @@ extension FilePath {
|
||||
}
|
||||
|
||||
// MARK - Renamed
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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() }
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
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 -> R
|
||||
) throws -> 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 -> Bool {
|
||||
return try path.withPlatformString {
|
||||
if system_mkdir($0, 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 -> FilePath {
|
||||
var tempDir = try _getTemporaryDirectory()
|
||||
tempDir.append(basename)
|
||||
|
||||
while true {
|
||||
tempDir.extension = createRandomString(length: 16)
|
||||
|
||||
if try makeLockedDownDirectory(at: tempDir) {
|
||||
return tempDir
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
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 -> 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 {
|
||||
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) {
|
||||
try recursiveRemove(
|
||||
in: dirfd.rawValue,
|
||||
name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress!
|
||||
)
|
||||
}
|
||||
|
||||
try path.withPlatformString {
|
||||
if system_rmdir($0) != 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 -> ()
|
||||
) throws {
|
||||
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 {
|
||||
// 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)
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
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 GetTempPath2W(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 = 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 {
|
||||
if !DeleteFileW($0) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, delete the parent
|
||||
try path.withPlatformString {
|
||||
if !RemoveDirectoryW($0) {
|
||||
throw Errno(windowsError: GetLastError())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // os(Windows)
|
||||
@@ -150,21 +150,19 @@ internal struct WindowsRootInfo {
|
||||
/// * Omitted volume from other forms: `\\.\`, `\\.\UNC\server\\`, `\\server\\`
|
||||
case empty
|
||||
|
||||
// TODO: NT paths? Admin paths using `$`?
|
||||
/// A specified drive.
|
||||
///
|
||||
/// * Traditional disk: `C:\`, `C:`
|
||||
/// * Device disk: `\\.\C:\`, `\\?\C:\`
|
||||
/// * UNC: `\\server\e:\`, `\\?\UNC\server\e:\`
|
||||
///
|
||||
/// TODO: NT paths? Admin paths using `$`?
|
||||
case drive(Character)
|
||||
|
||||
// TODO: GUID type?
|
||||
/// A volume with a GUID in a non-traditional path
|
||||
///
|
||||
/// * UNC: `\\host\Volume{0000-...}\`, `\\.\UNC\host\Volume{0000-...}\`
|
||||
/// * Device roots: `\\.\Volume{0000-...}\`, `\\?\Volume{000-...}\`
|
||||
///
|
||||
/// TODO: GUID type?
|
||||
case guid(String)
|
||||
|
||||
// TODO: Legacy DOS devices, such as COM1?
|
||||
|
||||
@@ -17,114 +17,111 @@
|
||||
/// let perms = FilePermissions(rawValue: 0o644)
|
||||
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
|
||||
@frozen
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C file permissions.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CInterop.Mode
|
||||
public let rawValue: CModeT
|
||||
|
||||
/// Create a strongly-typed file permission from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
|
||||
public init(rawValue: CModeT) { self.rawValue = rawValue }
|
||||
|
||||
/// Indicates that other users have read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherRead: FilePermissions { FilePermissions(0o4) }
|
||||
public static var otherRead: FilePermissions { .init(rawValue: 0o4) }
|
||||
|
||||
/// Indicates that other users have write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherWrite: FilePermissions { FilePermissions(0o2) }
|
||||
public static var otherWrite: FilePermissions { .init(rawValue: 0o2) }
|
||||
|
||||
/// Indicates that other users have execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherExecute: FilePermissions { FilePermissions(0o1) }
|
||||
public static var otherExecute: FilePermissions { .init(rawValue: 0o1) }
|
||||
|
||||
/// Indicates that other users have read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadWrite: FilePermissions { FilePermissions(0o6) }
|
||||
public static var otherReadWrite: FilePermissions { .init(rawValue: 0o6) }
|
||||
|
||||
/// Indicates that other users have read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadExecute: FilePermissions { FilePermissions(0o5) }
|
||||
public static var otherReadExecute: FilePermissions { .init(rawValue: 0o5) }
|
||||
|
||||
/// Indicates that other users have write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) }
|
||||
public static var otherWriteExecute: FilePermissions { .init(rawValue: 0o3) }
|
||||
|
||||
/// Indicates that other users have read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) }
|
||||
public static var otherReadWriteExecute: FilePermissions { .init(rawValue: 0o7) }
|
||||
|
||||
/// Indicates that the group has read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupRead: FilePermissions { FilePermissions(0o40) }
|
||||
public static var groupRead: FilePermissions { .init(rawValue: 0o40) }
|
||||
|
||||
/// Indicates that the group has write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupWrite: FilePermissions { FilePermissions(0o20) }
|
||||
public static var groupWrite: FilePermissions { .init(rawValue: 0o20) }
|
||||
|
||||
/// Indicates that the group has execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupExecute: FilePermissions { FilePermissions(0o10) }
|
||||
public static var groupExecute: FilePermissions { .init(rawValue: 0o10) }
|
||||
|
||||
/// Indicates that the group has read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadWrite: FilePermissions { FilePermissions(0o60) }
|
||||
public static var groupReadWrite: FilePermissions { .init(rawValue: 0o60) }
|
||||
|
||||
/// Indicates that the group has read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadExecute: FilePermissions { FilePermissions(0o50) }
|
||||
public static var groupReadExecute: FilePermissions { .init(rawValue: 0o50) }
|
||||
|
||||
/// Indicates that the group has write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) }
|
||||
public static var groupWriteExecute: FilePermissions { .init(rawValue: 0o30) }
|
||||
|
||||
/// Indicates that the group has read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) }
|
||||
public static var groupReadWriteExecute: FilePermissions { .init(rawValue: 0o70) }
|
||||
|
||||
/// Indicates that the owner has read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerRead: FilePermissions { FilePermissions(0o400) }
|
||||
public static var ownerRead: FilePermissions { .init(rawValue: 0o400) }
|
||||
|
||||
/// Indicates that the owner has write-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerWrite: FilePermissions { FilePermissions(0o200) }
|
||||
public static var ownerWrite: FilePermissions { .init(rawValue: 0o200) }
|
||||
|
||||
/// Indicates that the owner has execute-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerExecute: FilePermissions { FilePermissions(0o100) }
|
||||
public static var ownerExecute: FilePermissions { .init(rawValue: 0o100) }
|
||||
|
||||
/// Indicates that the owner has read-write permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) }
|
||||
public static var ownerReadWrite: FilePermissions { .init(rawValue: 0o600) }
|
||||
|
||||
/// Indicates that the owner has read-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) }
|
||||
public static var ownerReadExecute: FilePermissions { .init(rawValue: 0o500) }
|
||||
|
||||
/// Indicates that the owner has write-execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) }
|
||||
public static var ownerWriteExecute: FilePermissions { .init(rawValue: 0o300) }
|
||||
|
||||
/// Indicates that the owner has read, write, and execute permission.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) }
|
||||
public static var ownerReadWriteExecute: FilePermissions { .init(rawValue: 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 { FilePermissions(0o4000) }
|
||||
public static var setUserID: FilePermissions { .init(rawValue: 0o4000) }
|
||||
|
||||
/// Indicates that the file is executed as the group.
|
||||
///
|
||||
/// For more information, see the `setgid(2)` man page.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var setGroupID: FilePermissions { FilePermissions(0o2000) }
|
||||
public static var setGroupID: FilePermissions { .init(rawValue: 0o2000) }
|
||||
|
||||
/// Indicates that executable's text segment
|
||||
/// should be kept in swap space even after it exits.
|
||||
@@ -132,10 +129,10 @@ public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
/// For more information, see the `chmod(2)` man page's
|
||||
/// discussion of `S_ISVTX` (the sticky bit).
|
||||
@_alwaysEmitIntoClient
|
||||
public static var saveText: FilePermissions { FilePermissions(0o1000) }
|
||||
public static var saveText: FilePermissions { .init(rawValue: 0o1000) }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
extension FilePermissions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
extension String {
|
||||
internal init(
|
||||
_unsafeUninitializedCapacity capacity: Int,
|
||||
initializingUTF8With body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
|
||||
) rethrows {
|
||||
if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
|
||||
self = try String(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: body)
|
||||
return
|
||||
}
|
||||
|
||||
let array = try Array<UInt8>(
|
||||
unsafeUninitializedCapacity: capacity
|
||||
) { buffer, count in
|
||||
count = try body(buffer)
|
||||
}
|
||||
self = String(decoding: array, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,48 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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: - Public typealiases
|
||||
|
||||
/// The C `mode_t` type.
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@available(*, deprecated, renamed: "CInterop.Mode")
|
||||
public typealias CModeT = CInterop.Mode
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
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
|
||||
|
||||
// MARK: - Public typealiases
|
||||
|
||||
// FIXME: `CModeT` ought to be deprecated and replaced with `CInterop.Mode`
|
||||
// if/when the compiler becomes less strict about availability checking
|
||||
// of "namespaced" typealiases. (rdar://81722893)
|
||||
#if os(Windows)
|
||||
/// The C `mode_t` type.
|
||||
public typealias CModeT = CInt
|
||||
#else
|
||||
/// The C `mode_t` type.
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
public typealias CModeT = mode_t
|
||||
#endif
|
||||
|
||||
/// A namespace for C and platform types
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -11,20 +11,27 @@
|
||||
// they can be used anywhere without imports and without confusion to
|
||||
// unavailable local decls.
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
import CSystem
|
||||
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 os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERRNO_NOT_USED: CInt { 0 }
|
||||
#endif
|
||||
@@ -71,7 +78,7 @@ internal var _EACCES: CInt { EACCES }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFAULT: CInt { EFAULT }
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(Windows) && !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTBLK: CInt { ENOTBLK }
|
||||
#endif
|
||||
@@ -139,7 +146,13 @@ internal var _ERANGE: CInt { ERANGE }
|
||||
internal var _EAGAIN: CInt { EAGAIN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EWOULDBLOCK: CInt { EWOULDBLOCK }
|
||||
internal var _EWOULDBLOCK: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_EWOULDBLOCK()
|
||||
#else
|
||||
EWOULDBLOCK
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINPROGRESS: CInt { EINPROGRESS }
|
||||
@@ -165,6 +178,7 @@ internal var _ENOPROTOOPT: CInt { ENOPROTOOPT }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTONOSUPPORT: CInt { EPROTONOSUPPORT }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESOCKTNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
@@ -173,6 +187,7 @@ internal var _ESOCKTNOSUPPORT: CInt {
|
||||
return ESOCKTNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSUP: CInt {
|
||||
@@ -183,6 +198,7 @@ internal var _ENOTSUP: CInt {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPFNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
@@ -191,6 +207,7 @@ internal var _EPFNOSUPPORT: CInt {
|
||||
return EPFNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT }
|
||||
@@ -225,6 +242,7 @@ internal var _EISCONN: CInt { EISCONN }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCONN: CInt { ENOTCONN }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHUTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
@@ -242,6 +260,7 @@ internal var _ETOOMANYREFS: CInt {
|
||||
return ETOOMANYREFS
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIMEDOUT: CInt { ETIMEDOUT }
|
||||
@@ -255,6 +274,7 @@ internal var _ELOOP: CInt { ELOOP }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAMETOOLONG: CInt { ENAMETOOLONG }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
@@ -263,6 +283,7 @@ internal var _EHOSTDOWN: CInt {
|
||||
return EHOSTDOWN
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
|
||||
@@ -270,11 +291,12 @@ internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTEMPTY: CInt { ENOTEMPTY }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROCLIM: CInt { EPROCLIM }
|
||||
#endif
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUSERS: CInt {
|
||||
#if os(Windows)
|
||||
@@ -283,6 +305,7 @@ internal var _EUSERS: CInt {
|
||||
return EUSERS
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDQUOT: CInt {
|
||||
@@ -302,6 +325,7 @@ internal var _ESTALE: CInt {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTE: CInt {
|
||||
#if os(Windows)
|
||||
@@ -310,8 +334,9 @@ internal var _EREMOTE: CInt {
|
||||
return EREMOTE
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADRPC: CInt { EBADRPC }
|
||||
|
||||
@@ -334,7 +359,7 @@ internal var _ENOLCK: CInt { ENOLCK }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSYS: CInt { ENOSYS }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFTYPE: CInt { EFTYPE }
|
||||
|
||||
@@ -356,7 +381,7 @@ internal var _EDEVERR: CInt { EDEVERR }
|
||||
internal var _EOVERFLOW: CInt { EOVERFLOW }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADEXEC: CInt { EBADEXEC }
|
||||
|
||||
@@ -384,7 +409,7 @@ internal var _ENOMSG: CInt { ENOMSG }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EILSEQ: CInt { EILSEQ }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOATTR: CInt { ENOATTR }
|
||||
#endif
|
||||
@@ -393,32 +418,47 @@ internal var _ENOATTR: CInt { ENOATTR }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMSG: CInt { EBADMSG }
|
||||
|
||||
#if !os(OpenBSD)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMULTIHOP: CInt { EMULTIHOP }
|
||||
|
||||
#if !os(WASI)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODATA: CInt { ENODATA }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLINK: CInt { ENOLINK }
|
||||
|
||||
#if !os(WASI)
|
||||
@_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)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIME: CInt { ETIME }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
|
||||
internal var _EOPNOTSUPP: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_EOPNOTSUPP()
|
||||
#else
|
||||
EOPNOTSUPP
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPOLICY: CInt { ENOPOLICY }
|
||||
#endif
|
||||
@@ -431,7 +471,7 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
|
||||
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EQFULL: CInt { EQFULL }
|
||||
|
||||
@@ -451,18 +491,40 @@ 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 { O_ACCMODE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
|
||||
internal var _O_ACCMODE: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_ACCMODE()
|
||||
#else
|
||||
O_ACCMODE
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt { O_APPEND }
|
||||
internal var _O_NONBLOCK: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_NONBLOCK()
|
||||
#else
|
||||
O_NONBLOCK
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_APPEND()
|
||||
#else
|
||||
O_APPEND
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SHLOCK: CInt { O_SHLOCK }
|
||||
|
||||
@@ -471,24 +533,44 @@ 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
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CREAT: CInt { O_CREAT }
|
||||
internal var _O_CREAT: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_CREAT()
|
||||
#else
|
||||
O_CREAT
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt { O_TRUNC }
|
||||
internal var _O_TRUNC: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_TRUNC()
|
||||
#else
|
||||
O_TRUNC
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt { O_EXCL }
|
||||
internal var _O_EXCL: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_EXCL()
|
||||
#else
|
||||
O_EXCL
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EVTONLY: CInt { O_EVTONLY }
|
||||
#endif
|
||||
@@ -498,12 +580,17 @@ internal var _O_EVTONLY: CInt { O_EVTONLY }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOCTTY: CInt { O_NOCTTY }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECTORY: CInt { O_DIRECTORY }
|
||||
internal var _O_DIRECTORY: CInt {
|
||||
#if os(WASI)
|
||||
_getConst_O_DIRECTORY()
|
||||
#else
|
||||
O_DIRECTORY
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SYMLINK: CInt { O_SYMLINK }
|
||||
#endif
|
||||
@@ -522,11 +609,10 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_END: CInt { SEEK_END }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_DATA: CInt { SEEK_DATA }
|
||||
#endif
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -12,14 +12,22 @@
|
||||
|
||||
// TODO: Should CSystem just include all the header files we need?
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
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
|
||||
@@ -28,7 +36,7 @@ internal typealias _COffT = off_t
|
||||
|
||||
// MARK: syscalls and variables
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
internal var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
@@ -45,11 +53,26 @@ internal var system_errno: CInt {
|
||||
_ = ucrt._set_errno(newValue)
|
||||
}
|
||||
}
|
||||
#else
|
||||
#elseif canImport(Glibc)
|
||||
internal var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Musl)
|
||||
internal var system_errno: CInt {
|
||||
get { Musl.errno }
|
||||
set { Musl.errno = newValue }
|
||||
}
|
||||
#elseif canImport(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
|
||||
@@ -60,7 +83,10 @@ internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>!
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
internal func system_strlen(_ s: UnsafePointer<Int8>) -> Int {
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
@@ -78,6 +104,16 @@ internal func system_platform_strlen(_ s: UnsafePointer<CInterop.PlatformChar>)
|
||||
#endif
|
||||
}
|
||||
|
||||
// memset for raw buffers
|
||||
// FIXME: Do we really not have something like this in the stdlib already?
|
||||
internal func system_memset(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
to byte: UInt8
|
||||
) {
|
||||
guard buffer.count > 0 else { return }
|
||||
memset(buffer.baseAddress!, CInt(byte), buffer.count)
|
||||
}
|
||||
|
||||
// Interop between String and platfrom string
|
||||
extension String {
|
||||
internal func _withPlatformString<Result>(
|
||||
@@ -128,6 +164,24 @@ 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
|
||||
@@ -139,6 +193,8 @@ 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 {
|
||||
|
||||
@@ -19,9 +19,10 @@
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
internal struct Trace {
|
||||
internal struct Entry: Hashable {
|
||||
private var name: String
|
||||
private var arguments: [AnyHashable]
|
||||
internal struct Entry {
|
||||
|
||||
internal var name: String
|
||||
internal var arguments: [AnyHashable]
|
||||
|
||||
internal init(name: String, _ arguments: [AnyHashable]) {
|
||||
self.name = name
|
||||
@@ -62,7 +63,7 @@ internal class MockingDriver {
|
||||
|
||||
// Whether we should pretend to be Windows for syntactic operations
|
||||
// inside FilePath
|
||||
fileprivate var forceWindowsSyntaxForPaths = false
|
||||
fileprivate var forceWindowsSyntaxForPaths: Bool? = nil
|
||||
}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
@@ -109,8 +110,8 @@ private var contextualMockingEnabled: Bool {
|
||||
extension MockingDriver {
|
||||
internal static var enabled: Bool { mockingEnabled }
|
||||
|
||||
internal static var forceWindowsPaths: Bool {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
|
||||
internal static var forceWindowsPaths: Bool? {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +128,7 @@ internal var mockingEnabled: Bool {
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var forceWindowsPaths: Bool {
|
||||
internal var forceWindowsPaths: Bool? {
|
||||
#if !ENABLE_MOCKING
|
||||
return false
|
||||
#else
|
||||
@@ -146,7 +147,7 @@ private func originalSyscallName(_ function: String) -> String {
|
||||
|
||||
private func mockImpl(
|
||||
name: String,
|
||||
path: UnsafePointer<CChar>?,
|
||||
path: UnsafePointer<CInterop.PlatformChar>?,
|
||||
_ args: [AnyHashable]
|
||||
) -> CInt {
|
||||
precondition(mockingEnabled)
|
||||
@@ -177,33 +178,29 @@ private func mockImpl(
|
||||
}
|
||||
|
||||
internal func _mock(
|
||||
name: String = #function, path: UnsafePointer<CChar>? = nil, _ args: AnyHashable...
|
||||
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
|
||||
) -> CInt {
|
||||
return mockImpl(name: name, path: path, args)
|
||||
}
|
||||
internal func _mockInt(
|
||||
name: String = #function, path: UnsafePointer<CChar>? = nil, _ args: AnyHashable...
|
||||
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
|
||||
) -> Int {
|
||||
Int(mockImpl(name: name, path: path, args))
|
||||
}
|
||||
|
||||
internal func _mockOffT(
|
||||
name: String = #function, path: UnsafePointer<CChar>? = nil, _ args: AnyHashable...
|
||||
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
|
||||
) -> _COffT {
|
||||
_COffT(mockImpl(name: name, path: path, args))
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
// Force paths to be treated as Windows syntactically if `enabled` is
|
||||
// true.
|
||||
// true, and as POSIX syntactically if not.
|
||||
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
|
||||
#if ENABLE_MOCKING
|
||||
guard enabled else {
|
||||
body()
|
||||
return
|
||||
}
|
||||
MockingDriver.withMockingEnabled { driver in
|
||||
driver.forceWindowsSyntaxForPaths = true
|
||||
driver.forceWindowsSyntaxForPaths = enabled
|
||||
body()
|
||||
}
|
||||
#else
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// A copy-on-write fixed-size buffer of raw memory.
|
||||
internal struct _RawBuffer {
|
||||
internal var _storage: Storage?
|
||||
|
||||
internal init() {
|
||||
self._storage = nil
|
||||
}
|
||||
|
||||
internal init(minimumCapacity: Int) {
|
||||
if minimumCapacity > 0 {
|
||||
self._storage = Storage.create(minimumCapacity: minimumCapacity)
|
||||
} else {
|
||||
self._storage = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal var capacity: Int {
|
||||
_storage?.header ?? 0 // Note: not capacity!
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique() {
|
||||
guard _storage != nil else { return }
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique {
|
||||
_storage = _copy(capacity: capacity)
|
||||
}
|
||||
}
|
||||
|
||||
internal func _grow(desired: Int) -> Int {
|
||||
let next = Int(1.75 * Double(self.capacity))
|
||||
return Swift.max(next, desired)
|
||||
}
|
||||
|
||||
internal mutating func ensureUnique(capacity: Int) {
|
||||
let unique = isKnownUniquelyReferenced(&_storage)
|
||||
if !unique || self.capacity < capacity {
|
||||
_storage = _copy(capacity: _grow(desired: capacity))
|
||||
}
|
||||
}
|
||||
|
||||
internal func withUnsafeBytes<R>(
|
||||
_ body: (UnsafeRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let storage = _storage else {
|
||||
return try body(UnsafeRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
return try storage.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func withUnsafeMutableBytes<R>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
guard _storage != nil else {
|
||||
return try body(UnsafeMutableRawBufferPointer(start: nil, count: 0))
|
||||
}
|
||||
ensureUnique()
|
||||
return try _storage!.withUnsafeMutablePointers { count, bytes in
|
||||
let buffer = UnsafeMutableRawBufferPointer(start: bytes, count: count.pointee)
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _RawBuffer {
|
||||
internal class Storage: ManagedBuffer<Int, UInt8> {
|
||||
internal static func create(minimumCapacity: Int) -> Storage {
|
||||
Storage.create(
|
||||
minimumCapacity: minimumCapacity,
|
||||
makingHeaderWith: { $0.capacity }
|
||||
) as! Storage
|
||||
}
|
||||
}
|
||||
|
||||
internal func _copy(capacity: Int) -> Storage {
|
||||
let copy = Storage.create(minimumCapacity: capacity)
|
||||
copy.withUnsafeMutablePointers { dstlen, dst in
|
||||
self.withUnsafeBytes { src in
|
||||
guard src.count > 0 else { return }
|
||||
assert(src.count <= dstlen.pointee)
|
||||
UnsafeMutableRawPointer(dst)
|
||||
.copyMemory(
|
||||
from: src.baseAddress!,
|
||||
byteCount: Swift.min(src.count, dstlen.pointee))
|
||||
}
|
||||
}
|
||||
return copy
|
||||
}
|
||||
}
|
||||
@@ -1,18 +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
|
||||
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
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
@@ -54,7 +60,7 @@ internal func system_close(_ fd: Int32) -> Int32 {
|
||||
|
||||
// read
|
||||
internal func system_read(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
|
||||
@@ -64,12 +70,20 @@ internal func system_read(
|
||||
|
||||
// pread
|
||||
internal func system_pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
#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
|
||||
@@ -84,7 +98,7 @@ internal func system_lseek(
|
||||
|
||||
// write
|
||||
internal func system_write(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
|
||||
@@ -94,14 +108,23 @@ internal func system_write(
|
||||
|
||||
// pwrite
|
||||
internal func system_pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
#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
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
@@ -115,3 +138,122 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
#endif
|
||||
return dup2(fd, fd2)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(WASI)
|
||||
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fds) }
|
||||
#endif
|
||||
return pipe(fds)
|
||||
}
|
||||
#endif
|
||||
|
||||
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
#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
|
||||
if mockingEnabled { return _mock(path: path, mode) }
|
||||
#endif
|
||||
return mkdir(path, mode)
|
||||
}
|
||||
|
||||
internal func system_rmdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
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
|
||||
internal let SYSTEM_DT_DIR = DT_DIR
|
||||
internal typealias system_dirent = dirent
|
||||
#if os(Linux) || os(Android)
|
||||
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
|
||||
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<dirent>? {
|
||||
return readdir(dir)
|
||||
}
|
||||
|
||||
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
|
||||
if mockingEnabled {
|
||||
return _mock(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
return openat(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
|
||||
internal func system_umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
return umask(mode)
|
||||
}
|
||||
|
||||
internal func system_getenv(
|
||||
_ name: UnsafePointer<CChar>
|
||||
) -> UnsafeMutablePointer<CChar>? {
|
||||
return getenv(name)
|
||||
}
|
||||
@@ -12,13 +12,45 @@
|
||||
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 {
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
let decodedFlags = DecodedOpenFlags(oflag)
|
||||
|
||||
var saAttrs = SECURITY_ATTRIBUTES(
|
||||
nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
|
||||
lpSecurityDescriptor: nil,
|
||||
bInheritHandle: decodedFlags.bInheritHandle
|
||||
)
|
||||
|
||||
let hFile = CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
DWORD(FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE),
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
nil)
|
||||
|
||||
if hFile == INVALID_HANDLE_VALUE {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -26,10 +58,41 @@ internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
// TODO(compnerd): Apply read/write permissions
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
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
|
||||
)
|
||||
|
||||
let hFile = CreateFileW(path,
|
||||
decodedFlags.dwDesiredAccess,
|
||||
DWORD(FILE_SHARE_DELETE
|
||||
| FILE_SHARE_READ
|
||||
| FILE_SHARE_WRITE),
|
||||
&saAttrs,
|
||||
decodedFlags.dwCreationDisposition,
|
||||
decodedFlags.dwFlagsAndAttributes,
|
||||
nil)
|
||||
|
||||
if hFile == INVALID_HANDLE_VALUE {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return _open_osfhandle(intptr_t(bitPattern: hFile), oflag);
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -58,12 +121,29 @@ internal func write(
|
||||
Int(_write(fd, buf, numericCast(nbyte)))
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func lseek(
|
||||
_ fd: Int32, _ off: off_t, _ whence: Int32
|
||||
) -> off_t {
|
||||
_lseek(fd, off, whence)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func dup(_ fd: Int32) -> Int32 {
|
||||
_dup(fd)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
_dup2(fd, fd2)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
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 { return Int(EBADF) }
|
||||
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)!
|
||||
@@ -74,8 +154,7 @@ internal func pread(
|
||||
|
||||
var nNumberOfBytesRead: DWORD = 0
|
||||
if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesRead)
|
||||
@@ -86,7 +165,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 { return Int(EBADF) }
|
||||
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)!
|
||||
@@ -98,11 +177,482 @@ internal func pwrite(
|
||||
var nNumberOfBytesWritten: DWORD = 0
|
||||
if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten,
|
||||
&ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
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
|
||||
)
|
||||
|
||||
if !CreateDirectoryW(path, &saAttrs) {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func rmdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
if !RemoveDirectoryW(path) {
|
||||
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
|
||||
@@ -0,0 +1,377 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
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 swift(>=5.9) && SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
import Darwin.Mach
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public protocol MachPortRight {}
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@inlinable
|
||||
internal func _machPrecondition(
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line,
|
||||
_ body: @autoclosure () -> kern_return_t
|
||||
) {
|
||||
let kr = body()
|
||||
let expected = KERN_SUCCESS
|
||||
precondition(kr == expected, file: file, line: line)
|
||||
}
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
@frozen
|
||||
public enum Mach {
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public struct Port<RightType: MachPortRight>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _name: mach_port_name_t
|
||||
|
||||
@usableFromInline
|
||||
internal var _context: mach_port_context_t
|
||||
|
||||
/// Transfer ownership of an existing unmanaged Mach port right into a
|
||||
/// `Mach.Port` by name.
|
||||
///
|
||||
/// This initializer traps if `name` is `MACH_PORT_NULL`, or if `name` is
|
||||
/// `MACH_PORT_DEAD` and the `RightType` is `Mach.ReceiveRight`.
|
||||
///
|
||||
/// If the type of the right does not match the `RightType` of the
|
||||
/// `Mach.Port` being constructed, behavior is undefined.
|
||||
///
|
||||
/// The underlying port right will be automatically deallocated at the
|
||||
/// end of the `Mach.Port` instance's lifetime.
|
||||
///
|
||||
/// 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")
|
||||
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"
|
||||
)
|
||||
|
||||
let secret = mach_port_context_t(arc4random())
|
||||
_machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0))
|
||||
self._context = secret
|
||||
}
|
||||
else {
|
||||
self._context = 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrow access to the port name in a block that can perform
|
||||
/// non-consuming operations.
|
||||
///
|
||||
/// Take care when using this function; many operations consume rights,
|
||||
/// and send-once rights are easily consumed.
|
||||
///
|
||||
/// If the right is consumed, behavior is undefined.
|
||||
///
|
||||
/// The body block may optionally return something, which will then be
|
||||
/// returned to the caller of withBorrowedName.
|
||||
@inlinable
|
||||
public func withBorrowedName<ReturnType>(
|
||||
body: (mach_port_name_t) -> ReturnType
|
||||
) -> ReturnType {
|
||||
return body(_name)
|
||||
}
|
||||
|
||||
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)
|
||||
)
|
||||
} else {
|
||||
assert(
|
||||
RightType.self == SendRight.self ||
|
||||
RightType.self == SendOnceRight.self
|
||||
)
|
||||
_machPrecondition(mach_port_deallocate(mach_task_self_, _name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Possible errors that can be thrown by Mach.Port operations.
|
||||
public enum PortRightError : Error {
|
||||
/// Returned when an operation cannot be completed, because the Mach
|
||||
/// port right has become a dead name. This is caused by deallocation of the
|
||||
/// receive right on the other end.
|
||||
case deadName
|
||||
}
|
||||
|
||||
/// The MachPortRight type used to manage a receive right.
|
||||
@frozen
|
||||
public struct ReceiveRight: MachPortRight {}
|
||||
|
||||
/// The MachPortRight type used to manage a send right.
|
||||
@frozen
|
||||
public struct SendRight: MachPortRight {}
|
||||
|
||||
/// The MachPortRight type used to manage a send-once right.
|
||||
///
|
||||
/// Send-once rights are the most restrictive type of Mach port rights.
|
||||
/// They cannot create other rights, and are consumed upon use.
|
||||
///
|
||||
/// Upon destruction a send-once notification will be sent to the
|
||||
/// receiving end.
|
||||
@frozen
|
||||
public struct SendOnceRight: MachPortRight {}
|
||||
}
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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.
|
||||
///
|
||||
/// This initializer aborts if name is MACH_PORT_NULL.
|
||||
///
|
||||
/// If the type of the right does not match the type T of Mach.Port<T>
|
||||
/// being constructed, the behavior is undefined.
|
||||
///
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// Allocate a new Mach port with a receive right, creating a
|
||||
/// Mach.Port<Mach.ReceiveRight> to manage it.
|
||||
///
|
||||
/// This initializer will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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)
|
||||
)
|
||||
|
||||
// name-only init will guard ReceiveRights
|
||||
self.init(name: storage)
|
||||
}
|
||||
|
||||
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
/// Returns a tuple containing the Mach port name representing the right,
|
||||
/// and the context value used to guard the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public consuming func relinquish(
|
||||
) -> (name: mach_port_name_t, context: mach_port_context_t) {
|
||||
let destructured = (name: _name, context: _context)
|
||||
discard self
|
||||
return destructured
|
||||
}
|
||||
|
||||
/// Remove guard and transfer ownership of the underlying port right to
|
||||
/// the caller.
|
||||
///
|
||||
/// Returns the Mach port name representing the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
///
|
||||
/// This function makes a syscall to remove the guard from
|
||||
/// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract
|
||||
/// the context value along with the port name.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public consuming func unguardAndRelinquish() -> mach_port_name_t {
|
||||
let (name, context) = self.relinquish()
|
||||
_machPrecondition(mach_port_unguard(mach_task_self_, name, context))
|
||||
return name
|
||||
}
|
||||
|
||||
/// Borrow access to the port name in a block that can perform
|
||||
/// non-consuming operations.
|
||||
///
|
||||
/// Take care when using this function; many operations consume rights.
|
||||
///
|
||||
/// If the right is consumed, behavior is undefined.
|
||||
///
|
||||
/// The body block may optionally return something, which will then be
|
||||
/// returned to the caller of withBorrowedName.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public func withBorrowedName<ReturnType>(
|
||||
body: (mach_port_name_t, mach_port_context_t) -> ReturnType
|
||||
) -> ReturnType {
|
||||
return body(_name, _context)
|
||||
}
|
||||
|
||||
/// Create a send-once right for a given receive right.
|
||||
///
|
||||
/// This does not affect the makeSendCount of the receive right.
|
||||
///
|
||||
/// This function will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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
|
||||
)
|
||||
)
|
||||
|
||||
// The value of newRight is validated by the Mach.Port initializer
|
||||
precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE)
|
||||
|
||||
return Mach.Port(name: newRight)
|
||||
}
|
||||
|
||||
/// Create a send right for a given receive right.
|
||||
///
|
||||
/// This increments the makeSendCount of the receive right.
|
||||
///
|
||||
/// This function will abort if the right could not be created.
|
||||
/// Callers may assert that a valid right is always returned.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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)
|
||||
)
|
||||
)
|
||||
|
||||
return Mach.Port(name: _name)
|
||||
}
|
||||
|
||||
/// Access the make-send count.
|
||||
///
|
||||
/// Each get/set of this property makes a syscall.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
return status.mps_mscount
|
||||
}
|
||||
|
||||
set {
|
||||
_machPrecondition(mach_port_set_mscount(mach_task_self_, _name, newValue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
extension Mach.Port where RightType == Mach.SendRight {
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
/// Returns the Mach port name representing the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// Create another send right from a given send right.
|
||||
///
|
||||
/// This does not affect the makeSendCount of the receive right.
|
||||
///
|
||||
/// If the send right being copied has become a dead name, meaning the
|
||||
/// receiving side has been deallocated, then copySendRight() will throw
|
||||
/// a Mach.PortRightError.deadName error.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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 {
|
||||
throw Mach.PortRightError.deadName
|
||||
}
|
||||
_machPrecondition(kr)
|
||||
|
||||
return Mach.Port(name: _name)
|
||||
}
|
||||
}
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
extension Mach.Port where RightType == Mach.SendOnceRight {
|
||||
/// Transfer ownership of the underlying port right to the caller.
|
||||
///
|
||||
/// Returns the Mach port name representing the right.
|
||||
///
|
||||
/// This operation liberates the right from management by the Mach.Port,
|
||||
/// and the underlying right will no longer be automatically deallocated.
|
||||
///
|
||||
/// After this function completes, the Mach.Port is destroyed and no longer
|
||||
/// usable.
|
||||
@inlinable
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
public consuming func relinquish() -> mach_port_name_t {
|
||||
let name = _name
|
||||
discard self
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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,10 +20,61 @@ 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)
|
||||
}
|
||||
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter platformString: The null-terminated platform string to be
|
||||
/// interpreted as `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// If the content of the platform string isn't well-formed Unicode,
|
||||
/// this initializer replaces invalid bytes with U+FFFD.
|
||||
/// 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.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of String.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = platformString.withUnsafeBufferPointer {
|
||||
String(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use String.init(_ scalar: Unicode.Scalar)")
|
||||
public init(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of String.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = ""
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use a copy of the String argument")
|
||||
public init(platformString: String) {
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
self = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
self = platformString
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
@@ -38,6 +89,62 @@ extension String {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter platformString: The null-terminated platform string to be
|
||||
/// interpreted as `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// If the contents of the platform string isn't well-formed Unicode,
|
||||
/// this initializer returns `nil`.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(
|
||||
validatingPlatformString platformString: [CInterop.PlatformChar]
|
||||
) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of String.init(validatingPlatformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
guard let string = platformString.withUnsafeBufferPointer({
|
||||
String(validatingPlatformString: $0.baseAddress!)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
self = string
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")
|
||||
public init?(
|
||||
validatingPlatformString platformString: inout CInterop.PlatformChar
|
||||
) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of String.init(validatingPlatformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = ""
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use a copy of the String argument")
|
||||
public init?(
|
||||
validatingPlatformString platformString: String
|
||||
) {
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
self = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
self = platformString
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the string,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
@@ -58,6 +165,7 @@ extension String {
|
||||
|
||||
}
|
||||
|
||||
@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)
|
||||
@@ -67,6 +175,8 @@ extension CInterop.PlatformChar {
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@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)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
*/
|
||||
|
||||
// A platform-native character representation, currently used for file paths
|
||||
internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable {
|
||||
internal struct SystemChar:
|
||||
RawRepresentable, Sendable, Comparable, Hashable, Codable {
|
||||
internal typealias RawValue = CInterop.PlatformChar
|
||||
|
||||
internal var rawValue: RawValue
|
||||
@@ -53,15 +54,15 @@ extension SystemChar {
|
||||
internal var isLetter: Bool {
|
||||
guard isASCII else { return false }
|
||||
let asciiRaw: UInt8 = numericCast(rawValue)
|
||||
return (UInt8(ascii: "a") ..< UInt8(ascii: "z")).contains(asciiRaw) ||
|
||||
(UInt8(ascii: "A") ..< UInt8(ascii: "Z")).contains(asciiRaw)
|
||||
return (UInt8(ascii: "a") ... UInt8(ascii: "z")).contains(asciiRaw) ||
|
||||
(UInt8(ascii: "A") ... UInt8(ascii: "Z")).contains(asciiRaw)
|
||||
}
|
||||
}
|
||||
|
||||
// A platform-native string representation, currently for file paths
|
||||
//
|
||||
// Always null-terminated.
|
||||
internal struct SystemString {
|
||||
internal struct SystemString: Sendable {
|
||||
internal typealias Storage = [SystemChar]
|
||||
internal var nullTerminatedStorage: Storage
|
||||
}
|
||||
@@ -95,10 +96,18 @@ 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(nullTerminatedStorage.last! == .null)
|
||||
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
|
||||
precondition(_invariantsSatisfied())
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
@@ -141,42 +150,68 @@ 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? {
|
||||
try nullTerminatedStorage.withContiguousStorageIfAvailable(body)
|
||||
// Do not include the null terminator, it is outside the Collection
|
||||
try nullTerminatedStorage.withContiguousStorageIfAvailable {
|
||||
try body(.init(start: $0.baseAddress, count: $0.count-1))
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func withContiguousMutableStorageIfAvailable<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
|
||||
) rethrows -> R? {
|
||||
defer { _invariantCheck() }
|
||||
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString: Hashable, Codable {}
|
||||
extension SystemString: Hashable, 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"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
// TODO: Below include null terminator, is this desired?
|
||||
|
||||
internal func withSystemChars<T>(
|
||||
internal func withNullTerminatedSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withContiguousStorageIfAvailable(f)!
|
||||
try nullTerminatedStorage.withUnsafeBufferPointer(f)
|
||||
}
|
||||
|
||||
// withCodeUnits does not include the null terminator
|
||||
internal func withCodeUnits<T>(
|
||||
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars {
|
||||
// TODO: Is this the right way?
|
||||
let base = UnsafeRawPointer(
|
||||
$0.baseAddress
|
||||
)!.assumingMemoryBound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self)
|
||||
return try f(UnsafeBufferPointer(start: base, count: $0.count))
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,7 +226,9 @@ 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>(
|
||||
@@ -233,7 +270,11 @@ extension SystemString: ExpressibleByStringLiteral {
|
||||
}
|
||||
|
||||
extension SystemString: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
internal var string: String { String(decoding: self) }
|
||||
internal var string: String {
|
||||
self.withCodeUnits {
|
||||
String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self)
|
||||
}
|
||||
}
|
||||
|
||||
internal var description: String { string }
|
||||
internal var debugDescription: String { description.debugDescription }
|
||||
@@ -272,13 +313,15 @@ extension SystemString {
|
||||
internal func withPlatformString<T>(
|
||||
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars {
|
||||
// TODO: Is this the right way?
|
||||
let base = UnsafeRawPointer(
|
||||
$0.baseAddress
|
||||
)!.assumingMemoryBound(to: CInterop.PlatformChar.self)
|
||||
assert(base[self.count] == 0)
|
||||
return try f(base)
|
||||
try withNullTerminatedSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformChar.self,
|
||||
capacity: length / MemoryLayout<CInterop.PlatformChar>.stride
|
||||
) { pointer in
|
||||
assert(pointer[self.count] == 0)
|
||||
return try f(pointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
extension Array where Element == String {
|
||||
internal typealias CStr = UnsafePointer<CChar>?
|
||||
|
||||
/// Call `body` with a buffer of `UnsafePointer<CChar>?` values,
|
||||
/// suitable for passing to a C function that expects a C string array.
|
||||
/// The buffer is guaranteed to be followed by an extra storage slot
|
||||
/// containing a null pointer. (For C functions that expect an array
|
||||
/// terminated with a null pointer.)
|
||||
///
|
||||
/// This function is careful not to heap allocate memory unless there are
|
||||
/// too many strings, or if it needs to copy too much character data.
|
||||
internal func _withCStringArray<R>(
|
||||
_ body: (UnsafeBufferPointer<UnsafePointer<CChar>?>) throws -> R
|
||||
) rethrows -> R {
|
||||
if self.count == 0 {
|
||||
// Fast path: empty array.
|
||||
let p: CStr = nil
|
||||
return try Swift.withUnsafePointer(to: p) { array in
|
||||
try body(UnsafeBufferPointer(start: array, count: 0))
|
||||
}
|
||||
}
|
||||
#if SYSTEM_OS_BUILD // String._guts isn't accessible from SwiftPM or CMake
|
||||
if self.count == 1, self[0]._guts._isLargeZeroTerminatedContiguousUTF8 {
|
||||
// Fast path: Single fast string.
|
||||
let start = self[0]._guts._largeContiguousUTF8CodeUnits.baseAddress!
|
||||
var p: (CStr, CStr) = (
|
||||
UnsafeRawPointer(start).assumingMemoryBound(to: CChar.self),
|
||||
nil
|
||||
)
|
||||
return try Swift.withUnsafeBytes(of: &p) { buffer in
|
||||
let start = buffer.baseAddress!.assumingMemoryBound(to: CStr.self)
|
||||
return try body(UnsafeBufferPointer(start: start, count: 1))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// We need to create a buffer for the C array.
|
||||
return try _withStackBuffer(
|
||||
capacity: (self.count + 1) * MemoryLayout<CStr>.stride
|
||||
) { array in
|
||||
let array = array.bindMemory(to: CStr.self)
|
||||
// Calculate number of bytes we need for character storage
|
||||
let bytes = self.reduce(into: 0) { count, string in
|
||||
#if SYSTEM_OS_BUILD
|
||||
if string._guts._isLargeZeroTerminatedContiguousUTF8 { return }
|
||||
#endif
|
||||
count += string.utf8.count + 1 // Plus one for terminating NUL
|
||||
}
|
||||
#if SYSTEM_OS_BUILD
|
||||
if bytes == 0 {
|
||||
// Fast path: we only contain strings with stable null-terminated storage
|
||||
for i in self.indices {
|
||||
let string = self[i]
|
||||
precondition(string._guts._isLargeZeroTerminatedContiguousUTF8)
|
||||
let address = string._guts._largeContiguousUTF8CodeUnits.baseAddress!
|
||||
array[i] = UnsafeRawPointer(address).assumingMemoryBound(to: CChar.self)
|
||||
}
|
||||
array[self.count] = nil
|
||||
return try body(UnsafeBufferPointer(rebasing: array.dropLast()))
|
||||
}
|
||||
#endif
|
||||
return try _withStackBuffer(capacity: bytes) { chars in
|
||||
var chars = chars
|
||||
for i in self.indices {
|
||||
let (cstr, scratchUsed) = self[i]._getCStr(with: chars)
|
||||
array[i] = cstr.assumingMemoryBound(to: CChar.self)
|
||||
chars = .init(rebasing: chars[scratchUsed...])
|
||||
}
|
||||
array[self.count] = nil
|
||||
return try body(UnsafeBufferPointer(rebasing: array.dropLast()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
fileprivate func _getCStr(
|
||||
with scratch: UnsafeMutableRawBufferPointer
|
||||
) -> (cstr: UnsafeRawPointer, scratchUsed: Int) {
|
||||
#if SYSTEM_OS_BUILD
|
||||
if _guts._isLargeZeroTerminatedContiguousUTF8 {
|
||||
// This is a wonderful string, we can just use its storage address.
|
||||
let address = _guts._largeContiguousUTF8CodeUnits.baseAddress!
|
||||
return (UnsafeRawPointer(address), 0)
|
||||
}
|
||||
#endif
|
||||
let r: (UnsafeRawPointer, Int)? = self.utf8.withContiguousStorageIfAvailable { source in
|
||||
// This is a somewhat okay string -- we need to use memcpy.
|
||||
precondition(source.count <= scratch.count)
|
||||
let start = scratch.baseAddress!
|
||||
start.copyMemory(from: source.baseAddress!, byteCount: source.count)
|
||||
start.storeBytes(of: 0, toByteOffset: source.count, as: UInt8.self)
|
||||
return (UnsafeRawPointer(start), source.count + 1)
|
||||
}
|
||||
if let r = r { return r }
|
||||
|
||||
// What a horrible string; we need to copy individual bytes.
|
||||
precondition(self.utf8.count <= scratch.count)
|
||||
var c = 0
|
||||
for byte in self.utf8 {
|
||||
scratch[c] = byte
|
||||
c += 1
|
||||
}
|
||||
scratch[c] = 0
|
||||
c += 1
|
||||
return (UnsafeRawPointer(scratch.baseAddress!), c)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
*/
|
||||
|
||||
// Results in errno if i == -1
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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,7 +36,7 @@ internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
} while true
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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> {
|
||||
@@ -127,3 +127,38 @@ extension MutableCollection where Element: Equatable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal func _withOptionalUnsafePointerOrNull<T, R>(
|
||||
to value: T?,
|
||||
_ body: (UnsafePointer<T>?) throws -> R
|
||||
) rethrows -> R {
|
||||
guard let value = value else {
|
||||
return try body(nil)
|
||||
}
|
||||
return try withUnsafePointer(to: value, body)
|
||||
}
|
||||
|
||||
/// Calls `body` with a temporary buffer of the indicated size,
|
||||
/// possibly stack-allocated.
|
||||
internal func _withStackBuffer<R>(
|
||||
capacity: Int,
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
typealias StackStorage = (
|
||||
UInt64, UInt64, UInt64, UInt64,
|
||||
UInt64, UInt64, UInt64, UInt64,
|
||||
UInt64, UInt64, UInt64, UInt64,
|
||||
UInt64, UInt64, UInt64, UInt64
|
||||
)
|
||||
if capacity > MemoryLayout<StackStorage>.size {
|
||||
var buffer = _RawBuffer(minimumCapacity: capacity)
|
||||
return try buffer.withUnsafeMutableBytes { buffer in
|
||||
try body(.init(rebasing: buffer[..<capacity]))
|
||||
}
|
||||
} else {
|
||||
var storage: StackStorage = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
return try withUnsafeMutableBytes(of: &storage) { buffer in
|
||||
try body(.init(rebasing: buffer[..<capacity]))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import XCTest
|
||||
|
||||
import SystemTests
|
||||
|
||||
var tests = [XCTestCaseEntry]()
|
||||
tests += SystemTests.__allTests()
|
||||
|
||||
XCTMain(tests)
|
||||
@@ -15,7 +15,11 @@ import SystemPackage
|
||||
import System
|
||||
#endif
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
#if os(Windows)
|
||||
import WinSDK
|
||||
#endif
|
||||
|
||||
@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)
|
||||
@@ -32,7 +36,9 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(ENOMEM == Errno.noMemory.rawValue)
|
||||
XCTAssert(EACCES == Errno.permissionDenied.rawValue)
|
||||
XCTAssert(EFAULT == Errno.badAddress.rawValue)
|
||||
#if !os(Windows)
|
||||
XCTAssert(ENOTBLK == Errno.notBlockDevice.rawValue)
|
||||
#endif
|
||||
XCTAssert(EBUSY == Errno.resourceBusy.rawValue)
|
||||
XCTAssert(EEXIST == Errno.fileExists.rawValue)
|
||||
XCTAssert(EXDEV == Errno.improperLink.rawValue)
|
||||
@@ -42,8 +48,10 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(EINVAL == Errno.invalidArgument.rawValue)
|
||||
XCTAssert(ENFILE == Errno.tooManyOpenFilesInSystem.rawValue)
|
||||
XCTAssert(EMFILE == Errno.tooManyOpenFiles.rawValue)
|
||||
#if !os(Windows)
|
||||
XCTAssert(ENOTTY == Errno.inappropriateIOCTLForDevice.rawValue)
|
||||
XCTAssert(ETXTBSY == Errno.textFileBusy.rawValue)
|
||||
#endif
|
||||
XCTAssert(EFBIG == Errno.fileTooLarge.rawValue)
|
||||
XCTAssert(ENOSPC == Errno.noSpace.rawValue)
|
||||
XCTAssert(ESPIPE == Errno.illegalSeek.rawValue)
|
||||
@@ -61,9 +69,15 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(EPROTOTYPE == Errno.protocolWrongTypeForSocket.rawValue)
|
||||
XCTAssert(ENOPROTOOPT == Errno.protocolNotAvailable.rawValue)
|
||||
XCTAssert(EPROTONOSUPPORT == Errno.protocolNotSupported.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
|
||||
XCTAssert(WSAEOPNOTSUPP == Errno.notSupported.rawValue)
|
||||
XCTAssert(WSAEPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
|
||||
#else
|
||||
XCTAssert(ESOCKTNOSUPPORT == Errno.socketTypeNotSupported.rawValue)
|
||||
XCTAssert(ENOTSUP == Errno.notSupported.rawValue)
|
||||
XCTAssert(EPFNOSUPPORT == Errno.protocolFamilyNotSupported.rawValue)
|
||||
#endif
|
||||
XCTAssert(EAFNOSUPPORT == Errno.addressFamilyNotSupported.rawValue)
|
||||
XCTAssert(EADDRINUSE == Errno.addressInUse.rawValue)
|
||||
XCTAssert(EADDRNOTAVAIL == Errno.addressNotAvailable.rawValue)
|
||||
@@ -75,24 +89,38 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(ENOBUFS == Errno.noBufferSpace.rawValue)
|
||||
XCTAssert(EISCONN == Errno.socketIsConnected.rawValue)
|
||||
XCTAssert(ENOTCONN == Errno.socketNotConnected.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAESHUTDOWN == Errno.socketShutdown.rawValue)
|
||||
#else
|
||||
XCTAssert(ESHUTDOWN == Errno.socketShutdown.rawValue)
|
||||
#endif
|
||||
XCTAssert(ETIMEDOUT == Errno.timedOut.rawValue)
|
||||
XCTAssert(ECONNREFUSED == Errno.connectionRefused.rawValue)
|
||||
XCTAssert(ELOOP == Errno.tooManySymbolicLinkLevels.rawValue)
|
||||
XCTAssert(ENAMETOOLONG == Errno.fileNameTooLong.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAEHOSTDOWN == Errno.hostIsDown.rawValue)
|
||||
#else
|
||||
XCTAssert(EHOSTDOWN == Errno.hostIsDown.rawValue)
|
||||
#endif
|
||||
XCTAssert(EHOSTUNREACH == Errno.noRouteToHost.rawValue)
|
||||
XCTAssert(ENOTEMPTY == Errno.directoryNotEmpty.rawValue)
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EPROCLIM == Errno.tooManyProcesses.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAEUSERS == Errno.tooManyUsers.rawValue)
|
||||
XCTAssert(WSAEDQUOT == Errno.diskQuotaExceeded.rawValue)
|
||||
XCTAssert(WSAESTALE == Errno.staleNFSFileHandle.rawValue)
|
||||
#else
|
||||
XCTAssert(EUSERS == Errno.tooManyUsers.rawValue)
|
||||
XCTAssert(EDQUOT == Errno.diskQuotaExceeded.rawValue)
|
||||
XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EBADRPC == Errno.rpcUnsuccessful.rawValue)
|
||||
XCTAssert(ERPCMISMATCH == Errno.rpcVersionMismatch.rawValue)
|
||||
XCTAssert(EPROGUNAVAIL == Errno.rpcProgramUnavailable.rawValue)
|
||||
@@ -103,7 +131,7 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(ENOLCK == Errno.noLocks.rawValue)
|
||||
XCTAssert(ENOSYS == Errno.noFunction.rawValue)
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EFTYPE == Errno.badFileTypeOrFormat.rawValue)
|
||||
XCTAssert(EAUTH == Errno.authenticationError.rawValue)
|
||||
XCTAssert(ENEEDAUTH == Errno.needAuthenticator.rawValue)
|
||||
@@ -111,9 +139,11 @@ final class ErrnoTest: XCTestCase {
|
||||
XCTAssert(EDEVERR == Errno.deviceError.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssert(EOVERFLOW == Errno.overflow.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EBADEXEC == Errno.badExecutable.rawValue)
|
||||
XCTAssert(EBADARCH == Errno.badCPUType.rawValue)
|
||||
XCTAssert(ESHLIBVERS == Errno.sharedLibraryVersionMismatch.rawValue)
|
||||
@@ -121,14 +151,17 @@ final class ErrnoTest: XCTestCase {
|
||||
#endif
|
||||
|
||||
XCTAssert(ECANCELED == Errno.canceled.rawValue)
|
||||
#if !os(Windows)
|
||||
XCTAssert(EIDRM == Errno.identifierRemoved.rawValue)
|
||||
XCTAssert(ENOMSG == Errno.noMessage.rawValue)
|
||||
#endif
|
||||
XCTAssert(EILSEQ == Errno.illegalByteSequence.rawValue)
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(ENOATTR == Errno.attributeNotFound.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssert(EBADMSG == Errno.badMessage.rawValue)
|
||||
XCTAssert(EMULTIHOP == Errno.multiHop.rawValue)
|
||||
XCTAssert(ENODATA == Errno.noData.rawValue)
|
||||
@@ -137,21 +170,29 @@ final class ErrnoTest: XCTestCase {
|
||||
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
|
||||
XCTAssert(EWOULDBLOCK == Errno.wouldBlock.rawValue)
|
||||
#if os(Windows)
|
||||
XCTAssert(WSAETOOMANYREFS == Errno.tooManyReferences.rawValue)
|
||||
XCTAssert(WSAEREMOTE == Errno.tooManyRemoteLevels.rawValue)
|
||||
#else
|
||||
XCTAssert(ETOOMANYREFS == Errno.tooManyReferences.rawValue)
|
||||
XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(ENOPOLICY == Errno.noSuchPolicy.rawValue)
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssert(ENOTRECOVERABLE == Errno.notRecoverable.rawValue)
|
||||
XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue)
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssert(EQFULL == Errno.outputQueueFull.rawValue)
|
||||
XCTAssert(ELAST == Errno.lastErrnoValue.rawValue)
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
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 SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
extension FileDescriptor {
|
||||
internal func fileSize(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int64 {
|
||||
let current = try seek(offset: 0, from: .current)
|
||||
let size = try seek(offset: 0, from: .end)
|
||||
try seek(offset: current, from: .start)
|
||||
return size
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,12 @@
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
import System
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
final class FileOperationsTest: XCTestCase {
|
||||
func testSyscalls() {
|
||||
let fd = FileDescriptor(rawValue: 1)
|
||||
@@ -86,35 +86,116 @@ final class FileOperationsTest: XCTestCase {
|
||||
for test in syscallTestCases { test.runAllTests() }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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`.
|
||||
let pipe = try FileDescriptor.pipe()
|
||||
try pipe.readEnd.closeAfter {
|
||||
try pipe.writeEnd.closeAfter {
|
||||
var abc = "abc"
|
||||
try abc.withUTF8 {
|
||||
_ = try pipe.writeEnd.write(UnsafeRawBufferPointer($0))
|
||||
}
|
||||
let readLen = 3
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { buf, count in
|
||||
count = try pipe.readEnd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
XCTAssertEqual(readBytes, Array(abc.utf8))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAdHocOpen() {
|
||||
// Ad-hoc test touching a file system.
|
||||
do {
|
||||
// TODO: Test this against a virtual in-memory file system
|
||||
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)
|
||||
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))
|
||||
}
|
||||
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)
|
||||
XCTAssertEqual(readBytes.first!, "b".utf8.first!)
|
||||
XCTAssertEqual(readBytes, preadBytes)
|
||||
|
||||
// TODO: seek
|
||||
// TODO: seek
|
||||
}
|
||||
}
|
||||
} catch let err as Errno {
|
||||
print("caught \(err))")
|
||||
@@ -139,5 +220,49 @@ final class FileOperationsTest: XCTestCase {
|
||||
issue26.runAllTests()
|
||||
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
/*
|
||||
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 {
|
||||
// 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 {
|
||||
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(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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() {
|
||||
let testPaths: Array<TestPathComponents> = [
|
||||
var testPaths: Array<TestPathComponents> = [
|
||||
TestPathComponents("", root: nil, []),
|
||||
TestPathComponents("/", root: "/", []),
|
||||
TestPathComponents("foo", root: nil, ["foo"]),
|
||||
@@ -240,16 +240,28 @@ 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: "/", [".", ".."]),
|
||||
]
|
||||
testPaths.forEach { $0.runAllTests() }
|
||||
#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()
|
||||
}
|
||||
}
|
||||
|
||||
func testSeparatorNormalization() {
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
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: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
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(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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.
|
||||
@@ -51,7 +51,6 @@ extension FilePath {
|
||||
|
||||
/// Whether a lexically-normalized `self` contains a lexically-normalized
|
||||
/// `other`.
|
||||
///
|
||||
public func lexicallyContains(_ other: FilePath) -> Bool {
|
||||
guard !other.isEmpty else { return true }
|
||||
guard !isEmpty else { return false }
|
||||
|
||||
@@ -68,7 +68,7 @@ extension ParsingTestCase {
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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> = [
|
||||
|
||||
@@ -146,7 +146,7 @@ extension SyntaxTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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)! }
|
||||
@@ -342,7 +342,7 @@ private struct WindowsRootTestCase: TestCase {
|
||||
var line: UInt
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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) {
|
||||
@@ -357,7 +357,7 @@ extension WindowsRootTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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> = [
|
||||
@@ -1064,7 +1064,10 @@ 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/.."))
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
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,38 +15,63 @@ import SystemPackage
|
||||
import System
|
||||
#endif
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
func filePathFromUnterminatedBytes<S: Sequence>(_ bytes: S) -> FilePath where S.Element == UInt8 {
|
||||
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
|
||||
func filePathFromInvalidCodePointSequence<S: Sequence>(_ bytes: S) -> FilePath where S.Element == CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
var array = Array(bytes)
|
||||
assert(array.last != 0, "already null terminated")
|
||||
array += [0]
|
||||
|
||||
return array.withUnsafeBufferPointer {
|
||||
FilePath(platformString: $0.baseAddress!._asCChar)
|
||||
$0.withMemoryRebound(to: CInterop.PlatformChar.self) {
|
||||
FilePath(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
}
|
||||
let invalidBytes: [UInt8] = [0x2F, 0x61, 0x2F, 0x62, 0x2F, 0x83]
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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 validUTF8: Bool
|
||||
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 testPaths: [TestPath] = [
|
||||
#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] = [
|
||||
// empty
|
||||
TestPath(filePath: FilePath(), string: String(), validUTF8: true),
|
||||
TestPath(filePath: FilePath(), string: String(), validString: true),
|
||||
|
||||
// valid ascii
|
||||
TestPath(filePath: "/a/b/c", string: "/a/b/c", validUTF8: true),
|
||||
TestPath(filePath: "/a/b/c", string: "/a/b/c", validString: true),
|
||||
|
||||
// valid utf8
|
||||
TestPath(filePath: "/あ/🧟♀️", string: "/あ/🧟♀️", validUTF8: true),
|
||||
TestPath(filePath: "/あ/🧟♀️", string: "/あ/🧟♀️", validString: true),
|
||||
|
||||
// invalid utf8
|
||||
TestPath(filePath: filePathFromUnterminatedBytes(invalidBytes), string: String(decoding: invalidBytes, as: UTF8.self), validUTF8: false),
|
||||
// invalid sequence
|
||||
invalidSequenceTest,
|
||||
]
|
||||
|
||||
func testFilePath() {
|
||||
@@ -57,8 +82,8 @@ final class FilePathTest: XCTestCase {
|
||||
|
||||
XCTAssertEqual(testPath.string, String(decoding: testPath.filePath))
|
||||
|
||||
// TODO: test component UTF8 validation
|
||||
if testPath.validUTF8 {
|
||||
// TODO: test component CodeUnit representation validation
|
||||
if testPath.validString {
|
||||
XCTAssertEqual(testPath.filePath, FilePath(testPath.string))
|
||||
XCTAssertEqual(testPath.string, String(validating: testPath.filePath))
|
||||
} else {
|
||||
@@ -67,7 +92,11 @@ final class FilePathTest: XCTestCase {
|
||||
}
|
||||
|
||||
testPath.filePath.withPlatformString {
|
||||
#if os(Windows)
|
||||
XCTAssertEqual(testPath.string, String(decodingCString: $0, as: UTF16.self))
|
||||
#else
|
||||
XCTAssertEqual(testPath.string, String(cString: $0))
|
||||
#endif
|
||||
XCTAssertEqual(testPath.filePath, FilePath(platformString: $0))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import SystemPackage
|
||||
import System
|
||||
#endif
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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)
|
||||
@@ -29,16 +29,20 @@ final class FileDescriptorTest: XCTestCase {
|
||||
XCTAssertEqual(O_WRONLY, FileDescriptor.AccessMode.writeOnly.rawValue)
|
||||
XCTAssertEqual(O_RDWR, FileDescriptor.AccessMode.readWrite.rawValue)
|
||||
|
||||
#if !os(Windows)
|
||||
XCTAssertEqual(O_NONBLOCK, FileDescriptor.OpenOptions.nonBlocking.rawValue)
|
||||
#endif
|
||||
XCTAssertEqual(O_APPEND, FileDescriptor.OpenOptions.append.rawValue)
|
||||
XCTAssertEqual(O_CREAT, FileDescriptor.OpenOptions.create.rawValue)
|
||||
XCTAssertEqual(O_TRUNC, FileDescriptor.OpenOptions.truncate.rawValue)
|
||||
XCTAssertEqual(O_EXCL, FileDescriptor.OpenOptions.exclusiveCreate.rawValue)
|
||||
#if !os(Windows)
|
||||
XCTAssertEqual(O_NOFOLLOW, FileDescriptor.OpenOptions.noFollow.rawValue)
|
||||
XCTAssertEqual(O_CLOEXEC, FileDescriptor.OpenOptions.closeOnExec.rawValue)
|
||||
#endif
|
||||
|
||||
// BSD only
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue)
|
||||
XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue)
|
||||
XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue)
|
||||
@@ -49,7 +53,7 @@ final class FileDescriptorTest: XCTestCase {
|
||||
XCTAssertEqual(SEEK_CUR, FileDescriptor.SeekOrigin.current.rawValue)
|
||||
XCTAssertEqual(SEEK_END, FileDescriptor.SeekOrigin.end.rawValue)
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
XCTAssertEqual(SEEK_HOLE, FileDescriptor.SeekOrigin.nextHole.rawValue)
|
||||
XCTAssertEqual(SEEK_DATA, FileDescriptor.SeekOrigin.nextData.rawValue)
|
||||
#endif
|
||||
@@ -60,7 +64,7 @@ final class FileDescriptorTest: XCTestCase {
|
||||
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
@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() {
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
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 swift(>=5.9) && SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
import XCTest
|
||||
import Darwin.Mach
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#endif
|
||||
|
||||
@available(/*System 1.4.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *)
|
||||
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)
|
||||
}
|
||||
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 }
|
||||
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)
|
||||
|
||||
XCTAssertNotEqual(name, 0xFFFFFFFF)
|
||||
|
||||
let originalCount = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_RECEIVE)
|
||||
XCTAssertEqual(originalCount, 1)
|
||||
|
||||
let incrementedCount = scopedReceiveRight(name:name)
|
||||
XCTAssertEqual(incrementedCount, 1);
|
||||
|
||||
let deallocated = refCountForMachPortName(name:name, kind: MACH_PORT_RIGHT_RECEIVE)
|
||||
XCTAssertEqual(deallocated, 0);
|
||||
}
|
||||
|
||||
func consumeSendRightAutomatically(name:mach_port_name_t) -> mach_port_urefs_t {
|
||||
let send = Mach.Port<Mach.SendRight>(name:name) // this should automatically deallocate when going out of scope
|
||||
return send.withBorrowedName { name in
|
||||
// Get the ref count before automatic deallocation happens
|
||||
return refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND)
|
||||
}
|
||||
}
|
||||
|
||||
func testSendRightDeallocation() throws {
|
||||
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)
|
||||
let one = consumeSendRightAutomatically(name:name)
|
||||
XCTAssertEqual(one, 1);
|
||||
let zero = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND)
|
||||
XCTAssertEqual(zero, 0);
|
||||
}
|
||||
}
|
||||
|
||||
func testSendRightRelinquishment() throws {
|
||||
let recv = Mach.Port<Mach.ReceiveRight>()
|
||||
|
||||
let name = ({
|
||||
let send = recv.makeSendRight()
|
||||
let one = send.withBorrowedName { name in
|
||||
return self.refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND)
|
||||
}
|
||||
XCTAssertEqual(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)
|
||||
}
|
||||
|
||||
func testMakeSendCountSettable() throws {
|
||||
var recv = Mach.Port<Mach.ReceiveRight>()
|
||||
XCTAssertEqual(recv.makeSendCount, 0)
|
||||
recv.makeSendCount = 7
|
||||
XCTAssertEqual(recv.makeSendCount, 7)
|
||||
}
|
||||
|
||||
func makeSendRight() throws -> Mach.Port<Mach.SendRight> {
|
||||
let recv = Mach.Port<Mach.ReceiveRight>()
|
||||
let zero = recv.makeSendCount
|
||||
XCTAssertEqual(zero, 0)
|
||||
let send = recv.makeSendRight()
|
||||
let one = recv.makeSendCount
|
||||
XCTAssertEqual(one, 1)
|
||||
return send
|
||||
}
|
||||
|
||||
func testMakeSendCountIncrement() throws {
|
||||
_ = try makeSendRight()
|
||||
}
|
||||
|
||||
func testMakeSendOnceDoesntIncrementMakeSendCount() throws {
|
||||
let recv = Mach.Port<Mach.ReceiveRight>()
|
||||
let zero = recv.makeSendCount
|
||||
XCTAssertEqual(zero, 0)
|
||||
_ = recv.makeSendOnceRight()
|
||||
let same = recv.makeSendCount
|
||||
XCTAssertEqual(same, zero)
|
||||
}
|
||||
|
||||
func testMakeSendOnceIsUnique() throws {
|
||||
let recv = Mach.Port<Mach.ReceiveRight>()
|
||||
let once = recv.makeSendOnceRight()
|
||||
recv.withBorrowedName { rname in
|
||||
once.withBorrowedName { oname in
|
||||
XCTAssertNotEqual(oname, rname)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCopySend() throws {
|
||||
let recv = Mach.Port<Mach.ReceiveRight>()
|
||||
let zero = recv.makeSendCount
|
||||
XCTAssertEqual(zero, 0)
|
||||
let send = recv.makeSendRight()
|
||||
let one = recv.makeSendCount
|
||||
XCTAssertEqual(one, 1)
|
||||
_ = try send.copySendRight()
|
||||
let same = recv.makeSendCount
|
||||
XCTAssertEqual(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
|
||||
@@ -15,7 +15,7 @@ import XCTest
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
|
||||
@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)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
final class SystemCharTest: XCTestCase {
|
||||
func testIsLetter() {
|
||||
let valid = SystemString(
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
for char in valid {
|
||||
XCTAssertTrue(char.isLetter)
|
||||
}
|
||||
|
||||
// non printable
|
||||
for value in 0..<(UInt8(ascii: " ")) {
|
||||
XCTAssertFalse(SystemChar(codeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit(value)).isLetter)
|
||||
}
|
||||
XCTAssertFalse(SystemChar(codeUnit: 0x7F).isLetter) // DEL
|
||||
|
||||
// misc other
|
||||
let invalid = SystemString(
|
||||
##" !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~"##)
|
||||
for char in invalid {
|
||||
XCTAssertFalse(char.isLetter)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
@@ -10,29 +10,6 @@
|
||||
// Tests for PlatformString, SystemString, and FilePath's forwarding APIs
|
||||
|
||||
// TODO: Adapt test to Windows
|
||||
extension UnsafePointer where Pointee == UInt8 {
|
||||
internal var _asCChar: UnsafePointer<CChar> {
|
||||
UnsafeRawPointer(self).assumingMemoryBound(to: CChar.self)
|
||||
}
|
||||
}
|
||||
extension UnsafePointer where Pointee == CChar {
|
||||
internal var _asUInt8: UnsafePointer<UInt8> {
|
||||
UnsafeRawPointer(self).assumingMemoryBound(to: UInt8.self)
|
||||
}
|
||||
}
|
||||
extension UnsafeBufferPointer where Element == UInt8 {
|
||||
internal var _asCChar: UnsafeBufferPointer<CChar> {
|
||||
let base = baseAddress?._asCChar
|
||||
return UnsafeBufferPointer<CChar>(start: base, count: self.count)
|
||||
}
|
||||
}
|
||||
extension UnsafeBufferPointer where Element == CChar {
|
||||
internal var _asUInt8: UnsafeBufferPointer<UInt8> {
|
||||
let base = baseAddress?._asUInt8
|
||||
return UnsafeBufferPointer<UInt8>(start: base, count: self.count)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
import XCTest
|
||||
|
||||
@@ -46,7 +23,11 @@ private func makeRaw(
|
||||
_ str: String
|
||||
) -> [CInterop.PlatformChar] {
|
||||
var str = str
|
||||
var array = str.withUTF8 { Array($0._asCChar) }
|
||||
#if os(Windows)
|
||||
var array = Array(str.utf16)
|
||||
#else
|
||||
var array = str.withUTF8 { $0.withMemoryRebound(to: CChar.self, Array.init) }
|
||||
#endif
|
||||
array.append(0)
|
||||
return array
|
||||
}
|
||||
@@ -120,7 +101,7 @@ struct StringTest: TestCase {
|
||||
// Test null insertion
|
||||
let rawChars = raw.lazy.map { SystemChar($0) }
|
||||
expectEqual(sysRaw, SystemString(rawChars.dropLast()))
|
||||
sysRaw.withSystemChars { // TODO: assuming we want null in withSysChars
|
||||
sysRaw.withNullTerminatedSystemChars {
|
||||
expectEqualSequence(rawChars, $0, "rawChars")
|
||||
}
|
||||
|
||||
@@ -273,5 +254,172 @@ 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 {
|
||||
func test_String_initWithArrayConversion() {
|
||||
let source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
let str = String(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(str, String(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_initWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var str: String
|
||||
str = String(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(str, String(platformString: $0))
|
||||
}
|
||||
str = String(platformString: "")
|
||||
XCTAssertEqual(str.isEmpty, true)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let str = String(platformString: &c)
|
||||
// Any other value of `c` would violate the null-terminated precondition
|
||||
XCTAssertEqual(str.isEmpty, true)
|
||||
}
|
||||
|
||||
func test_String_validatingPlatformStringWithArrayConversion() {
|
||||
var source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
var str: String?
|
||||
str = String(validatingPlatformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(str, String(validatingPlatformString: $0.baseAddress!))
|
||||
}
|
||||
source[1] = CInterop.PlatformChar(truncatingIfNeeded: 0xdfff)
|
||||
str = String(validatingPlatformString: source)
|
||||
XCTAssertNil(str)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_validatingPlatformStringWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var str: String?
|
||||
str = String(validatingPlatformString: source)
|
||||
XCTAssertNotNil(str)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(str, String.init(validatingPlatformString: $0))
|
||||
}
|
||||
str = String(validatingPlatformString: "")
|
||||
XCTAssertNotNil(str)
|
||||
XCTAssertEqual(str?.isEmpty, true)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_validatingPlatformStringWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let str = String(validatingPlatformString: &c)
|
||||
// Any other value of `c` would violate the null-terminated precondition
|
||||
XCTAssertNotNil(str)
|
||||
XCTAssertEqual(str?.isEmpty, true)
|
||||
}
|
||||
|
||||
func test_FilePath_initWithArrayConversion() {
|
||||
let source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
let path = FilePath(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(path, FilePath(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePath_initWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var path: FilePath
|
||||
path = FilePath(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(path, FilePath(platformString: $0))
|
||||
}
|
||||
path = FilePath(platformString: "")
|
||||
XCTAssertEqual(path.string.isEmpty, true)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePath_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let path = FilePath(platformString: &c)
|
||||
// Any other value of `c` would violate the null-terminated precondition
|
||||
XCTAssertEqual(path.string.isEmpty, true)
|
||||
}
|
||||
|
||||
func test_FilePathComponent_initWithArrayConversion() {
|
||||
var source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
var component: FilePath.Component?
|
||||
component = FilePath.Component(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(component, .init(platformString: $0.baseAddress!))
|
||||
}
|
||||
source[1] = CInterop.PlatformChar(truncatingIfNeeded: 0xffff)
|
||||
component = FilePath.Component(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(component, .init(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathComponent_initWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var component: FilePath.Component?
|
||||
component = FilePath.Component(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(component, FilePath.Component(platformString: $0))
|
||||
}
|
||||
component = FilePath.Component(platformString: "")
|
||||
XCTAssertNil(component)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathComponent_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let component = FilePath.Component(platformString: &c)
|
||||
XCTAssertNil(component)
|
||||
}
|
||||
|
||||
func test_FilePathRoot_initWithArrayConversion() {
|
||||
let source: [CInterop.PlatformChar]
|
||||
#if os(Windows)
|
||||
source = [0x41, 0x3a, 0x5c, 0, 0x7f]
|
||||
#else // unix
|
||||
source = [0x2f, 0, 0x7f]
|
||||
#endif
|
||||
var root: FilePath.Root?
|
||||
root = FilePath.Root(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(root, FilePath.Root(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathRoot_initWithStringConversion() {
|
||||
#if os(Windows)
|
||||
let source = "C:\\\0 and the rest"
|
||||
#else // unix
|
||||
let source = "/\0 and the rest"
|
||||
#endif
|
||||
var root: FilePath.Root?
|
||||
root = FilePath.Root(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(root, FilePath.Root(platformString: $0))
|
||||
}
|
||||
root = FilePath.Root(platformString: "")
|
||||
XCTAssertNil(root)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathRoot_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let root = FilePath.Root(platformString: &c)
|
||||
XCTAssertNil(root)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,25 @@ import XCTest
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
internal struct Wildcard: Hashable {}
|
||||
|
||||
extension Trace.Entry {
|
||||
/// This implements `==` with wildcard matching.
|
||||
/// (`Entry` cannot conform to `Equatable`/`Hashable` this way because
|
||||
/// the wildcard matching `==` relation isn't transitive.)
|
||||
internal func matches(_ other: Self) -> Bool {
|
||||
guard self.name == other.name else { return false }
|
||||
guard self.arguments.count == other.arguments.count else { return false }
|
||||
for i in self.arguments.indices {
|
||||
if self.arguments[i] is Wildcard || other.arguments[i] is Wildcard {
|
||||
continue
|
||||
}
|
||||
guard self.arguments[i] == other.arguments[i] else { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// To aid debugging, force failures to fatal error
|
||||
internal var forceFatalFailures = false
|
||||
|
||||
@@ -40,7 +59,7 @@ extension TestCase {
|
||||
_ message: String? = nil
|
||||
) where S1.Element: Equatable, S1.Element == S2.Element {
|
||||
if !expected.elementsEqual(actual) {
|
||||
defer { print("expected: \(expected), actual: \(actual)") }
|
||||
defer { print("expected: \(expected)\n actual: \(actual)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
@@ -49,7 +68,7 @@ extension TestCase {
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if actual != expected {
|
||||
defer { print("expected: \(expected), actual: \(actual)") }
|
||||
defer { print("expected: \(expected)\n actual: \(actual)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
@@ -62,6 +81,27 @@ extension TestCase {
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectMatch(
|
||||
_ expected: Trace.Entry?, _ actual: Trace.Entry?,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
func check() -> Bool {
|
||||
switch (expected, actual) {
|
||||
case let (expected?, actual?):
|
||||
return expected.matches(actual)
|
||||
case (nil, nil):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !check() {
|
||||
let e = expected.map { "\($0)" } ?? "nil"
|
||||
let a = actual.map { "\($0)" } ?? "nil"
|
||||
defer { print("expected: \(e)\n actual: \(a)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectNil<T>(
|
||||
_ actual: T?,
|
||||
_ message: String? = nil
|
||||
@@ -149,7 +189,7 @@ internal struct MockTestCase: TestCase {
|
||||
// Test our API mappings to the lower-level syscall invocation
|
||||
do {
|
||||
try body(true)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue())
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
@@ -158,9 +198,9 @@ internal struct MockTestCase: TestCase {
|
||||
guard interruptBehavior != .noError else {
|
||||
do {
|
||||
try body(interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue())
|
||||
try body(!interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue())
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
@@ -177,7 +217,7 @@ internal struct MockTestCase: TestCase {
|
||||
self.fail()
|
||||
} catch Errno.interrupted {
|
||||
// Success!
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue())
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
@@ -188,13 +228,13 @@ internal struct MockTestCase: TestCase {
|
||||
mocking.forceErrno = .counted(errno: EINTR, count: 3)
|
||||
|
||||
try body(interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // Success
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue()) // Success
|
||||
} catch Errno.interrupted {
|
||||
self.expectFalse(interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
class UtilTests: XCTestCase {
|
||||
func testStackBuffer() {
|
||||
// Exercises _withStackBuffer a bit, in hopes any bugs will
|
||||
// show up as ASan failures.
|
||||
for size in stride(from: 0, to: 1000, by: 5) {
|
||||
var called = false
|
||||
_withStackBuffer(capacity: size) { buffer in
|
||||
XCTAssertFalse(called)
|
||||
called = true
|
||||
|
||||
buffer.initializeMemory(as: UInt8.self, repeating: 42)
|
||||
}
|
||||
XCTAssertTrue(called)
|
||||
}
|
||||
}
|
||||
|
||||
func testCStringArray() {
|
||||
func check(
|
||||
_ array: [String],
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) {
|
||||
array._withCStringArray { carray in
|
||||
let actual = carray.map { $0.map { String(cString: $0) } ?? "<NULL>" }
|
||||
XCTAssertEqual(actual, array, file: file, line: line)
|
||||
// Verify that there is a null pointer following the last item in
|
||||
// carray. (Note: this is intentionally addressing beyond the
|
||||
// end of the buffer, as the function promises that is going to be okay.)
|
||||
XCTAssertNil((carray.baseAddress! + carray.count).pointee)
|
||||
}
|
||||
}
|
||||
|
||||
check([])
|
||||
check([""])
|
||||
check(["", ""])
|
||||
check(["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""])
|
||||
// String literals of various sizes and counts
|
||||
check(["hello"])
|
||||
check(["hello", "world"])
|
||||
check(["This is a rather large string literal"])
|
||||
check([
|
||||
"This is a rather large string literal",
|
||||
"This is small",
|
||||
"This one is not that small -- it's even longer than the first",
|
||||
])
|
||||
check([
|
||||
"This is a rather large string literal",
|
||||
"This one is not that small -- it's even longer than the first",
|
||||
"And this is the largest of them all. I wonder if it even fits on a line"
|
||||
])
|
||||
check(Array(repeating: "", count: 100))
|
||||
check(Array(repeating: "Hiii", count: 100))
|
||||
check(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"])
|
||||
check(["", "b", "", "d", "", "f", "", "h", "", "j", "", "👨👨👧👦👩❤️💋👨", "m"])
|
||||
|
||||
var girls = ["Dörothy", "Róse", "Blánche", "Sőphia"]
|
||||
check(girls) // Small strings
|
||||
for i in girls.indices {
|
||||
// Convert to native
|
||||
girls[i] = "\(girls[i]) \(girls[i]) \(girls[i])"
|
||||
}
|
||||
check(girls) // Native large strings
|
||||
for i in girls.indices {
|
||||
let data = girls[i].data(using: .utf16)!
|
||||
girls[i] = NSString(
|
||||
data: data,
|
||||
encoding: String.Encoding.utf16.rawValue
|
||||
)! as String
|
||||
}
|
||||
check(girls) // UTF-16 Cocoa strings
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
#if !canImport(ObjectiveC)
|
||||
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),
|
||||
("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 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(SystemStringTest.__allTests__SystemStringTest),
|
||||
]
|
||||
}
|
||||
#endif
|
||||
Executable
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# This script can be used to automatically add/remove `@available` attributes to
|
||||
# declarations in Swift sources in this package.
|
||||
#
|
||||
# In order for this to work, ABI-impacting declarations need to be annotated
|
||||
# with special comments in the following format:
|
||||
#
|
||||
# @available(/*System 0.0.2*/iOS 8, *)
|
||||
# public func greeting() -> String {
|
||||
# "Hello"
|
||||
# }
|
||||
#
|
||||
# (The iOS 8 availability is a dummy no-op declaration -- it only has to be
|
||||
# there because `@available(*)` isn't valid syntax, and commenting out the
|
||||
# entire `@available` attribute would interfere with parser tools for doc
|
||||
# comments. `iOS 8` is the shortest version string that matches the minimum
|
||||
# possible deployment target for Swift code, so we use that as our dummy
|
||||
# availability version. `@available(iOS 8, *)` is functionally equivalent to not
|
||||
# having an `@available` attribute at all.)
|
||||
#
|
||||
# The script adds full availability incantations to these comments. It can run
|
||||
# in one of two modes:
|
||||
#
|
||||
# By default, `expand-availability.py` expands availability macros within the
|
||||
# comments. This is useful during package development to cross-reference
|
||||
# availability across `SystemPackage` and the ABI-stable `System` module that
|
||||
# ships in Apple's OS releases:
|
||||
#
|
||||
# @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
# public func greeting() -> String {
|
||||
# "Hello"
|
||||
# }
|
||||
#
|
||||
# `expand-availability.py --attributes` adds actual availability declarations.
|
||||
# This is used by maintainers to build ABI stable releases of System on Apple's
|
||||
# platforms:
|
||||
#
|
||||
# @available(/*System 0.0.2: */macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
|
||||
# public func greeting() -> String {
|
||||
# "Hello"
|
||||
# }
|
||||
#
|
||||
# The script recognizes all three forms of these annotations and updates them on
|
||||
# every run, so we can run the script to enable/disable attributes as needed.
|
||||
|
||||
import os
|
||||
import os.path
|
||||
import fileinput
|
||||
import re
|
||||
import sys
|
||||
import argparse
|
||||
|
||||
versions = {
|
||||
"System 0.0.1": "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0",
|
||||
"System 0.0.2": "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0",
|
||||
"System 1.1.0": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4",
|
||||
"System 1.2.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
|
||||
"System 1.3.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
|
||||
"System 1.4.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
|
||||
}
|
||||
|
||||
parser = argparse.ArgumentParser(description="Expand availability macros.")
|
||||
parser.add_argument("--attributes", help="Add @available attributes",
|
||||
action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
def swift_sources_in(path):
|
||||
result = []
|
||||
for (dir, _, files) in os.walk(path):
|
||||
for file in files:
|
||||
extension = os.path.splitext(file)[1]
|
||||
if extension == ".swift":
|
||||
result.append(os.path.join(dir, file))
|
||||
return result
|
||||
|
||||
# Old-style syntax:
|
||||
# /*System 0.0.2*/
|
||||
# /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
# /*System 0.0.2*/@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
|
||||
old_macro_pattern = re.compile(
|
||||
r"/\*(System [^ *]+)(, @available\([^)]*\))?\*/(@available\([^)]*\))?")
|
||||
|
||||
# New-style comments:
|
||||
# @available(/*SwiftSystem 0.0.2*/macOS 10, *)
|
||||
# @available(/*SwiftSystem 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
|
||||
# @available(/*SwiftSystem 0.0.2*/macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
|
||||
#
|
||||
# These do not interfere with our tools' ability to find doc comments.
|
||||
macro_pattern = re.compile(
|
||||
r"@available\(/\*(System [^ *:]+)[^*/)]*\*/([^)]*)\*\)")
|
||||
|
||||
def available_attribute(filename, lineno, symbolic_version):
|
||||
expansion = versions[symbolic_version]
|
||||
if expansion is None:
|
||||
raise ValueError("{0}:{1}: error: Unknown System version '{0}'"
|
||||
.format(fileinput.filename(), fileinput.lineno(), symbolic_version))
|
||||
if args.attributes:
|
||||
attribute = "@available(/*{0}*/{1}, *)".format(symbolic_version, expansion)
|
||||
else:
|
||||
# Sadly `@available(*)` is not valid syntax, so we have to mention at
|
||||
# least one actual platform here.
|
||||
attribute = "@available(/*{0}: {1}*/iOS 8, *)".format(symbolic_version, expansion)
|
||||
return attribute
|
||||
|
||||
|
||||
sources = swift_sources_in("Sources") + swift_sources_in("Tests")
|
||||
for line in fileinput.input(files=sources, inplace=True):
|
||||
match = re.search(macro_pattern, line)
|
||||
if match is None:
|
||||
match = re.search(old_macro_pattern, line)
|
||||
if match:
|
||||
symbolic_version = match.group(1)
|
||||
replacement = available_attribute(
|
||||
fileinput.filename(), fileinput.lineno(), symbolic_version)
|
||||
line = line[:match.start()] + replacement + line[match.end():]
|
||||
print(line, end="")
|
||||
@@ -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
|
||||
#]]
|
||||
|
||||
set(SWIFT_SYSTEM_EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftSystemExports.cmake)
|
||||
|
||||
configure_file(SwiftSystemConfig.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/SwiftSystemConfig.cmake)
|
||||
|
||||
get_property(SWIFT_SYSTEM_EXPORTS GLOBAL PROPERTY SWIFT_SYSTEM_EXPORTS)
|
||||
export(TARGETS ${SWIFT_SYSTEM_EXPORTS}
|
||||
NAMESPACE SwiftSystem::
|
||||
FILE ${SWIFT_SYSTEM_EXPORTS_FILE}
|
||||
EXPORT_LINK_INTERFACE_LIBRARIES)
|
||||
@@ -17,8 +17,12 @@ See https://swift.org/LICENSE.txt for license information
|
||||
function(get_swift_host_arch result_var_name)
|
||||
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
|
||||
set("${result_var_name}" "x86_64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "aarch64")
|
||||
set("${result_var_name}" "aarch64" PARENT_SCOPE)
|
||||
elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64|ARM64")
|
||||
if(CMAKE_SYSTEM_NAME MATCHES Darwin)
|
||||
set("${result_var_name}" "arm64" PARENT_SCOPE)
|
||||
else()
|
||||
set("${result_var_name}" "aarch64" PARENT_SCOPE)
|
||||
endif()
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
|
||||
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
|
||||
@@ -31,6 +35,8 @@ function(get_swift_host_arch result_var_name)
|
||||
set("${result_var_name}" "armv7" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
|
||||
set("${result_var_name}" "armv7" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "amd64")
|
||||
set("${result_var_name}" "amd64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
|
||||
set("${result_var_name}" "x86_64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#[[
|
||||
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(NOT TARGET SystemPackage)
|
||||
include("@SWIFT_SYSTEM_EXPORTS_FILE@")
|
||||
endif()
|
||||
Reference in new issue
Block a user