Compare commits

..
21 Commits
Author SHA1 Message Date
Guillaume Lessard 0b30161977 Merge branch 'release/1.5.0' into ‘release/1.6.0’ 2026-07-16 13:02:41 -07:00
Guillaume Lessard b349ff8c05 Update pull request workflow 2026-07-16 12:41:01 -07:00
Guillaume Lessard 7cb32eb7a4 Cherry-pick: remove unnecessary type casting
The compiler now imports these as their canonical type, allowing us to directly use without the explicit type cast. Due to the floor of Swift 6.3, we must preserve the type cast values. Introduce an overlay to explicitly cast the values in the older compilers.

Cherry-pick of #308
2026-07-16 10:21:23 -07:00
David Smith 669763cfd5 Merge pull request #309 from apple/david/ioring-crash-fix
Fix a crash when work is interleaved between prepare and submit in IORing
2026-06-04 16:38:10 -07:00
David Smith 6fa5c8a6c1 Explain why this is a class 2026-06-04 16:05:44 -07:00
David Smith 2cae953181 Fix a crash when work is interleaved between prepare and submit in IORing 2026-06-04 16:05:28 -07:00
Guillaume Lessard 7c6ad0fc39 Merge pull request #286 from apple/dev/fix-pread-truncation-windows-1.6.0
[Windows] fix pread/pwrite truncation
2026-01-13 13:53:28 -08:00
lee 13851a3421 Fix silent buffer size truncation in Windows pread/pwrite 2026-01-13 13:37:44 -08:00
Guillaume Lessard 8f8d80a4fe Merge pull request #285 from glessard/fix-HRESULT_FACILITY-1.6.0
[Windows] Fix HRESULT_FACILITY
2026-01-13 13:33:25 -08:00
Guillaume Lessard 608a75b962 Merge pull request #284 from glessard/workflow-edits-1.6.0-again
[ci] re-allow 5.9 and 5.10 for 1.6.x
2026-01-13 12:49:27 -08:00
AZero13 0dbbab4aa1 Fix HRESULT_FACILITY
HRESULT_FACILITY is >> 16 & 0x1fff, not <<
2026-01-13 12:41:47 -08:00
Guillaume Lessard 2eb655e0b7 [ci] re-allow 5.9 and 5.10
- they were excluded in error.
2026-01-13 12:38:57 -08:00
Guillaume Lessard 07a3f090d7 Merge pull request #280 from glessard/workflow-edits-1.6.0
[ci] adjust the pull-request action
2026-01-08 17:06:26 -08:00
Guillaume Lessard dda2b535b7 [ci] adjust the pull-request action 2026-01-08 16:46:01 -08:00
Guillaume Lessard 9ddc89964b Merge pull request #263 from apple/workflow-edits-1.6.0
[1.6.0] Apply GitHub workflow edits
2025-09-18 11:14:47 -07:00
Guillaume Lessard 18a52c4729 [workflows] declare 2D exclusions 2025-09-18 10:47:41 -07:00
Guillaume Lessard 1c1ad1d3f4 [workflows] change ubuntus to test against 2025-09-18 10:09:02 -07:00
Guillaume Lessard 395a77f0aa Merge pull request #260 from apple/eng/PR-duplicate-as-release/1.6.0
[1.6] Fix: FileDescriptor.duplicate(as:) returns an invalid file descriptor on Windows
2025-09-15 10:31:53 -07:00
Jake Petroules b1618475cc [1.6] Fix: FileDescriptor.duplicate(as:) returns an invalid file descriptor on Windows
FileDescriptor.duplicate(as:) is backed by dup2 on Unix, and _dup2 on Windows.
On Unix, dup2 returns its second argument. On Windows, _dup2 instead returns
0 on success and -1 on error. This results in the newly returned FileDescriptor
object always containing a '0' file descriptor rather than the newly created
file descriptor, in violation of the documented behavior.

Account for the platform difference in the syscall wrapper to fix this.

Closes #192

(cherry picked from commit b2711a872a)
2025-09-15 10:16:15 -07:00
Guillaume Lessard 890830fff1 Merge pull request #254 from jrflat/fix-generic-int-typedefs-1.6.0 2025-08-03 17:11:41 -07:00
Jonathan Flat a5f13c77b8 Fix typedef errors on platforms with _ASM_GENERIC_INT headers 2025-08-03 11:24:24 -06:00
33 changed files with 873 additions and 299 deletions

No files matched your search

