mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
704705c5c5 | ||
|
|
16cfbd4f8b | ||
|
|
755a5b4b3d | ||
|
|
6485260369 | ||
|
|
d4e86324e9 | ||
|
|
29b14a3025 | ||
|
|
6a63f086f6 | ||
|
|
b9e0ecaa60 | ||
|
|
8ac955bde7 | ||
|
|
617edb8398 | ||
|
|
5db65c3086 | ||
|
|
2159235ef0 | ||
|
|
353a48d98d | ||
|
|
aa7ed87b5f | ||
|
|
73067f8221 | ||
|
|
a352b4c224 | ||
|
|
cd18a372c0 | ||
|
|
0d9e29baa0 | ||
|
|
4966bcbf8b | ||
|
|
71be76265f | ||
|
|
90a174256e | ||
|
|
a9597cc068 | ||
|
|
50688cacbd | ||
|
|
bd155c104f | ||
|
|
52930bf6be | ||
|
|
7c072c0d97 | ||
|
|
5d61ccdc7e | ||
|
|
2b266acf85 | ||
|
|
101cc809ba | ||
|
|
0b30161977 | ||
|
|
b349ff8c05 | ||
|
|
7cb32eb7a4 | ||
|
|
a6515006f5 | ||
|
|
7edc09a749 | ||
|
|
03604ffcd9 | ||
|
|
2d0912acba | ||
|
|
16cdb0d008 | ||
|
|
e2ae946862 | ||
|
|
f05c1d815d | ||
|
|
0601f0edec | ||
|
|
a10991ab88 | ||
|
|
b5544ba79a | ||
|
|
dda389ed2b | ||
|
|
d3c632e868 | ||
|
|
326260ee3b | ||
|
|
d5f004e6f1 | ||
|
|
38cd4aaf65 | ||
|
|
41de235573 | ||
|
|
efc401eb32 | ||
|
|
73da907161 | ||
|
|
124e17164c | ||
|
|
d7ca4a9e4c | ||
|
|
4a55025558 | ||
|
|
8771bb6199 | ||
|
|
e927959165 | ||
|
|
f52438c1b8 | ||
|
|
636e14a3d2 | ||
|
|
7c504cabbf | ||
|
|
0b7fc03c76 | ||
|
|
a7e7c56fec | ||
|
|
c124911240 | ||
|
|
a17caca7af | ||
|
|
1cfd5105b2 | ||
|
|
76a2dc6162 | ||
|
|
e0aa78a944 | ||
|
|
1494bb89fc | ||
|
|
e358151f96 | ||
|
|
e7723528a1 | ||
|
|
58bce128ce | ||
|
|
5b670937e3 | ||
|
|
74bc402c95 | ||
|
|
96c5f3b852 | ||
|
|
776989a955 | ||
|
|
671bd1a573 | ||
|
|
69ba2cd76e | ||
|
|
ede51c41cb | ||
|
|
64545cfc87 | ||
|
|
8af20f00ab | ||
|
|
9a8bef12be | ||
|
|
c6cc06d24d | ||
|
|
2986958695 | ||
|
|
30d09ac188 | ||
|
|
686feb3a39 |
No files matched your search
@@ -10,7 +10,7 @@ on:
|
||||
jobs:
|
||||
tests:
|
||||
name: Test
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.12
|
||||
with:
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
|
||||
enable_linux_checks: true
|
||||
@@ -24,6 +24,8 @@ jobs:
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_macos_checks: true
|
||||
@@ -42,6 +44,8 @@ jobs:
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_wasm_sdk_build: true
|
||||
@@ -51,14 +55,17 @@ jobs:
|
||||
{"os_version": "focal", "swift_version": "6.2"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.3"},
|
||||
{"os_version": "focal", "swift_version": "6.3"},
|
||||
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "6.4.x"},
|
||||
{"os_version": "focal", "swift_version": "nightly-main"},
|
||||
]
|
||||
enable_android_sdk_build: true
|
||||
enable_android_sdk_checks: true
|
||||
enable_freebsd_checks: true
|
||||
|
||||
build-abi-stable:
|
||||
name: Build ABI Stable
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.10
|
||||
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.12
|
||||
with:
|
||||
enable_linux_checks: false
|
||||
enable_macos_checks: true
|
||||
@@ -69,9 +76,43 @@ jobs:
|
||||
# Enable availability to match ABI stable verion of system.
|
||||
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE"
|
||||
|
||||
cmake_build:
|
||||
name: CMake Validation
|
||||
runs-on: ubuntu-latest
|
||||
container: swiftlang/swift:nightly-main-noble
|
||||
steps:
|
||||
- name: Copy Sources
|
||||
uses: actions/checkout@v6
|
||||
- name: Install Dependencies
|
||||
shell: bash
|
||||
run: apt update && apt install -y cmake ninja-build jq
|
||||
- name: Configure Project
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p build/.cmake/api/v1/query
|
||||
touch build/.cmake/api/v1/query/codemodel-v2
|
||||
cmake -G 'Ninja' -B build -S . -DCMAKE_C_COMPILER=clang -DCMAKE_Swift_COMPILER=swiftc -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=YES
|
||||
- name: Validate CMake File Lists
|
||||
shell: bash
|
||||
run: |
|
||||
swift package describe --type json > /tmp/swiftpm.json
|
||||
cat build/.cmake/api/v1/reply/target-SystemPackage-*.json > /tmp/cmake.json
|
||||
jq '.targets[] | select(.name == "SystemPackage") | .sources[]' /tmp/swiftpm.json | sort > /tmp/swiftpm-list.txt
|
||||
jq '.sources[].path[15:]' /tmp/cmake.json | sort > /tmp/cmake-list.txt
|
||||
comm -23 /tmp/swiftpm-list.txt /tmp/cmake-list.txt > /tmp/missing.txt
|
||||
if [ -s /tmp/missing.txt ]; then
|
||||
echo "::error::SystemPackage CMakeLists.txt does not match SwiftPM. Missing sources:"
|
||||
cat /tmp/missing.txt
|
||||
exit 1
|
||||
fi
|
||||
echo "::notice::SystemPackage CMakeLists.txt matches SwiftPM"
|
||||
- name: Build Project with CMake
|
||||
shell: bash
|
||||
run: cmake --build build
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.10
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.12
|
||||
with:
|
||||
license_header_check_project_name: "Swift.org"
|
||||
# https://github.com/apple/swift-system/issues/224
|
||||
|
||||
@@ -13,6 +13,8 @@ project(SwiftSystem
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
set(CMAKE_Swift_LANGUAGE_VERSION 6)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
+3
-7
@@ -59,13 +59,9 @@ let availability: [Available] = [
|
||||
Available("1.3.2", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
Available("1.4.0", "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.0"),
|
||||
|
||||
Available("1.4.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.4.2", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.5.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.6.0", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.6.1", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("1.7.0", "macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0"),
|
||||
|
||||
Available("99", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
Available("199", "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999"),
|
||||
]
|
||||
|
||||
let swiftSettingsAvailability = availability.map(\.swiftSetting)
|
||||
@@ -148,5 +144,5 @@ let package = Package(
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [.enableUpcomingFeature("MemberImportVisibility")]),
|
||||
],
|
||||
swiftLanguageModes: [.v5]
|
||||
swiftLanguageModes: [.v6]
|
||||
)
|
||||
@@ -79,7 +79,7 @@ These initializers use a typed `throws(Errno)` and require Swift 6.0 or later.
|
||||
|
||||
See the **Appendix** section at the end of this proposal for a table view of Swift API to C mappings.
|
||||
|
||||
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability.
|
||||
All API are marked `@_alwaysEmitIntoClient` for performance and back-dating of availability, except `Stat`'s `==` and `hash(into:)`, which are ordinary `public` API.
|
||||
|
||||
### FileType
|
||||
|
||||
@@ -693,24 +693,27 @@ public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number is used to distinguish between different files
|
||||
/// that have used the same inode over time.
|
||||
/// The file generation number may be used to distinguish between different
|
||||
/// files that have used the same inode over time.
|
||||
///
|
||||
/// The corresponding C property is `st_gen`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
public var generationNumber: Int { get set }
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
|
||||
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
|
||||
public var generationNumber: UInt64 { get set }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
extension Stat: Equatable {
|
||||
/// Compares the raw bytes of two `Stat` structs for equality.
|
||||
/// Compares the meaningful file-metadata fields of two `Stat` values.
|
||||
///
|
||||
/// Alignment padding and platform reserved/"spare" fields are not compared.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool
|
||||
}
|
||||
|
||||
extension Stat: Hashable {
|
||||
/// Hashes the raw bytes of this `Stat` struct.
|
||||
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
|
||||
public func hash(into hasher: inout Hasher)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
# Add support for `dup3` and `pipe2` POSIX API to `FileDescriptor`
|
||||
|
||||
* Proposal: SYS-0007
|
||||
- Author(s): Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
|
||||
* Authors: Jake Petroules <jake.petroules@apple.com>, Guillaume Lessard <guillaume.lessard@apple.com>
|
||||
|
||||
* Other Reviews: [Swift Forums Pitch](https://forums.swift.org/t/82486)
|
||||
|
||||
##### Revision history
|
||||
#### Revision history
|
||||
|
||||
* **v1** Initial version
|
||||
|
||||
- **v2** Add Windows version of `pipe(options:)`
|
||||
* **v2** Add Windows version of `pipe(options:)`
|
||||
* **v3** Add Darwin versions of `dup3` and `pipe2` wrappers
|
||||
|
||||
## Introduction
|
||||
|
||||
Swift System today provides `FileDescriptor.duplicate()`, `FileDescriptor.duplicate(as:)` and `FileDescriptor.pipe()` cover APIs for the POSIX `dup`, `dup2`, and `pipe` functions, respectively.
|
||||
|
||||
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD and Android.
|
||||
This proposal adds additional `FileDescriptor` overloads to cover new POSIX 2024 functions in this family of APIs. These overloads will be available on Linux, FreeBSD, Android, and the Apple operating systems based on Darwin 27.0 or newer; `pipe(options:)` will also be available on Windows.
|
||||
|
||||
## Motivation
|
||||
|
||||
It is considered best practice to set the `O_CLOEXEC` (close-on-exec) bit on newly created file descriptors to prevent them from being inherited by subprocesses.
|
||||
|
||||
Some POSIX functions such as `open` provide a "flags" parameter allowing this the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`.
|
||||
Some POSIX functions such as `open` provide a "flags" parameter allowing the close-on-exec bit to be set atomically on the newly created file descriptor. However, others provide no such flags parameter, and require the caller to use `fcntl` to set the close-on-exec bit after the fact. This can lead to race conditions and security bugs where file descriptors can be inherited between calling the function creating the file descriptor, and calling `fcntl`.
|
||||
|
||||
POSIX 2024 corrects this deficiency for `dup2` and `pipe` by introducing `dup3` and `pipe2` variants that allow the close-on-exec bit to be set atomically.
|
||||
|
||||
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defence in depth with respect to opened file descriptors.
|
||||
While it's *also* considered best practice for subprocess spawning code to close all open file descriptors in the newly created subprocess (swiftlang/swift-subprocess does this for example), there is no guarantee that a user of Swift System is using a mechanism which does so throughout their entire process, and might be using process spawning code they don't control. Adding the proposed overloads will allow developers to write code which adopts a posture of defense in depth with respect to opened file descriptors.
|
||||
|
||||
## Proposed solution
|
||||
|
||||
@@ -38,7 +38,7 @@ import System
|
||||
|
||||
let fd0 = try FileDescriptor.open("/tmp/test.txt", .readOnly)
|
||||
let fd1 = FileDescriptor(rawValue: 731)
|
||||
let fd2 = fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec])
|
||||
let fd2 = try fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec])
|
||||
```
|
||||
|
||||
## Detailed design
|
||||
@@ -50,6 +50,11 @@ struct FileDescriptor {
|
||||
/// Creates a unidirectional data channel, which can be used for
|
||||
/// interprocess communication.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options. On Windows, the
|
||||
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
|
||||
/// but this overload disables it when called with an empty option set.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - options: The behavior for creating the pipe.
|
||||
///
|
||||
@@ -70,9 +75,14 @@ struct FileDescriptor {
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
///
|
||||
/// If the `target` descriptor is the same as `self`, then EINVAL is thrown.
|
||||
/// If the `target` descriptor is already in use, then it is first
|
||||
/// deallocated as if a close(2) call had been done first.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options, because `dup3` with
|
||||
/// no set options is not required to behave identically to `dup2`.
|
||||
///
|
||||
/// File descriptors are merely references to some underlying system resource.
|
||||
/// The system does not distinguish between the original and the new file
|
||||
/// descriptor in any way. For example, read, write and seek operations on
|
||||
@@ -167,8 +177,6 @@ struct FileDescriptor {
|
||||
}
|
||||
```
|
||||
|
||||
These API additions are unavailable on Darwin, as the underlying `dup3` and `pipe2` APIs do not exist.
|
||||
|
||||
`pipe(options:)` is added for Windows with the option `.closeOnExec`, but `duplicate(as:options:)` is not added because the underlying API does not match `dup3`.
|
||||
|
||||
`closeOnFork` is unavailable on Linux and Android, as the underlying `O_CLOFORK` constant does not exist.
|
||||
|
||||
@@ -13,10 +13,13 @@ target_include_directories(CSystem PUBLIC
|
||||
$<INSTALL_INTERFACE:include/CSystem>)
|
||||
|
||||
install(FILES
|
||||
include/CSystemDarwin.h
|
||||
include/CSystemLinux.h
|
||||
include/CSystemShared.h
|
||||
include/CSystemWASI.h
|
||||
include/CSystemWindows.h
|
||||
include/CSystemFreeBSD.h
|
||||
include/io_uring.h
|
||||
include/module.modulemap
|
||||
DESTINATION include/CSystem)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if defined(__APPLE__)
|
||||
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifdef O_CLOFORK
|
||||
#define COMPATIBILITY_O_CLOFORK O_CLOFORK
|
||||
#else
|
||||
#define COMPATIBILITY_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#endif // defined(__APPLE__)
|
||||
@@ -12,10 +12,9 @@
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifdef O_CLOFORK
|
||||
#define FREEBSD_O_CLOFORK O_CLOFORK
|
||||
#define COMPATIBILITY_O_CLOFORK O_CLOFORK
|
||||
#else
|
||||
#define FREEBSD_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#define COMPATIBILITY_O_CLOFORK 0
|
||||
#endif
|
||||
|
||||
#endif // defined(__FreeBSD__)
|
||||
@@ -81,7 +81,7 @@
|
||||
#ifdef IORING_TIMEOUT_BOOTTIME
|
||||
// Kernel version >= 5.15, io_uring_sqe has file_index
|
||||
// and all current Swift operations are supported.
|
||||
#define __SWIFT_IORING_SUPPORTED true
|
||||
#define __SWIFT_IORING_SUPPORTED 1
|
||||
typedef struct io_uring_sqe swift_io_uring_sqe;
|
||||
#else
|
||||
// io_uring_sqe is missing properties that IORequest expects.
|
||||
@@ -89,7 +89,7 @@ typedef struct io_uring_sqe swift_io_uring_sqe;
|
||||
//
|
||||
// Define a fallback struct to avoid build errors, but IORing
|
||||
// will throw ENOTSUP on initialization.
|
||||
#define __SWIFT_IORING_SUPPORTED false
|
||||
#define __SWIFT_IORING_SUPPORTED 0
|
||||
typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
#endif
|
||||
|
||||
@@ -107,13 +107,14 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
|
||||
// Minimal fallback definitions when linux/io_uring.h is not available (e.g. static SDK)
|
||||
#include <stdint.h>
|
||||
|
||||
#define __SWIFT_IORING_SUPPORTED false
|
||||
#define __SWIFT_IORING_SUPPORTED 0
|
||||
|
||||
#define IORING_OFF_SQ_RING 0ULL
|
||||
#define IORING_OFF_CQ_RING 0x8000000ULL
|
||||
#define IORING_OFF_SQES 0x10000000ULL
|
||||
|
||||
#define IORING_ENTER_GETEVENTS (1U << 0)
|
||||
#define IORING_ENTER_GETEVENTS (1U << 0)
|
||||
#define IORING_ENTER_EXT_ARG (1U << 3)
|
||||
|
||||
#define IORING_FEAT_SINGLE_MMAP (1U << 0)
|
||||
#define IORING_FEAT_NODROP (1U << 1)
|
||||
@@ -235,7 +236,7 @@ static inline int io_uring_enter2(int fd, unsigned int to_submit, unsigned int m
|
||||
unsigned int flags, void *args, size_t sz)
|
||||
{
|
||||
return syscall(__NR_io_uring_enter, fd, to_submit, min_complete,
|
||||
flags, args, _NSIG / 8);
|
||||
flags, args, sz);
|
||||
}
|
||||
|
||||
static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
module CSystem {
|
||||
header "CSystemShared.h"
|
||||
header "CSystemDarwin.h"
|
||||
header "CSystemLinux.h"
|
||||
header "CSystemWASI.h"
|
||||
header "CSystemWindows.h"
|
||||
|
||||
+29
-11
@@ -7,8 +7,10 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if defined(__FreeBSD__) || defined(__OpenBSD__)
|
||||
#if defined(__FreeBSD__)
|
||||
#define __BSD_VISIBLE
|
||||
#endif
|
||||
#if defined(__FreeBSD__) || defined(__OpenBSD__)
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
@@ -31,24 +33,40 @@
|
||||
#define HAVE_PIPE2_DUP3
|
||||
#endif
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#include <Availability.h>
|
||||
#if defined(__MAC_27_0)
|
||||
#include <unistd.h>
|
||||
#define HAVE_PIPE2_DUP3
|
||||
#endif
|
||||
#endif // defined(__APPLE__)
|
||||
|
||||
// Wrappers are required because _GNU_SOURCE causes a conflict with other imports when defined in CSystemLinux.h
|
||||
|
||||
#if !defined(_WIN32)
|
||||
extern int csystem_posix_pipe2(int fildes[2], int flag) {
|
||||
#ifdef HAVE_PIPE2_DUP3
|
||||
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
|
||||
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
|
||||
return pipe2(fildes, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
__builtin_trap();
|
||||
#elif defined(HAVE_PIPE2_DUP3)
|
||||
return pipe2(fildes, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
#endif // !defined(_WIN32)
|
||||
|
||||
extern int csystem_posix_dup3(int fildes, int fildes2, int flag) {
|
||||
#ifdef HAVE_PIPE2_DUP3
|
||||
#if defined(__APPLE__) && defined(HAVE_PIPE2_DUP3)
|
||||
if (__builtin_available(macOS 27, iOS 27, tvOS 27, watchOS 27, visionOS 27, *))
|
||||
return dup3(fildes, fildes2, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
__builtin_trap();
|
||||
#elif defined(HAVE_PIPE2_DUP3)
|
||||
return dup3(fildes, fildes2, flag);
|
||||
#else
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
@@ -9,6 +9,7 @@ See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
add_library(SystemPackage
|
||||
Errno.swift
|
||||
ErrnoWindows.swift
|
||||
FileDescriptor.swift
|
||||
FileHelpers.swift
|
||||
FileOperations.swift
|
||||
@@ -18,9 +19,32 @@ add_library(SystemPackage
|
||||
SystemString.swift
|
||||
Util.swift
|
||||
Util+StringArray.swift
|
||||
UtilConsumers.swift)
|
||||
UtilConsumers.swift
|
||||
WinSDK+Overlay.swift)
|
||||
set_target_properties(SystemPackage PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
# Availability macro definitions.
|
||||
# Should stay in sync with the `availability` array in Package.swift,
|
||||
# matching `sourceAvailability`, which is the minimum Swift availability.
|
||||
# Availability support for Darwin platforms is omitted.
|
||||
set(SWIFT_SYSTEM_AVAILABILITY_VERSIONS
|
||||
0.0.1 0.0.2 0.0.3
|
||||
1.1.0 1.1.1 1.2.0 1.2.1 1.3.0 1.3.1 1.3.2 1.4.0
|
||||
1.7.0
|
||||
199)
|
||||
set(SWIFT_SYSTEM_SOURCE_AVAILABILITY
|
||||
"macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, visionOS 1.0")
|
||||
set(SWIFT_SYSTEM_AVAILABILITY_MACRO)
|
||||
foreach(version IN LISTS SWIFT_SYSTEM_AVAILABILITY_VERSIONS)
|
||||
list(APPEND SWIFT_SYSTEM_AVAILABILITY_MACRO
|
||||
"SHELL:-enable-experimental-feature \"AvailabilityMacro=System ${version}:${SWIFT_SYSTEM_SOURCE_AVAILABILITY}\"")
|
||||
endforeach()
|
||||
|
||||
target_compile_options(SystemPackage PRIVATE
|
||||
-enable-experimental-feature Lifetimes
|
||||
${SWIFT_SYSTEM_AVAILABILITY_MACRO}
|
||||
"SHELL:-package-name swift-system")
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePath.swift
|
||||
FilePath/FilePathComponents.swift
|
||||
@@ -28,7 +52,24 @@ target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePathParsing.swift
|
||||
FilePath/FilePathString.swift
|
||||
FilePath/FilePathSyntax.swift
|
||||
FilePath/FilePathTemp.swift
|
||||
FilePath/FilePathTempPosix.swift
|
||||
FilePath/FilePathTempWindows.swift
|
||||
FilePath/FilePathWindows.swift)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FileSystem/FileFlags.swift
|
||||
FileSystem/FileMode.swift
|
||||
FileSystem/FileType.swift
|
||||
FileSystem/Identifiers.swift
|
||||
FileSystem/Stat.swift)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
IORing/IOCompletion.swift
|
||||
IORing/IORequest.swift
|
||||
IORing/IORing.swift
|
||||
IORing/IORing+Util.swift
|
||||
IORing/RawIORequest.swift)
|
||||
endif()
|
||||
target_sources(SystemPackage PRIVATE
|
||||
Internals/Backcompat.swift
|
||||
Internals/CInterop.swift
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2021 - 2024 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 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
|
||||
|
||||
@@ -301,7 +301,6 @@ extension FileDescriptor {
|
||||
public static var O_EVTONLY: OpenOptions { eventOnly }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
@@ -319,16 +318,17 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_CLOEXEC: OpenOptions { closeOnExec }
|
||||
|
||||
#if os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_NOINHERIT: OpenOptions { closeOnExec }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Options that specify behavior for a newly-created pipe.
|
||||
@frozen
|
||||
@available(macOS, unavailable)
|
||||
@available(iOS, unavailable)
|
||||
@available(tvOS, unavailable)
|
||||
@available(watchOS, unavailable)
|
||||
@available(visionOS, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
public struct PipeOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -399,11 +399,7 @@ extension FileDescriptor {
|
||||
/// Options that specify behavior for a duplicated file descriptor.
|
||||
@frozen
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS, unavailable)
|
||||
@available(iOS, unavailable)
|
||||
@available(tvOS, unavailable)
|
||||
@available(watchOS, unavailable)
|
||||
@available(visionOS, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable {
|
||||
/// The raw C options.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -528,7 +524,6 @@ extension FileDescriptor {
|
||||
@available(*, unavailable, renamed: "nextData")
|
||||
public static var SEEK_DATA: SeekOrigin { nextData }
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -55,6 +57,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -88,8 +92,10 @@ extension FileDescriptor {
|
||||
if let permissions = permissions {
|
||||
return system_open(path, oFlag, permissions.rawValue)
|
||||
}
|
||||
precondition(!options.contains(.create),
|
||||
"Create must be given permissions")
|
||||
if options.contains(.create) {
|
||||
fatalError(
|
||||
"FileDescriptor.open: 'permissions' must not be nil when 'options' contains '.create'")
|
||||
}
|
||||
return system_open(path, oFlag)
|
||||
}
|
||||
return descOrError.map { FileDescriptor(rawValue: $0) }
|
||||
@@ -102,6 +108,8 @@ extension FileDescriptor {
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// This value must not be `nil` when `options` contains `.create`;
|
||||
/// passing `nil` in that case is a programmer error and traps at runtime.
|
||||
/// - retryOnInterrupt: Whether to retry the open operation
|
||||
/// if it throws ``Errno/interrupted``.
|
||||
/// The default is `true`.
|
||||
@@ -222,7 +230,7 @@ extension FileDescriptor {
|
||||
internal func _read(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<Int, Errno> {
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_read(self.rawValue, buffer.baseAddress, buffer.count)
|
||||
}
|
||||
@@ -370,13 +378,13 @@ extension FileDescriptor {
|
||||
#if !os(WASI)
|
||||
@available(System 0.0.2, *)
|
||||
extension FileDescriptor {
|
||||
/// Duplicates this file descriptor and return the newly created copy.
|
||||
/// Duplicates this file descriptor and returns the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
/// the copy is assigned to the file descriptor with the lowest raw value
|
||||
/// that is not currently in use by the process.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// - retryOnInterrupt: Whether to retry the duplicate operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
@@ -415,7 +423,7 @@ extension FileDescriptor {
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
///
|
||||
/// If the `target` descriptor the same as `self`, then EINVAL is thrown.
|
||||
/// If the `target` descriptor is the same as `self`, then EINVAL is thrown.
|
||||
/// If the `target` descriptor is already in use, then it is first
|
||||
/// deallocated as if a close(2) call had been done first.
|
||||
///
|
||||
@@ -436,20 +444,19 @@ extension FileDescriptor {
|
||||
/// close-on-fork flags.
|
||||
///
|
||||
/// The corresponding C function is `dup3`.
|
||||
@discardableResult
|
||||
@_alwaysEmitIntoClient
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS, unavailable)
|
||||
@available(iOS, unavailable)
|
||||
@available(tvOS, unavailable)
|
||||
@available(watchOS, unavailable)
|
||||
@available(visionOS, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@_alwaysEmitIntoClient
|
||||
@discardableResult
|
||||
public func duplicate(
|
||||
as target: FileDescriptor,
|
||||
options: DuplicateOptions,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws(Errno) -> FileDescriptor {
|
||||
try _duplicate(as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt).get()
|
||||
let result = _duplicate(
|
||||
as: target, options: options.rawValue, retryOnInterrupt: retryOnInterrupt
|
||||
)
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
@@ -468,11 +475,7 @@ extension FileDescriptor {
|
||||
}
|
||||
|
||||
@available(Windows, unavailable)
|
||||
@available(macOS, unavailable)
|
||||
@available(iOS, unavailable)
|
||||
@available(tvOS, unavailable)
|
||||
@available(watchOS, unavailable)
|
||||
@available(visionOS, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor,
|
||||
@@ -502,7 +505,7 @@ extension FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
#if !os(WASI)
|
||||
@available(System 1.1.0, *)
|
||||
@@ -524,9 +527,9 @@ extension FileDescriptor {
|
||||
/// interprocess communication.
|
||||
///
|
||||
/// NOTE: This overload called with an empty option set is not necessarily
|
||||
/// equivalent to calling the overload with no options. On Windows, this
|
||||
/// overload with empty options disables the `closeOnExec` behaviour,
|
||||
/// which is enabled by the overload without options.
|
||||
/// equivalent to calling the overload with no options. On Windows, the
|
||||
/// no-parameter `pipe()` overload enables the `.closeOnExec` behaviour,
|
||||
/// but this overload disables it when called with an empty option set.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - options: The behavior for creating the pipe.
|
||||
@@ -535,11 +538,7 @@ extension FileDescriptor {
|
||||
///
|
||||
/// The corresponding C function is `pipe2`.
|
||||
@_alwaysEmitIntoClient
|
||||
@available(macOS, unavailable)
|
||||
@available(iOS, unavailable)
|
||||
@available(tvOS, unavailable)
|
||||
@available(watchOS, unavailable)
|
||||
@available(visionOS, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
public static func pipe(
|
||||
options: PipeOptions
|
||||
) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
@@ -560,11 +559,7 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS, unavailable)
|
||||
@available(iOS, unavailable)
|
||||
@available(tvOS, unavailable)
|
||||
@available(watchOS, unavailable)
|
||||
@available(visionOS, unavailable)
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
@usableFromInline
|
||||
internal static func _pipe(
|
||||
options: Int32,
|
||||
@@ -585,7 +580,7 @@ extension FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
@available(System 1.2.0, *)
|
||||
extension FileDescriptor {
|
||||
@@ -674,4 +669,4 @@ extension FilePermissions {
|
||||
return system_umask(mode)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
@@ -461,7 +461,10 @@ extension String {
|
||||
public init(decoding path: FilePath) {
|
||||
self.init(_decoding: path)
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 0.0.2, *)
|
||||
extension String {
|
||||
/// Creates a string from a file path, validating its contents as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
///
|
||||
@@ -470,6 +473,7 @@ extension String {
|
||||
///
|
||||
/// If the contents of the file path isn't a well-formed Unicode string,
|
||||
/// this initializer returns `nil`.
|
||||
@available(System 0.0.2, *)
|
||||
public init?(validating path: FilePath) {
|
||||
self.init(_validating: path)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -45,7 +45,7 @@
|
||||
///
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileFlags: OptionSet, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C flags.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -14,7 +14,7 @@
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileMode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C mode.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -34,7 +34,7 @@
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct FileType: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw file-type bits from the C mode.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -12,7 +12,7 @@
|
||||
#if !os(Windows)
|
||||
/// A Swift wrapper of the C `uid_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `uid_t`.
|
||||
@@ -30,7 +30,7 @@ public struct UserID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// A Swift wrapper of the C `gid_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `gid_t`.
|
||||
@@ -48,7 +48,7 @@ public struct GroupID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// A Swift wrapper of the C `dev_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `dev_t`.
|
||||
@@ -66,7 +66,7 @@ public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// A Swift wrapper of the C `ino_t` type.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct Inode: RawRepresentable, Sendable, Hashable, Codable {
|
||||
|
||||
/// The raw C `ino_t`.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -35,7 +35,7 @@ import Android
|
||||
///
|
||||
/// - Note: Only available on Unix-like platforms.
|
||||
@frozen
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// The raw C `stat` struct.
|
||||
@@ -521,42 +521,93 @@ public struct Stat: RawRepresentable, Sendable {
|
||||
|
||||
/// File generation number
|
||||
///
|
||||
/// The file generation number is used to distinguish between different files
|
||||
/// that have used the same inode over time.
|
||||
/// The file generation number may be used to distinguish between different
|
||||
/// files that have used the same inode over time.
|
||||
///
|
||||
/// The corresponding C property is `st_gen`.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD.
|
||||
/// - Note: Only available on Darwin, FreeBSD, and OpenBSD. The underlying C
|
||||
/// field is 32-bit on Darwin and OpenBSD, and 64-bit on FreeBSD.
|
||||
@_alwaysEmitIntoClient
|
||||
public var generationNumber: Int {
|
||||
get { Int(rawValue.st_gen) }
|
||||
set { rawValue.st_gen = numericCast(newValue)}
|
||||
public var generationNumber: UInt64 {
|
||||
get { UInt64(rawValue.st_gen) }
|
||||
set { rawValue.st_gen = numericCast(newValue) }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Equatable and Hashable
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension Stat: Equatable {
|
||||
@_alwaysEmitIntoClient
|
||||
/// Compares the raw bytes of two `Stat` structs for equality.
|
||||
/// Compares the meaningful file-metadata fields of two `Stat` values.
|
||||
///
|
||||
/// Alignment padding and platform reserved/"spare" fields are not compared.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
return withUnsafeBytes(of: lhs.rawValue) { lhsBytes in
|
||||
withUnsafeBytes(of: rhs.rawValue) { rhsBytes in
|
||||
lhsBytes.elementsEqual(rhsBytes)
|
||||
}
|
||||
guard lhs.rawValue.st_dev == rhs.rawValue.st_dev,
|
||||
lhs.rawValue.st_ino == rhs.rawValue.st_ino,
|
||||
lhs.rawValue.st_mode == rhs.rawValue.st_mode,
|
||||
lhs.rawValue.st_nlink == rhs.rawValue.st_nlink,
|
||||
lhs.rawValue.st_uid == rhs.rawValue.st_uid,
|
||||
lhs.rawValue.st_gid == rhs.rawValue.st_gid,
|
||||
lhs.rawValue.st_rdev == rhs.rawValue.st_rdev,
|
||||
lhs.rawValue.st_size == rhs.rawValue.st_size,
|
||||
lhs.rawValue.st_blksize == rhs.rawValue.st_blksize,
|
||||
lhs.rawValue.st_blocks == rhs.rawValue.st_blocks,
|
||||
lhs.st_atim.tv_sec == rhs.st_atim.tv_sec,
|
||||
lhs.st_atim.tv_nsec == rhs.st_atim.tv_nsec,
|
||||
lhs.st_mtim.tv_sec == rhs.st_mtim.tv_sec,
|
||||
lhs.st_mtim.tv_nsec == rhs.st_mtim.tv_nsec,
|
||||
lhs.st_ctim.tv_sec == rhs.st_ctim.tv_sec,
|
||||
lhs.st_ctim.tv_nsec == rhs.st_ctim.tv_nsec else {
|
||||
return false
|
||||
}
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
guard lhs.st_birthtim.tv_sec == rhs.st_birthtim.tv_sec,
|
||||
lhs.st_birthtim.tv_nsec == rhs.st_birthtim.tv_nsec else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
guard lhs.rawValue.st_flags == rhs.rawValue.st_flags,
|
||||
lhs.rawValue.st_gen == rhs.rawValue.st_gen else {
|
||||
return false
|
||||
}
|
||||
#endif
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension Stat: Hashable {
|
||||
@_alwaysEmitIntoClient
|
||||
/// Hashes the raw bytes of this `Stat` struct.
|
||||
/// Hashes the meaningful file-metadata fields of a `Stat` struct.
|
||||
///
|
||||
/// These are the same fields compared by `==`, fed in the same order.
|
||||
/// Alignment padding and platform reserved/"spare" fields are not hashed.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
withUnsafeBytes(of: rawValue) { bytes in
|
||||
hasher.combine(bytes: bytes)
|
||||
}
|
||||
hasher.combine(rawValue.st_dev)
|
||||
hasher.combine(rawValue.st_ino)
|
||||
hasher.combine(rawValue.st_mode)
|
||||
hasher.combine(rawValue.st_nlink)
|
||||
hasher.combine(rawValue.st_uid)
|
||||
hasher.combine(rawValue.st_gid)
|
||||
hasher.combine(rawValue.st_rdev)
|
||||
hasher.combine(rawValue.st_size)
|
||||
hasher.combine(rawValue.st_blksize)
|
||||
hasher.combine(rawValue.st_blocks)
|
||||
hasher.combine(st_atim.tv_sec)
|
||||
hasher.combine(st_atim.tv_nsec)
|
||||
hasher.combine(st_mtim.tv_sec)
|
||||
hasher.combine(st_mtim.tv_nsec)
|
||||
hasher.combine(st_ctim.tv_sec)
|
||||
hasher.combine(st_ctim.tv_nsec)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
hasher.combine(st_birthtim.tv_sec)
|
||||
hasher.combine(st_birthtim.tv_nsec)
|
||||
#endif
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
hasher.combine(rawValue.st_flags)
|
||||
hasher.combine(rawValue.st_gen)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -564,7 +615,7 @@ extension Stat: Hashable {
|
||||
|
||||
// MARK: - FileDescriptor Extensions
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension FileDescriptor {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FileDescriptor`.
|
||||
@@ -580,7 +631,7 @@ extension FileDescriptor {
|
||||
|
||||
// MARK: - FilePath Extensions
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension FilePath {
|
||||
|
||||
/// Creates a `Stat` struct for the file referenced by this `FilePath`.
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
#if compiler(>=6.2) && $Lifetimes
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
/// Throwing wrapper around the `io_uring_enter2` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result (the number of SQEs
|
||||
/// consumed by the kernel). On failure, reads `errno` and throws the matching
|
||||
/// `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringEnter2(
|
||||
ringDescriptor: Int32,
|
||||
toSubmit: UInt32,
|
||||
minComplete: UInt32,
|
||||
flags: UInt32,
|
||||
args: UnsafeMutablePointer<swift_io_uring_getevents_arg>?,
|
||||
argsSize: Int
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_enter2(
|
||||
ringDescriptor, toSubmit, minComplete, flags, args, argsSize
|
||||
)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `io_uring_enter` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result (the number of SQEs
|
||||
/// consumed by the kernel). On failure, reads `errno` and throws the matching
|
||||
/// `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringEnter(
|
||||
ringDescriptor: Int32,
|
||||
toSubmit: UInt32,
|
||||
minComplete: UInt32,
|
||||
flags: UInt32,
|
||||
sig: UnsafeMutablePointer<sigset_t>?
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_enter(ringDescriptor, toSubmit, minComplete, flags, sig)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
/// Throwing wrapper around the `io_uring_register` shim.
|
||||
///
|
||||
/// On success returns the syscall's non-negative result. On failure, reads
|
||||
/// `errno` and throws the matching `Errno`. `EINTR` is retried automatically.
|
||||
@usableFromInline
|
||||
internal func _ioUringRegister(
|
||||
ringDescriptor: Int32,
|
||||
opcode: UInt32,
|
||||
arg: UnsafeMutableRawPointer?,
|
||||
nrArgs: UInt32
|
||||
) throws(Errno) -> Int32 {
|
||||
let result = valueOrErrno(retryOnInterrupt: true) {
|
||||
io_uring_register(ringDescriptor, opcode, arg, nrArgs)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -128,23 +128,30 @@ internal func _enter(
|
||||
// Ring always needs enter right now;
|
||||
// TODO: support SQPOLL here
|
||||
while true {
|
||||
let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil)
|
||||
do {
|
||||
let ret = try _ioUringEnter(
|
||||
ringDescriptor: ringDescriptor,
|
||||
toSubmit: numEvents,
|
||||
minComplete: minCompletions,
|
||||
flags: flags,
|
||||
sig: nil
|
||||
)
|
||||
if _getSubmissionQueueCount(ring: ring) > 0 {
|
||||
// See https://github.com/axboe/liburing/issues/309,
|
||||
// in some cases not all pending requests are submitted
|
||||
continue
|
||||
}
|
||||
return ret
|
||||
// error handling:
|
||||
// EAGAIN / EINTR (try again),
|
||||
// EAGAIN (try again),
|
||||
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
|
||||
// (failure in ring lifetime management, fatal),
|
||||
// EINVAL (bad constant flag?, fatal),
|
||||
// EFAULT (bad address for argument from library, fatal)
|
||||
if ret == -EAGAIN || ret == -EINTR {
|
||||
} catch Errno.resourceTemporarilyUnavailable {
|
||||
//TODO: should we wait a bit on AGAIN?
|
||||
//alternatively we could treat EAGAIN the same as EINTR in the wrapper
|
||||
continue
|
||||
} else if ret < 0 {
|
||||
throw(Errno(rawValue: -ret))
|
||||
} else if _getSubmissionQueueCount(ring: ring) > 0 {
|
||||
// See https://github.com/axboe/liburing/issues/309, in some cases not all pending requests are submitted
|
||||
continue
|
||||
} else {
|
||||
return ret
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -517,34 +524,44 @@ public struct IORing: ~Copyable {
|
||||
if count < minimumCount {
|
||||
while count < minimumCount {
|
||||
var sz = 0
|
||||
var flags = IORING_ENTER_GETEVENTS
|
||||
if extraArgs != nil {
|
||||
sz = MemoryLayout<swift_io_uring_getevents_arg>.size
|
||||
flags |= IORING_ENTER_EXT_ARG
|
||||
}
|
||||
let res = io_uring_enter2(
|
||||
ringDescriptor,
|
||||
0,
|
||||
minimumCount,
|
||||
IORING_ENTER_GETEVENTS,
|
||||
extraArgs,
|
||||
sz
|
||||
)
|
||||
do {
|
||||
_ = try _ioUringEnter2(
|
||||
ringDescriptor: ringDescriptor,
|
||||
toSubmit: 0,
|
||||
minComplete: minimumCount,
|
||||
flags: flags,
|
||||
args: extraArgs,
|
||||
argsSize: sz
|
||||
)
|
||||
break
|
||||
// error handling:
|
||||
// EAGAIN / EINTR (try again),
|
||||
// EAGAIN (try again),
|
||||
// EBADF / EBADFD / EOPNOTSUPP / ENXIO
|
||||
// (failure in ring lifetime management, fatal),
|
||||
// EINVAL (bad constant flag?, fatal),
|
||||
// EFAULT (bad address for argument from library, fatal)
|
||||
// EBUSY (not enough space for events; implies events filled
|
||||
// by kernel between kernelTail load and now)
|
||||
if res >= 0 || res == -EBUSY {
|
||||
// ETIME (timeout from extraArgs.ts elapsed before
|
||||
// minimumCount completions arrived)
|
||||
} catch Errno.resourceBusy {
|
||||
break
|
||||
} else if res == -EAGAIN || res == -EINTR {
|
||||
} catch Errno.resourceTemporarilyUnavailable {
|
||||
continue
|
||||
} catch Errno.timeout {
|
||||
try consumer(nil, .timeout, true)
|
||||
return
|
||||
} catch {
|
||||
fatalError(
|
||||
"fatal error in receiving requests: "
|
||||
+ error.debugDescription
|
||||
)
|
||||
}
|
||||
fatalError(
|
||||
"fatal error in receiving requests: "
|
||||
+ Errno(rawValue: -res).debugDescription
|
||||
)
|
||||
}
|
||||
var count = 0
|
||||
while let completion = _tryConsumeCompletion(ring: completionRing) {
|
||||
@@ -660,31 +677,22 @@ public struct IORing: ~Copyable {
|
||||
/// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information.
|
||||
public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) {
|
||||
var rawfd = descriptor.rawValue
|
||||
let result = withUnsafePointer(to: &rawfd) { fdptr in
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.registerEventFD.rawValue,
|
||||
UnsafeMutableRawPointer(mutating: fdptr),
|
||||
1
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
if let result {
|
||||
throw result
|
||||
}
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.registerEventFD.rawValue,
|
||||
arg: &rawfd,
|
||||
nrArgs: 1
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes a registered event file descriptor from the ring
|
||||
public mutating func unregisterEventFD() throws(Errno) {
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.unregisterEventFD.rawValue,
|
||||
nil,
|
||||
0
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterEventFD.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
if result < 0 {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers `count` files with the ring for later use in IO operations
|
||||
@@ -693,18 +701,13 @@ public struct IORing: ~Copyable {
|
||||
precondition(count < UInt32.max)
|
||||
let files = [UInt32](repeating: UInt32.max, count: count)
|
||||
|
||||
let regResult = files.withUnsafeBufferPointer { bPtr in
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.registerFiles.rawValue,
|
||||
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
|
||||
UInt32(truncatingIfNeeded: count)
|
||||
try files.withUnsafeBufferPointer { bPtr throws(Errno) in
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.registerFiles.rawValue,
|
||||
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
|
||||
nrArgs: UInt32(truncatingIfNeeded: count)
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
|
||||
if let regResult {
|
||||
throw regResult
|
||||
}
|
||||
|
||||
_registeredFiles = files
|
||||
@@ -712,16 +715,13 @@ public struct IORing: ~Copyable {
|
||||
}
|
||||
|
||||
/// Removes registered files from the ring
|
||||
public func unregisterFiles() throws {
|
||||
let result = io_uring_register(
|
||||
ringDescriptor,
|
||||
RegistrationOps.unregisterFiles.rawValue,
|
||||
nil,
|
||||
0
|
||||
public func unregisterFiles() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterFiles.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
if result < 0 {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Allows access to registered files by index
|
||||
@@ -737,18 +737,13 @@ public struct IORing: ~Copyable {
|
||||
precondition(buffers.count < UInt32.max)
|
||||
precondition(_registeredBuffers.isEmpty)
|
||||
let iovecs = buffers.map { $0.to_iovec() }
|
||||
let regResult = iovecs.withUnsafeBufferPointer { bPtr in
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.registerBuffers.rawValue,
|
||||
UnsafeMutableRawPointer(mutating: bPtr.baseAddress!),
|
||||
UInt32(truncatingIfNeeded: buffers.count)
|
||||
try iovecs.withUnsafeBufferPointer { bPtr throws(Errno) in
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.registerBuffers.rawValue,
|
||||
arg: UnsafeMutableRawPointer(mutating: bPtr.baseAddress),
|
||||
nrArgs: UInt32(truncatingIfNeeded: buffers.count)
|
||||
)
|
||||
return result >= 0 ? nil : Errno(rawValue: -result)
|
||||
}
|
||||
|
||||
if let regResult {
|
||||
throw regResult
|
||||
}
|
||||
|
||||
_registeredBuffers = iovecs
|
||||
@@ -786,16 +781,13 @@ public struct IORing: ~Copyable {
|
||||
RegisteredResources(resources: _registeredBuffers)
|
||||
}
|
||||
|
||||
public func unregisterBuffers() throws {
|
||||
let result = io_uring_register(
|
||||
self.ringDescriptor,
|
||||
RegistrationOps.unregisterBuffers.rawValue,
|
||||
nil,
|
||||
0
|
||||
public func unregisterBuffers() throws(Errno) {
|
||||
_ = try _ioUringRegister(
|
||||
ringDescriptor: self.ringDescriptor,
|
||||
opcode: RegistrationOps.unregisterBuffers.rawValue,
|
||||
arg: nil,
|
||||
nrArgs: 0
|
||||
)
|
||||
guard result >= 0 else {
|
||||
throw Errno(rawValue: -result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring.
|
||||
|
||||
@@ -2,7 +2,12 @@
|
||||
#if os(Linux)
|
||||
|
||||
import CSystem
|
||||
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
internal struct RawIORequest: ~Copyable {
|
||||
// swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where
|
||||
@@ -176,20 +181,20 @@ extension RawIORequest {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func withTimeoutRequest<R>(
|
||||
static func withTimeoutRequest<R, E: Error>(
|
||||
linkedTo opEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
in timeoutEntry: UnsafeMutablePointer<swift_io_uring_sqe>,
|
||||
duration: Duration,
|
||||
flags: TimeOutFlags,
|
||||
work: () throws -> R) rethrows -> R {
|
||||
duration: Duration,
|
||||
flags: TimeOutFlags,
|
||||
work: () throws(E) -> R) throws(E) -> R {
|
||||
|
||||
opEntry.pointee.flags |= Flags.linkRequest.rawValue
|
||||
opEntry.pointee.off = 1
|
||||
var ts = timespec(
|
||||
tv_sec: Int(duration.components.seconds),
|
||||
tv_sec: Int(duration.components.seconds),
|
||||
tv_nsec: Int(duration.components.attoseconds / 1_000_000_000)
|
||||
)
|
||||
return try withUnsafePointer(to: &ts) { tsPtr in
|
||||
return try withUnsafePointer(to: &ts) { tsPtr throws(E) -> R in
|
||||
var req: RawIORequest = RawIORequest()
|
||||
req.operation = .link_timeout
|
||||
req.rawValue.timeout_flags = flags.rawValue
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -13,10 +13,10 @@ import Darwin
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
@@ -106,7 +106,7 @@ extension CInterop {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
extension CInterop {
|
||||
public typealias DeviceID = dev_t
|
||||
public typealias Inode = ino_t
|
||||
|
||||
@@ -14,16 +14,12 @@
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import CSystem
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
@@ -31,6 +27,8 @@ import Android
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import CSystem
|
||||
|
||||
// MARK: errno
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -631,10 +629,10 @@ internal var _O_CLOEXEC: CInt {
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOFORK: CInt {
|
||||
#if !os(WASI) && !os(Linux) && !os(Android) && !canImport(Darwin) && !os(FreeBSD)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
COMPATIBILITY_O_CLOFORK
|
||||
#elseif !os(WASI) && !os(Linux) && !os(Android)
|
||||
O_CLOFORK
|
||||
#elseif os(FreeBSD)
|
||||
FREEBSD_O_CLOFORK
|
||||
#else
|
||||
0
|
||||
#endif
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -18,15 +18,15 @@ import Darwin
|
||||
import CSystem
|
||||
import ucrt
|
||||
#elseif canImport(Glibc)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Musl
|
||||
#elseif canImport(WASILibc)
|
||||
import WASILibc
|
||||
#elseif canImport(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import CSystem
|
||||
import Android
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
@@ -96,15 +96,15 @@ internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
internal func system_stat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
stat(p, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_lstat(_ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat) -> Int32 {
|
||||
lstat(p, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
|
||||
fstat(fd, &s)
|
||||
}
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 {
|
||||
fstatat(fd, p, &s, flags)
|
||||
}
|
||||
@@ -185,8 +185,9 @@ extension String {
|
||||
#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 {
|
||||
// Mock TLS storage for single-threaded WASI.
|
||||
// Carries no state of its own, and only used to index `sharedTLSStorage`.
|
||||
internal final class _PlatformTLSKey: @unchecked Sendable {
|
||||
fileprivate init() {}
|
||||
}
|
||||
private final class TLSStorage: @unchecked Sendable {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
import CSystem
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@@ -23,8 +24,6 @@ import Android
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
import CSystem
|
||||
|
||||
// Interacting with the mocking system, tracing, etc., is a potentially significant
|
||||
// amount of code size, so we hand outline that code for every syscall
|
||||
|
||||
@@ -141,13 +140,14 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
return dup2(fd, fd2)
|
||||
}
|
||||
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
internal func system_dup3(_ fd: Int32, _ fd2: Int32, _ oflag: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, fd2, oflag) }
|
||||
#endif
|
||||
#endif
|
||||
return csystem_posix_dup3(fd, fd2, oflag)
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
#if !os(WASI)
|
||||
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
@@ -157,13 +157,14 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
return pipe(fds)
|
||||
}
|
||||
|
||||
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
|
||||
internal func system_pipe2(_ fds: UnsafeMutablePointer<Int32>, _ oflag: Int32) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fds, oflag) }
|
||||
#endif
|
||||
return csystem_posix_pipe2(fds, oflag)
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
@@ -201,7 +202,7 @@ internal func system_confstr(
|
||||
) -> Int {
|
||||
return confstr(name, buf, len)
|
||||
}
|
||||
#endif
|
||||
#endif // SYSTEM_PACKAGE_DARWIN
|
||||
|
||||
#if !os(Windows)
|
||||
internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR
|
||||
@@ -269,7 +270,7 @@ internal func system_openat(
|
||||
#endif
|
||||
return openat(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
#endif // !os(Windows)
|
||||
|
||||
#if !os(WASI) // WASI has no umask
|
||||
internal func system_umask(
|
||||
@@ -277,7 +278,7 @@ internal func system_umask(
|
||||
) -> CInterop.Mode {
|
||||
return umask(mode)
|
||||
}
|
||||
#endif
|
||||
#endif // !os(WASI)
|
||||
|
||||
internal func system_getenv(
|
||||
_ name: UnsafePointer<CChar>
|
||||
|
||||
@@ -11,16 +11,15 @@
|
||||
|
||||
import ucrt
|
||||
import WinSDK
|
||||
import Synchronization
|
||||
|
||||
fileprivate var _umask: CInterop.Mode = 0o22
|
||||
private let _umask = Atomic<CInterop.Mode>(0o22)
|
||||
|
||||
@inline(__always)
|
||||
func umask(
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInterop.Mode {
|
||||
let oldMask = _umask
|
||||
_umask = mode
|
||||
return oldMask
|
||||
_umask.exchange(mode, ordering: .relaxed)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@@ -58,7 +57,7 @@ internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
let actualMode = mode & ~_umask
|
||||
let actualMode = mode & ~_umask.load(ordering: .relaxed)
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else {
|
||||
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
|
||||
@@ -248,7 +247,7 @@ internal func mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
let actualMode = mode & ~_umask
|
||||
let actualMode = mode & ~_umask.load(ordering: .relaxed)
|
||||
|
||||
guard let pSD = _createSecurityDescriptor(from: actualMode,
|
||||
for: .directory) else {
|
||||
|
||||
@@ -12,18 +12,20 @@
|
||||
// private CSystem module.
|
||||
//
|
||||
// For new type wrappers introduced to System, access their C members here:
|
||||
// - Import the platform overlay (Glibc/Musl), as consumers do.
|
||||
// - Import the platform overlay (Glibc/Musl/Android), as consumers do.
|
||||
// - Access raw C members of vended types (e.g. CInterop.Stat) as a downstream
|
||||
// consumer would. Don't go through the Swift (e.g. Stat) wrapper since its
|
||||
// accesses happen inside System, where importing CSystem is fine.
|
||||
// - Touch every direct member the public API exposes. One field is not always
|
||||
// a safe proxy for the rest.
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl)
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#endif
|
||||
import SystemPackage
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -36,7 +36,7 @@ import Android
|
||||
@Suite("FileMode")
|
||||
private struct FileModeTests {
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func basics() async throws {
|
||||
var mode = FileMode(rawValue: S_IFREG | 0o644) // Regular file, rw-r--r--
|
||||
#expect(mode.type == .regular)
|
||||
@@ -67,7 +67,7 @@ private struct FileModeTests {
|
||||
#expect(mode.type == mode2.type)
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func invalidInput() async throws {
|
||||
// No permissions, all other bits set
|
||||
var invalidMode = FileMode(rawValue: ~0o7777)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -157,7 +157,8 @@ final class FileOperationsTest: XCTestCase {
|
||||
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
|
||||
}
|
||||
|
||||
#if !os(WASI) // WASI has no pipe
|
||||
#if !os(WASI) // WASI has no pipe
|
||||
@available(System 1.1.0, *)
|
||||
func testAdHocPipe() throws {
|
||||
// Ad-hoc test testing `Pipe` functionality.
|
||||
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
|
||||
@@ -177,8 +178,10 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN
|
||||
func testAdHocPipeWithOptions() throws {
|
||||
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
|
||||
throw XCTSkip("pipe2 and PipeOptions require Darwin 27 or newer")
|
||||
}
|
||||
// Ad-hoc test testing `Pipe` functionality.
|
||||
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
|
||||
let options: FileDescriptor.PipeOptions = [.closeOnExec]
|
||||
@@ -198,10 +201,9 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // !SYSTEM_PACKAGE_DARWIN
|
||||
#endif // !os(WASI)
|
||||
#endif // !os(WASI)
|
||||
|
||||
#if !os(Windows)
|
||||
#if !os(Windows)
|
||||
func testAdHocDuplicate2() throws {
|
||||
try withTemporaryFilePath(basename: "test") {
|
||||
let path = $0.appending("foo2.txt")
|
||||
@@ -238,10 +240,11 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // !os(Windows)
|
||||
|
||||
#if !SYSTEM_PACKAGE_DARWIN && !os(Windows)
|
||||
func testAdHocDuplicate3() throws {
|
||||
guard #available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *) else {
|
||||
throw XCTSkip("dup3 and DuplicateOptions require Darwin 27 or newer")
|
||||
}
|
||||
|
||||
try withTemporaryFilePath(basename: "test") {
|
||||
let path = $0.appending("foo3.txt")
|
||||
@@ -274,7 +277,7 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // !SYSTEM_PACKAGE_DARWIN && !os(Windows)
|
||||
#endif // !os(Windows)
|
||||
|
||||
func testAdHocOpen() {
|
||||
// Ad-hoc test touching a file system.
|
||||
@@ -334,6 +337,7 @@ final class FileOperationsTest: XCTestCase {
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
@available(System 1.2.0, *)
|
||||
func testResizeFile() throws {
|
||||
try withTemporaryFilePath(basename: "testResizeFile") { path in
|
||||
let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
|
||||
@@ -18,6 +18,7 @@ import XCTest
|
||||
#endif
|
||||
|
||||
import WinSDK
|
||||
import ucrt
|
||||
|
||||
private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA)
|
||||
private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE)
|
||||
@@ -295,6 +296,38 @@ final class FileOperationsTestWindows: XCTestCase {
|
||||
// We can't easily test this without allocating 4GB, but the boundary is correct
|
||||
}
|
||||
}
|
||||
|
||||
func testCloseOnExecOpenOption() throws {
|
||||
try withTemporaryFilePath(basename: "testCloseOnExec") { path in
|
||||
|
||||
func hasInheritFlag(of fd: FileDescriptor) throws -> Bool {
|
||||
let osfHandle = _get_osfhandle(fd.rawValue)
|
||||
let handle = try XCTUnwrap(HANDLE(bitPattern: osfHandle))
|
||||
var flags: DWORD = 0
|
||||
XCTAssertTrue(GetHandleInformation(handle, &flags))
|
||||
return flags & DWORD(HANDLE_FLAG_INHERIT) == DWORD(HANDLE_FLAG_INHERIT)
|
||||
}
|
||||
|
||||
var fd: FileDescriptor
|
||||
fd = try FileDescriptor.open(
|
||||
path.appending("wontinherit.txt"), .readWrite,
|
||||
options: [.create, .truncate, .closeOnExec],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
XCTAssertEqual(try hasInheritFlag(of: fd), false)
|
||||
}
|
||||
|
||||
fd = try FileDescriptor.open(
|
||||
path.appending("inheritable.txt"), .readWrite,
|
||||
options: [.create, .truncate],
|
||||
permissions: .ownerReadWrite
|
||||
)
|
||||
try fd.closeAfter {
|
||||
XCTAssertEqual(try hasInheritFlag(of: fd), true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // os(Windows)
|
||||
@@ -3,6 +3,11 @@
|
||||
|
||||
import XCTest
|
||||
import CSystem //for eventfd
|
||||
#if canImport(Glibc)
|
||||
import Glibc // for errno
|
||||
#elseif canImport(Musl)
|
||||
import Musl // for errno
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
@@ -10,29 +15,80 @@ import SystemPackage
|
||||
import System
|
||||
#endif
|
||||
|
||||
func uringEnabled() throws -> Bool {
|
||||
// Cache `isUringEnabled()`. The probe is complex and the answer doesn't change
|
||||
// during a test run.
|
||||
let uringEnabled: Bool = {
|
||||
do {
|
||||
let procPath = FilePath("/proc/sys/kernel/io_uring_disabled")
|
||||
let fd = try FileDescriptor.open(procPath, .readOnly)
|
||||
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0)
|
||||
_ = try fd.read(into: buffer)
|
||||
if buffer.load(fromByteOffset: 0, as: Int.self) == 0 {
|
||||
return true
|
||||
}
|
||||
} catch (_) {
|
||||
return try isUringEnabled()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}()
|
||||
|
||||
func isUringEnabled() throws -> Bool {
|
||||
// Even if the kernel supports io_uring, the SystemPackage build may have
|
||||
// been compiled against older kernel headers that lack features it needs
|
||||
// (gated on IORING_TIMEOUT_BOOTTIME in CSystem); in that configuration
|
||||
// IORing.init throws ENOTSUP. Treat that as disabled so tests skip cleanly
|
||||
// instead of failing.
|
||||
do throws(Errno) {
|
||||
_ = try IORing(queueDepth: 1, flags: [])
|
||||
} catch {
|
||||
switch error {
|
||||
case .notSupported, .noFunction, .invalidArgument,
|
||||
.notPermitted, .permissionDenied:
|
||||
return false
|
||||
default:
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// The ideal test uses /proc/sys/kernel/io_uring_disabled (Linux >= 6.6).
|
||||
if let fd = try? FileDescriptor.open(
|
||||
"/proc/sys/kernel/io_uring_disabled", .readOnly)
|
||||
{
|
||||
defer { try? fd.close() }
|
||||
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1, alignment: 1)
|
||||
defer { buffer.deallocate() }
|
||||
let n = try fd.read(into: buffer)
|
||||
return n == 1 && (buffer.load(as: UInt8.self) == UInt8(ascii: "0"))
|
||||
}
|
||||
|
||||
// Fallback for older kernels: simply attempt io_uring_setup.
|
||||
// - ENOSYS -> syscall doesn't exist (Linux < 5.1) -> disabled.
|
||||
// - EPERM or EACCES -> treat as disabled
|
||||
// - propagate any other error.
|
||||
var params = io_uring_params()
|
||||
let raw = io_uring_setup(1, ¶ms)
|
||||
if raw < 0 {
|
||||
let err = Errno(rawValue: errno)
|
||||
switch err {
|
||||
case .noFunction, .notPermitted, .permissionDenied:
|
||||
return false
|
||||
default:
|
||||
throw err
|
||||
}
|
||||
}
|
||||
try? FileDescriptor(rawValue: raw).close()
|
||||
return true
|
||||
}
|
||||
|
||||
final class IORingTests: XCTestCase {
|
||||
func testIsUringEnabled() throws {
|
||||
// If `isUringEnabled()` throws, it is incomplete in some way.
|
||||
let enabled = try isUringEnabled()
|
||||
if !enabled {
|
||||
print("IORing tests will be skipped.")
|
||||
}
|
||||
}
|
||||
|
||||
func testInit() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
guard uringEnabled else { return }
|
||||
_ = try IORing(queueDepth: 32, flags: [])
|
||||
}
|
||||
|
||||
func testNop() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
guard uringEnabled else { return }
|
||||
var ring = try IORing(queueDepth: 32, flags: [])
|
||||
_ = try ring.submit(linkedRequests: .nop())
|
||||
let completion = try ring.blockingConsumeCompletion()
|
||||
@@ -68,7 +124,7 @@ final class IORingTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testUndersizedSubmissionQueue() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
guard uringEnabled else { return }
|
||||
var ring: IORing = try IORing(queueDepth: 1)
|
||||
let enqueued = ring.prepare(linkedRequests: .nop(), .nop())
|
||||
XCTAssertFalse(enqueued)
|
||||
@@ -76,7 +132,7 @@ final class IORingTests: XCTestCase {
|
||||
|
||||
// Exercises opening, reading, closing, registered files, registered buffers, and eventfd
|
||||
func testOpenReadAndWriteFixedFile() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
guard uringEnabled else { return }
|
||||
let (parent, path) = try makeHelloWorldFile()
|
||||
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
|
||||
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
|
||||
@@ -117,7 +173,6 @@ final class IORingTests: XCTestCase {
|
||||
_ = try ring.blockingConsumeCompletion() //close
|
||||
memset(rawBuffer.baseAddress!, 0, rawBuffer.count)
|
||||
//Verify using a non-ring IO method that what we wrote matches our expectations
|
||||
print("about to open")
|
||||
let nonRingFD = try FileDescriptor.open(path, .readOnly)
|
||||
let bytesRead = try nonRingFD.read(into: rawBuffer)
|
||||
XCTAssert(bytesRead == 13)
|
||||
@@ -134,7 +189,7 @@ final class IORingTests: XCTestCase {
|
||||
// dangling pointer. Here we deliberately let the FilePath go out of scope
|
||||
// between prepare and submit, then churn the heap to make UAFs observable.
|
||||
func testPathBufferLifetimeAcrossPrepareSubmit() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
guard uringEnabled else { return }
|
||||
let (parent, _) = try makeHelloWorldFile()
|
||||
var ring = try IORing(queueDepth: 6)
|
||||
|
||||
@@ -168,7 +223,7 @@ final class IORingTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testPathBufferLifetimeAcrossLinkedRequests() throws {
|
||||
guard try uringEnabled() else { return }
|
||||
guard uringEnabled else { return }
|
||||
let (parent, _) = try makeHelloWorldFile()
|
||||
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
|
||||
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
|
||||
@@ -202,6 +257,59 @@ final class IORingTests: XCTestCase {
|
||||
try cleanUpHelloWorldFile(parent)
|
||||
rawBuffer.deallocate()
|
||||
}
|
||||
|
||||
// Timeout test for `blockingConsumeCompletion(timeout:)`:
|
||||
func testBlockingConsumeCompletionWithTimeoutOnIdleRing() throws {
|
||||
guard uringEnabled else { return }
|
||||
let ring = try IORing(queueDepth: 4, flags: [])
|
||||
guard ring.supportedFeatures.contains(.extendedArguments) else {
|
||||
// Kernel < 5.11: timeouts in io_uring_enter aren't supported.
|
||||
return
|
||||
}
|
||||
|
||||
let clock = ContinuousClock()
|
||||
let start = clock.now
|
||||
|
||||
var thrown: Errno? = nil
|
||||
do throws(Errno) {
|
||||
_ = try ring.blockingConsumeCompletion(timeout: .milliseconds(100))
|
||||
XCTFail("expected timeout, got a completion on an idle ring")
|
||||
} catch {
|
||||
thrown = error
|
||||
}
|
||||
|
||||
let elapsed = start.duration(to: clock.now)
|
||||
|
||||
XCTAssertEqual(thrown, .timeout)
|
||||
XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(50))
|
||||
}
|
||||
|
||||
func testRegisterEventFDTwiceThrows() throws {
|
||||
guard uringEnabled else { return }
|
||||
var ring = try IORing(queueDepth: 4)
|
||||
let efd = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE)))
|
||||
defer { try? efd.close() }
|
||||
|
||||
try ring.registerEventFD(efd)
|
||||
do throws(Errno) {
|
||||
try ring.registerEventFD(efd) // second registration -> EBUSY
|
||||
XCTFail("expected second registerEventFD to throw")
|
||||
} catch {
|
||||
XCTAssertEqual(error, .resourceBusy)
|
||||
}
|
||||
}
|
||||
|
||||
func testSubmitOnDisabledRingThrows() throws {
|
||||
guard uringEnabled else { return }
|
||||
var ring = try IORing(queueDepth: 4, flags: [.startDisabled])
|
||||
|
||||
do throws(Errno) {
|
||||
_ = try ring.submit(linkedRequests: .nop())
|
||||
XCTFail("expected submit on a disabled ring to throw")
|
||||
} catch {
|
||||
XCTAssertEqual(error, Errno(rawValue: EBADFD))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // os(Linux)
|
||||
#endif // compiler(>=6.2) && $Lifetimes
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift System open source project
|
||||
//
|
||||
// Copyright (c) 2025 Apple Inc. and the Swift System project authors
|
||||
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -39,7 +39,7 @@ import Android
|
||||
@Suite("Stat")
|
||||
private struct StatTests {
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func basics() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_basics") { tempDir in
|
||||
let dirStatFromFilePath = try tempDir.stat()
|
||||
@@ -81,7 +81,7 @@ private struct StatTests {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func followSymlinkInits() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_followSymlinkInits") { tempDir in
|
||||
let targetFilePath = tempDir.appending("target.txt")
|
||||
@@ -190,7 +190,7 @@ private struct StatTests {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func permissions() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_permissions") { tempDir in
|
||||
let testFile = tempDir.appending("test.txt")
|
||||
@@ -220,8 +220,13 @@ private struct StatTests {
|
||||
}
|
||||
}
|
||||
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func times() async throws {
|
||||
// This test pauses with `usleep` between some measurements to ensure that
|
||||
// the timestamp used by the filesystem will advance. On Linux and Android
|
||||
// the granularity of that clock may be as much as 10ms. We use 50ms
|
||||
// in order to have a comfortable margin.
|
||||
let timestampSleep: useconds_t = 50_000
|
||||
var start = timespec()
|
||||
try #require(clock_gettime(CLOCK_REALTIME, &start) == 0, "\(Errno.current)")
|
||||
start.tv_sec -= 1 // A little wiggle room
|
||||
@@ -247,8 +252,7 @@ private struct StatTests {
|
||||
#expect(dirCreationTime0 < startUpperBound)
|
||||
#endif
|
||||
|
||||
// Fails intermittently if less than 5ms
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
let file1 = tempDir.appending("test1.txt")
|
||||
let fd1 = try FileDescriptor.open(file1, .writeOnly, options: .create, permissions: .ownerReadWrite)
|
||||
@@ -274,7 +278,7 @@ private struct StatTests {
|
||||
#expect(dirCreationTime1 == dirCreationTime0)
|
||||
#endif
|
||||
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
// Changing permissions only updates directory change time
|
||||
|
||||
@@ -302,7 +306,7 @@ private struct StatTests {
|
||||
let file1CreationTime1 = stat1.st_birthtim
|
||||
#endif
|
||||
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
try fd1.writeAll("Hello, world!".utf8)
|
||||
stat1 = try file1.stat()
|
||||
@@ -330,7 +334,7 @@ private struct StatTests {
|
||||
#expect(dirStat.st_birthtim == dirCreationTime1)
|
||||
#endif
|
||||
|
||||
usleep(10000)
|
||||
usleep(timestampSleep)
|
||||
|
||||
let file2 = tempDir.appending("test2.txt")
|
||||
let fd2 = try FileDescriptor.open(file2, .writeOnly, options: .create, permissions: .ownerReadWrite)
|
||||
@@ -339,9 +343,9 @@ private struct StatTests {
|
||||
}
|
||||
|
||||
let stat2 = try file2.stat()
|
||||
#expect(stat2.st_atim > file1AccessTime2)
|
||||
#expect(stat2.st_mtim > file1ModificationTime2)
|
||||
#expect(stat2.st_ctim > file1ChangeTime2)
|
||||
#expect(stat2.st_atim >= file1AccessTime2)
|
||||
#expect(stat2.st_mtim >= file1ModificationTime2)
|
||||
#expect(stat2.st_ctim >= file1ChangeTime2)
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
|
||||
#expect(stat2.st_birthtim > file1CreationTime2)
|
||||
#endif
|
||||
@@ -349,7 +353,7 @@ private struct StatTests {
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
|
||||
@available(System 99, *)
|
||||
@available(System 1.7.0, *)
|
||||
@Test func flags() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_flags") { tempDir in
|
||||
let filePath = tempDir.appending("test.txt")
|
||||
@@ -397,6 +401,38 @@ private struct StatTests {
|
||||
}
|
||||
#endif
|
||||
|
||||
@available(System 1.7.0, *)
|
||||
@Test func equalityAndHashing() async throws {
|
||||
try withTemporaryFilePath(basename: "Stat_equality") { tempDir in
|
||||
let file = tempDir.appending("test.txt")
|
||||
let fd = try FileDescriptor.open(
|
||||
file, .writeOnly, options: .create, permissions: .ownerReadWrite)
|
||||
defer { try? fd.close() }
|
||||
|
||||
// Two stats of the same, unchanged file compare equal and hash equal,
|
||||
// so they coalesce in a Set.
|
||||
let stat1 = try file.stat()
|
||||
var stat2 = try file.stat()
|
||||
stat2.st_atim = stat1.st_atim // stat() can bump access time
|
||||
#expect(stat1 == stat2)
|
||||
#expect(stat1.hashValue == stat2.hashValue)
|
||||
#expect(Set([stat1, stat2]).count == 1)
|
||||
|
||||
// Reserved/"spare" and padding bytes must not affect equality.
|
||||
// Poke a reserved field and confirm equality/hashing are stable.
|
||||
#if SYSTEM_PACKAGE_DARWIN
|
||||
var stat3 = stat1
|
||||
stat3.rawValue.st_lspare = stat1.rawValue.st_lspare &+ 1
|
||||
#expect(stat1 == stat3)
|
||||
#expect(stat1.hashValue == stat3.hashValue)
|
||||
#endif
|
||||
|
||||
// A stat of a different file (the containing directory) is not equal.
|
||||
let dirStat = try tempDir.stat()
|
||||
#expect(stat1 != dirStat)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Comparison operators for timespec until UTCClock.Instant properties are available
|
||||
|
||||
Reference in new issue
Block a user