+51 -16
View File
@@ -1,5 +1,8 @@
name: Pull request name: Pull request
permissions:
contents: read
on: on:
pull_request: pull_request:
types: [opened, reopened, synchronize] types: [opened, reopened, synchronize]
@@ -9,18 +12,56 @@ jobs:
name: Test name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with: with:
linux_os_versions: '["jammy", "focal"]'
enable_macos_checks: true
# FIXME: https://github.com/swiftlang/github-workflows/pull/140
# Xcode 16.0 and 16.1 are not actually available
macos_exclude_xcode_versions: |
[
{"xcode_version": "16.0"},
{"xcode_version": "16.1"},
]
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI" swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI"
enable_linux_checks: true
linux_os_versions: '["noble", "jammy", "focal"]'
linux_exclude_swift_versions: |
[
{"os_version": "noble", "swift_version": "5.9"},
{"os_version": "noble", "swift_version": "5.10"},
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
{"os_version": "focal", "swift_version": "6.4.x"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_macos_checks: true
macos_exclude_xcode_versions: '[]'
enable_windows_checks: true
windows_exclude_swift_versions: |
[
{"swift_version": "5.9"},
{"swift_version": "5.10"}
]
enable_linux_static_sdk_build: true enable_linux_static_sdk_build: true
linux_static_sdk_exclude_swift_versions: |
[
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
{"os_version": "focal", "swift_version": "6.4.x"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_wasm_sdk_build: true enable_wasm_sdk_build: true
wasm_exclude_swift_versions: |
[
{"os_version": "focal", "swift_version": "nightly-6.2"},
{"os_version": "focal", "swift_version": "6.2"},
{"os_version": "focal", "swift_version": "nightly-6.3"},
{"os_version": "focal", "swift_version": "6.3"},
{"os_version": "focal", "swift_version": "nightly-6.4.x"},
{"os_version": "focal", "swift_version": "6.4.x"},
{"os_version": "focal", "swift_version": "nightly-main"},
]
enable_android_sdk_build: true
android_exclude_swift_versions: |
[
{"os_version": "focal", "swift_version": "nightly-main"},
]
build-abi-stable: build-abi-stable:
name: Build ABI Stable name: Build ABI Stable
@@ -31,13 +72,7 @@ jobs:
enable_windows_checks: false enable_windows_checks: false
# Only build # Only build
macos_build_command: "xcrun swift build --build-tests" macos_build_command: "xcrun swift build --build-tests"
# FIXME: https://github.com/swiftlang/github-workflows/pull/140 macos_exclude_xcode_versions: '[]'
# Xcode 16.0 and 16.1 are not actually available
macos_exclude_xcode_versions: |
[
{"xcode_version": "16.0"},
{"xcode_version": "16.1"},
]
# Enable availability to match ABI stable verion of system. # Enable availability to match ABI stable verion of system.
swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE" swift_flags: "-Xbuild-tools-swiftc -DSYSTEM_CI -Xbuild-tools-swiftc -DSYSTEM_ABI_STABLE"
+2
View File
@@ -134,11 +134,13 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe;
#define IORING_FEAT_RW_ATTR (1U << 16) #define IORING_FEAT_RW_ATTR (1U << 16)
#define IORING_FEAT_NO_IOWAIT (1U << 17) #define IORING_FEAT_NO_IOWAIT (1U << 17)
#if !defined(_ASM_GENERIC_INT_LL64_H) && !defined(_ASM_GENERIC_INT_L64_H) && !defined(_UAPI_ASM_GENERIC_INT_LL64_H) && !defined(_UAPI_ASM_GENERIC_INT_L64_H)
typedef uint8_t __u8; typedef uint8_t __u8;
typedef uint16_t __u16; typedef uint16_t __u16;
typedef uint32_t __u32; typedef uint32_t __u32;
typedef uint64_t __u64; typedef uint64_t __u64;
typedef int32_t __s32; typedef int32_t __s32;
#endif
#ifndef __kernel_rwf_t #ifndef __kernel_rwf_t
typedef int __kernel_rwf_t; typedef int __kernel_rwf_t;
+2 -14
View File
@@ -11,7 +11,7 @@
/// occurred. /// occurred.
@frozen @frozen
@available(System 0.0.1, *) @available(System 0.0.1, *)
public struct Errno: RawRepresentable, Error, Hashable { public struct Errno: RawRepresentable, Error, Hashable, Codable {
/// The raw C error number. /// The raw C error number.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public let rawValue: CInt public let rawValue: CInt
@@ -160,7 +160,7 @@ public struct Errno: RawRepresentable, Error, Hashable {
/// No child processes. /// No child processes.
/// ///
/// A `wait(2)` or `waitpid(2)` function was executed /// A `wait(2)` or `waitpid(2)` function was executed
/// by a process that dosn't have any existing child processes /// by a process that doesn't have any existing child processes
/// or whose child processes are all already being waited for. /// or whose child processes are all already being waited for.
/// ///
/// The corresponding C error is `ECHILD`. /// The corresponding C error is `ECHILD`.
@@ -1562,8 +1562,6 @@ extension Errno: CustomStringConvertible, CustomDebugStringConvertible {
public var debugDescription: String { self.description } public var debugDescription: String { self.description }
} }
#if !$Embedded
@available(System 0.0.1, *) @available(System 0.0.1, *)
extension Errno { extension Errno {
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
@@ -1573,13 +1571,3 @@ extension Errno {
} }
} }
@available(System 0.0.1, *)
extension Errno: Codable {}
public typealias SystemError = any Error
#else
public typealias SystemError = Errno
#endif // !$Embedded
+4 -20
View File
@@ -15,7 +15,7 @@
/// in the same way as you manage a raw C file handle. /// in the same way as you manage a raw C file handle.
@frozen @frozen
@available(System 0.0.1, *) @available(System 0.0.1, *)
public struct FileDescriptor: RawRepresentable, Hashable { public struct FileDescriptor: RawRepresentable, Hashable, Codable {
/// The raw C file handle. /// The raw C file handle.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public let rawValue: CInt public let rawValue: CInt
@@ -46,7 +46,7 @@ extension FileDescriptor {
/// The desired read and write access for a newly opened file. /// The desired read and write access for a newly opened file.
@frozen @frozen
@available(System 0.0.1, *) @available(System 0.0.1, *)
public struct AccessMode: RawRepresentable, Sendable, Hashable { public struct AccessMode: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C access mode. /// The raw C access mode.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public var rawValue: CInt public var rawValue: CInt
@@ -89,7 +89,7 @@ extension FileDescriptor {
/// Options that specify behavior for a newly-opened file. /// Options that specify behavior for a newly-opened file.
@frozen @frozen
@available(System 0.0.1, *) @available(System 0.0.1, *)
public struct OpenOptions: OptionSet, Sendable, Hashable { public struct OpenOptions: OptionSet, Sendable, Hashable, Codable {
/// The raw C options. /// The raw C options.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public var rawValue: CInt public var rawValue: CInt
@@ -327,7 +327,7 @@ extension FileDescriptor {
/// Options for specifying what a file descriptor's offset is relative to. /// Options for specifying what a file descriptor's offset is relative to.
@frozen @frozen
@available(System 0.0.1, *) @available(System 0.0.1, *)
public struct SeekOrigin: RawRepresentable, Sendable, Hashable { public struct SeekOrigin: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C value. /// The raw C value.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public var rawValue: CInt public var rawValue: CInt
@@ -402,22 +402,6 @@ extension FileDescriptor {
} }
} }
#if !$Embedded
@available(System 0.0.1, *)
extension FileDescriptor: Codable {}
@available(System 0.0.1, *)
extension FileDescriptor.AccessMode: Codable {}
@available(System 0.0.1, *)
extension FileDescriptor.OpenOptions: Codable {}
@available(System 0.0.1, *)
extension FileDescriptor.SeekOrigin: Codable {}
#endif // !$Embedded
@available(System 0.0.1, *) @available(System 0.0.1, *)
extension FileDescriptor.AccessMode extension FileDescriptor.AccessMode
: CustomStringConvertible, CustomDebugStringConvertible : CustomStringConvertible, CustomDebugStringConvertible
+28 -28
View File
@@ -30,24 +30,24 @@ extension FileDescriptor {
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil, permissions: FilePermissions? = nil,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor { ) throws -> FileDescriptor {
#if !os(Windows) #if !os(Windows)
return try path.withCString { (cString) throws(SystemError) in return try path.withCString {
try FileDescriptor.open( try FileDescriptor.open(
cString, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
} }
#else #else
return try path.withPlatformString { (platformString) throws(SystemError) in return try path.withPlatformString {
try FileDescriptor.open( try FileDescriptor.open(
platformString, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
} }
#endif #endif
} }
#if !os(Windows) #if !os(Windows)
// On Darwin, `CInterop.PlatformChar` is less available than // On Darwin, `CInterop.PlatformChar` is less available than
// `FileDescriptor.open`, so we need to use `CChar` instead. // `FileDescriptor.open`, so we need to use `CChar` instead.
/// Opens or creates a file for reading or writing. /// Opens or creates a file for reading or writing.
/// ///
/// - Parameters: /// - Parameters:
@@ -69,7 +69,7 @@ extension FileDescriptor {
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil, permissions: FilePermissions? = nil,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor { ) throws -> FileDescriptor {
try FileDescriptor._open( try FileDescriptor._open(
path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt
).get() ).get()
@@ -116,7 +116,7 @@ extension FileDescriptor {
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
permissions: FilePermissions? = nil, permissions: FilePermissions? = nil,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor { ) throws -> FileDescriptor {
try FileDescriptor._open( try FileDescriptor._open(
path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt
).get() ).get()
@@ -149,7 +149,7 @@ extension FileDescriptor {
/// ///
/// The corresponding C function is `close`. /// The corresponding C function is `close`.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public func close() throws(SystemError) { try _close().get() } public func close() throws { try _close().get() }
@usableFromInline @usableFromInline
internal func _close() -> Result<(), Errno> { internal func _close() -> Result<(), Errno> {
@@ -169,7 +169,7 @@ extension FileDescriptor {
@discardableResult @discardableResult
public func seek( public func seek(
offset: Int64, from whence: FileDescriptor.SeekOrigin offset: Int64, from whence: FileDescriptor.SeekOrigin
) throws(SystemError) -> Int64 { ) throws -> Int64 {
try _seek(offset: offset, from: whence).get() try _seek(offset: offset, from: whence).get()
} }
@@ -187,7 +187,7 @@ extension FileDescriptor {
@available(*, unavailable, renamed: "seek") @available(*, unavailable, renamed: "seek")
public func lseek( public func lseek(
offset: Int64, from whence: FileDescriptor.SeekOrigin offset: Int64, from whence: FileDescriptor.SeekOrigin
) throws(SystemError) -> Int64 { ) throws -> Int64 {
try seek(offset: offset, from: whence) try seek(offset: offset, from: whence)
} }
@@ -214,7 +214,7 @@ extension FileDescriptor {
public func read( public func read(
into buffer: UnsafeMutableRawBufferPointer, into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> Int { ) throws -> Int {
try _read(into: buffer, retryOnInterrupt: retryOnInterrupt).get() try _read(into: buffer, retryOnInterrupt: retryOnInterrupt).get()
} }
@@ -222,7 +222,7 @@ extension FileDescriptor {
internal func _read( internal func _read(
into buffer: UnsafeMutableRawBufferPointer, into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool retryOnInterrupt: Bool
) throws(SystemError) -> Result<Int, Errno> { ) throws -> Result<Int, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) { valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_read(self.rawValue, buffer.baseAddress, buffer.count) system_read(self.rawValue, buffer.baseAddress, buffer.count)
} }
@@ -251,7 +251,7 @@ extension FileDescriptor {
fromAbsoluteOffset offset: Int64, fromAbsoluteOffset offset: Int64,
into buffer: UnsafeMutableRawBufferPointer, into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> Int { ) throws -> Int {
try _read( try _read(
fromAbsoluteOffset: offset, fromAbsoluteOffset: offset,
into: buffer, into: buffer,
@@ -276,7 +276,7 @@ extension FileDescriptor {
fromAbsoluteOffset offset: Int64, fromAbsoluteOffset offset: Int64,
into buffer: UnsafeMutableRawBufferPointer, into buffer: UnsafeMutableRawBufferPointer,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> Int { ) throws -> Int {
try read( try read(
fromAbsoluteOffset: offset, fromAbsoluteOffset: offset,
into: buffer, into: buffer,
@@ -303,7 +303,7 @@ extension FileDescriptor {
public func write( public func write(
_ buffer: UnsafeRawBufferPointer, _ buffer: UnsafeRawBufferPointer,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> Int { ) throws -> Int {
try _write(buffer, retryOnInterrupt: retryOnInterrupt).get() try _write(buffer, retryOnInterrupt: retryOnInterrupt).get()
} }
@@ -337,7 +337,7 @@ extension FileDescriptor {
toAbsoluteOffset offset: Int64, toAbsoluteOffset offset: Int64,
_ buffer: UnsafeRawBufferPointer, _ buffer: UnsafeRawBufferPointer,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> Int { ) throws -> Int {
try _write(toAbsoluteOffset: offset, buffer, retryOnInterrupt: retryOnInterrupt).get() try _write(toAbsoluteOffset: offset, buffer, retryOnInterrupt: retryOnInterrupt).get()
} }
@@ -359,7 +359,7 @@ extension FileDescriptor {
toAbsoluteOffset offset: Int64, toAbsoluteOffset offset: Int64,
into buffer: UnsafeRawBufferPointer, into buffer: UnsafeRawBufferPointer,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> Int { ) throws -> Int {
try write( try write(
toAbsoluteOffset: offset, toAbsoluteOffset: offset,
buffer, buffer,
@@ -402,7 +402,7 @@ extension FileDescriptor {
public func duplicate( public func duplicate(
as target: FileDescriptor? = nil, as target: FileDescriptor? = nil,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) -> FileDescriptor { ) throws -> FileDescriptor {
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get() try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
} }
@@ -411,7 +411,7 @@ extension FileDescriptor {
internal func _duplicate( internal func _duplicate(
as target: FileDescriptor?, as target: FileDescriptor?,
retryOnInterrupt: Bool retryOnInterrupt: Bool
) throws(SystemError) -> Result<FileDescriptor, Errno> { ) throws -> Result<FileDescriptor, Errno> {
valueOrErrno(retryOnInterrupt: retryOnInterrupt) { valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
if let target = target { if let target = target {
return system_dup2(self.rawValue, target.rawValue) return system_dup2(self.rawValue, target.rawValue)
@@ -422,13 +422,13 @@ extension FileDescriptor {
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
@available(*, unavailable, renamed: "duplicate") @available(*, unavailable, renamed: "duplicate")
public func dup() throws(SystemError) -> FileDescriptor { public func dup() throws -> FileDescriptor {
fatalError("Not implemented") fatalError("Not implemented")
} }
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
@available(*, unavailable, renamed: "duplicate") @available(*, unavailable, renamed: "duplicate")
public func dup2() throws(SystemError) -> FileDescriptor { public func dup2() throws -> FileDescriptor {
fatalError("Not implemented") fatalError("Not implemented")
} }
} }
@@ -444,7 +444,7 @@ extension FileDescriptor {
/// The corresponding C function is `pipe`. /// The corresponding C function is `pipe`.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
@available(System 1.1.0, *) @available(System 1.1.0, *)
public static func pipe() throws(SystemError) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
try _pipe().get() try _pipe().get()
} }
@@ -490,7 +490,7 @@ extension FileDescriptor {
public func resize( public func resize(
to newSize: Int64, to newSize: Int64,
retryOnInterrupt: Bool = true retryOnInterrupt: Bool = true
) throws(SystemError) { ) throws {
try _resize( try _resize(
to: newSize, to: newSize,
retryOnInterrupt: retryOnInterrupt retryOnInterrupt: retryOnInterrupt
@@ -537,7 +537,7 @@ extension FilePermissions {
/// afterwards, because of the way reading the creation mask works. /// afterwards, because of the way reading the creation mask works.
internal static func withCreationMask<R>( internal static func withCreationMask<R>(
_ permissions: FilePermissions, _ permissions: FilePermissions,
body: () throws(SystemError) -> R body: () throws -> R
) rethrows -> R { ) rethrows -> R {
let oldMask = _umask(permissions.rawValue) let oldMask = _umask(permissions.rawValue)
defer { defer {
-4
View File
@@ -68,8 +68,6 @@ extension FilePath {
@available(System 0.0.1, *) @available(System 0.0.1, *)
extension FilePath: Hashable {} extension FilePath: Hashable {}
#if !$Embedded
@available(System 0.0.1, *) @available(System 0.0.1, *)
extension FilePath: Codable { extension FilePath: Codable {
// Encoder is synthesized; it probably should have been explicit and used // Encoder is synthesized; it probably should have been explicit and used
@@ -90,5 +88,3 @@ extension FilePath: Codable {
} }
} }
} }
#endif // !$Embedded
@@ -128,8 +128,6 @@ extension SystemString {
} }
} }
#if !$Embedded
// Unifying protocol for common functionality between roots, components, // Unifying protocol for common functionality between roots, components,
// and views onto SystemString and FilePath. // and views onto SystemString and FilePath.
internal protocol _StrSlice: _PlatformStringable, Hashable, Codable { internal protocol _StrSlice: _PlatformStringable, Hashable, Codable {
@@ -140,20 +138,6 @@ internal protocol _StrSlice: _PlatformStringable, Hashable, Codable {
func _invariantCheck() func _invariantCheck()
} }
#else
internal protocol _StrSlice: _PlatformStringable, Hashable {
var _storage: SystemString { get }
var _range: Range<SystemString.Index> { get }
init?(_ str: SystemString)
func _invariantCheck()
}
#endif // !$Embedded
extension _StrSlice { extension _StrSlice {
internal var _slice: Slice<SystemString> { internal var _slice: Slice<SystemString> {
Slice(base: _storage, bounds: _range) Slice(base: _storage, bounds: _range)
+5 -5
View File
@@ -64,7 +64,7 @@ extension FilePath {
} }
#if !os(Windows) #if !os(Windows)
// Note: This function should have been opaque, but it shipped as // Note: This function should have been opaque, but it shipped as
// `@_alwaysEmitIntoClient` in macOS 12/iOS 15, and now it is stuck // `@_alwaysEmitIntoClient` in macOS 12/iOS 15, and now it is stuck
// this way forever. (Or until the language provides a way for us // this way forever. (Or until the language provides a way for us
// to declare separate availability for a function's exported symbol // to declare separate availability for a function's exported symbol
@@ -84,7 +84,7 @@ extension FilePath {
/// Don't try to store the pointer for later use. /// Don't try to store the pointer for later use.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public func withPlatformString<Result>( public func withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result { ) rethrows -> Result {
return try withCString(body) return try withCString(body)
} }
@@ -102,7 +102,7 @@ extension FilePath {
/// only during the execution of this method. /// only during the execution of this method.
/// Don't try to store the pointer for later use. /// Don't try to store the pointer for later use.
public func withPlatformString<Result>( public func withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result { ) rethrows -> Result {
return try _withPlatformString(body) return try _withPlatformString(body)
} }
@@ -595,8 +595,8 @@ extension FilePath {
/// For backwards compatibility only. This function is equivalent to /// For backwards compatibility only. This function is equivalent to
/// the preferred `withPlatformString`. /// the preferred `withPlatformString`.
public func withCString<Result>( public func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws(SystemError) -> Result _ body: (UnsafePointer<CChar>) throws -> Result
) throws(SystemError) -> Result { ) rethrows -> Result {
return try _withPlatformString(body) return try _withPlatformString(body)
} }
} }
+6 -6
View File
@@ -20,8 +20,8 @@
/// deletes the directory and all of its contents before returning. /// deletes the directory and all of its contents before returning.
internal func withTemporaryFilePath<R>( internal func withTemporaryFilePath<R>(
basename: FilePath.Component, basename: FilePath.Component,
_ body: (FilePath) throws(SystemError) -> R _ body: (FilePath) throws -> R
) throws(SystemError) -> R { ) throws -> R {
let temporaryDir = try createUniqueTemporaryDirectory(basename: basename) let temporaryDir = try createUniqueTemporaryDirectory(basename: basename)
defer { defer {
try? _recursiveRemove(at: temporaryDir) try? _recursiveRemove(at: temporaryDir)
@@ -44,9 +44,9 @@ fileprivate let base64 = Array<UInt8>(
/// ///
/// This function will throw if there is an error, except if the error /// This function will throw if there is an error, except if the error
/// is that the directory exists, in which case it returns `false`. /// is that the directory exists, in which case it returns `false`.
fileprivate func makeLockedDownDirectory(at path: FilePath) throws(SystemError) -> Bool { fileprivate func makeLockedDownDirectory(at path: FilePath) throws -> Bool {
return try path.withPlatformString { (platformString) throws(SystemError) in return try path.withPlatformString {
if system_mkdir(platformString, 0o700) == 0 { if system_mkdir($0, 0o700) == 0 {
return true return true
} }
let err = system_errno let err = system_errno
@@ -83,7 +83,7 @@ fileprivate func createRandomString(length: Int) -> String {
/// string of characters. /// string of characters.
fileprivate func createUniqueTemporaryDirectory( fileprivate func createUniqueTemporaryDirectory(
basename: FilePath.Component basename: FilePath.Component
) throws(SystemError) -> FilePath { ) throws -> FilePath {
var tempDir = try _getTemporaryDirectory() var tempDir = try _getTemporaryDirectory()
tempDir.append(basename) tempDir.append(basename)
@@ -10,7 +10,7 @@
#if !os(Windows) #if !os(Windows)
/// Get the path to the system temporary directory. /// Get the path to the system temporary directory.
internal func _getTemporaryDirectory() throws(SystemError) -> FilePath { internal func _getTemporaryDirectory() throws -> FilePath {
guard let tmp = system_getenv("TMPDIR") else { guard let tmp = system_getenv("TMPDIR") else {
return "/tmp" return "/tmp"
} }
@@ -26,22 +26,22 @@ internal func _getTemporaryDirectory() throws(SystemError) -> FilePath {
/// Removes a directory completely, including all of its contents. /// Removes a directory completely, including all of its contents.
internal func _recursiveRemove( internal func _recursiveRemove(
at path: FilePath at path: FilePath
) throws(SystemError) { ) throws {
let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory) let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory)
defer { defer {
try? dirfd.close() try? dirfd.close()
} }
let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0) let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0)
try withUnsafeBytes(of: dot) { (bytes) throws(SystemError) in try withUnsafeBytes(of: dot) {
try recursiveRemove( try recursiveRemove(
in: dirfd.rawValue, in: dirfd.rawValue,
name: bytes.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress! name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress!
) )
} }
try path.withPlatformString { (platformString) throws(SystemError) in try path.withPlatformString {
if system_rmdir(platformString) != 0 { if system_rmdir($0) != 0 {
throw Errno.current throw Errno.current
} }
} }
@@ -81,8 +81,8 @@ fileprivate func impl_opendirat(
fileprivate func forEachFile( fileprivate func forEachFile(
in dirfd: CInt, in dirfd: CInt,
subdir: UnsafePointer<CInterop.PlatformChar>, subdir: UnsafePointer<CInterop.PlatformChar>,
_ body: (system_dirent) throws(SystemError) -> () _ body: (system_dirent) throws -> ()
) throws(SystemError) { ) throws {
guard let dir = impl_opendirat(dirfd, subdir) else { guard let dir = impl_opendirat(dirfd, subdir) else {
throw Errno.current throw Errno.current
} }
@@ -113,7 +113,7 @@ fileprivate func forEachFile(
fileprivate func recursiveRemove( fileprivate func recursiveRemove(
in dirfd: CInt, in dirfd: CInt,
name: UnsafePointer<CInterop.PlatformChar> name: UnsafePointer<CInterop.PlatformChar>
) throws(SystemError) { ) throws {
// First, deal with subdirectories // First, deal with subdirectories
try forEachFile(in: dirfd, subdir: name) { dirent in try forEachFile(in: dirfd, subdir: name) { dirent in
if dirent.d_type == SYSTEM_DT_DIR { if dirent.d_type == SYSTEM_DT_DIR {
@@ -73,7 +73,7 @@ internal func _recursiveRemove(
) throws { ) throws {
// First, deal with subdirectories // First, deal with subdirectories
try forEachFile(at: path) { findData in try forEachFile(at: path) { findData in
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 {
let name = withUnsafeBytes(of: findData.cFileName) { let name = withUnsafeBytes(of: findData.cFileName) {
return SystemString(platformString: $0.assumingMemoryBound( return SystemString(platformString: $0.assumingMemoryBound(
to: CInterop.PlatformChar.self).baseAddress!) to: CInterop.PlatformChar.self).baseAddress!)
@@ -94,7 +94,7 @@ internal func _recursiveRemove(
let component = FilePath.Component(name)! let component = FilePath.Component(name)!
let subpath = path.appending(component) let subpath = path.appending(component)
if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 {
try subpath.withPlatformString { subpath in try subpath.withPlatformString { subpath in
if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) { if try !subpath.withCanonicalPathRepresentation({ DeleteFileW($0) }) {
throw Errno(windowsError: GetLastError()) throw Errno(windowsError: GetLastError())
@@ -517,7 +517,7 @@ fileprivate func HRESULT_CODE(_ hr: HRESULT) -> DWORD {
@inline(__always) @inline(__always)
fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD { fileprivate func HRESULT_FACILITY(_ hr: HRESULT) -> DWORD {
DWORD(hr << 16) & 0x1fff DWORD(hr >> 16) & 0x1fff
} }
@inline(__always) @inline(__always)
@@ -529,7 +529,7 @@ fileprivate func SUCCEEDED(_ hr: HRESULT) -> Bool {
// an HRESULT to a Win32 error code. // an HRESULT to a Win32 error code.
@inline(__always) @inline(__always)
fileprivate func WIN32_FROM_HRESULT(_ hr: HRESULT) -> DWORD { fileprivate func WIN32_FROM_HRESULT(_ hr: HRESULT) -> DWORD {
if SUCCEEDED(hr) { return DWORD(ERROR_SUCCESS) } if SUCCEEDED(hr) { return ERROR_SUCCESS }
if HRESULT_FACILITY(hr) == FACILITY_WIN32 { if HRESULT_FACILITY(hr) == FACILITY_WIN32 {
return HRESULT_CODE(hr) return HRESULT_CODE(hr)
} }
+1 -6
View File
@@ -18,7 +18,7 @@
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true /// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
@frozen @frozen
@available(System 0.0.1, *) @available(System 0.0.1, *)
public struct FilePermissions: OptionSet, Sendable, Hashable { public struct FilePermissions: OptionSet, Sendable, Hashable, Codable {
/// The raw C file permissions. /// The raw C file permissions.
@_alwaysEmitIntoClient @_alwaysEmitIntoClient
public let rawValue: CModeT public let rawValue: CModeT
@@ -172,8 +172,3 @@ extension FilePermissions
/// A textual representation of the file permissions, suitable for debugging. /// A textual representation of the file permissions, suitable for debugging.
public var debugDescription: String { self.description } public var debugDescription: String { self.description }
} }
#if !$Embedded
@available(System 0.0.1, *)
extension FilePermissions: Codable {}
#endif
+7 -18
View File
@@ -320,7 +320,7 @@ extension IORing.Request {
* ASYNC_CANCEL flags. * ASYNC_CANCEL flags.
* *
* IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key * IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key
* IORING_ASYNC_CANCEL_FD Key off 'fd' for cancellation rather than the * IORING_ASYNC_CANCEL_FD Key off 'fd' for cancelation rather than the
* request 'user_data' * request 'user_data'
* IORING_ASYNC_CANCEL_ANY Match any request * IORING_ASYNC_CANCEL_ANY Match any request
* IORING_ASYNC_CANCEL_FD_FIXED 'fd' passed in is a fixed descriptor * IORING_ASYNC_CANCEL_FD_FIXED 'fd' passed in is a fixed descriptor
@@ -388,7 +388,9 @@ extension IORing.Request {
} }
@inline(__always) @inlinable @inline(__always) @inlinable
internal consuming func makeRawRequest() -> RawIORequest { internal consuming func makeRawRequest(
pathBuffers: PendingPathBuffers
) -> RawIORequest {
var request = RawIORequest() var request = RawIORequest()
switch extractCore() { switch extractCore() {
case .nop: case .nop:
@@ -400,27 +402,19 @@ extension IORing.Request {
request.operation = .openAt request.operation = .openAt
request.fileDescriptor = atDirectory request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64( request.rawValue.addr = UInt64(
UInt( UInt(bitPattern: pathBuffers.pin(path)))
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.len = permissions?.rawValue ?? 0
request.rawValue.file_index = UInt32(fileSlot.index + 1) request.rawValue.file_index = UInt32(fileSlot.index + 1)
request.path = path
request.rawValue.user_data = context request.rawValue.user_data = context
case .openat( case .openat(
let atDirectory, let path, let mode, let options, let permissions, let context): let atDirectory, let path, let mode, let options, let permissions, let context):
request.operation = .openAt request.operation = .openAt
request.fileDescriptor = atDirectory request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64( request.rawValue.addr = UInt64(
UInt( UInt(bitPattern: pathBuffers.pin(path)))
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
}))
request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue)
request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.len = permissions?.rawValue ?? 0
request.path = path
request.rawValue.user_data = context request.rawValue.user_data = context
case .write(let file, let buffer, let offset, let context): case .write(let file, let buffer, let offset, let context):
request.operation = .writeFixed request.operation = .writeFixed
@@ -466,12 +460,7 @@ extension IORing.Request {
request.operation = .unlinkAt request.operation = .unlinkAt
request.fileDescriptor = atDirectory request.fileDescriptor = atDirectory
request.rawValue.addr = UInt64( request.rawValue.addr = UInt64(
UInt( UInt(bitPattern: pathBuffers.pin(path)))
bitPattern: path.withPlatformString { ptr in
ptr //this is unsavory, but we keep it alive by storing path alongside it in the request
})
)
request.path = path
request.rawValue.user_data = context request.rawValue.user_data = context
case .cancelContext(let flags, let targetContext): case .cancelContext(let flags, let targetContext):
request.operation = .asyncCancel request.operation = .asyncCancel
+54 -6
View File
@@ -41,6 +41,33 @@ extension UnsafeMutableRawBufferPointer {
} }
} }
/// Owns the FilePaths whose interior pointers have been written into pending
/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to
/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap
/// This is a class purely to avoid making methods calling `pin` mutating, which would be an API break
@usableFromInline
internal final class PendingPathBuffers {
@usableFromInline
var paths: [FilePath] = []
init(reservedCapacity: Int) {
paths.reserveCapacity(reservedCapacity)
}
@usableFromInline
func pin(_ path: FilePath) -> UnsafePointer<CInterop.PlatformChar> {
paths.append(path)
// Safe to escape: `paths` keeps the FilePath (and its underlying
// [SystemChar] buffer) alive until clear() or class deinit.
return paths.last!.withPlatformString { $0 }
}
@usableFromInline
func clear() {
paths.removeAll(keepingCapacity: true)
}
}
// all pointers in this struct reference kernel-visible memory // all pointers in this struct reference kernel-visible memory
@usableFromInline struct SQRing: ~Copyable { @usableFromInline struct SQRing: ~Copyable {
@usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>> @usableFromInline let kernelHead: UnsafePointer<Atomic<UInt32>>
@@ -200,7 +227,14 @@ private func setUpRing(
throw err throw err
} }
if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0 // We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced
// pathnames (and other inline data) out of userspace before io_uring_enter
// returns; the path-buffer side store on IORing relies on this to free
// path buffers as soon as a submission completes.
let requiredFeatures =
IORing.Features.nonDroppingCompletions.rawValue
| IORing.Features.stableSubmissions.rawValue
if params.features & requiredFeatures != requiredFeatures
{ {
close(ringDescriptor) close(ringDescriptor)
throw Errno.invalidArgument throw Errno.invalidArgument
@@ -324,6 +358,8 @@ public struct IORing: ~Copyable {
@usableFromInline var _registeredFiles: [UInt32] @usableFromInline var _registeredFiles: [UInt32]
@usableFromInline var _registeredBuffers: [iovec] @usableFromInline var _registeredBuffers: [iovec]
@usableFromInline let _pendingPathBuffers: PendingPathBuffers
var features = Features(rawValue: 0) var features = Features(rawValue: 0)
/// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them. /// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them.
@@ -444,6 +480,7 @@ public struct IORing: ~Copyable {
self.completionRingSize = tmpCQSize self.completionRingSize = tmpCQSize
self._registeredFiles = [] self._registeredFiles = []
self._registeredBuffers = [] self._registeredBuffers = []
self._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries))
self.submissionRing = submissionRing self.submissionRing = submissionRing
self.completionRing = completionRing self.completionRing = completionRing
self.submissionQueueEntries = submissionQueueEntries self.submissionQueueEntries = submissionQueueEntries
@@ -765,6 +802,10 @@ public struct IORing: ~Copyable {
@inlinable @inlinable
public func submitPreparedRequests() throws(Errno) { public func submitPreparedRequests() throws(Errno) {
try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor)
// IORING_FEAT_SUBMIT_STABLE guarantees the kernel has copied any
// SQE-referenced data (e.g. openat/unlinkAt pathnames) before
// io_uring_enter returns; safe to release path storage now.
_pendingPathBuffers.clear()
} }
/// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available. /// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available.
@@ -790,9 +831,14 @@ public struct IORing: ~Copyable {
/// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request /// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request
@inlinable @inlinable
public mutating func prepare(request: __owned Request) -> Bool { public mutating func prepare(request: __owned Request) -> Bool {
var raw: RawIORequest? = request.makeRawRequest() guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else {
return _tryWriteRequest( return false
}
var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers)
let ok = _tryWriteRequest(
raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(ok)
return ok
} }
/// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. /// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order.
@@ -806,18 +852,20 @@ public struct IORing: ~Copyable {
return false return false
} }
let last = linkedRequests.last! let last = linkedRequests.last!
var allAdded = true
for req in linkedRequests.dropLast() { for req in linkedRequests.dropLast() {
var raw = req.makeRawRequest() var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers)
raw.linkToNextRequest() raw.linkToNextRequest()
let successfullyAdded = _tryWriteRequest( let successfullyAdded = _tryWriteRequest(
raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded) assert(successfullyAdded)
allAdded = allAdded && successfullyAdded
} }
let successfullyAdded = _tryWriteRequest( let successfullyAdded = _tryWriteRequest(
last.makeRawRequest(), ring: &submissionRing, last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing,
submissionQueueEntries: submissionQueueEntries) submissionQueueEntries: submissionQueueEntries)
assert(successfullyAdded) assert(successfullyAdded)
return true return allAdded && successfullyAdded
} }
/// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space. /// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space.
-1
View File
@@ -8,7 +8,6 @@ internal struct RawIORequest: ~Copyable {
// swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where // swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where
// IORing is supported (currently requires kernel version >= 5.15). // IORing is supported (currently requires kernel version >= 5.15).
@usableFromInline var rawValue: swift_io_uring_sqe @usableFromInline var rawValue: swift_io_uring_sqe
@usableFromInline var path: FilePath? //buffer owner for the path pointer that the sqe may have
@inlinable public init() { @inlinable public init() {
self.rawValue = swift_io_uring_sqe() self.rawValue = swift_io_uring_sqe()
+3 -3
View File
@@ -116,9 +116,9 @@ internal func system_memset(
// Interop between String and platfrom string // Interop between String and platfrom string
extension String { extension String {
internal func _withPlatformString<Success, Failure: Error>( internal func _withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(Failure) -> Success _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) throws(Failure) -> Success { ) rethrows -> Result {
// Need to #if because CChar may be signed // Need to #if because CChar may be signed
#if os(Windows) #if os(Windows)
return try withCString(encodedAs: CInterop.PlatformUnicodeEncoding.self, body) return try withCString(encodedAs: CInterop.PlatformUnicodeEncoding.self, body)
+9 -9
View File
@@ -17,7 +17,7 @@
// enabled in testing builds of System currently, to minimize runtime overhead of release builds. // enabled in testing builds of System currently, to minimize runtime overhead of release builds.
// //
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
internal struct Trace { internal struct Trace {
internal struct Entry { internal struct Entry {
@@ -115,12 +115,12 @@ extension MockingDriver {
} }
} }
#endif // ENABLE_MOCKING && !$Embedded #endif // ENABLE_MOCKING
@inline(__always) @inline(__always)
internal var mockingEnabled: Bool { internal var mockingEnabled: Bool {
// Fast constant-foldable check for release builds // Fast constant-foldable check for release builds
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
return contextualMockingEnabled return contextualMockingEnabled
#else #else
return false return false
@@ -129,15 +129,15 @@ internal var mockingEnabled: Bool {
@inline(__always) @inline(__always)
internal var forceWindowsPaths: Bool? { internal var forceWindowsPaths: Bool? {
#if ENABLE_MOCKING && !$Embedded #if !ENABLE_MOCKING
return MockingDriver.forceWindowsPaths
#else
return nil return nil
#else
return MockingDriver.forceWindowsPaths
#endif #endif
} }
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
// Strip the mock_system prefix and the arg list suffix // Strip the mock_system prefix and the arg list suffix
private func originalSyscallName(_ function: String) -> String { private func originalSyscallName(_ function: String) -> String {
// `function` must be of format `system_<name>(<parameters>)` // `function` must be of format `system_<name>(<parameters>)`
@@ -193,12 +193,12 @@ internal func _mockOffT(
) -> _COffT { ) -> _COffT {
_COffT(mockImpl(name: name, path: path, args)) _COffT(mockImpl(name: name, path: path, args))
} }
#endif // ENABLE_MOCKING && !$Embedded #endif // ENABLE_MOCKING
// Force paths to be treated as Windows syntactically if `enabled` is // Force paths to be treated as Windows syntactically if `enabled` is
// true, and as POSIX syntactically if not. // true, and as POSIX syntactically if not.
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) { internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
MockingDriver.withMockingEnabled { driver in MockingDriver.withMockingEnabled { driver in
driver.forceWindowsSyntaxForPaths = enabled driver.forceWindowsSyntaxForPaths = enabled
body() body()
+16 -16
View File
@@ -31,7 +31,7 @@ import Android
internal func system_open( internal func system_open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32 _ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
) -> CInt { ) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { if mockingEnabled {
return _mock(path: path, oflag) return _mock(path: path, oflag)
} }
@@ -43,7 +43,7 @@ internal func system_open(
_ path: UnsafePointer<CInterop.PlatformChar>, _ path: UnsafePointer<CInterop.PlatformChar>,
_ oflag: Int32, _ mode: CInterop.Mode _ oflag: Int32, _ mode: CInterop.Mode
) -> CInt { ) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { if mockingEnabled {
return _mock(path: path, oflag, mode) return _mock(path: path, oflag, mode)
} }
@@ -53,7 +53,7 @@ internal func system_open(
// close // close
internal func system_close(_ fd: Int32) -> Int32 { internal func system_close(_ fd: Int32) -> Int32 {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(fd) } if mockingEnabled { return _mock(fd) }
#endif #endif
return close(fd) return close(fd)
@@ -63,7 +63,7 @@ internal func system_close(_ fd: Int32) -> Int32 {
internal func system_read( internal func system_read(
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int _ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int
) -> Int { ) -> Int {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte) } if mockingEnabled { return _mockInt(fd, buf, nbyte) }
#endif #endif
return read(fd, buf, nbyte) return read(fd, buf, nbyte)
@@ -73,7 +73,7 @@ internal func system_read(
internal func system_pread( internal func system_pread(
_ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int, _ offset: off_t _ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int, _ offset: off_t
) -> Int { ) -> Int {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif #endif
#if os(Android) #if os(Android)
@@ -91,7 +91,7 @@ internal func system_pread(
internal func system_lseek( internal func system_lseek(
_ fd: Int32, _ off: off_t, _ whence: Int32 _ fd: Int32, _ off: off_t, _ whence: Int32
) -> off_t { ) -> off_t {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mockOffT(fd, off, whence) } if mockingEnabled { return _mockOffT(fd, off, whence) }
#endif #endif
return lseek(fd, off, whence) return lseek(fd, off, whence)
@@ -101,7 +101,7 @@ internal func system_lseek(
internal func system_write( internal func system_write(
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int _ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int
) -> Int { ) -> Int {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte) } if mockingEnabled { return _mockInt(fd, buf, nbyte) }
#endif #endif
return write(fd, buf, nbyte) return write(fd, buf, nbyte)
@@ -111,7 +111,7 @@ internal func system_write(
internal func system_pwrite( internal func system_pwrite(
_ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int, _ offset: off_t _ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int, _ offset: off_t
) -> Int { ) -> Int {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif #endif
#if os(Android) #if os(Android)
@@ -127,14 +127,14 @@ internal func system_pwrite(
#if !os(WASI) #if !os(WASI)
internal func system_dup(_ fd: Int32) -> Int32 { internal func system_dup(_ fd: Int32) -> Int32 {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(fd) } if mockingEnabled { return _mock(fd) }
#endif #endif
return dup(fd) return dup(fd)
} }
internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 { internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, fd2) } if mockingEnabled { return _mock(fd, fd2) }
#endif #endif
return dup2(fd, fd2) return dup2(fd, fd2)
@@ -143,7 +143,7 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
#if !os(WASI) #if !os(WASI)
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt { internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(fds) } if mockingEnabled { return _mock(fds) }
#endif #endif
return pipe(fds) return pipe(fds)
@@ -151,7 +151,7 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#endif #endif
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, length) } if mockingEnabled { return _mock(fd, length) }
#endif #endif
return ftruncate(fd, length) return ftruncate(fd, length)
@@ -161,7 +161,7 @@ internal func system_mkdir(
_ path: UnsafePointer<CInterop.PlatformChar>, _ path: UnsafePointer<CInterop.PlatformChar>,
_ mode: CInterop.Mode _ mode: CInterop.Mode
) -> CInt { ) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(path: path, mode) } if mockingEnabled { return _mock(path: path, mode) }
#endif #endif
return mkdir(path, mode) return mkdir(path, mode)
@@ -170,7 +170,7 @@ internal func system_mkdir(
internal func system_rmdir( internal func system_rmdir(
_ path: UnsafePointer<CInterop.PlatformChar> _ path: UnsafePointer<CInterop.PlatformChar>
) -> CInt { ) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(path: path) } if mockingEnabled { return _mock(path: path) }
#endif #endif
return rmdir(path) return rmdir(path)
@@ -208,7 +208,7 @@ internal func system_unlinkat(
_ path: UnsafePointer<CInterop.PlatformChar>, _ path: UnsafePointer<CInterop.PlatformChar>,
_ flag: CInt _ flag: CInt
) -> CInt { ) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { return _mock(fd, path, flag) } if mockingEnabled { return _mock(fd, path, flag) }
#endif #endif
return unlinkat(fd, path, flag) return unlinkat(fd, path, flag)
@@ -247,7 +247,7 @@ internal func system_openat(
_ path: UnsafePointer<CInterop.PlatformChar>, _ path: UnsafePointer<CInterop.PlatformChar>,
_ oflag: Int32 _ oflag: Int32
) -> CInt { ) -> CInt {
#if ENABLE_MOCKING && !$Embedded #if ENABLE_MOCKING
if mockingEnabled { if mockingEnabled {
return _mock(fd, path, oflag) return _mock(fd, path, oflag)
} }
@@ -38,9 +38,9 @@ internal func open(
guard let hFile = try? path.withCanonicalPathRepresentation({ path in guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path, CreateFileW(path,
decodedFlags.dwDesiredAccess, decodedFlags.dwDesiredAccess,
DWORD(FILE_SHARE_DELETE FILE_SHARE_DELETE
| FILE_SHARE_READ | FILE_SHARE_READ
| FILE_SHARE_WRITE), | FILE_SHARE_WRITE,
&saAttrs, &saAttrs,
decodedFlags.dwCreationDisposition, decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes, decodedFlags.dwFlagsAndAttributes,
@@ -80,9 +80,9 @@ internal func open(
guard let hFile = try? path.withCanonicalPathRepresentation({ path in guard let hFile = try? path.withCanonicalPathRepresentation({ path in
CreateFileW(path, CreateFileW(path,
decodedFlags.dwDesiredAccess, decodedFlags.dwDesiredAccess,
DWORD(FILE_SHARE_DELETE FILE_SHARE_DELETE
| FILE_SHARE_READ | FILE_SHARE_READ
| FILE_SHARE_WRITE), | FILE_SHARE_WRITE,
&saAttrs, &saAttrs,
decodedFlags.dwCreationDisposition, decodedFlags.dwCreationDisposition,
decodedFlags.dwFlagsAndAttributes, decodedFlags.dwFlagsAndAttributes,
@@ -135,7 +135,11 @@ internal func dup(_ fd: Int32) -> Int32 {
@inline(__always) @inline(__always)
internal func dup2(_ fd: Int32, _ fd2: Int32) -> Int32 { internal func dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
_dup2(fd, fd2) // _dup2 returns 0 to indicate success.
if _dup2(fd, fd2) == 0 {
return fd2
}
return -1
} }
@inline(__always) @inline(__always)
@@ -145,6 +149,12 @@ internal func pread(
let handle: intptr_t = _get_osfhandle(fd) let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 } if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows ReadFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it // NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)! let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -167,6 +177,12 @@ internal func pwrite(
let handle: intptr_t = _get_osfhandle(fd) let handle: intptr_t = _get_osfhandle(fd)
if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 } if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 }
// Windows WriteFile accepts DWORD (32-bit) for buffer size, so validate nbyte doesn't exceed it
if nbyte > Int(DWORD.max) {
ucrt._set_errno(EINVAL)
return -1
}
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it // NOTE: this is a non-owning handle, do *not* call CloseHandle on it
let hFile: HANDLE = HANDLE(bitPattern: handle)! let hFile: HANDLE = HANDLE(bitPattern: handle)!
@@ -202,16 +218,16 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
// Save the current position and restore it when we're done // Save the current position and restore it when we're done
if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset, if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset,
DWORD(FILE_CURRENT)) { FILE_CURRENT) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1 return -1
} }
defer { defer {
_ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN)); _ = SetFilePointerEx(hFile, liCurrentOffset, nil, FILE_BEGIN);
} }
// Truncate (or extend) the file // Truncate (or extend) the file
if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN)) if !SetFilePointerEx(hFile, liDesiredLength, nil, FILE_BEGIN)
|| !SetEndOfFile(hFile) { || !SetEndOfFile(hFile) {
ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError()))
return -1 return -1
@@ -263,7 +279,7 @@ internal func rmdir(
} }
internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt {
switch Int32(errorCode) { switch errorCode {
case ERROR_SUCCESS: case ERROR_SUCCESS:
return 0 return 0
case ERROR_INVALID_FUNCTION, case ERROR_INVALID_FUNCTION,
@@ -342,28 +358,28 @@ fileprivate func rightsFromModeBits(
var rights: DWORD = 0 var rights: DWORD = 0
if (bits & 0o4) != 0 { if (bits & 0o4) != 0 {
rights |= DWORD(FILE_READ_ATTRIBUTES rights |= (FILE_READ_ATTRIBUTES
| FILE_READ_DATA | FILE_READ_DATA
| FILE_READ_EA | FILE_READ_EA
| STANDARD_RIGHTS_READ | STANDARD_RIGHTS_READ
| SYNCHRONIZE) | SYNCHRONIZE)
} }
if (bits & 0o2) != 0 { if (bits & 0o2) != 0 {
rights |= DWORD(FILE_APPEND_DATA rights |= (FILE_APPEND_DATA
| FILE_WRITE_ATTRIBUTES | FILE_WRITE_ATTRIBUTES
| FILE_WRITE_DATA | FILE_WRITE_DATA
| FILE_WRITE_EA | FILE_WRITE_EA
| STANDARD_RIGHTS_WRITE | STANDARD_RIGHTS_WRITE
| SYNCHRONIZE) | SYNCHRONIZE)
if fileOrDirectory == .directory && !sticky { if fileOrDirectory == .directory && !sticky {
rights |= DWORD(FILE_DELETE_CHILD) rights |= FILE_DELETE_CHILD
} }
} }
if (bits & 0o1) != 0 { if (bits & 0o1) != 0 {
rights |= DWORD(FILE_EXECUTE rights |= (FILE_EXECUTE
| FILE_READ_ATTRIBUTES | FILE_READ_ATTRIBUTES
| STANDARD_RIGHTS_EXECUTE | STANDARD_RIGHTS_EXECUTE
| SYNCHRONIZE) | SYNCHRONIZE)
} }
return rights return rights
@@ -431,7 +447,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var everyone: PSID? = nil var everyone: PSID? = nil
guard AllocateAndInitializeSid(&SIDAuthWorld, 1, guard AllocateAndInitializeSid(&SIDAuthWorld, 1,
DWORD(SECURITY_WORLD_RID), SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&everyone) else { &everyone) else {
return nil return nil
@@ -472,7 +488,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W( EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerRights, grfAccessPermissions: ownerRights,
grfAccessMode: GRANT_ACCESS, grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE), grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W( Trustee: TRUSTEE_W(
pMultipleTrustee: nil, pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -485,7 +501,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W( EXPLICIT_ACCESS_W(
grfAccessPermissions: groupRights, grfAccessPermissions: groupRights,
grfAccessMode: GRANT_ACCESS, grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE), grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W( Trustee: TRUSTEE_W(
pMultipleTrustee: nil, pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -498,7 +514,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W( EXPLICIT_ACCESS_W(
grfAccessPermissions: otherRights, grfAccessPermissions: otherRights,
grfAccessMode: GRANT_ACCESS, grfAccessMode: GRANT_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE), grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W( Trustee: TRUSTEE_W(
pMultipleTrustee: nil, pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -515,7 +531,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W( EXPLICIT_ACCESS_W(
grfAccessPermissions: ownerDenyRights, grfAccessPermissions: ownerDenyRights,
grfAccessMode: DENY_ACCESS, grfAccessMode: DENY_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE), grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W( Trustee: TRUSTEE_W(
pMultipleTrustee: nil, pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -533,7 +549,7 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
EXPLICIT_ACCESS_W( EXPLICIT_ACCESS_W(
grfAccessPermissions: groupDenyRights, grfAccessPermissions: groupDenyRights,
grfAccessMode: DENY_ACCESS, grfAccessMode: DENY_ACCESS,
grfInheritance: DWORD(NO_INHERITANCE), grfInheritance: NO_INHERITANCE,
Trustee: TRUSTEE_W( Trustee: TRUSTEE_W(
pMultipleTrustee: nil, pMultipleTrustee: nil,
MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
@@ -562,13 +578,13 @@ internal func _createSecurityDescriptor(from mode: CInterop.Mode,
var descriptor = SECURITY_DESCRIPTOR() var descriptor = SECURITY_DESCRIPTOR()
guard InitializeSecurityDescriptor(&descriptor, guard InitializeSecurityDescriptor(&descriptor,
DWORD(SECURITY_DESCRIPTOR_REVISION)) else { SECURITY_DESCRIPTOR_REVISION) else {
return nil return nil
} }
guard SetSecurityDescriptorControl(&descriptor, guard SetSecurityDescriptorControl(&descriptor,
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED), SE_DACL_PROTECTED,
SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED)) SE_DACL_PROTECTED)
&& SetSecurityDescriptorOwner(&descriptor, user, false) && SetSecurityDescriptorOwner(&descriptor, user, false)
&& SetSecurityDescriptorGroup(&descriptor, group, false) && SetSecurityDescriptorGroup(&descriptor, group, false)
&& SetSecurityDescriptorDacl(&descriptor, && SetSecurityDescriptorDacl(&descriptor,
@@ -608,15 +624,15 @@ fileprivate struct DecodedOpenFlags {
init(_ oflag: Int32) { init(_ oflag: Int32) {
switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) { switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) {
case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC: case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC:
dwCreationDisposition = DWORD(CREATE_NEW) dwCreationDisposition = CREATE_NEW
case _O_CREAT: case _O_CREAT:
dwCreationDisposition = DWORD(OPEN_ALWAYS) dwCreationDisposition = OPEN_ALWAYS
case _O_CREAT | _O_TRUNC: case _O_CREAT | _O_TRUNC:
dwCreationDisposition = DWORD(CREATE_ALWAYS) dwCreationDisposition = CREATE_ALWAYS
case _O_TRUNC: case _O_TRUNC:
dwCreationDisposition = DWORD(TRUNCATE_EXISTING) dwCreationDisposition = TRUNCATE_EXISTING
default: default:
dwCreationDisposition = DWORD(OPEN_EXISTING) dwCreationDisposition = OPEN_EXISTING
} }
// The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping // The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping
@@ -625,11 +641,11 @@ fileprivate struct DecodedOpenFlags {
dwDesiredAccess = 0 dwDesiredAccess = 0
switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) { switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) {
case _O_RDONLY: case _O_RDONLY:
dwDesiredAccess |= DWORD(GENERIC_READ) dwDesiredAccess |= GENERIC_READ
case _O_WRONLY: case _O_WRONLY:
dwDesiredAccess |= DWORD(GENERIC_WRITE) dwDesiredAccess |= GENERIC_WRITE
case _O_RDWR: case _O_RDWR:
dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE) dwDesiredAccess |= GENERIC_READ | GENERIC_WRITE
default: default:
break break
} }
@@ -638,19 +654,19 @@ fileprivate struct DecodedOpenFlags {
dwFlagsAndAttributes = 0 dwFlagsAndAttributes = 0
if (oflag & _O_SEQUENTIAL) != 0 { if (oflag & _O_SEQUENTIAL) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN) dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN
} }
if (oflag & _O_RANDOM) != 0 { if (oflag & _O_RANDOM) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS) dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS
} }
if (oflag & _O_TEMPORARY) != 0 { if (oflag & _O_TEMPORARY) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE) dwFlagsAndAttributes |= FILE_FLAG_DELETE_ON_CLOSE
} }
if (oflag & _O_SHORT_LIVED) != 0 { if (oflag & _O_SHORT_LIVED) != 0 {
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY) dwFlagsAndAttributes |= FILE_ATTRIBUTE_TEMPORARY
} else { } else {
dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL) dwFlagsAndAttributes |= FILE_ATTRIBUTE_NORMAL
} }
} }
} }
+4 -4
View File
@@ -158,8 +158,8 @@ extension String {
/// only during the execution of this method. /// only during the execution of this method.
/// Don't try to store the pointer for later use. /// Don't try to store the pointer for later use.
public func withPlatformString<Result>( public func withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) throws(SystemError) -> Result { ) rethrows -> Result {
try _withPlatformString(body) try _withPlatformString(body)
} }
@@ -189,8 +189,8 @@ extension CInterop.PlatformUnicodeEncoding.CodeUnit {
internal protocol _PlatformStringable { internal protocol _PlatformStringable {
func _withPlatformString<Result>( func _withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws(SystemError) -> Result _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) throws(SystemError) -> Result ) rethrows -> Result
init?(_platformString: UnsafePointer<CInterop.PlatformChar>) init?(_platformString: UnsafePointer<CInterop.PlatformChar>)
} }
+4 -16
View File
@@ -9,7 +9,7 @@
// A platform-native character representation, currently used for file paths // A platform-native character representation, currently used for file paths
internal struct SystemChar: internal struct SystemChar:
RawRepresentable, Sendable, Comparable, Hashable { RawRepresentable, Sendable, Comparable, Hashable, Codable {
internal typealias RawValue = CInterop.PlatformChar internal typealias RawValue = CInterop.PlatformChar
internal var rawValue: RawValue internal var rawValue: RawValue
@@ -23,12 +23,6 @@ internal struct SystemChar:
} }
} }
#if !$Embedded
extension SystemChar: Codable {}
#endif // !$Embedded
extension SystemChar { extension SystemChar {
internal init(ascii: Unicode.Scalar) { internal init(ascii: Unicode.Scalar) {
self.init(rawValue: numericCast(UInt8(ascii: ascii))) self.init(rawValue: numericCast(UInt8(ascii: ascii)))
@@ -110,7 +104,7 @@ extension SystemString {
} }
return true return true
} }
fileprivate func _invariantCheck() { fileprivate func _invariantCheck() {
#if DEBUG #if DEBUG
precondition(_invariantsSatisfied()) precondition(_invariantsSatisfied())
@@ -179,14 +173,10 @@ extension SystemString: RangeReplaceableCollection {
} }
} }
extension SystemString: Hashable {} extension SystemString: Hashable, Codable {
#if !$Embedded
extension SystemString: Codable {
// Encoder is synthesized; it probably should have been explicit and used // Encoder is synthesized; it probably should have been explicit and used
// a single-value container, but making that change now is somewhat risky. // a single-value container, but making that change now is somewhat risky.
// Decoder is written explicitly to ensure that we validate invariants on // Decoder is written explicitly to ensure that we validate invariants on
// untrusted input. // untrusted input.
public init(from decoder: any Decoder) throws { public init(from decoder: any Decoder) throws {
@@ -205,8 +195,6 @@ extension SystemString: Codable {
} }
} }
#endif // !$Embedded
extension SystemString { extension SystemString {
internal func withNullTerminatedSystemChars<T>( internal func withNullTerminatedSystemChars<T>(
-4
View File
@@ -43,8 +43,6 @@ internal func nothingOrErrno<I: FixedWidthInteger>(
valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () } valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () }
} }
#if !$Embedded
// Run a precondition for debug client builds // Run a precondition for debug client builds
internal func _debugPrecondition( internal func _debugPrecondition(
_ condition: @autoclosure () -> Bool, _ condition: @autoclosure () -> Bool,
@@ -58,8 +56,6 @@ internal func _debugPrecondition(
} }
} }
#endif // !$Embedded
extension OpaquePointer { extension OpaquePointer {
internal var _isNULL: Bool { internal var _isNULL: Bool {
OpaquePointer(bitPattern: Int(bitPattern: self)) == nil OpaquePointer(bitPattern: Int(bitPattern: self)) == nil
+2 -2
View File
@@ -52,13 +52,13 @@ extension Slice where Element: Equatable {
return self[...idx] return self[...idx]
} }
// If `e` is present, eat up to first occurrence of `e` // If `e` is present, eat up to first occurence of `e`
internal mutating func _eatUntil(_ e: Element) -> Slice? { internal mutating func _eatUntil(_ e: Element) -> Slice? {
guard let idx = self.firstIndex(of: e) else { return nil } guard let idx = self.firstIndex(of: e) else { return nil }
return _eatUntil(idx) return _eatUntil(idx)
} }
// If `e` is present, eat up to and through first occurrence of `e` // If `e` is present, eat up to and through first occurence of `e`
internal mutating func _eatThrough(_ e: Element) -> Slice? { internal mutating func _eatThrough(_ e: Element) -> Slice? {
guard let idx = self.firstIndex(of: e) else { return nil } guard let idx = self.firstIndex(of: e) else { return nil }
return _eatThrough(idx) return _eatThrough(idx)
+439
View File
@@ -0,0 +1,439 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2024 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if os(Windows)
import WinSDK
@_transparent
internal var CREATE_ALWAYS: DWORD {
DWORD(WinSDK.CREATE_ALWAYS)
}
@_transparent
internal var CREATE_NEW: DWORD {
DWORD(WinSDK.CREATE_NEW)
}
@_transparent
internal var ERROR_ACCESS_DENIED: DWORD {
DWORD(WinSDK.ERROR_ACCESS_DENIED)
}
@_transparent
internal var ERROR_ALREADY_EXISTS: DWORD {
DWORD(WinSDK.ERROR_ALREADY_EXISTS)
}
@_transparent
internal var ERROR_ARENA_TRASHED: DWORD {
DWORD(WinSDK.ERROR_ARENA_TRASHED)
}
@_transparent
internal var ERROR_BAD_ENVIRONMENT: DWORD {
DWORD(WinSDK.ERROR_BAD_ENVIRONMENT)
}
@_transparent
internal var ERROR_BAD_FORMAT: DWORD {
DWORD(WinSDK.ERROR_BAD_FORMAT)
}
@_transparent
internal var ERROR_BAD_NET_NAME: DWORD {
DWORD(WinSDK.ERROR_BAD_NET_NAME)
}
@_transparent
internal var ERROR_BAD_NETPATH: DWORD {
DWORD(WinSDK.ERROR_BAD_NETPATH)
}
@_transparent
internal var ERROR_BAD_PATHNAME: DWORD {
DWORD(WinSDK.ERROR_BAD_PATHNAME)
}
@_transparent
internal var ERROR_BROKEN_PIPE: DWORD {
DWORD(WinSDK.ERROR_BROKEN_PIPE)
}
@_transparent
internal var ERROR_CANNOT_MAKE: DWORD {
DWORD(WinSDK.ERROR_CANNOT_MAKE)
}
@_transparent
internal var ERROR_CHILD_NOT_COMPLETE: DWORD {
DWORD(WinSDK.ERROR_CHILD_NOT_COMPLETE)
}
@_transparent
internal var ERROR_CURRENT_DIRECTORY: DWORD {
DWORD(WinSDK.ERROR_CURRENT_DIRECTORY)
}
@_transparent
internal var ERROR_DIR_NOT_EMPTY: DWORD {
DWORD(WinSDK.ERROR_DIR_NOT_EMPTY)
}
@_transparent
internal var ERROR_DISK_FULL: DWORD {
DWORD(WinSDK.ERROR_DISK_FULL)
}
@_transparent
internal var ERROR_DRIVE_LOCKED: DWORD {
DWORD(WinSDK.ERROR_DRIVE_LOCKED)
}
@_transparent
internal var ERROR_DIRECT_ACCESS_HANDLE: DWORD {
DWORD(WinSDK.ERROR_DIRECT_ACCESS_HANDLE)
}
@_transparent
internal var ERROR_FILE_EXISTS: DWORD {
DWORD(WinSDK.ERROR_FILE_EXISTS)
}
@_transparent
internal var ERROR_FILE_NOT_FOUND: DWORD {
DWORD(WinSDK.ERROR_FILE_NOT_FOUND)
}
@_transparent
internal var ERROR_FAIL_I24: DWORD {
DWORD(WinSDK.ERROR_FAIL_I24)
}
@_transparent
internal var ERROR_FILENAME_EXCED_RANGE: DWORD {
DWORD(WinSDK.ERROR_FILENAME_EXCED_RANGE)
}
@_transparent
internal var ERROR_NEGATIVE_SEEK: DWORD {
DWORD(WinSDK.ERROR_NEGATIVE_SEEK)
}
@_transparent
internal var ERROR_NO_MORE_FILES: DWORD {
DWORD(WinSDK.ERROR_NO_MORE_FILES)
}
@_transparent
internal var ERROR_NO_UNICODE_TRANSLATION: DWORD {
DWORD(WinSDK.ERROR_NO_UNICODE_TRANSLATION)
}
@_transparent
internal var ERROR_NOT_ENOUGH_MEMORY: DWORD {
DWORD(WinSDK.ERROR_NOT_ENOUGH_MEMORY)
}
@_transparent
internal var ERROR_INVALID_ACCESS: DWORD {
DWORD(WinSDK.ERROR_INVALID_ACCESS)
}
@_transparent
internal var ERROR_INVALID_BLOCK: DWORD {
DWORD(WinSDK.ERROR_INVALID_BLOCK)
}
@_transparent
internal var ERROR_INVALID_DATA: DWORD {
DWORD(WinSDK.ERROR_INVALID_DATA)
}
@_transparent
internal var ERROR_INVALID_DRIVE: DWORD {
DWORD(WinSDK.ERROR_INVALID_DRIVE)
}
@_transparent
internal var ERROR_INVALID_FUNCTION: DWORD {
DWORD(WinSDK.ERROR_INVALID_FUNCTION)
}
@_transparent
internal var ERROR_INVALID_HANDLE: DWORD {
DWORD(WinSDK.ERROR_INVALID_HANDLE)
}
@_transparent
internal var ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD {
DWORD(WinSDK.ERROR_INFLOOP_IN_RELOC_CHAIN)
}
@_transparent
internal var ERROR_INVALID_PARAMETER: DWORD {
DWORD(WinSDK.ERROR_INVALID_PARAMETER)
}
@_transparent
internal var ERROR_INVALID_STARTING_CODESEG: DWORD {
DWORD(WinSDK.ERROR_INVALID_STARTING_CODESEG)
}
@_transparent
internal var ERROR_INVALID_TARGET_HANDLE: DWORD {
DWORD(WinSDK.ERROR_INVALID_TARGET_HANDLE)
}
@_transparent
internal var ERROR_LOCK_FAILED: DWORD {
DWORD(WinSDK.ERROR_LOCK_FAILED)
}
@_transparent
internal var ERROR_LOCK_VIOLATION: DWORD {
DWORD(WinSDK.ERROR_LOCK_VIOLATION)
}
@_transparent
internal var ERROR_MAX_THRDS_REACHED: DWORD {
DWORD(WinSDK.ERROR_MAX_THRDS_REACHED)
}
@_transparent
internal var ERROR_NESTING_NOT_ALLOWED: DWORD {
DWORD(WinSDK.ERROR_NESTING_NOT_ALLOWED)
}
@_transparent
internal var ERROR_NETWORK_ACCESS_DENIED: DWORD {
DWORD(WinSDK.ERROR_NETWORK_ACCESS_DENIED)
}
@_transparent
internal var ERROR_NO_PROC_SLOTS: DWORD {
DWORD(WinSDK.ERROR_NO_PROC_SLOTS)
}
@_transparent
internal var ERROR_NOT_ENOUGH_QUOTA: DWORD {
DWORD(WinSDK.ERROR_NOT_ENOUGH_QUOTA)
}
@_transparent
internal var ERROR_NOT_LOCKED: DWORD {
DWORD(WinSDK.ERROR_NOT_LOCKED)
}
@_transparent
internal var ERROR_NOT_SAME_DEVICE: DWORD {
DWORD(WinSDK.ERROR_NOT_SAME_DEVICE)
}
@_transparent
internal var ERROR_PATH_NOT_FOUND: DWORD {
DWORD(WinSDK.ERROR_PATH_NOT_FOUND)
}
@_transparent
internal var ERROR_SEEK_ON_DEVICE: DWORD {
DWORD(WinSDK.ERROR_SEEK_ON_DEVICE)
}
@_transparent
internal var ERROR_SHARING_BUFFER_EXCEEDED: DWORD {
DWORD(WinSDK.ERROR_SHARING_BUFFER_EXCEEDED)
}
@_transparent
internal var ERROR_SUCCESS: DWORD {
DWORD(WinSDK.ERROR_SUCCESS)
}
@_transparent
internal var ERROR_WAIT_NO_CHILDREN: DWORD {
DWORD(WinSDK.ERROR_WAIT_NO_CHILDREN)
}
@_transparent
internal var ERROR_WRITE_PROTECT: DWORD {
DWORD(WinSDK.ERROR_WRITE_PROTECT)
}
@_transparent
internal var ERROR_TOO_MANY_OPEN_FILES: DWORD {
DWORD(WinSDK.ERROR_TOO_MANY_OPEN_FILES)
}
@_transparent
internal var FILE_APPEND_DATA: DWORD {
DWORD(WinSDK.FILE_APPEND_DATA)
}
@_transparent
internal var FILE_ATTRIBUTE_DIRECTORY: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_DIRECTORY)
}
@_transparent
internal var FILE_ATTRIBUTE_NORMAL: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_NORMAL)
}
@_transparent
internal var FILE_ATTRIBUTE_TEMPORARY: DWORD {
DWORD(WinSDK.FILE_ATTRIBUTE_TEMPORARY)
}
@_transparent
internal var FILE_BEGIN: DWORD {
DWORD(WinSDK.FILE_BEGIN)
}
@_transparent
internal var FILE_CURRENT: DWORD {
DWORD(WinSDK.FILE_CURRENT)
}
@_transparent
internal var FILE_DELETE_CHILD: DWORD {
DWORD(WinSDK.FILE_DELETE_CHILD)
}
@_transparent
package var FILE_EXECUTE: DWORD {
DWORD(WinSDK.FILE_EXECUTE)
}
@_transparent
internal var FILE_FLAG_DELETE_ON_CLOSE: DWORD {
DWORD(WinSDK.FILE_FLAG_DELETE_ON_CLOSE)
}
@_transparent
internal var FILE_FLAG_RANDOM_ACCESS: DWORD {
DWORD(WinSDK.FILE_FLAG_RANDOM_ACCESS)
}
@_transparent
internal var FILE_FLAG_SEQUENTIAL_SCAN: DWORD {
DWORD(WinSDK.FILE_FLAG_SEQUENTIAL_SCAN)
}
@_transparent
package var FILE_READ_ATTRIBUTES: DWORD {
DWORD(WinSDK.FILE_READ_ATTRIBUTES)
}
@_transparent
internal var FILE_READ_DATA: DWORD {
DWORD(WinSDK.FILE_READ_DATA)
}
@_transparent
internal var FILE_READ_EA: DWORD {
DWORD(WinSDK.FILE_READ_EA)
}
@_transparent
internal var FILE_SHARE_DELETE: DWORD {
DWORD(WinSDK.FILE_SHARE_DELETE)
}
@_transparent
internal var FILE_SHARE_READ: DWORD {
DWORD(WinSDK.FILE_SHARE_READ)
}
@_transparent
internal var FILE_SHARE_WRITE: DWORD {
DWORD(WinSDK.FILE_SHARE_WRITE)
}
@_transparent
package var FILE_WRITE_ATTRIBUTES: DWORD {
DWORD(WinSDK.FILE_WRITE_ATTRIBUTES)
}
@_transparent
internal var FILE_WRITE_DATA: DWORD {
DWORD(WinSDK.FILE_WRITE_DATA)
}
@_transparent
internal var FILE_WRITE_EA: DWORD {
DWORD(WinSDK.FILE_WRITE_EA)
}
@_transparent
internal var GENERIC_READ: DWORD {
DWORD(WinSDK.GENERIC_READ)
}
@_transparent
internal var GENERIC_WRITE: DWORD {
DWORD(WinSDK.GENERIC_WRITE)
}
@_transparent
internal var NO_INHERITANCE: DWORD {
DWORD(WinSDK.NO_INHERITANCE)
}
@_transparent
internal var OPEN_ALWAYS: DWORD {
DWORD(WinSDK.OPEN_ALWAYS)
}
@_transparent
internal var OPEN_EXISTING: DWORD {
DWORD(WinSDK.OPEN_EXISTING)
}
@_transparent
internal var SE_DACL_PROTECTED: SECURITY_DESCRIPTOR_CONTROL {
SECURITY_DESCRIPTOR_CONTROL(WinSDK.SE_DACL_PROTECTED)
}
@_transparent
internal var SECURITY_DESCRIPTOR_REVISION: DWORD {
DWORD(WinSDK.SECURITY_DESCRIPTOR_REVISION)
}
@_transparent
internal var SECURITY_WORLD_RID: DWORD {
DWORD(WinSDK.SECURITY_WORLD_RID)
}
@_transparent
internal var STANDARD_RIGHTS_READ: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_READ)
}
@_transparent
internal var STANDARD_RIGHTS_EXECUTE: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_EXECUTE)
}
@_transparent
internal var STANDARD_RIGHTS_WRITE: DWORD {
DWORD(WinSDK.STANDARD_RIGHTS_WRITE)
}
@_transparent
internal var SYNCHRONIZE: DWORD {
DWORD(WinSDK.SYNCHRONIZE)
}
@_transparent
internal var TRUNCATE_EXISTING: DWORD {
DWORD(WinSDK.TRUNCATE_EXISTING)
}
#endif
+2 -4
View File
@@ -22,7 +22,7 @@ import CSystem
@available(System 0.0.1, *) @available(System 0.0.1, *)
final class FileOperationsTest: XCTestCase { final class FileOperationsTest: XCTestCase {
#if ENABLE_MOCKING && !os(WASI) // Would need to use _getConst funcs from CSystem #if !os(WASI) // Would need to use _getConst funcs from CSystem
func testSyscalls() { func testSyscalls() {
let fd = FileDescriptor(rawValue: 1) let fd = FileDescriptor(rawValue: 1)
@@ -91,7 +91,7 @@ final class FileOperationsTest: XCTestCase {
for test in syscallTestCases { test.runAllTests() } for test in syscallTestCases { test.runAllTests() }
} }
#endif // ENABLE_MOCKING && !os(WASI) #endif // !os(WASI)
func testWriteFromEmptyBuffer() throws { func testWriteFromEmptyBuffer() throws {
#if os(Windows) #if os(Windows)
@@ -215,7 +215,6 @@ final class FileOperationsTest: XCTestCase {
} }
} }
#if ENABLE_MOCKING
func testGithubIssues() { func testGithubIssues() {
// https://github.com/apple/swift-system/issues/26 // https://github.com/apple/swift-system/issues/26
#if os(WASI) #if os(WASI)
@@ -234,7 +233,6 @@ final class FileOperationsTest: XCTestCase {
} }
issue26.runAllTests() issue26.runAllTests()
} }
#endif // ENABLE_MOCKING
func testResizeFile() throws { func testResizeFile() throws {
try withTemporaryFilePath(basename: "testResizeFile") { path in try withTemporaryFilePath(basename: "testResizeFile") { path in
@@ -19,6 +19,10 @@ import XCTest
import WinSDK import WinSDK
private let FILE_APPEND_DATA = DWORD(WinSDK.FILE_APPEND_DATA)
private let FILE_EXECUTE = DWORD(WinSDK.FILE_EXECUTE)
private let FILE_READ_ATTRIBUTES = DWORD(WinSDK.FILE_READ_ATTRIBUTES)
@available(iOS 8, *) @available(iOS 8, *)
final class FileOperationsTestWindows: XCTestCase { final class FileOperationsTestWindows: XCTestCase {
private let r = ACCESS_MASK( private let r = ACCESS_MASK(
@@ -43,6 +47,8 @@ final class FileOperationsTestWindows: XCTestCase {
| SYNCHRONIZE | SYNCHRONIZE
) )
private let none = ACCESS_MASK(0)
private struct Test { private struct Test {
var permissions: CModeT var permissions: CModeT
var ownerAccess: ACCESS_MASK var ownerAccess: ACCESS_MASK
@@ -72,7 +78,7 @@ final class FileOperationsTestWindows: XCTestCase {
var psidEveryone: PSID? = nil var psidEveryone: PSID? = nil
XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1, XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1,
DWORD(SECURITY_WORLD_RID), SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&psidEveryone)) &psidEveryone))
defer { defer {
@@ -106,7 +112,7 @@ final class FileOperationsTestWindows: XCTestCase {
&psidGroup, &psidGroup,
&pDacl, &pDacl,
nil, nil,
&pSD), DWORD(ERROR_SUCCESS)) &pSD), ERROR_SUCCESS)
defer { defer {
LocalFree(pSD) LocalFree(pSD)
} }
@@ -135,15 +141,15 @@ final class FileOperationsTestWindows: XCTestCase {
XCTAssertEqual(GetEffectiveRightsFromAclW( XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl, pDacl,
&owner, &owner,
&ownerAccess), DWORD(ERROR_SUCCESS)) &ownerAccess), ERROR_SUCCESS)
XCTAssertEqual(GetEffectiveRightsFromAclW( XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl, pDacl,
&group, &group,
&groupAccess), DWORD(ERROR_SUCCESS)) &groupAccess), ERROR_SUCCESS)
XCTAssertEqual(GetEffectiveRightsFromAclW( XCTAssertEqual(GetEffectiveRightsFromAclW(
pDacl, pDacl,
&everyone, &everyone,
&otherAccess), DWORD(ERROR_SUCCESS)) &otherAccess), ERROR_SUCCESS)
return (ownerAccess, groupAccess, otherAccess) return (ownerAccess, groupAccess, otherAccess)
} }
@@ -182,9 +188,9 @@ final class FileOperationsTestWindows: XCTestCase {
try withTemporaryFilePath(basename: "testUmask") { path in try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [ let tests = [
Test(0o000, 0, 0, 0), Test(0o000, none, none, none),
Test(0o700, r|w|x, 0, 0), Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|x, 0), Test(0o770, r|w|x, r|x, none),
Test(0o777, r|w|x, r|x, r|x) Test(0o777, r|w|x, r|x, r|x)
] ]
@@ -195,9 +201,9 @@ final class FileOperationsTestWindows: XCTestCase {
.otherWrite, .otherExecute]) { .otherWrite, .otherExecute]) {
try withTemporaryFilePath(basename: "testUmask") { path in try withTemporaryFilePath(basename: "testUmask") { path in
let tests = [ let tests = [
Test(0o000, 0, 0, 0), Test(0o000, none, none, none),
Test(0o700, r|w|x, 0, 0), Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r, 0), Test(0o770, r|w|x, r, none),
Test(0o777, r|w|x, r, r) Test(0o777, r|w|x, r, r)
] ]
@@ -214,34 +220,81 @@ final class FileOperationsTestWindows: XCTestCase {
try FilePermissions.withCreationMask([]) { try FilePermissions.withCreationMask([]) {
try withTemporaryFilePath(basename: "testPermissions") { path in try withTemporaryFilePath(basename: "testPermissions") { path in
let tests = [ let tests = [
Test(0o000, 0, 0, 0), Test(0o000, none, none, none),
Test(0o400, r, 0, 0), Test(0o400, r, none, none),
Test(0o200, w, 0, 0), Test(0o200, w, none, none),
Test(0o100, x, 0, 0), Test(0o100, x, none, none),
Test(0o040, 0, r, 0), Test(0o040, none, r, none),
Test(0o020, 0, w, 0), Test(0o020, none, w, none),
Test(0o010, 0, x, 0), Test(0o010, none, x, none),
Test(0o004, 0, 0, r), Test(0o004, none, none, r),
Test(0o002, 0, 0, w), Test(0o002, none, none, w),
Test(0o001, 0, 0, x), Test(0o001, none, none, x),
Test(0o700, r|w|x, 0, 0), Test(0o700, r|w|x, none, none),
Test(0o770, r|w|x, r|w|x, 0), Test(0o770, r|w|x, r|w|x, none),
Test(0o777, r|w|x, r|w|x, r|w|x), Test(0o777, r|w|x, r|w|x, r|w|x),
Test(0o755, r|w|x, r|x, r|x), Test(0o755, r|w|x, r|x, r|x),
Test(0o644, r|w, r, r), Test(0o644, r|w, r, r),
Test(0o007, 0, 0, r|w|x), Test(0o007, none, none, r|w|x),
Test(0o070, 0, r|w|x, 0), Test(0o070, none, r|w|x, none),
Test(0o077, 0, r|w|x, r|w|x), Test(0o077, none, r|w|x, r|w|x),
] ]
try runTests(tests, at: path) try runTests(tests, at: path)
} }
} }
} }
/// Test that buffer sizes exceeding DWORD.max (4GB) are properly rejected
func testBufferSizeLimit() throws {
try withTemporaryFilePath(basename: "testBufferSizeLimit") { path in
let fd = try FileDescriptor.open(
path.appending("test.txt"),
.readWrite,
options: [.create, .truncate],
permissions: .ownerReadWrite
)
defer { try? fd.close() }
// Write some data first
try fd.writeAll("test data".utf8)
// Allocate a small buffer for testing
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 1)
defer { buffer.deallocate() }
// Test that a count exceeding DWORD.max (UInt32.max = 4,294,967,295) returns EINVAL
// We use a buffer pointer but pass a count > DWORD.max
let oversizedCount = Int(DWORD.max) + 1
let oversizedBuffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress,
count: oversizedCount
)
// pread should fail with EINVAL
do {
_ = try fd.read(fromAbsoluteOffset: 0, into: oversizedBuffer)
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// pwrite should also fail with EINVAL
do {
_ = try fd.write(toAbsoluteOffset: 0, UnsafeRawBufferPointer(oversizedBuffer))
XCTFail("Expected EINVAL for buffer size exceeding DWORD.max")
} catch let err as Errno {
XCTAssertEqual(err, .invalidArgument, "Expected EINVAL, got \(err)")
}
// Verify that exactly DWORD.max works (if we had a buffer that large)
// We can't easily test this without allocating 4GB, but the boundary is correct
}
}
} }
#endif // os(Windows) #endif // os(Windows)
@@ -7,7 +7,6 @@
See https://swift.org/LICENSE.txt for license information See https://swift.org/LICENSE.txt for license information
*/ */
#if ENABLE_MOCKING
import XCTest import XCTest
#if SYSTEM_PACKAGE #if SYSTEM_PACKAGE
@@ -106,4 +105,3 @@ final class FilePathParsingTest: XCTestCase {
} }
} }
} }
#endif // ENABLE_MOCKING
@@ -7,7 +7,6 @@
See https://swift.org/LICENSE.txt for license information See https://swift.org/LICENSE.txt for license information
*/ */
#if ENABLE_MOCKING
import XCTest import XCTest
#if SYSTEM_PACKAGE #if SYSTEM_PACKAGE
@@ -1239,4 +1238,3 @@ final class FilePathSyntaxTest: XCTestCase {
} }
} }
#endif // ENABLE_MOCKING
+2 -1
View File
@@ -22,7 +22,8 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] {
// which are known to work correctly. // which are known to work correctly.
final class IORequestTests: XCTestCase { final class IORequestTests: XCTestCase {
func testNop() { func testNop() {
let req = IORing.Request.nop().makeRawRequest() let req = IORing.Request.nop().makeRawRequest(
pathBuffers: PendingPathBuffers(reservedCapacity: 0))
let sourceBytes = requestBytes(req) let sourceBytes = requestBytes(req)
// convenient property of nop: it's all zeros! // convenient property of nop: it's all zeros!
// for some unknown reason, liburing sets the fd field to -1. // for some unknown reason, liburing sets the fd field to -1.
+75
View File
@@ -127,6 +127,81 @@ final class IORingTests: XCTestCase {
efdBuf.deallocate() efdBuf.deallocate()
rawBuffer.deallocate() rawBuffer.deallocate()
} }
// Prior to the fix this is testing, prepare() escaped a pointer obtained
// inside `path.withPlatformString { ... }` into the SQE and dropped the
// owning FilePath before submit, so io_uring_enter handed the kernel a
// dangling pointer. Here we deliberately let the FilePath go out of scope
// between prepare and submit, then churn the heap to make UAFs observable.
func testPathBufferLifetimeAcrossPrepareSubmit() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
var ring = try IORing(queueDepth: 6)
func enqueueOpen() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly))
XCTAssertTrue(ok)
}
enqueueOpen()
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
}
for buf in churn { buf.deallocate() }
churn.removeAll()
try ring.submitPreparedRequests()
let completion = try ring.blockingConsumeCompletion()
XCTAssertGreaterThanOrEqual(
completion.result, 0,
"open should succeed; got \(completion.result)")
if completion.result >= 0 {
let fd = FileDescriptor(rawValue: Int32(completion.result))
try fd.close()
}
try cleanUpHelloWorldFile(parent)
}
func testPathBufferLifetimeAcrossLinkedRequests() throws {
guard try uringEnabled() else { return }
let (parent, _) = try makeHelloWorldFile()
let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16)
var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer])
func enqueueLinkedReadback() {
let path: FilePath = "/tmp/IORingTests/test.txt"
let ok = ring.prepare(linkedRequests:
.open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly),
.read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]),
.close(ring.registeredFileSlots[0]))
XCTAssertTrue(ok)
}
enqueueLinkedReadback()
var churn: [UnsafeMutableRawBufferPointer] = []
for _ in 0..<256 {
let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1)
memset(buf.baseAddress!, 0x41, 64)
churn.append(buf)
}
for buf in churn { buf.deallocate() }
try ring.submitPreparedRequests()
_ = try ring.blockingConsumeCompletion() // open
_ = try ring.blockingConsumeCompletion() // read
_ = try ring.blockingConsumeCompletion() // close
let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!)
XCTAssertEqual(result, "Hello, World!")
try cleanUpHelloWorldFile(parent)
rawBuffer.deallocate()
}
} }
#endif // os(Linux) #endif // os(Linux)
#endif // compiler(>=6.2) && $Lifetimes #endif // compiler(>=6.2) && $Lifetimes
-2
View File
@@ -7,7 +7,6 @@
See https://swift.org/LICENSE.txt for license information See https://swift.org/LICENSE.txt for license information
*/ */
#if ENABLE_MOCKING
import XCTest import XCTest
#if SYSTEM_PACKAGE #if SYSTEM_PACKAGE
@@ -49,4 +48,3 @@ final class MockingTest: XCTestCase {
XCTAssertFalse(mockingEnabled) XCTAssertFalse(mockingEnabled)
} }
} }
#endif // ENABLE_MOCKING
@@ -17,7 +17,6 @@ import XCTest
internal struct Wildcard: Hashable {} internal struct Wildcard: Hashable {}
#if ENABLE_MOCKING
extension Trace.Entry { extension Trace.Entry {
/// This implements `==` with wildcard matching. /// This implements `==` with wildcard matching.
/// (`Entry` cannot conform to `Equatable`/`Hashable` this way because /// (`Entry` cannot conform to `Equatable`/`Hashable` this way because
@@ -34,7 +33,6 @@ extension Trace.Entry {
return true return true
} }
} }
#endif // ENABLE_MOCKING
// To aid debugging, force failures to fatal error // To aid debugging, force failures to fatal error
internal var forceFatalFailures = false internal var forceFatalFailures = false
@@ -83,7 +81,6 @@ extension TestCase {
fail(message) fail(message)
} }
} }
#if ENABLE_MOCKING
func expectMatch( func expectMatch(
_ expected: Trace.Entry?, _ actual: Trace.Entry?, _ expected: Trace.Entry?, _ actual: Trace.Entry?,
_ message: String? = nil _ message: String? = nil
@@ -105,7 +102,6 @@ extension TestCase {
fail(message) fail(message)
} }
} }
#endif // ENABLE_MOCKING
func expectNil<T>( func expectNil<T>(
_ actual: T?, _ actual: T?,
_ message: String? = nil _ message: String? = nil
@@ -146,7 +142,6 @@ extension TestCase {
} }
#if ENABLE_MOCKING
internal struct MockTestCase: TestCase { internal struct MockTestCase: TestCase {
var file: StaticString var file: StaticString
var line: UInt var line: UInt
@@ -246,7 +241,6 @@ internal struct MockTestCase: TestCase {
} }
} }
} }
#endif // ENABLE_MOCKING
internal func withWindowsPaths(enabled: Bool, _ body: () -> ()) { internal func withWindowsPaths(enabled: Bool, _ body: () -> ()) {
_withWindowsPaths(enabled: enabled, body) _withWindowsPaths(enabled: enabled, body)