diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..70e4f6c --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,13 @@ +# Lines starting with '#' are comments. +# Each line is a case-sensitive file pattern followed by one or more owners. +# Order is important. The last matching pattern has the most precedence. +# More information: https://docs.github.com/en/articles/about-code-owners +# +# Please mirror the repository's file hierarchy in case-sensitive lexicographic +# order. + +# Default owners +* @glessard @lorentey @milseman + +# Swift CI configuration files +.swiftci/ @shahmishal diff --git a/.gitignore b/.gitignore index 2c0658b..51ae994 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,8 @@ /.swiftpm /.build /Packages -swift-system.xcodeproj +/*.xcodeproj xcuserdata/ .*.sw? +/.swiftpm .docc-build diff --git a/.spi.yml b/.spi.yml new file mode 100644 index 0000000..b9cbb71 --- /dev/null +++ b/.spi.yml @@ -0,0 +1,4 @@ +version: 1 +builder: + configs: + - documentation_targets: [SystemPackage] diff --git a/.swiftci/5_10_ubuntu2204 b/.swiftci/5_10_ubuntu2204 new file mode 100644 index 0000000..0c65ec1 --- /dev/null +++ b/.swiftci/5_10_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.10-jammy" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/5_8_ubuntu2204 b/.swiftci/5_8_ubuntu2204 new file mode 100644 index 0000000..0daee62 --- /dev/null +++ b/.swiftci/5_8_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.8-jammy" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/5_9_ubuntu2204 b/.swiftci/5_9_ubuntu2204 new file mode 100644 index 0000000..1ede34f --- /dev/null +++ b/.swiftci/5_9_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.9-jammy" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/nightly_6_0_macos b/.swiftci/nightly_6_0_macos new file mode 100644 index 0000000..9acdfa2 --- /dev/null +++ b/.swiftci/nightly_6_0_macos @@ -0,0 +1,5 @@ +macOSSwiftPackageJob { + swift_version = "6.0" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/nightly_6_0_ubuntu2204 b/.swiftci/nightly_6_0_ubuntu2204 new file mode 100644 index 0000000..aaa4671 --- /dev/null +++ b/.swiftci/nightly_6_0_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + nightly_docker_tag = "nightly-6.0-jammy" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/nightly_main_macos b/.swiftci/nightly_main_macos new file mode 100644 index 0000000..329aef7 --- /dev/null +++ b/.swiftci/nightly_main_macos @@ -0,0 +1,5 @@ +macOSSwiftPackageJob { + swift_version = "main" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/nightly_main_ubuntu2204 b/.swiftci/nightly_main_ubuntu2204 new file mode 100644 index 0000000..7e03ac0 --- /dev/null +++ b/.swiftci/nightly_main_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + nightly_docker_tag = "nightly-jammy" + repo = "swift-system" + branch = "main" +} diff --git a/.swiftci/nightly_main_windows b/.swiftci/nightly_main_windows new file mode 100644 index 0000000..b3d52fd --- /dev/null +++ b/.swiftci/nightly_main_windows @@ -0,0 +1,7 @@ +WindowsSwiftPackageWithDockerImageJob { + docker_image = "swiftlang/swift:nightly-windowsservercore-1809" + repo = "swift-system" + branch = "main" + sub_dir = "swift-system" + label = "windows-server-2019" +} diff --git a/Package.swift b/Package.swift index 1c058ac..93991df 100644 --- a/Package.swift +++ b/Package.swift @@ -1,10 +1,9 @@ -// swift-tools-version:5.2 -// The swift-tools-version declares the minimum version of Swift required to build this package. +// swift-tools-version:5.8 /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020-2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -12,17 +11,26 @@ import PackageDescription +let DarwinPlatforms: [Platform] +#if swift(<5.9) +DarwinPlatforms = [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS] +#else +DarwinPlatforms = [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS] +#endif + let package = Package( name: "swift-system", products: [ - .library(name: "SystemPackage", targets: ["SystemPackage"]), + .library(name: "SystemPackage", targets: ["SystemPackage"]) ], dependencies: [ .package(url: "https://github.com/apple/swift-atomics", from: "1.1.0") ], targets: [ - .systemLibrary( - name: "CSystem"), + .target( + name: "CSystem", + dependencies: [], + exclude: ["CMakeLists.txt"]), .target( name: "SystemPackage", dependencies: [ @@ -30,18 +38,21 @@ let package = Package( .product(name: "Atomics", package: "swift-atomics") ], path: "Sources/System", + exclude: ["CMakeLists.txt"], cSettings: [ - .define("_CRT_SECURE_NO_WARNINGS") + .define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])) ], swiftSettings: [ .define("SYSTEM_PACKAGE"), + .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)), .define("ENABLE_MOCKING", .when(configuration: .debug)) ]), .testTarget( name: "SystemTests", dependencies: ["SystemPackage"], swiftSettings: [ - .define("SYSTEM_PACKAGE") + .define("SYSTEM_PACKAGE"), + .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)), ]), ] ) diff --git a/README.md b/README.md index 11e57eb..b5b5535 100644 --- a/README.md +++ b/README.md @@ -22,13 +22,15 @@ try fd.closeAfter { } ``` +[API documentation](https://swiftpackageindex.com/apple/swift-system/main/documentation/SystemPackage) + ## Adding `SystemPackage` as a Dependency To use the `SystemPackage` library in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file: ```swift -.package(url: "https://github.com/apple/swift-system", from: "1.0.0"), +.package(url: "https://github.com/apple/swift-system", from: "1.3.0"), ``` Finally, include `"SystemPackage"` as a dependency for your executable target: @@ -37,7 +39,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target: let package = Package( // name, platforms, products, etc. dependencies: [ - .package(url: "https://github.com/apple/swift-system", from: "1.0.0"), + .package(url: "https://github.com/apple/swift-system", from: "1.3.0"), // other dependencies ], targets: [ diff --git a/Sources/CSystem/CSystemWASI.h b/Sources/CSystem/CSystemWASI.h new file mode 100644 index 0000000..9877853 --- /dev/null +++ b/Sources/CSystem/CSystemWASI.h @@ -0,0 +1,31 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +#pragma once + +#if __wasi__ + +#include +#include + +// wasi-libc defines the following constants in a way that Clang Importer can't +// understand, so we need to expose them manually. +static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; } +static inline int32_t _getConst_O_APPEND(void) { return O_APPEND; } +static inline int32_t _getConst_O_CREAT(void) { return O_CREAT; } +static inline int32_t _getConst_O_DIRECTORY(void) { return O_DIRECTORY; } +static inline int32_t _getConst_O_EXCL(void) { return O_EXCL; } +static inline int32_t _getConst_O_NONBLOCK(void) { return O_NONBLOCK; } +static inline int32_t _getConst_O_TRUNC(void) { return O_TRUNC; } +static inline int32_t _getConst_O_WRONLY(void) { return O_WRONLY; } + +static inline int32_t _getConst_EWOULDBLOCK(void) { return EWOULDBLOCK; } +static inline int32_t _getConst_EOPNOTSUPP(void) { return EOPNOTSUPP; } + +#endif diff --git a/Sources/CSystem/module.modulemap b/Sources/CSystem/module.modulemap index 776f776..6e8b89e 100644 --- a/Sources/CSystem/module.modulemap +++ b/Sources/CSystem/module.modulemap @@ -1,5 +1,6 @@ module CSystem { header "CSystemLinux.h" + header "CSystemWASI.h" header "CSystemWindows.h" export * } diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index f7c038b..1f3420a 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -41,6 +41,10 @@ target_sources(SystemPackage PRIVATE target_link_libraries(SystemPackage PUBLIC CSystem) +set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS") +if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS) + target_compile_definitions(SystemPackage PRIVATE SYSTEM_PACKAGE_DARWIN) +endif() _install_target(SystemPackage) set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage) diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index d55e52b..093023d 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2021 - 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 @@ -20,13 +20,10 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient public init(rawValue: CInt) { self.rawValue = rawValue } - @_alwaysEmitIntoClient - private init(_ raw: CInt) { self.init(rawValue: raw) } - -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Error. Not used. @_alwaysEmitIntoClient - public static var notUsed: Errno { Errno(_ERRNO_NOT_USED) } + public static var notUsed: Errno { .init(rawValue: _ERRNO_NOT_USED) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notUsed") @@ -41,7 +38,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPERM`. @_alwaysEmitIntoClient - public static var notPermitted: Errno { Errno(_EPERM) } + public static var notPermitted: Errno { .init(rawValue: _EPERM) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notPermitted") @@ -54,7 +51,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOENT`. @_alwaysEmitIntoClient - public static var noSuchFileOrDirectory: Errno { Errno(_ENOENT) } + public static var noSuchFileOrDirectory: Errno { .init(rawValue: _ENOENT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noSuchFileOrDirectory") @@ -66,7 +63,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ESRCH`. @_alwaysEmitIntoClient - public static var noSuchProcess: Errno { Errno(_ESRCH) } + public static var noSuchProcess: Errno { .init(rawValue: _ESRCH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noSuchProcess") @@ -81,7 +78,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EINTR`. @_alwaysEmitIntoClient - public static var interrupted: Errno { Errno(_EINTR) } + public static var interrupted: Errno { .init(rawValue: _EINTR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "interrupted") @@ -96,7 +93,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EIO`. @_alwaysEmitIntoClient - public static var ioError: Errno { Errno(_EIO) } + public static var ioError: Errno { .init(rawValue: _EIO) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "ioError") @@ -111,7 +108,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENXIO`. @_alwaysEmitIntoClient - public static var noSuchAddressOrDevice: Errno { Errno(_ENXIO) } + public static var noSuchAddressOrDevice: Errno { .init(rawValue: _ENXIO) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noSuchAddressOrDevice") @@ -125,7 +122,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `E2BIG`. @_alwaysEmitIntoClient - public static var argListTooLong: Errno { Errno(_E2BIG) } + public static var argListTooLong: Errno { .init(rawValue: _E2BIG) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "argListTooLong") @@ -139,10 +136,10 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOEXEC`. @_alwaysEmitIntoClient - public static var execFormatError: Errno { Errno(_ENOEXEC) } + public static var execFormatError: Errno { .init(rawValue: _ENOEXEC) } @_alwaysEmitIntoClient - @available(*, unavailable, renamed: "noExec") + @available(*, unavailable, renamed: "execFormatError") public static var ENOEXEC: Errno { execFormatError } /// Bad file descriptor. @@ -154,7 +151,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EBADF`. @_alwaysEmitIntoClient - public static var badFileDescriptor: Errno { Errno(_EBADF) } + public static var badFileDescriptor: Errno { .init(rawValue: _EBADF) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "badFileDescriptor") @@ -168,7 +165,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ECHILD`. @_alwaysEmitIntoClient - public static var noChildProcess: Errno { Errno(_ECHILD) } + public static var noChildProcess: Errno { .init(rawValue: _ECHILD) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noChildProcess") @@ -181,7 +178,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EDEADLK`. @_alwaysEmitIntoClient - public static var deadlock: Errno { Errno(_EDEADLK) } + public static var deadlock: Errno { .init(rawValue: _EDEADLK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "deadlock") @@ -198,7 +195,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOMEM`. @_alwaysEmitIntoClient - public static var noMemory: Errno { Errno(_ENOMEM) } + public static var noMemory: Errno { .init(rawValue: _ENOMEM) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noMemory") @@ -211,7 +208,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EACCES`. @_alwaysEmitIntoClient - public static var permissionDenied: Errno { Errno(_EACCES) } + public static var permissionDenied: Errno { .init(rawValue: _EACCES) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "permissionDenied") @@ -223,20 +220,20 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EFAULT`. @_alwaysEmitIntoClient - public static var badAddress: Errno { Errno(_EFAULT) } + public static var badAddress: Errno { .init(rawValue: _EFAULT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "badAddress") public static var EFAULT: Errno { badAddress } -#if !os(Windows) +#if !os(Windows) && !os(WASI) /// Not a block device. /// /// You attempted a block device operation on a nonblock device or file. /// /// The corresponding C error is `ENOTBLK`. @_alwaysEmitIntoClient - public static var notBlockDevice: Errno { Errno(_ENOTBLK) } + public static var notBlockDevice: Errno { .init(rawValue: _ENOTBLK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notBlockDevice") @@ -250,7 +247,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EBUSY`. @_alwaysEmitIntoClient - public static var resourceBusy: Errno { Errno(_EBUSY) } + public static var resourceBusy: Errno { .init(rawValue: _EBUSY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "resourceBusy") @@ -263,7 +260,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EEXIST`. @_alwaysEmitIntoClient - public static var fileExists: Errno { Errno(_EEXIST) } + public static var fileExists: Errno { .init(rawValue: _EEXIST) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "fileExists") @@ -275,7 +272,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EXDEV`. @_alwaysEmitIntoClient - public static var improperLink: Errno { Errno(_EXDEV) } + public static var improperLink: Errno { .init(rawValue: _EXDEV) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "improperLink") @@ -288,7 +285,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENODEV`. @_alwaysEmitIntoClient - public static var operationNotSupportedByDevice: Errno { Errno(_ENODEV) } + public static var operationNotSupportedByDevice: Errno { .init(rawValue: _ENODEV) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "operationNotSupportedByDevice") @@ -302,7 +299,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOTDIR`. @_alwaysEmitIntoClient - public static var notDirectory: Errno { Errno(_ENOTDIR) } + public static var notDirectory: Errno { .init(rawValue: _ENOTDIR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notDirectory") @@ -315,7 +312,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EISDIR`. @_alwaysEmitIntoClient - public static var isDirectory: Errno { Errno(_EISDIR) } + public static var isDirectory: Errno { .init(rawValue: _EISDIR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "isDirectory") @@ -328,7 +325,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EINVAL`. @_alwaysEmitIntoClient - public static var invalidArgument: Errno { Errno(_EINVAL) } + public static var invalidArgument: Errno { .init(rawValue: _EINVAL) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "invalidArgument") @@ -343,7 +340,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENFILE`. @_alwaysEmitIntoClient - public static var tooManyOpenFilesInSystem: Errno { Errno(_ENFILE) } + public static var tooManyOpenFilesInSystem: Errno { .init(rawValue: _ENFILE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyOpenFilesInSystem") @@ -356,7 +353,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EMFILE`. @_alwaysEmitIntoClient - public static var tooManyOpenFiles: Errno { Errno(_EMFILE) } + public static var tooManyOpenFiles: Errno { .init(rawValue: _EMFILE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyOpenFiles") @@ -371,7 +368,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOTTY`. @_alwaysEmitIntoClient - public static var inappropriateIOCTLForDevice: Errno { Errno(_ENOTTY) } + public static var inappropriateIOCTLForDevice: Errno { .init(rawValue: _ENOTTY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "inappropriateIOCTLForDevice") @@ -386,7 +383,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ETXTBSY`. @_alwaysEmitIntoClient - public static var textFileBusy: Errno { Errno(_ETXTBSY) } + public static var textFileBusy: Errno { .init(rawValue: _ETXTBSY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "textFileBusy") @@ -401,7 +398,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EFBIG`. @_alwaysEmitIntoClient - public static var fileTooLarge: Errno { Errno(_EFBIG) } + public static var fileTooLarge: Errno { .init(rawValue: _EFBIG) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "fileTooLarge") @@ -418,7 +415,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOSPC`. @_alwaysEmitIntoClient - public static var noSpace: Errno { Errno(_ENOSPC) } + public static var noSpace: Errno { .init(rawValue: _ENOSPC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noSpace") @@ -430,7 +427,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ESPIPE`. @_alwaysEmitIntoClient - public static var illegalSeek: Errno { Errno(_ESPIPE) } + public static var illegalSeek: Errno { .init(rawValue: _ESPIPE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "illegalSeek") @@ -443,7 +440,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EROFS`. @_alwaysEmitIntoClient - public static var readOnlyFileSystem: Errno { Errno(_EROFS) } + public static var readOnlyFileSystem: Errno { .init(rawValue: _EROFS) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "readOnlyFileSystem") @@ -456,7 +453,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EMLINK`. @_alwaysEmitIntoClient - public static var tooManyLinks: Errno { Errno(_EMLINK) } + public static var tooManyLinks: Errno { .init(rawValue: _EMLINK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyLinks") @@ -469,7 +466,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPIPE`. @_alwaysEmitIntoClient - public static var brokenPipe: Errno { Errno(_EPIPE) } + public static var brokenPipe: Errno { .init(rawValue: _EPIPE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "brokenPipe") @@ -482,7 +479,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EDOM`. @_alwaysEmitIntoClient - public static var outOfDomain: Errno { Errno(_EDOM) } + public static var outOfDomain: Errno { .init(rawValue: _EDOM) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "outOfDomain") @@ -497,7 +494,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ERANGE`. @_alwaysEmitIntoClient - public static var outOfRange: Errno { Errno(_ERANGE) } + public static var outOfRange: Errno { .init(rawValue: _ERANGE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "outOfRange") @@ -511,7 +508,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EAGAIN`. @_alwaysEmitIntoClient - public static var resourceTemporarilyUnavailable: Errno { Errno(_EAGAIN) } + public static var resourceTemporarilyUnavailable: Errno { .init(rawValue: _EAGAIN) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "resourceTemporarilyUnavailable") @@ -526,10 +523,10 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EINPROGRESS`. @_alwaysEmitIntoClient - public static var nowInProgress: Errno { Errno(_EINPROGRESS) } + public static var nowInProgress: Errno { .init(rawValue: _EINPROGRESS) } @_alwaysEmitIntoClient - @available(*, unavailable, renamed: "nowInProcess") + @available(*, unavailable, renamed: "nowInProgress") public static var EINPROGRESS: Errno { nowInProgress } /// Operation already in progress. @@ -539,7 +536,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EALREADY`. @_alwaysEmitIntoClient - public static var alreadyInProcess: Errno { Errno(_EALREADY) } + public static var alreadyInProcess: Errno { .init(rawValue: _EALREADY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "alreadyInProcess") @@ -549,7 +546,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOTSOCK`. @_alwaysEmitIntoClient - public static var notSocket: Errno { Errno(_ENOTSOCK) } + public static var notSocket: Errno { .init(rawValue: _ENOTSOCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notSocket") @@ -561,7 +558,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EDESTADDRREQ`. @_alwaysEmitIntoClient - public static var addressRequired: Errno { Errno(_EDESTADDRREQ) } + public static var addressRequired: Errno { .init(rawValue: _EDESTADDRREQ) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "addressRequired") @@ -574,7 +571,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EMSGSIZE`. @_alwaysEmitIntoClient - public static var messageTooLong: Errno { Errno(_EMSGSIZE) } + public static var messageTooLong: Errno { .init(rawValue: _EMSGSIZE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "messageTooLong") @@ -589,7 +586,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPROTOTYPE`. @_alwaysEmitIntoClient - public static var protocolWrongTypeForSocket: Errno { Errno(_EPROTOTYPE) } + public static var protocolWrongTypeForSocket: Errno { .init(rawValue: _EPROTOTYPE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "protocolWrongTypeForSocket") @@ -602,7 +599,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOPROTOOPT`. @_alwaysEmitIntoClient - public static var protocolNotAvailable: Errno { Errno(_ENOPROTOOPT) } + public static var protocolNotAvailable: Errno { .init(rawValue: _ENOPROTOOPT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "protocolNotAvailable") @@ -615,12 +612,13 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPROTONOSUPPORT`. @_alwaysEmitIntoClient - public static var protocolNotSupported: Errno { Errno(_EPROTONOSUPPORT) } + public static var protocolNotSupported: Errno { .init(rawValue: _EPROTONOSUPPORT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "protocolNotSupported") public static var EPROTONOSUPPORT: Errno { protocolNotSupported } +#if !os(WASI) /// Socket type not supported. /// /// Support for the socket type hasn't been configured into the system @@ -628,11 +626,12 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ESOCKTNOSUPPORT`. @_alwaysEmitIntoClient - public static var socketTypeNotSupported: Errno { Errno(_ESOCKTNOSUPPORT) } + public static var socketTypeNotSupported: Errno { .init(rawValue: _ESOCKTNOSUPPORT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "socketTypeNotSupported") public static var ESOCKTNOSUPPORT: Errno { socketTypeNotSupported } +#endif /// Not supported. /// @@ -641,12 +640,13 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOTSUP`. @_alwaysEmitIntoClient - public static var notSupported: Errno { Errno(_ENOTSUP) } + public static var notSupported: Errno { .init(rawValue: _ENOTSUP) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notSupported") public static var ENOTSUP: Errno { notSupported } +#if !os(WASI) /// Protocol family not supported. /// /// The protocol family hasn't been configured into the system @@ -654,11 +654,12 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPFNOSUPPORT`. @_alwaysEmitIntoClient - public static var protocolFamilyNotSupported: Errno { Errno(_EPFNOSUPPORT) } + public static var protocolFamilyNotSupported: Errno { .init(rawValue: _EPFNOSUPPORT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "protocolFamilyNotSupported") public static var EPFNOSUPPORT: Errno { protocolFamilyNotSupported } +#endif /// The address family isn't supported by the protocol family. /// @@ -668,7 +669,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EAFNOSUPPORT`. @_alwaysEmitIntoClient - public static var addressFamilyNotSupported: Errno { Errno(_EAFNOSUPPORT) } + public static var addressFamilyNotSupported: Errno { .init(rawValue: _EAFNOSUPPORT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "addressFamilyNotSupported") @@ -680,7 +681,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EADDRINUSE`. @_alwaysEmitIntoClient - public static var addressInUse: Errno { Errno(_EADDRINUSE) } + public static var addressInUse: Errno { .init(rawValue: _EADDRINUSE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "addressInUse") @@ -693,7 +694,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EADDRNOTAVAIL`. @_alwaysEmitIntoClient - public static var addressNotAvailable: Errno { Errno(_EADDRNOTAVAIL) } + public static var addressNotAvailable: Errno { .init(rawValue: _EADDRNOTAVAIL) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "addressNotAvailable") @@ -705,7 +706,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENETDOWN`. @_alwaysEmitIntoClient - public static var networkDown: Errno { Errno(_ENETDOWN) } + public static var networkDown: Errno { .init(rawValue: _ENETDOWN) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "networkDown") @@ -717,7 +718,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENETUNREACH`. @_alwaysEmitIntoClient - public static var networkUnreachable: Errno { Errno(_ENETUNREACH) } + public static var networkUnreachable: Errno { .init(rawValue: _ENETUNREACH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "networkUnreachable") @@ -729,7 +730,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENETRESET`. @_alwaysEmitIntoClient - public static var networkReset: Errno { Errno(_ENETRESET) } + public static var networkReset: Errno { .init(rawValue: _ENETRESET) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "networkReset") @@ -741,7 +742,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ECONNABORTED`. @_alwaysEmitIntoClient - public static var connectionAbort: Errno { Errno(_ECONNABORTED) } + public static var connectionAbort: Errno { .init(rawValue: _ECONNABORTED) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "connectionAbort") @@ -755,7 +756,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ECONNRESET`. @_alwaysEmitIntoClient - public static var connectionReset: Errno { Errno(_ECONNRESET) } + public static var connectionReset: Errno { .init(rawValue: _ECONNRESET) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "connectionReset") @@ -769,7 +770,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOBUFS`. @_alwaysEmitIntoClient - public static var noBufferSpace: Errno { Errno(_ENOBUFS) } + public static var noBufferSpace: Errno { .init(rawValue: _ENOBUFS) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noBufferSpace") @@ -784,7 +785,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EISCONN`. @_alwaysEmitIntoClient - public static var socketIsConnected: Errno { Errno(_EISCONN) } + public static var socketIsConnected: Errno { .init(rawValue: _EISCONN) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "socketIsConnected") @@ -799,12 +800,13 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOTCONN`. @_alwaysEmitIntoClient - public static var socketNotConnected: Errno { Errno(_ENOTCONN) } + public static var socketNotConnected: Errno { .init(rawValue: _ENOTCONN) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "socketNotConnected") public static var ENOTCONN: Errno { socketNotConnected } +#if !os(WASI) /// Can't send after socket shutdown. /// /// A request to send data wasn't permitted @@ -813,11 +815,12 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ESHUTDOWN`. @_alwaysEmitIntoClient - public static var socketShutdown: Errno { Errno(_ESHUTDOWN) } + public static var socketShutdown: Errno { .init(rawValue: _ESHUTDOWN) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "socketShutdown") public static var ESHUTDOWN: Errno { socketShutdown } +#endif /// Operation timed out. /// @@ -828,7 +831,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ETIMEDOUT`. @_alwaysEmitIntoClient - public static var timedOut: Errno { Errno(_ETIMEDOUT) } + public static var timedOut: Errno { .init(rawValue: _ETIMEDOUT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "timedOut") @@ -843,7 +846,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ECONNREFUSED`. @_alwaysEmitIntoClient - public static var connectionRefused: Errno { Errno(_ECONNREFUSED) } + public static var connectionRefused: Errno { .init(rawValue: _ECONNREFUSED) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "connectionRefused") @@ -855,7 +858,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ELOOP`. @_alwaysEmitIntoClient - public static var tooManySymbolicLinkLevels: Errno { Errno(_ELOOP) } + public static var tooManySymbolicLinkLevels: Errno { .init(rawValue: _ELOOP) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManySymbolicLinkLevels") @@ -868,23 +871,25 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENAMETOOLONG`. @_alwaysEmitIntoClient - public static var fileNameTooLong: Errno { Errno(_ENAMETOOLONG) } + public static var fileNameTooLong: Errno { .init(rawValue: _ENAMETOOLONG) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "fileNameTooLong") public static var ENAMETOOLONG: Errno { fileNameTooLong } +#if !os(WASI) /// The host is down. /// /// A socket operation failed because the destination host was down. /// /// The corresponding C error is `EHOSTDOWN`. @_alwaysEmitIntoClient - public static var hostIsDown: Errno { Errno(_EHOSTDOWN) } + public static var hostIsDown: Errno { .init(rawValue: _EHOSTDOWN) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "hostIsDown") public static var EHOSTDOWN: Errno { hostIsDown } +#endif /// No route to host. /// @@ -892,7 +897,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EHOSTUNREACH`. @_alwaysEmitIntoClient - public static var noRouteToHost: Errno { Errno(_EHOSTUNREACH) } + public static var noRouteToHost: Errno { .init(rawValue: _EHOSTUNREACH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noRouteToHost") @@ -905,35 +910,37 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOTEMPTY`. @_alwaysEmitIntoClient - public static var directoryNotEmpty: Errno { Errno(_ENOTEMPTY) } + public static var directoryNotEmpty: Errno { .init(rawValue: _ENOTEMPTY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "directoryNotEmpty") public static var ENOTEMPTY: Errno { directoryNotEmpty } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Too many processes. /// /// The corresponding C error is `EPROCLIM`. @_alwaysEmitIntoClient - public static var tooManyProcesses: Errno { Errno(_EPROCLIM) } + public static var tooManyProcesses: Errno { .init(rawValue: _EPROCLIM) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyProcesses") public static var EPROCLIM: Errno { tooManyProcesses } #endif +#if !os(WASI) /// Too many users. /// /// The quota system ran out of table entries. /// /// The corresponding C error is `EUSERS`. @_alwaysEmitIntoClient - public static var tooManyUsers: Errno { Errno(_EUSERS) } + public static var tooManyUsers: Errno { .init(rawValue: _EUSERS) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyUsers") public static var EUSERS: Errno { tooManyUsers } +#endif /// Disk quota exceeded. /// @@ -946,7 +953,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EDQUOT`. @_alwaysEmitIntoClient - public static var diskQuotaExceeded: Errno { Errno(_EDQUOT) } + public static var diskQuotaExceeded: Errno { .init(rawValue: _EDQUOT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "diskQuotaExceeded") @@ -961,14 +968,14 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ESTALE`. @_alwaysEmitIntoClient - public static var staleNFSFileHandle: Errno { Errno(_ESTALE) } + public static var staleNFSFileHandle: Errno { .init(rawValue: _ESTALE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "staleNFSFileHandle") public static var ESTALE: Errno { staleNFSFileHandle } // TODO: Add Linux's RPC equivalents -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// The structure of the remote procedure call (RPC) is bad. /// @@ -976,7 +983,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EBADRPC`. @_alwaysEmitIntoClient - public static var rpcUnsuccessful: Errno { Errno(_EBADRPC) } + public static var rpcUnsuccessful: Errno { .init(rawValue: _EBADRPC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "rpcUnsuccessful") @@ -989,7 +996,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ERPCMISMATCH`. @_alwaysEmitIntoClient - public static var rpcVersionMismatch: Errno { Errno(_ERPCMISMATCH) } + public static var rpcVersionMismatch: Errno { .init(rawValue: _ERPCMISMATCH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "rpcVersionMismatch") @@ -1001,7 +1008,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPROGUNAVAIL`. @_alwaysEmitIntoClient - public static var rpcProgramUnavailable: Errno { Errno(_EPROGUNAVAIL) } + public static var rpcProgramUnavailable: Errno { .init(rawValue: _EPROGUNAVAIL) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "rpcProgramUnavailable") @@ -1014,7 +1021,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPROGMISMATCH`. @_alwaysEmitIntoClient - public static var rpcProgramVersionMismatch: Errno { Errno(_EPROGMISMATCH) } + public static var rpcProgramVersionMismatch: Errno { .init(rawValue: _EPROGMISMATCH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "rpcProgramVersionMismatch") @@ -1027,7 +1034,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPROCUNAVAIL`. @_alwaysEmitIntoClient - public static var rpcProcedureUnavailable: Errno { Errno(_EPROCUNAVAIL) } + public static var rpcProcedureUnavailable: Errno { .init(rawValue: _EPROCUNAVAIL) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "rpcProcedureUnavailable") @@ -1041,7 +1048,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOLCK`. @_alwaysEmitIntoClient - public static var noLocks: Errno { Errno(_ENOLCK) } + public static var noLocks: Errno { .init(rawValue: _ENOLCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noLocks") @@ -1053,14 +1060,14 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOSYS`. @_alwaysEmitIntoClient - public static var noFunction: Errno { Errno(_ENOSYS) } + public static var noFunction: Errno { .init(rawValue: _ENOSYS) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noFunction") public static var ENOSYS: Errno { noFunction } // BSD -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Inappropriate file type or format. /// /// The file was the wrong type for the operation, @@ -1068,21 +1075,21 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EFTYPE`. @_alwaysEmitIntoClient - public static var badFileTypeOrFormat: Errno { Errno(_EFTYPE) } + public static var badFileTypeOrFormat: Errno { .init(rawValue: _EFTYPE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "badFileTypeOrFormat") public static var EFTYPE: Errno { badFileTypeOrFormat } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Authentication error. /// /// The authentication ticket used to mount an NFS file system was invalid. /// /// The corresponding C error is `EAUTH`. @_alwaysEmitIntoClient - public static var authenticationError: Errno { Errno(_EAUTH) } + public static var authenticationError: Errno { .init(rawValue: _EAUTH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "authenticationError") @@ -1095,19 +1102,19 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENEEDAUTH`. @_alwaysEmitIntoClient - public static var needAuthenticator: Errno { Errno(_ENEEDAUTH) } + public static var needAuthenticator: Errno { .init(rawValue: _ENEEDAUTH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "needAuthenticator") public static var ENEEDAUTH: Errno { needAuthenticator } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Device power is off. /// /// The corresponding C error is `EPWROFF`. @_alwaysEmitIntoClient - public static var devicePowerIsOff: Errno { Errno(_EPWROFF) } + public static var devicePowerIsOff: Errno { .init(rawValue: _EPWROFF) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "devicePowerIsOff") @@ -1120,7 +1127,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EDEVERR`. @_alwaysEmitIntoClient - public static var deviceError: Errno { Errno(_EDEVERR) } + public static var deviceError: Errno { .init(rawValue: _EDEVERR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "deviceError") @@ -1135,21 +1142,21 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EOVERFLOW`. @_alwaysEmitIntoClient - public static var overflow: Errno { Errno(_EOVERFLOW) } + public static var overflow: Errno { .init(rawValue: _EOVERFLOW) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "overflow") public static var EOVERFLOW: Errno { overflow } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Bad executable or shared library. /// /// The executable or shared library being referenced was malformed. /// /// The corresponding C error is `EBADEXEC`. @_alwaysEmitIntoClient - public static var badExecutable: Errno { Errno(_EBADEXEC) } + public static var badExecutable: Errno { .init(rawValue: _EBADEXEC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "badExecutable") @@ -1161,7 +1168,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EBADARCH`. @_alwaysEmitIntoClient - public static var badCPUType: Errno { Errno(_EBADARCH) } + public static var badCPUType: Errno { .init(rawValue: _EBADARCH) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "badCPUType") @@ -1174,7 +1181,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ESHLIBVERS`. @_alwaysEmitIntoClient - public static var sharedLibraryVersionMismatch: Errno { Errno(_ESHLIBVERS) } + public static var sharedLibraryVersionMismatch: Errno { .init(rawValue: _ESHLIBVERS) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "sharedLibraryVersionMismatch") @@ -1186,7 +1193,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EBADMACHO`. @_alwaysEmitIntoClient - public static var malformedMachO: Errno { Errno(_EBADMACHO) } + public static var malformedMachO: Errno { .init(rawValue: _EBADMACHO) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "malformedMachO") @@ -1199,7 +1206,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ECANCELED`. @_alwaysEmitIntoClient - public static var canceled: Errno { Errno(_ECANCELED) } + public static var canceled: Errno { .init(rawValue: _ECANCELED) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "canceled") @@ -1212,7 +1219,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EIDRM`. @_alwaysEmitIntoClient - public static var identifierRemoved: Errno { Errno(_EIDRM) } + public static var identifierRemoved: Errno { .init(rawValue: _EIDRM) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "identifierRemoved") @@ -1225,7 +1232,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOMSG`. @_alwaysEmitIntoClient - public static var noMessage: Errno { Errno(_ENOMSG) } + public static var noMessage: Errno { .init(rawValue: _ENOMSG) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noMessage") @@ -1240,20 +1247,20 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EILSEQ`. @_alwaysEmitIntoClient - public static var illegalByteSequence: Errno { Errno(_EILSEQ) } + public static var illegalByteSequence: Errno { .init(rawValue: _EILSEQ) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "illegalByteSequence") public static var EILSEQ: Errno { illegalByteSequence } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Attribute not found. /// /// The specified extended attribute doesn't exist. /// /// The corresponding C error is `ENOATTR`. @_alwaysEmitIntoClient - public static var attributeNotFound: Errno { Errno(_ENOATTR) } + public static var attributeNotFound: Errno { .init(rawValue: _ENOATTR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "attributeNotFound") @@ -1268,7 +1275,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EBADMSG`. @_alwaysEmitIntoClient - public static var badMessage: Errno { Errno(_EBADMSG) } + public static var badMessage: Errno { .init(rawValue: _EBADMSG) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "badMessage") @@ -1281,23 +1288,25 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EMULTIHOP`. @_alwaysEmitIntoClient - public static var multiHop: Errno { Errno(_EMULTIHOP) } + public static var multiHop: Errno { .init(rawValue: _EMULTIHOP) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "multiHop") public static var EMULTIHOP: Errno { multiHop } +#if !os(WASI) /// No message available. /// /// No message was available to be received by the requested operation. /// /// The corresponding C error is `ENODATA`. @_alwaysEmitIntoClient - public static var noData: Errno { Errno(_ENODATA) } + public static var noData: Errno { .init(rawValue: _ENODATA) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noData") public static var ENODATA: Errno { noData } +#endif /// Reserved. /// @@ -1305,19 +1314,20 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOLINK`. @_alwaysEmitIntoClient - public static var noLink: Errno { Errno(_ENOLINK) } + public static var noLink: Errno { .init(rawValue: _ENOLINK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noLink") public static var ENOLINK: Errno { noLink } +#if !os(WASI) /// Reserved. /// /// This error is reserved for future use. /// /// The corresponding C error is `ENOSR`. @_alwaysEmitIntoClient - public static var noStreamResources: Errno { Errno(_ENOSR) } + public static var noStreamResources: Errno { .init(rawValue: _ENOSR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noStreamResources") @@ -1329,11 +1339,12 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `ENOSTR`. @_alwaysEmitIntoClient - public static var notStream: Errno { Errno(_ENOSTR) } + public static var notStream: Errno { .init(rawValue: _ENOSTR) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notStream") public static var ENOSTR: Errno { notStream } +#endif #endif /// Protocol error. @@ -1344,20 +1355,20 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EPROTO`. @_alwaysEmitIntoClient - public static var protocolError: Errno { Errno(_EPROTO) } + public static var protocolError: Errno { .init(rawValue: _EPROTO) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "protocolError") public static var EPROTO: Errno { protocolError } -#if !os(OpenBSD) +#if !os(OpenBSD) && !os(WASI) /// Reserved. /// /// This error is reserved for future use. /// /// The corresponding C error is `ETIME`. @_alwaysEmitIntoClient - public static var timeout: Errno { Errno(_ETIME) } + public static var timeout: Errno { .init(rawValue: _ETIME) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "timeout") @@ -1372,7 +1383,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// The corresponding C error is `EOPNOTSUPP`. @_alwaysEmitIntoClient - public static var notSupportedOnSocket: Errno { Errno(_EOPNOTSUPP) } + public static var notSupportedOnSocket: Errno { .init(rawValue: _EOPNOTSUPP) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notSupportedOnSocket") @@ -1382,22 +1393,22 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { // Constants defined in header but not man page @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) extension Errno { - /// Operation would block. /// /// The corresponding C error is `EWOULDBLOCK`. @_alwaysEmitIntoClient - public static var wouldBlock: Errno { Errno(_EWOULDBLOCK) } + public static var wouldBlock: Errno { .init(rawValue: _EWOULDBLOCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "wouldBlock") public static var EWOULDBLOCK: Errno { wouldBlock } +#if !os(WASI) /// Too many references: can't splice. /// /// The corresponding C error is `ETOOMANYREFS`. @_alwaysEmitIntoClient - public static var tooManyReferences: Errno { Errno(_ETOOMANYREFS) } + public static var tooManyReferences: Errno { .init(rawValue: _ETOOMANYREFS) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyReferences") @@ -1407,18 +1418,19 @@ extension Errno { /// /// The corresponding C error is `EREMOTE`. @_alwaysEmitIntoClient - public static var tooManyRemoteLevels: Errno { Errno(_EREMOTE) } + public static var tooManyRemoteLevels: Errno { .init(rawValue: _EREMOTE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyRemoteLevels") public static var EREMOTE: Errno { tooManyRemoteLevels } +#endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// No such policy registered. /// /// The corresponding C error is `ENOPOLICY`. @_alwaysEmitIntoClient - public static var noSuchPolicy: Errno { Errno(_ENOPOLICY) } + public static var noSuchPolicy: Errno { .init(rawValue: _ENOPOLICY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noSuchPolicy") @@ -1430,7 +1442,7 @@ extension Errno { /// /// The corresponding C error is `ENOTRECOVERABLE`. @_alwaysEmitIntoClient - public static var notRecoverable: Errno { Errno(_ENOTRECOVERABLE) } + public static var notRecoverable: Errno { .init(rawValue: _ENOTRECOVERABLE) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notRecoverable") @@ -1440,19 +1452,19 @@ extension Errno { /// /// The corresponding C error is `EOWNERDEAD`. @_alwaysEmitIntoClient - public static var previousOwnerDied: Errno { Errno(_EOWNERDEAD) } + public static var previousOwnerDied: Errno { .init(rawValue: _EOWNERDEAD) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "previousOwnerDied") public static var EOWNERDEAD: Errno { previousOwnerDied } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Interface output queue is full. /// /// The corresponding C error is `EQFULL`. @_alwaysEmitIntoClient - public static var outputQueueFull: Errno { Errno(_EQFULL) } + public static var outputQueueFull: Errno { .init(rawValue: _EQFULL) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "outputQueueFull") @@ -1466,7 +1478,7 @@ extension Errno { /// /// The corresponding C error is `ELAST`. @_alwaysEmitIntoClient - public static var lastErrnoValue: Errno { Errno(_ELAST) } + public static var lastErrnoValue: Errno { .init(rawValue: _ELAST) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "lastErrnoValue") diff --git a/Sources/System/ErrnoWindows.swift b/Sources/System/ErrnoWindows.swift new file mode 100644 index 0000000..cc481cb --- /dev/null +++ b/Sources/System/ErrnoWindows.swift @@ -0,0 +1,20 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +#if os(Windows) + +import WinSDK + +extension Errno { + internal init(windowsError: DWORD) { + self.init(rawValue: _mapWindowsErrorToErrno(windowsError)) + } +} + +#endif diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 556e63e..d7b931e 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -45,7 +45,8 @@ extension FileDescriptor { extension FileDescriptor { /// The desired read and write access for a newly opened file. @frozen - public struct AccessMode: RawRepresentable, Hashable, Codable { + @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) + public struct AccessMode: RawRepresentable, Sendable, Hashable, Codable { /// The raw C access mode. @_alwaysEmitIntoClient public var rawValue: CInt @@ -87,7 +88,8 @@ extension FileDescriptor { /// Options that specify behavior for a newly-opened file. @frozen - public struct OpenOptions: OptionSet, Hashable, Codable { + @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) + public struct OpenOptions: OptionSet, Sendable, Hashable, Codable { /// The raw C options. @_alwaysEmitIntoClient public var rawValue: CInt @@ -96,9 +98,6 @@ extension FileDescriptor { @_alwaysEmitIntoClient public init(rawValue: CInt) { self.rawValue = rawValue } - @_alwaysEmitIntoClient - private init(_ raw: CInt) { self.init(rawValue: raw) } - #if !os(Windows) /// Indicates that opening the file doesn't /// wait for the file or device to become available. @@ -115,7 +114,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_NONBLOCK`. @_alwaysEmitIntoClient - public static var nonBlocking: OpenOptions { OpenOptions(_O_NONBLOCK) } + public static var nonBlocking: OpenOptions { .init(rawValue: _O_NONBLOCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "nonBlocking") @@ -131,7 +130,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_APPEND`. @_alwaysEmitIntoClient - public static var append: OpenOptions { OpenOptions(_O_APPEND) } + public static var append: OpenOptions { .init(rawValue: _O_APPEND) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "append") @@ -141,7 +140,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_CREAT`. @_alwaysEmitIntoClient - public static var create: OpenOptions { OpenOptions(_O_CREAT) } + public static var create: OpenOptions { .init(rawValue: _O_CREAT) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "create") @@ -155,7 +154,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_TRUNC`. @_alwaysEmitIntoClient - public static var truncate: OpenOptions { OpenOptions(_O_TRUNC) } + public static var truncate: OpenOptions { .init(rawValue: _O_TRUNC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "truncate") @@ -177,13 +176,13 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_EXCL`. @_alwaysEmitIntoClient - public static var exclusiveCreate: OpenOptions { OpenOptions(_O_EXCL) } + public static var exclusiveCreate: OpenOptions { .init(rawValue: _O_EXCL) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "exclusiveCreate") public static var O_EXCL: OpenOptions { exclusiveCreate } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Indicates that opening the file /// atomically obtains a shared lock on the file. /// @@ -195,7 +194,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_SHLOCK`. @_alwaysEmitIntoClient - public static var sharedLock: OpenOptions { OpenOptions(_O_SHLOCK) } + public static var sharedLock: OpenOptions { .init(rawValue: _O_SHLOCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "sharedLock") @@ -212,7 +211,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_EXLOCK`. @_alwaysEmitIntoClient - public static var exclusiveLock: OpenOptions { OpenOptions(_O_EXLOCK) } + public static var exclusiveLock: OpenOptions { .init(rawValue: _O_EXLOCK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "exclusiveLock") @@ -230,7 +229,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_NOFOLLOW`. @_alwaysEmitIntoClient - public static var noFollow: OpenOptions { OpenOptions(_O_NOFOLLOW) } + public static var noFollow: OpenOptions { .init(rawValue: _O_NOFOLLOW) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noFollow") @@ -244,14 +243,14 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_DIRECTORY`. @_alwaysEmitIntoClient - public static var directory: OpenOptions { OpenOptions(_O_DIRECTORY) } + public static var directory: OpenOptions { .init(rawValue: _O_DIRECTORY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "directory") public static var O_DIRECTORY: OpenOptions { directory } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Indicates that opening the file /// opens symbolic links instead of following them. /// @@ -263,7 +262,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_SYMLINK`. @_alwaysEmitIntoClient - public static var symlink: OpenOptions { OpenOptions(_O_SYMLINK) } + public static var symlink: OpenOptions { .init(rawValue: _O_SYMLINK) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "symlink") @@ -279,7 +278,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_EVTONLY`. @_alwaysEmitIntoClient - public static var eventOnly: OpenOptions { OpenOptions(_O_EVTONLY) } + public static var eventOnly: OpenOptions { .init(rawValue: _O_EVTONLY) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "eventOnly") @@ -301,7 +300,7 @@ extension FileDescriptor { /// /// The corresponding C constant is `O_CLOEXEC`. @_alwaysEmitIntoClient - public static var closeOnExec: OpenOptions { OpenOptions(_O_CLOEXEC) } + public static var closeOnExec: OpenOptions { .init(rawValue: _O_CLOEXEC) } @_alwaysEmitIntoClient @available(*, unavailable, renamed: "closeOnExec") @@ -311,7 +310,8 @@ extension FileDescriptor { /// Options for specifying what a file descriptor's offset is relative to. @frozen - public struct SeekOrigin: RawRepresentable, Hashable, Codable { + @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) + public struct SeekOrigin: RawRepresentable, Sendable, Hashable, Codable { /// The raw C value. @_alwaysEmitIntoClient public var rawValue: CInt @@ -354,7 +354,7 @@ extension FileDescriptor { // TODO: These are available on some versions of Linux with appropriate // macro defines. -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// Indicates that the offset should be set /// to the next hole after the specified number of bytes. /// @@ -416,7 +416,7 @@ extension FileDescriptor.SeekOrigin case .start: return "start" case .current: return "current" case .end: return "end" -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN case .nextHole: return "nextHole" case .nextData: return "nextData" #endif @@ -435,7 +435,7 @@ extension FileDescriptor.OpenOptions /// A textual representation of the open options. @inline(never) public var description: String { -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN let descriptions: [(Element, StaticString)] = [ (.nonBlocking, ".nonBlocking"), (.append, ".append"), @@ -475,18 +475,7 @@ extension FileDescriptor.OpenOptions public var debugDescription: String { self.description } } -#if compiler(>=5.5) && canImport(_Concurrency) // The decision on whether to make FileDescriptor Sendable or not // is currently being discussed in https://github.com/apple/swift-system/pull/112 //@available(*, unavailable, message: "File descriptors are not completely thread-safe.") //extension FileDescriptor: Sendable {} - -@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -extension FileDescriptor.AccessMode: Sendable {} - -@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -extension FileDescriptor.OpenOptions: Sendable {} - -@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -extension FileDescriptor.SeekOrigin: Sendable {} -#endif diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index 2297aeb..3412834 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -135,8 +135,6 @@ extension FileDescriptor { if let permissions = permissions { return system_open(path, oFlag, permissions.rawValue) } - precondition(!options.contains(.create), - "Create must be given permissions") return system_open(path, oFlag) } return descOrError.map { FileDescriptor(rawValue: $0) } @@ -369,6 +367,7 @@ extension FileDescriptor { } } +#if !os(WASI) @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) extension FileDescriptor { /// Duplicates this file descriptor and return the newly created copy. @@ -433,9 +432,10 @@ extension FileDescriptor { fatalError("Not implemented") } } +#endif -#if !os(Windows) -@available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) +#if !os(WASI) +@available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *) extension FileDescriptor { /// Creates a unidirectional data channel, which can be used for interprocess communication. /// @@ -443,12 +443,12 @@ extension FileDescriptor { /// /// The corresponding C function is `pipe`. @_alwaysEmitIntoClient - @available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) + @available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *) public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { try _pipe().get() } - @available(/*System 1.1.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) + @available(/*System 1.1.0: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4*/iOS 8, *) @usableFromInline internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { var fds: (Int32, Int32) = (-1, -1) @@ -463,7 +463,6 @@ extension FileDescriptor { } #endif -#if !os(Windows) @available(/*System 1.2.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) extension FileDescriptor { /// Truncates or extends the file referenced by this file descriptor. @@ -509,4 +508,47 @@ extension FileDescriptor { } } } -#endif + +extension FilePermissions { + /// The file creation permission mask (aka "umask"). + /// + /// Permissions set in this mask will be cleared by functions that create + /// files or directories. Note that this mask is process-wide, and that + /// *getting* it is not thread safe. + @_alwaysEmitIntoClient + internal static var creationMask: FilePermissions { + get { + let oldMask = _umask(0o22) + _ = _umask(oldMask) + return FilePermissions(rawValue: oldMask) + } + set { + _ = _umask(newValue.rawValue) + } + } + + /// Change the file creation permission mask, run some code, then + /// restore it to its original value. + /// + /// - Parameters: + /// - permissions: The new permission mask. + /// + /// This is more efficient than reading `creationMask` and restoring it + /// afterwards, because of the way reading the creation mask works. + @_alwaysEmitIntoClient + internal static func withCreationMask( + _ permissions: FilePermissions, + body: () throws -> R + ) rethrows -> R { + let oldMask = _umask(permissions.rawValue) + defer { + _ = _umask(oldMask) + } + return try body() + } + + @usableFromInline + internal static func _umask(_ mode: CModeT) -> CModeT { + return system_umask(mode) + } +} diff --git a/Sources/System/FilePath/FilePath.swift b/Sources/System/FilePath/FilePath.swift index c1dfd7f..67752c0 100644 --- a/Sources/System/FilePath/FilePath.swift +++ b/Sources/System/FilePath/FilePath.swift @@ -38,7 +38,7 @@ /// are file-system–specific and have additional considerations /// like case insensitivity, Unicode normalization, and symbolic links. @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -public struct FilePath { +public struct FilePath: Sendable { // TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition, // components, etc. internal var _storage: SystemString @@ -66,9 +66,22 @@ extension FilePath { } @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -extension FilePath: Hashable, Codable {} - -#if compiler(>=5.5) && canImport(_Concurrency) -@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -extension FilePath: Sendable {} -#endif +extension FilePath: Hashable, Codable { + // Encoder is synthesized; it probably should have been explicit and used + // a single-value container, but making that change now is somewhat risky. + + // Decoder is written explicitly to ensure that we validate invariants on + // untrusted input. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self._storage = try container.decode(SystemString.self, forKey: ._storage) + guard _invariantsSatisfied() else { + throw DecodingError.dataCorruptedError( + forKey: ._storage, + in: container, + debugDescription: + "Encoding does not satisfy the invariants of FilePath" + ) + } + } +} diff --git a/Sources/System/FilePath/FilePathComponentView.swift b/Sources/System/FilePath/FilePathComponentView.swift index efdd084..39381b4 100644 --- a/Sources/System/FilePath/FilePathComponentView.swift +++ b/Sources/System/FilePath/FilePathComponentView.swift @@ -28,7 +28,8 @@ extension FilePath { /// /// path.components.removeAll { $0.kind == .currentDirectory } /// // path is "/home/username/bin/scripts/tree" - public struct ComponentView { + @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) + public struct ComponentView: Sendable { internal var _path: FilePath internal var _start: SystemString.Index @@ -39,30 +40,6 @@ extension FilePath { } } - #if SYSTEM_PACKAGE // Workaround for a __consuming getter bug in Swift 5.3.3 - /// View the non-root components that make up this path. - public var components: ComponentView { - get { ComponentView(self) } - _modify { - // RRC's empty init means that we can't guarantee that the yielded - // view will restore our root. So copy it out first. - // - // TODO(perf): Small-form root (especially on Unix). Have Root - // always copy out (not worth ref counting). Make sure that we're - // not needlessly sliding values around or triggering a COW - let rootStr = self.root?._systemString ?? SystemString() - var comp = ComponentView(self) - self = FilePath() - defer { - self = comp._path - if root?._slice.elementsEqual(rootStr) != true { - self.root = Root(rootStr) - } - } - yield &comp - } - } - #else /// View the non-root components that make up this path. public var components: ComponentView { __consuming get { ComponentView(self) } @@ -85,13 +62,14 @@ extension FilePath { yield &comp } } - #endif } @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) extension FilePath.ComponentView: BidirectionalCollection { public typealias Element = FilePath.Component - public struct Index: Comparable, Hashable { + + @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) + public struct Index: Sendable, Comparable, Hashable { internal typealias Storage = SystemString.Index internal var _storage: Storage @@ -239,11 +217,3 @@ extension FilePath.ComponentView { #endif // DEBUG } } - -#if compiler(>=5.5) && canImport(_Concurrency) -@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) -extension FilePath.ComponentView: Sendable {} - -@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) -extension FilePath.ComponentView.Index: Sendable {} -#endif diff --git a/Sources/System/FilePath/FilePathComponents.swift b/Sources/System/FilePath/FilePathComponents.swift index ecd713e..b304a0a 100644 --- a/Sources/System/FilePath/FilePathComponents.swift +++ b/Sources/System/FilePath/FilePathComponents.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -28,7 +28,8 @@ extension FilePath { /// * `\\server\share\` /// * `\\?\UNC\server\share\` /// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\` - public struct Root { + @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) + public struct Root: Sendable { internal var _path: FilePath internal var _rootEnd: SystemString.Index @@ -54,7 +55,8 @@ extension FilePath { /// file.kind == .regular // true /// file.extension // "txt" /// path.append(file) // path is "/tmp/foo.txt" - public struct Component { + @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) + public struct Component: Sendable { internal var _path: FilePath internal var _range: Range @@ -78,7 +80,8 @@ extension FilePath.Component { /// Whether a component is a regular file or directory name, or a special /// directory `.` or `..` @frozen - public enum Kind { + @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) + public enum Kind: Sendable { /// The special directory `.`, representing the current directory. case currentDirectory @@ -143,7 +146,7 @@ extension _StrSlice { internal func _withSystemChars( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try _storage.withSystemChars { + try _storage.withNullTerminatedSystemChars { try f(UnsafeBufferPointer(rebasing: $0[_range])) } } @@ -285,14 +288,3 @@ extension FilePath.Root { #endif } } - -#if compiler(>=5.5) && canImport(_Concurrency) -@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) -extension FilePath.Root: Sendable {} - -@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) -extension FilePath.Component: Sendable {} - -@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) -extension FilePath.Component.Kind: Sendable {} -#endif diff --git a/Sources/System/FilePath/FilePathParsing.swift b/Sources/System/FilePath/FilePathParsing.swift index 6d01477..c31e6a5 100644 --- a/Sources/System/FilePath/FilePathParsing.swift +++ b/Sources/System/FilePath/FilePathParsing.swift @@ -89,6 +89,11 @@ extension SystemString { // `_prenormalizeWindowsRoots` and resume. readIdx = _prenormalizeWindowsRoots() writeIdx = readIdx + + // Skip redundant separators + while readIdx < endIndex && isSeparator(self[readIdx]) { + self.formIndex(after: &readIdx) + } } else { assert(genericSeparator == platformSeparator) } @@ -330,10 +335,13 @@ extension FilePath { // Whether we are providing Windows paths @inline(__always) internal var _windowsPaths: Bool { + if let forceWindowsPaths = forceWindowsPaths { + return forceWindowsPaths + } #if os(Windows) return true #else - return forceWindowsPaths + return false #endif } @@ -367,13 +375,18 @@ extension FilePath { // MARK: - Invariants @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) extension FilePath { - internal func _invariantCheck() { - #if DEBUG + internal func _invariantsSatisfied() -> Bool { var normal = self normal._normalizeSeparators() - precondition(self == normal) - precondition(!self._storage._hasTrailingSeparator()) - precondition(_hasRoot == (self.root != nil)) + guard self == normal else { return false } + guard !self._storage._hasTrailingSeparator() else { return false } + guard _hasRoot == (self.root != nil) else { return false } + return true + } + + internal func _invariantCheck() { + #if DEBUG + precondition(_invariantsSatisfied()) #endif // DEBUG } } diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift new file mode 100644 index 0000000..c0edf95 --- /dev/null +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -0,0 +1,97 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +// MARK: - API + +/// Create a temporary path for the duration of the closure. +/// +/// - Parameters: +/// - basename: The base name for the temporary path. +/// - body: The closure to execute. +/// +/// Creates a temporary directory with a name based on the given `basename`, +/// executes `body`, passing in the path of the created directory, then +/// deletes the directory and all of its contents before returning. +internal func withTemporaryFilePath( + basename: FilePath.Component, + _ body: (FilePath) throws -> R +) throws -> R { + let temporaryDir = try createUniqueTemporaryDirectory(basename: basename) + defer { + try? _recursiveRemove(at: temporaryDir) + } + + return try body(temporaryDir) +} + +// MARK: - Internals + +fileprivate let base64 = Array( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8 +) + +/// Create a directory that is only accessible to the current user. +/// +/// - Parameters: +/// - path: The path of the directory to create. +/// - Returns: `true` if a new directory was created. +/// +/// This function will throw if there is an error, except if the error +/// is that the directory exists, in which case it returns `false`. +fileprivate func makeLockedDownDirectory(at path: FilePath) throws -> Bool { + return try path.withPlatformString { + if system_mkdir($0, 0o700) == 0 { + return true + } + let err = system_errno + if err == Errno.fileExists.rawValue { + return false + } else { + throw Errno(rawValue: err) + } + } +} + +/// Generate a random string of base64 filename safe characters. +/// +/// - Parameters: +/// - length: The number of characters in the returned string. +/// - Returns: A random string of length `length`. +fileprivate func createRandomString(length: Int) -> String { + return String( + decoding: (0.. FilePath { + var tempDir = try _getTemporaryDirectory() + tempDir.append(basename) + + while true { + tempDir.extension = createRandomString(length: 16) + + if try makeLockedDownDirectory(at: tempDir) { + return tempDir + } + } +} diff --git a/Sources/System/FilePath/FilePathTempPosix.swift b/Sources/System/FilePath/FilePathTempPosix.swift new file mode 100644 index 0000000..e8713c2 --- /dev/null +++ b/Sources/System/FilePath/FilePathTempPosix.swift @@ -0,0 +1,153 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information + */ + +#if !os(Windows) + +/// Get the path to the system temporary directory. +internal func _getTemporaryDirectory() throws -> FilePath { + guard let tmp = system_getenv("TMPDIR") else { + return "/tmp" + } + + return FilePath(SystemString(platformString: tmp)) +} + +/// Delete the entire contents of a directory, including its subdirectories. +/// +/// - Parameters: +/// - path: The directory to be deleted. +/// +/// Removes a directory completely, including all of its contents. +internal func _recursiveRemove( + at path: FilePath +) throws { + let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory) + defer { + try? dirfd.close() + } + + let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0) + try withUnsafeBytes(of: dot) { + try recursiveRemove( + in: dirfd.rawValue, + name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress! + ) + } + + try path.withPlatformString { + if system_rmdir($0) != 0 { + throw Errno.current + } + } +} + +/// Open a directory by reference to its parent and name. +/// +/// - Parameters: +/// - dirfd: An open file descriptor for the parent directory. +/// - name: The name of the directory to open. +/// - Returns: A pointer to a `DIR` structure. +/// +/// This is like `opendir()`, but instead of taking a path, it uses a +/// file descriptor pointing at the parent, thus avoiding path length +/// limits. +fileprivate func impl_opendirat( + _ dirfd: CInt, + _ name: UnsafePointer +) -> system_DIRPtr? { + let fd = system_openat(dirfd, name, + FileDescriptor.AccessMode.readOnly.rawValue + | FileDescriptor.OpenOptions.directory.rawValue) + if fd < 0 { + return nil + } + return system_fdopendir(fd) +} + +/// Invoke a closure for each file within a particular directory. +/// +/// - Parameters: +/// - dirfd: The parent of the directory to be enumerated. +/// - subdir: The subdirectory to be enumerated. +/// - body: The closure that will be invoked. +/// +/// We skip the `.` and `..` pseudo-entries. +fileprivate func forEachFile( + in dirfd: CInt, + subdir: UnsafePointer, + _ body: (system_dirent) throws -> () +) throws { + guard let dir = impl_opendirat(dirfd, subdir) else { + throw Errno.current + } + defer { + _ = system_closedir(dir) + } + + while let dirent = system_readdir(dir) { + // Skip . and .. + if dirent.pointee.d_name.0 == 46 + && (dirent.pointee.d_name.1 == 0 + || (dirent.pointee.d_name.1 == 46 + && dirent.pointee.d_name.2 == 0)) { + continue + } + + try body(dirent.pointee) + } +} + +/// Delete the entire contents of a directory, including its subdirectories. +/// +/// - Parameters: +/// - dirfd: The parent of the directory to be removed. +/// - name: The name of the directory to be removed. +/// +/// Removes a directory completely, including all of its contents. +fileprivate func recursiveRemove( + in dirfd: CInt, + name: UnsafePointer +) throws { + // First, deal with subdirectories + try forEachFile(in: dirfd, subdir: name) { dirent in + if dirent.d_type == SYSTEM_DT_DIR { + try withUnsafeBytes(of: dirent.d_name) { + try recursiveRemove( + in: dirfd, + name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self) + .baseAddress! + ) + } + } + } + + // Now delete the contents of this directory + try forEachFile(in: dirfd, subdir: name) { dirent in + let flag: CInt + + if dirent.d_type == SYSTEM_DT_DIR { + flag = SYSTEM_AT_REMOVE_DIR + } else { + flag = 0 + } + + let result = withUnsafeBytes(of: dirent.d_name) { + system_unlinkat(dirfd, + $0.assumingMemoryBound(to: CInterop.PlatformChar.self) + .baseAddress!, + flag) + } + + if result != 0 { + throw Errno.current + } + } +} + +#endif // !os(Windows) diff --git a/Sources/System/FilePath/FilePathTempWindows.swift b/Sources/System/FilePath/FilePathTempWindows.swift new file mode 100644 index 0000000..0d97edc --- /dev/null +++ b/Sources/System/FilePath/FilePathTempWindows.swift @@ -0,0 +1,114 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +#if os(Windows) + +import WinSDK + +/// Get the path to the system temporary directory. +internal func _getTemporaryDirectory() throws -> FilePath { + return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self, + capacity: Int(MAX_PATH) + 1) { + buffer in + + guard GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) != 0 else { + throw Errno(windowsError: GetLastError()) + } + + return FilePath(SystemString(platformString: buffer.baseAddress!)) + } +} + +/// Invoke a closure for each file within a particular directory. +/// +/// - Parameters: +/// - path: The path at which we should enumerate items. +/// - body: The closure that will be invoked. +/// +/// We skip the `.` and `..` pseudo-entries. +fileprivate func forEachFile( + at path: FilePath, + _ body: (WIN32_FIND_DATAW) throws -> () +) rethrows { + let searchPath = path.appending("\\*") + + try searchPath.withPlatformString { szPath in + var findData = WIN32_FIND_DATAW() + let hFind = FindFirstFileW(szPath, &findData) + if hFind == INVALID_HANDLE_VALUE { + throw Errno(windowsError: GetLastError()) + } + defer { + FindClose(hFind) + } + + repeat { + // Skip . and .. + if findData.cFileName.0 == 46 + && (findData.cFileName.1 == 0 + || (findData.cFileName.1 == 46 + && findData.cFileName.2 == 0)) { + continue + } + + try body(findData) + } while FindNextFileW(hFind, &findData) + } +} + +/// Delete the entire contents of a directory, including its subdirectories. +/// +/// - Parameters: +/// - path: The directory to be deleted. +/// +/// Removes a directory completely, including all of its contents. +internal func _recursiveRemove( + at path: FilePath +) throws { + // First, deal with subdirectories + try forEachFile(at: path) { findData in + if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 { + let name = withUnsafeBytes(of: findData.cFileName) { + return SystemString(platformString: $0.assumingMemoryBound( + to: CInterop.PlatformChar.self).baseAddress!) + } + let component = FilePath.Component(name)! + let subpath = path.appending(component) + + try _recursiveRemove(at: subpath) + } + } + + // Now delete everything else + try forEachFile(at: path) { findData in + let name = withUnsafeBytes(of: findData.cFileName) { + return SystemString(platformString: $0.assumingMemoryBound( + to: CInterop.PlatformChar.self).baseAddress!) + } + let component = FilePath.Component(name)! + let subpath = path.appending(component) + + if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 { + try subpath.withPlatformString { + if !DeleteFileW($0) { + throw Errno(windowsError: GetLastError()) + } + } + } + } + + // Finally, delete the parent + try path.withPlatformString { + if !RemoveDirectoryW($0) { + throw Errno(windowsError: GetLastError()) + } + } +} + +#endif // os(Windows) diff --git a/Sources/System/FilePermissions.swift b/Sources/System/FilePermissions.swift index 9bd6c5f..918246e 100644 --- a/Sources/System/FilePermissions.swift +++ b/Sources/System/FilePermissions.swift @@ -18,7 +18,7 @@ /// perms == [.ownerReadWrite, .groupRead, .otherRead] // true @frozen @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -public struct FilePermissions: OptionSet, Hashable, Codable { +public struct FilePermissions: OptionSet, Sendable, Hashable, Codable { /// The raw C file permissions. @_alwaysEmitIntoClient public let rawValue: CModeT @@ -27,104 +27,101 @@ public struct FilePermissions: OptionSet, Hashable, Codable { @_alwaysEmitIntoClient public init(rawValue: CModeT) { self.rawValue = rawValue } - @_alwaysEmitIntoClient - private init(_ raw: CModeT) { self.init(rawValue: raw) } - /// Indicates that other users have read-only permission. @_alwaysEmitIntoClient - public static var otherRead: FilePermissions { FilePermissions(0o4) } + public static var otherRead: FilePermissions { .init(rawValue: 0o4) } /// Indicates that other users have write-only permission. @_alwaysEmitIntoClient - public static var otherWrite: FilePermissions { FilePermissions(0o2) } + public static var otherWrite: FilePermissions { .init(rawValue: 0o2) } /// Indicates that other users have execute-only permission. @_alwaysEmitIntoClient - public static var otherExecute: FilePermissions { FilePermissions(0o1) } + public static var otherExecute: FilePermissions { .init(rawValue: 0o1) } /// Indicates that other users have read-write permission. @_alwaysEmitIntoClient - public static var otherReadWrite: FilePermissions { FilePermissions(0o6) } + public static var otherReadWrite: FilePermissions { .init(rawValue: 0o6) } /// Indicates that other users have read-execute permission. @_alwaysEmitIntoClient - public static var otherReadExecute: FilePermissions { FilePermissions(0o5) } + public static var otherReadExecute: FilePermissions { .init(rawValue: 0o5) } /// Indicates that other users have write-execute permission. @_alwaysEmitIntoClient - public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) } + public static var otherWriteExecute: FilePermissions { .init(rawValue: 0o3) } /// Indicates that other users have read, write, and execute permission. @_alwaysEmitIntoClient - public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) } + public static var otherReadWriteExecute: FilePermissions { .init(rawValue: 0o7) } /// Indicates that the group has read-only permission. @_alwaysEmitIntoClient - public static var groupRead: FilePermissions { FilePermissions(0o40) } + public static var groupRead: FilePermissions { .init(rawValue: 0o40) } /// Indicates that the group has write-only permission. @_alwaysEmitIntoClient - public static var groupWrite: FilePermissions { FilePermissions(0o20) } + public static var groupWrite: FilePermissions { .init(rawValue: 0o20) } /// Indicates that the group has execute-only permission. @_alwaysEmitIntoClient - public static var groupExecute: FilePermissions { FilePermissions(0o10) } + public static var groupExecute: FilePermissions { .init(rawValue: 0o10) } /// Indicates that the group has read-write permission. @_alwaysEmitIntoClient - public static var groupReadWrite: FilePermissions { FilePermissions(0o60) } + public static var groupReadWrite: FilePermissions { .init(rawValue: 0o60) } /// Indicates that the group has read-execute permission. @_alwaysEmitIntoClient - public static var groupReadExecute: FilePermissions { FilePermissions(0o50) } + public static var groupReadExecute: FilePermissions { .init(rawValue: 0o50) } /// Indicates that the group has write-execute permission. @_alwaysEmitIntoClient - public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) } + public static var groupWriteExecute: FilePermissions { .init(rawValue: 0o30) } /// Indicates that the group has read, write, and execute permission. @_alwaysEmitIntoClient - public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) } + public static var groupReadWriteExecute: FilePermissions { .init(rawValue: 0o70) } /// Indicates that the owner has read-only permission. @_alwaysEmitIntoClient - public static var ownerRead: FilePermissions { FilePermissions(0o400) } + public static var ownerRead: FilePermissions { .init(rawValue: 0o400) } /// Indicates that the owner has write-only permission. @_alwaysEmitIntoClient - public static var ownerWrite: FilePermissions { FilePermissions(0o200) } + public static var ownerWrite: FilePermissions { .init(rawValue: 0o200) } /// Indicates that the owner has execute-only permission. @_alwaysEmitIntoClient - public static var ownerExecute: FilePermissions { FilePermissions(0o100) } + public static var ownerExecute: FilePermissions { .init(rawValue: 0o100) } /// Indicates that the owner has read-write permission. @_alwaysEmitIntoClient - public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) } + public static var ownerReadWrite: FilePermissions { .init(rawValue: 0o600) } /// Indicates that the owner has read-execute permission. @_alwaysEmitIntoClient - public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) } + public static var ownerReadExecute: FilePermissions { .init(rawValue: 0o500) } /// Indicates that the owner has write-execute permission. @_alwaysEmitIntoClient - public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) } + public static var ownerWriteExecute: FilePermissions { .init(rawValue: 0o300) } /// Indicates that the owner has read, write, and execute permission. @_alwaysEmitIntoClient - public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) } + public static var ownerReadWriteExecute: FilePermissions { .init(rawValue: 0o700) } /// Indicates that the file is executed as the owner. /// /// For more information, see the `setuid(2)` man page. @_alwaysEmitIntoClient - public static var setUserID: FilePermissions { FilePermissions(0o4000) } + public static var setUserID: FilePermissions { .init(rawValue: 0o4000) } /// Indicates that the file is executed as the group. /// /// For more information, see the `setgid(2)` man page. @_alwaysEmitIntoClient - public static var setGroupID: FilePermissions { FilePermissions(0o2000) } + public static var setGroupID: FilePermissions { .init(rawValue: 0o2000) } /// Indicates that executable's text segment /// should be kept in swap space even after it exits. @@ -132,7 +129,7 @@ public struct FilePermissions: OptionSet, Hashable, Codable { /// For more information, see the `chmod(2)` man page's /// discussion of `S_ISVTX` (the sticky bit). @_alwaysEmitIntoClient - public static var saveText: FilePermissions { FilePermissions(0o1000) } + public static var saveText: FilePermissions { .init(rawValue: 0o1000) } } @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) @@ -175,8 +172,3 @@ extension FilePermissions /// A textual representation of the file permissions, suitable for debugging. public var debugDescription: String { self.description } } - -#if compiler(>=5.5) && canImport(_Concurrency) -@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) -extension FilePermissions: Sendable {} -#endif diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index a71ef12..80d37d0 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -1,13 +1,13 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN import Darwin #elseif os(Windows) import CSystem @@ -18,6 +18,11 @@ import Glibc #elseif canImport(Musl) @_implementationOnly import CSystem import Musl +#elseif canImport(WASILibc) +import WASILibc +#elseif canImport(Bionic) +@_implementationOnly import CSystem +import Bionic #else #error("Unsupported Platform") #endif diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 592e38c..904e5b2 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -11,7 +11,7 @@ // they can be used anywhere without imports and without confusion to // unavailable local decls. -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN import Darwin #elseif os(Windows) import CSystem @@ -21,12 +21,17 @@ import Glibc #elseif canImport(Musl) import CSystem import Musl +#elseif canImport(WASILibc) +import CSystem +import WASILibc +#elseif canImport(Android) +import Android #else #error("Unsupported Platform") #endif // MARK: errno -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _ERRNO_NOT_USED: CInt { 0 } #endif @@ -73,7 +78,7 @@ internal var _EACCES: CInt { EACCES } @_alwaysEmitIntoClient internal var _EFAULT: CInt { EFAULT } -#if !os(Windows) +#if !os(Windows) && !os(WASI) @_alwaysEmitIntoClient internal var _ENOTBLK: CInt { ENOTBLK } #endif @@ -141,7 +146,13 @@ internal var _ERANGE: CInt { ERANGE } internal var _EAGAIN: CInt { EAGAIN } @_alwaysEmitIntoClient -internal var _EWOULDBLOCK: CInt { EWOULDBLOCK } +internal var _EWOULDBLOCK: CInt { +#if os(WASI) + _getConst_EWOULDBLOCK() +#else + EWOULDBLOCK +#endif +} @_alwaysEmitIntoClient internal var _EINPROGRESS: CInt { EINPROGRESS } @@ -167,6 +178,7 @@ internal var _ENOPROTOOPT: CInt { ENOPROTOOPT } @_alwaysEmitIntoClient internal var _EPROTONOSUPPORT: CInt { EPROTONOSUPPORT } +#if !os(WASI) @_alwaysEmitIntoClient internal var _ESOCKTNOSUPPORT: CInt { #if os(Windows) @@ -175,6 +187,7 @@ internal var _ESOCKTNOSUPPORT: CInt { return ESOCKTNOSUPPORT #endif } +#endif @_alwaysEmitIntoClient internal var _ENOTSUP: CInt { @@ -185,6 +198,7 @@ internal var _ENOTSUP: CInt { #endif } +#if !os(WASI) @_alwaysEmitIntoClient internal var _EPFNOSUPPORT: CInt { #if os(Windows) @@ -193,6 +207,7 @@ internal var _EPFNOSUPPORT: CInt { return EPFNOSUPPORT #endif } +#endif @_alwaysEmitIntoClient internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT } @@ -227,6 +242,7 @@ internal var _EISCONN: CInt { EISCONN } @_alwaysEmitIntoClient internal var _ENOTCONN: CInt { ENOTCONN } +#if !os(WASI) @_alwaysEmitIntoClient internal var _ESHUTDOWN: CInt { #if os(Windows) @@ -244,6 +260,7 @@ internal var _ETOOMANYREFS: CInt { return ETOOMANYREFS #endif } +#endif @_alwaysEmitIntoClient internal var _ETIMEDOUT: CInt { ETIMEDOUT } @@ -257,6 +274,7 @@ internal var _ELOOP: CInt { ELOOP } @_alwaysEmitIntoClient internal var _ENAMETOOLONG: CInt { ENAMETOOLONG } +#if !os(WASI) @_alwaysEmitIntoClient internal var _EHOSTDOWN: CInt { #if os(Windows) @@ -265,6 +283,7 @@ internal var _EHOSTDOWN: CInt { return EHOSTDOWN #endif } +#endif @_alwaysEmitIntoClient internal var _EHOSTUNREACH: CInt { EHOSTUNREACH } @@ -272,11 +291,12 @@ internal var _EHOSTUNREACH: CInt { EHOSTUNREACH } @_alwaysEmitIntoClient internal var _ENOTEMPTY: CInt { ENOTEMPTY } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EPROCLIM: CInt { EPROCLIM } #endif +#if !os(WASI) @_alwaysEmitIntoClient internal var _EUSERS: CInt { #if os(Windows) @@ -285,6 +305,7 @@ internal var _EUSERS: CInt { return EUSERS #endif } +#endif @_alwaysEmitIntoClient internal var _EDQUOT: CInt { @@ -304,6 +325,7 @@ internal var _ESTALE: CInt { #endif } +#if !os(WASI) @_alwaysEmitIntoClient internal var _EREMOTE: CInt { #if os(Windows) @@ -312,8 +334,9 @@ internal var _EREMOTE: CInt { return EREMOTE #endif } +#endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EBADRPC: CInt { EBADRPC } @@ -336,7 +359,7 @@ internal var _ENOLCK: CInt { ENOLCK } @_alwaysEmitIntoClient internal var _ENOSYS: CInt { ENOSYS } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EFTYPE: CInt { EFTYPE } @@ -358,7 +381,7 @@ internal var _EDEVERR: CInt { EDEVERR } internal var _EOVERFLOW: CInt { EOVERFLOW } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EBADEXEC: CInt { EBADEXEC } @@ -386,7 +409,7 @@ internal var _ENOMSG: CInt { ENOMSG } @_alwaysEmitIntoClient internal var _EILSEQ: CInt { EILSEQ } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _ENOATTR: CInt { ENOATTR } #endif @@ -399,32 +422,43 @@ internal var _EBADMSG: CInt { EBADMSG } @_alwaysEmitIntoClient internal var _EMULTIHOP: CInt { EMULTIHOP } +#if !os(WASI) @_alwaysEmitIntoClient internal var _ENODATA: CInt { ENODATA } +#endif @_alwaysEmitIntoClient internal var _ENOLINK: CInt { ENOLINK } +#if !os(WASI) @_alwaysEmitIntoClient internal var _ENOSR: CInt { ENOSR } @_alwaysEmitIntoClient internal var _ENOSTR: CInt { ENOSTR } #endif +#endif @_alwaysEmitIntoClient internal var _EPROTO: CInt { EPROTO } -#if !os(OpenBSD) +#if !os(OpenBSD) && !os(WASI) @_alwaysEmitIntoClient internal var _ETIME: CInt { ETIME } #endif #endif -@_alwaysEmitIntoClient -internal var _EOPNOTSUPP: CInt { EOPNOTSUPP } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +@_alwaysEmitIntoClient +internal var _EOPNOTSUPP: CInt { +#if os(WASI) + _getConst_EOPNOTSUPP() +#else + EOPNOTSUPP +#endif +} + +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _ENOPOLICY: CInt { ENOPOLICY } #endif @@ -437,7 +471,7 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE } internal var _EOWNERDEAD: CInt { EOWNERDEAD } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EQFULL: CInt { EQFULL } @@ -462,17 +496,35 @@ internal var _O_ACCMODE: CInt { 0x03|O_SEARCH } #else // TODO: API? @_alwaysEmitIntoClient -internal var _O_ACCMODE: CInt { O_ACCMODE } +internal var _O_ACCMODE: CInt { +#if os(WASI) + _getConst_O_ACCMODE() +#else + O_ACCMODE +#endif +} #endif @_alwaysEmitIntoClient -internal var _O_NONBLOCK: CInt { O_NONBLOCK } +internal var _O_NONBLOCK: CInt { +#if os(WASI) + _getConst_O_NONBLOCK() +#else + O_NONBLOCK +#endif +} #endif @_alwaysEmitIntoClient -internal var _O_APPEND: CInt { O_APPEND } +internal var _O_APPEND: CInt { +#if os(WASI) + _getConst_O_APPEND() +#else + O_APPEND +#endif +} -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_SHLOCK: CInt { O_SHLOCK } @@ -481,24 +533,44 @@ internal var _O_EXLOCK: CInt { O_EXLOCK } #endif #if !os(Windows) +#if !os(WASI) // TODO: API? @_alwaysEmitIntoClient internal var _O_ASYNC: CInt { O_ASYNC } +#endif @_alwaysEmitIntoClient internal var _O_NOFOLLOW: CInt { O_NOFOLLOW } #endif @_alwaysEmitIntoClient -internal var _O_CREAT: CInt { O_CREAT } +internal var _O_CREAT: CInt { +#if os(WASI) + _getConst_O_CREAT() +#else + O_CREAT +#endif +} @_alwaysEmitIntoClient -internal var _O_TRUNC: CInt { O_TRUNC } +internal var _O_TRUNC: CInt { +#if os(WASI) + _getConst_O_TRUNC() +#else + O_TRUNC +#endif +} @_alwaysEmitIntoClient -internal var _O_EXCL: CInt { O_EXCL } +internal var _O_EXCL: CInt { +#if os(WASI) + _getConst_O_EXCL() +#else + O_EXCL +#endif +} -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_EVTONLY: CInt { O_EVTONLY } #endif @@ -509,10 +581,16 @@ internal var _O_EVTONLY: CInt { O_EVTONLY } internal var _O_NOCTTY: CInt { O_NOCTTY } @_alwaysEmitIntoClient -internal var _O_DIRECTORY: CInt { O_DIRECTORY } +internal var _O_DIRECTORY: CInt { +#if os(WASI) + _getConst_O_DIRECTORY() +#else + O_DIRECTORY +#endif +} #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_SYMLINK: CInt { O_SYMLINK } #endif @@ -531,7 +609,7 @@ internal var _SEEK_CUR: CInt { SEEK_CUR } @_alwaysEmitIntoClient internal var _SEEK_END: CInt { SEEK_END } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _SEEK_HOLE: CInt { SEEK_HOLE } diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 57abc6f..d18102a 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -12,7 +12,7 @@ // TODO: Should CSystem just include all the header files we need? -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN import Darwin #elseif os(Windows) import CSystem @@ -23,6 +23,11 @@ import Glibc #elseif canImport(Musl) @_implementationOnly import CSystem import Musl +#elseif canImport(WASILibc) +import WASILibc +#elseif canImport(Android) +@_implementationOnly import CSystem +import Android #else #error("Unsupported Platform") #endif @@ -31,7 +36,7 @@ internal typealias _COffT = off_t // MARK: syscalls and variables -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN internal var system_errno: CInt { get { Darwin.errno } set { Darwin.errno = newValue } @@ -58,6 +63,16 @@ internal var system_errno: CInt { get { Musl.errno } set { Musl.errno = newValue } } +#elseif canImport(WASILibc) +internal var system_errno: CInt { + get { WASILibc.errno } + set { WASILibc.errno = newValue } +} +#elseif canImport(Android) +internal var system_errno: CInt { + get { Android.errno } + set { Android.errno = newValue } +} #endif // MARK: C stdlib decls @@ -149,6 +164,24 @@ extension String { // TLS #if os(Windows) internal typealias _PlatformTLSKey = DWORD +#elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded)) +// Mock TLS storage for single-threaded WASI +internal final class _PlatformTLSKey { + fileprivate init() {} +} +private final class TLSStorage: @unchecked Sendable { + var storage = [ObjectIdentifier: UnsafeMutableRawPointer]() +} +private let sharedTLSStorage = TLSStorage() + +func pthread_setspecific(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) -> Int { + sharedTLSStorage.storage[ObjectIdentifier(key)] = p + return 0 +} + +func pthread_getspecific(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? { + sharedTLSStorage.storage[ObjectIdentifier(key)] +} #else internal typealias _PlatformTLSKey = pthread_key_t #endif @@ -160,6 +193,8 @@ internal func makeTLSKey() -> _PlatformTLSKey { fatalError("Unable to create key") } return raw + #elseif os(WASI) && (swift(<6.1) || !_runtime(_multithreaded)) + return _PlatformTLSKey() #else var raw = pthread_key_t() guard 0 == pthread_key_create(&raw, nil) else { diff --git a/Sources/System/Internals/Mocking.swift b/Sources/System/Internals/Mocking.swift index 405dc34..2945651 100644 --- a/Sources/System/Internals/Mocking.swift +++ b/Sources/System/Internals/Mocking.swift @@ -63,7 +63,7 @@ internal class MockingDriver { // Whether we should pretend to be Windows for syntactic operations // inside FilePath - fileprivate var forceWindowsSyntaxForPaths = false + fileprivate var forceWindowsSyntaxForPaths: Bool? = nil } private let driverKey: _PlatformTLSKey = { makeTLSKey() }() @@ -110,8 +110,8 @@ private var contextualMockingEnabled: Bool { extension MockingDriver { internal static var enabled: Bool { mockingEnabled } - internal static var forceWindowsPaths: Bool { - currentMockingDriver?.forceWindowsSyntaxForPaths ?? false + internal static var forceWindowsPaths: Bool? { + currentMockingDriver?.forceWindowsSyntaxForPaths } } @@ -128,7 +128,7 @@ internal var mockingEnabled: Bool { } @inline(__always) -internal var forceWindowsPaths: Bool { +internal var forceWindowsPaths: Bool? { #if !ENABLE_MOCKING return false #else @@ -196,15 +196,11 @@ internal func _mockOffT( #endif // ENABLE_MOCKING // Force paths to be treated as Windows syntactically if `enabled` is -// true. +// true, and as POSIX syntactically if not. internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) { #if ENABLE_MOCKING - guard enabled else { - body() - return - } MockingDriver.withMockingEnabled { driver in - driver.forceWindowsSyntaxForPaths = true + driver.forceWindowsSyntaxForPaths = enabled body() } #else diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 9fcb2f9..6f885be 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -1,20 +1,24 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN import Darwin #elseif canImport(Glibc) import Glibc #elseif canImport(Musl) import Musl +#elseif canImport(WASILibc) +import WASILibc #elseif os(Windows) import ucrt +#elseif canImport(Android) +import Android #else #error("Unsupported Platform") #endif @@ -71,7 +75,15 @@ internal func system_pread( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif +#if os(Android) + var zero = UInt8.zero + return withUnsafeMutablePointer(to: &zero) { + // this pread has a non-nullable `buf` pointer + pread(fd, buf ?? UnsafeMutableRawPointer($0), nbyte, offset) + } +#else return pread(fd, buf, nbyte, offset) +#endif } // lseek @@ -101,9 +113,18 @@ internal func system_pwrite( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif +#if os(Android) + var zero = UInt8.zero + return withUnsafeMutablePointer(to: &zero) { + // this pwrite has a non-nullable `buf` pointer + pwrite(fd, buf ?? UnsafeRawPointer($0), nbyte, offset) + } +#else return pwrite(fd, buf, nbyte, offset) +#endif } +#if !os(WASI) internal func system_dup(_ fd: Int32) -> Int32 { #if ENABLE_MOCKING if mockingEnabled { return _mock(fd) } @@ -117,8 +138,9 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 { #endif return dup2(fd, fd2) } +#endif -#if !os(Windows) +#if !os(WASI) internal func system_pipe(_ fds: UnsafeMutablePointer) -> CInt { #if ENABLE_MOCKING if mockingEnabled { return _mock(fds) } @@ -127,11 +149,111 @@ internal func system_pipe(_ fds: UnsafeMutablePointer) -> CInt { } #endif -#if !os(Windows) internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { #if ENABLE_MOCKING if mockingEnabled { return _mock(fd, length) } #endif return ftruncate(fd, length) } + +internal func system_mkdir( + _ path: UnsafePointer, + _ mode: CInterop.Mode +) -> CInt { +#if ENABLE_MOCKING + if mockingEnabled { return _mock(path: path, mode) } #endif + return mkdir(path, mode) +} + +internal func system_rmdir( + _ path: UnsafePointer +) -> CInt { +#if ENABLE_MOCKING + if mockingEnabled { return _mock(path: path) } +#endif + return rmdir(path) +} + +#if SYSTEM_PACKAGE_DARWIN +internal let SYSTEM_CS_DARWIN_USER_TEMP_DIR = _CS_DARWIN_USER_TEMP_DIR + +internal func system_confstr( + _ name: CInt, + _ buf: UnsafeMutablePointer, + _ len: Int +) -> Int { + return confstr(name, buf, len) +} +#endif + +#if !os(Windows) +internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR +internal let SYSTEM_DT_DIR = DT_DIR +internal typealias system_dirent = dirent +#if os(Linux) || os(Android) +internal typealias system_DIRPtr = OpaquePointer +#else +internal typealias system_DIRPtr = UnsafeMutablePointer +#endif + +internal func system_unlinkat( + _ fd: CInt, + _ path: UnsafePointer, + _ flag: CInt +) -> CInt { +#if ENABLE_MOCKING + if mockingEnabled { return _mock(fd, path, flag) } +#endif +return unlinkat(fd, path, flag) +} + +internal func system_fdopendir( + _ fd: CInt +) -> system_DIRPtr? { + return fdopendir(fd) +} + +internal func system_readdir( + _ dir: system_DIRPtr +) -> UnsafeMutablePointer? { + return readdir(dir) +} + +internal func system_rewinddir( + _ dir: system_DIRPtr +) { + return rewinddir(dir) +} + +internal func system_closedir( + _ dir: system_DIRPtr +) -> CInt { + return closedir(dir) +} + +internal func system_openat( + _ fd: CInt, + _ path: UnsafePointer, + _ oflag: Int32 +) -> CInt { +#if ENABLE_MOCKING + if mockingEnabled { + return _mock(fd, path, oflag) + } +#endif + return openat(fd, path, oflag) +} +#endif + +internal func system_umask( + _ mode: CInterop.Mode +) -> CInterop.Mode { + return umask(mode) +} + +internal func system_getenv( + _ name: UnsafePointer +) -> UnsafeMutablePointer? { + return getenv(name) +} diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index 2f3851b..048377b 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -12,13 +12,45 @@ import ucrt import WinSDK +fileprivate var _umask: CInterop.Mode = 0o22 + +@inline(__always) +func umask( + _ mode: CInterop.Mode +) -> CInterop.Mode { + let oldMask = _umask + _umask = mode + return oldMask +} + @inline(__always) internal func open( _ path: UnsafePointer, _ oflag: Int32 ) -> CInt { - var fh: CInt = -1 - _ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE) - return fh + let decodedFlags = DecodedOpenFlags(oflag) + + var saAttrs = SECURITY_ATTRIBUTES( + nLength: DWORD(MemoryLayout.size), + lpSecurityDescriptor: nil, + bInheritHandle: decodedFlags.bInheritHandle + ) + + let hFile = CreateFileW(path, + decodedFlags.dwDesiredAccess, + DWORD(FILE_SHARE_DELETE + | FILE_SHARE_READ + | FILE_SHARE_WRITE), + &saAttrs, + decodedFlags.dwCreationDisposition, + decodedFlags.dwFlagsAndAttributes, + nil) + + if hFile == INVALID_HANDLE_VALUE { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return _open_osfhandle(intptr_t(bitPattern: hFile), oflag); } @inline(__always) @@ -26,10 +58,41 @@ internal func open( _ path: UnsafePointer, _ oflag: Int32, _ mode: CInterop.Mode ) -> CInt { - // TODO(compnerd): Apply read/write permissions - var fh: CInt = -1 - _ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE) - return fh + let actualMode = mode & ~_umask + + guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + defer { + pSD.deallocate() + } + + let decodedFlags = DecodedOpenFlags(oflag) + + var saAttrs = SECURITY_ATTRIBUTES( + nLength: DWORD(MemoryLayout.size), + lpSecurityDescriptor: pSD, + bInheritHandle: decodedFlags.bInheritHandle + ) + + let hFile = CreateFileW(path, + decodedFlags.dwDesiredAccess, + DWORD(FILE_SHARE_DELETE + | FILE_SHARE_READ + | FILE_SHARE_WRITE), + &saAttrs, + decodedFlags.dwCreationDisposition, + decodedFlags.dwFlagsAndAttributes, + nil) + + if hFile == INVALID_HANDLE_VALUE { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return _open_osfhandle(intptr_t(bitPattern: hFile), oflag); } @inline(__always) @@ -80,7 +143,7 @@ internal func pread( _ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t ) -> Int { let handle: intptr_t = _get_osfhandle(fd) - if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) } + if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 } // NOTE: this is a non-owning handle, do *not* call CloseHandle on it let hFile: HANDLE = HANDLE(bitPattern: handle)! @@ -91,8 +154,7 @@ internal func pread( var nNumberOfBytesRead: DWORD = 0 if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) { - let _ = GetLastError() - // TODO(compnerd) map windows error to errno + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return Int(-1) } return Int(nNumberOfBytesRead) @@ -103,7 +165,7 @@ internal func pwrite( _ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t ) -> Int { let handle: intptr_t = _get_osfhandle(fd) - if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) } + if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 } // NOTE: this is a non-owning handle, do *not* call CloseHandle on it let hFile: HANDLE = HANDLE(bitPattern: handle)! @@ -115,11 +177,483 @@ internal func pwrite( var nNumberOfBytesWritten: DWORD = 0 if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten, &ovlOverlapped) { - let _ = GetLastError() - // TODO(compnerd) map windows error to errno + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return Int(-1) } return Int(nNumberOfBytesWritten) } +@inline(__always) +internal func pipe(_ fds: UnsafeMutablePointer) -> CInt { + return _pipe(fds, 4096, _O_BINARY | _O_NOINHERIT); +} + +@inline(__always) +internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { + let handle: intptr_t = _get_osfhandle(fd) + if handle == /* INVALID_HANDLE_VALUE */ -1 { ucrt._set_errno(EBADF); return -1 } + + // NOTE: this is a non-owning handle, do *not* call CloseHandle on it + let hFile: HANDLE = HANDLE(bitPattern: handle)! + let liDesiredLength = LARGE_INTEGER(QuadPart: LONGLONG(length)) + var liCurrentOffset = LARGE_INTEGER(QuadPart: 0) + + // Save the current position and restore it when we're done + if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset, + DWORD(FILE_CURRENT)) { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + defer { + _ = SetFilePointerEx(hFile, liCurrentOffset, nil, DWORD(FILE_BEGIN)); + } + + // Truncate (or extend) the file + if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN)) + || !SetEndOfFile(hFile) { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return 0; +} + +@inline(__always) +internal func mkdir( + _ path: UnsafePointer, + _ mode: CInterop.Mode +) -> CInt { + let actualMode = mode & ~_umask + + guard let pSD = _createSecurityDescriptor(from: actualMode, + for: .directory) else { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + defer { + pSD.deallocate() + } + + var saAttrs = SECURITY_ATTRIBUTES( + nLength: DWORD(MemoryLayout.size), + lpSecurityDescriptor: pSD, + bInheritHandle: false + ) + + if !CreateDirectoryW(path, &saAttrs) { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return 0; +} + +@inline(__always) +internal func rmdir( + _ path: UnsafePointer +) -> CInt { + if !RemoveDirectoryW(path) { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return 0; +} + +@usableFromInline +internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { + switch Int32(errorCode) { + case ERROR_SUCCESS: + return 0 + case ERROR_INVALID_FUNCTION, + ERROR_INVALID_ACCESS, + ERROR_INVALID_DATA, + ERROR_INVALID_PARAMETER, + ERROR_NEGATIVE_SEEK: + return EINVAL + case ERROR_FILE_NOT_FOUND, + ERROR_PATH_NOT_FOUND, + ERROR_INVALID_DRIVE, + ERROR_NO_MORE_FILES, + ERROR_BAD_NETPATH, + ERROR_BAD_NET_NAME, + ERROR_BAD_PATHNAME, + ERROR_FILENAME_EXCED_RANGE: + return ENOENT + case ERROR_TOO_MANY_OPEN_FILES: + return EMFILE + case ERROR_ACCESS_DENIED, + ERROR_CURRENT_DIRECTORY, + ERROR_LOCK_VIOLATION, + ERROR_NETWORK_ACCESS_DENIED, + ERROR_CANNOT_MAKE, + ERROR_FAIL_I24, + ERROR_DRIVE_LOCKED, + ERROR_SEEK_ON_DEVICE, + ERROR_NOT_LOCKED, + ERROR_LOCK_FAILED, + ERROR_WRITE_PROTECT...ERROR_SHARING_BUFFER_EXCEEDED: + return EACCES + case ERROR_INVALID_HANDLE, + ERROR_INVALID_TARGET_HANDLE, + ERROR_DIRECT_ACCESS_HANDLE: + return EBADF + case ERROR_ARENA_TRASHED, + ERROR_NOT_ENOUGH_MEMORY, + ERROR_INVALID_BLOCK, + ERROR_NOT_ENOUGH_QUOTA: + return ENOMEM + case ERROR_BAD_ENVIRONMENT: + return E2BIG + case ERROR_BAD_FORMAT, + ERROR_INVALID_STARTING_CODESEG...ERROR_INFLOOP_IN_RELOC_CHAIN: + return ENOEXEC + case ERROR_NOT_SAME_DEVICE: + return EXDEV + case ERROR_FILE_EXISTS, + ERROR_ALREADY_EXISTS: + return EEXIST + case ERROR_NO_PROC_SLOTS, + ERROR_MAX_THRDS_REACHED, + ERROR_NESTING_NOT_ALLOWED: + return EAGAIN + case ERROR_BROKEN_PIPE: + return EPIPE + case ERROR_DISK_FULL: + return ENOSPC + case ERROR_WAIT_NO_CHILDREN, + ERROR_CHILD_NOT_COMPLETE: + return ECHILD + case ERROR_DIR_NOT_EMPTY: + return ENOTEMPTY + case ERROR_NO_UNICODE_TRANSLATION: + return EILSEQ + default: + return EINVAL + } +} + +fileprivate func rightsFromModeBits( + _ bits: Int, + sticky: Bool = false, + for fileOrDirectory: _FileOrDirectory +) -> DWORD { + var rights: DWORD = 0 + + if (bits & 0o4) != 0 { + rights |= DWORD(FILE_READ_ATTRIBUTES + | FILE_READ_DATA + | FILE_READ_EA + | STANDARD_RIGHTS_READ + | SYNCHRONIZE) + } + if (bits & 0o2) != 0 { + rights |= DWORD(FILE_APPEND_DATA + | FILE_WRITE_ATTRIBUTES + | FILE_WRITE_DATA + | FILE_WRITE_EA + | STANDARD_RIGHTS_WRITE + | SYNCHRONIZE) + if fileOrDirectory == .directory && !sticky { + rights |= DWORD(FILE_DELETE_CHILD) + } + } + if (bits & 0o1) != 0 { + rights |= DWORD(FILE_EXECUTE + | FILE_READ_ATTRIBUTES + | STANDARD_RIGHTS_EXECUTE + | SYNCHRONIZE) + } + + return rights +} + +fileprivate func getTokenInformation( + of: T.Type, + hToken: HANDLE, + ticTokenClass: TOKEN_INFORMATION_CLASS +) -> UnsafePointer? { + var capacity = 1024 + for _ in 0..<2 { + let buffer = UnsafeMutableRawPointer.allocate( + byteCount: capacity, + alignment: MemoryLayout.alignment + ) + + var dwLength = DWORD(0) + + if GetTokenInformation(hToken, + ticTokenClass, + buffer, + DWORD(capacity), + &dwLength) { + return UnsafePointer(buffer.assumingMemoryBound(to: T.self)) + } + + buffer.deallocate() + + capacity = Int(dwLength) + } + return nil +} + +@usableFromInline +internal enum _FileOrDirectory { + case file + case directory +} + +/// Build a SECURITY_DESCRIPTOR from UNIX-style "mode" bits. This only +/// takes account of the rwx and sticky bits; there's really nothing that +/// we can do about setuid/setgid. +@usableFromInline +internal func _createSecurityDescriptor(from mode: CInterop.Mode, + for fileOrDirectory: _FileOrDirectory) + -> PSECURITY_DESCRIPTOR? { + let ownerPerm = (Int(mode) >> 6) & 0o7 + let groupPerm = (Int(mode) >> 3) & 0o7 + let otherPerm = Int(mode) & 0o7 + + let ownerRights = rightsFromModeBits(ownerPerm, for: fileOrDirectory) + let groupRights = rightsFromModeBits(groupPerm, + sticky: (mode & 0o1000) != 0, + for: fileOrDirectory) + let otherRights = rightsFromModeBits(otherPerm, + sticky: (mode & 0o1000) != 0, + for: fileOrDirectory) + + // If group or other permissions are *more* permissive, then we need + // some DENY ACEs as well to implement the expected semantics + let ownerDenyRights = ((ownerRights ^ groupRights) & groupRights) | + ((ownerRights ^ otherRights) & otherRights) + let groupDenyRights = (groupRights ^ otherRights) & otherRights + + var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1)) + var everyone: PSID? = nil + + guard AllocateAndInitializeSid(&SIDAuthWorld, 1, + DWORD(SECURITY_WORLD_RID), + 0, 0, 0, 0, 0, 0, 0, + &everyone) else { + return nil + } + guard let everyone = everyone else { + return nil + } + defer { + FreeSid(everyone) + } + + let hToken = GetCurrentThreadEffectiveToken()! + + guard let pTokenUser = getTokenInformation(of: TOKEN_USER.self, + hToken: hToken, + ticTokenClass: TokenUser) else { + return nil + } + defer { + pTokenUser.deallocate() + } + + guard let pTokenPrimaryGroup = getTokenInformation( + of: TOKEN_PRIMARY_GROUP.self, + hToken: hToken, + ticTokenClass: TokenPrimaryGroup + ) else { + return nil + } + defer { + pTokenPrimaryGroup.deallocate() + } + + let user = pTokenUser.pointee.User.Sid! + let group = pTokenPrimaryGroup.pointee.PrimaryGroup! + + var eas = [ + EXPLICIT_ACCESS_W( + grfAccessPermissions: ownerRights, + grfAccessMode: GRANT_ACCESS, + grfInheritance: DWORD(NO_INHERITANCE), + Trustee: TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_USER, + ptstrName: + user.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + ), + EXPLICIT_ACCESS_W( + grfAccessPermissions: groupRights, + grfAccessMode: GRANT_ACCESS, + grfInheritance: DWORD(NO_INHERITANCE), + Trustee: TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + group.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + ), + EXPLICIT_ACCESS_W( + grfAccessPermissions: otherRights, + grfAccessMode: GRANT_ACCESS, + grfInheritance: DWORD(NO_INHERITANCE), + Trustee: TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + everyone.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + ) + ] + + if ownerDenyRights != 0 { + eas.append( + EXPLICIT_ACCESS_W( + grfAccessPermissions: ownerDenyRights, + grfAccessMode: DENY_ACCESS, + grfInheritance: DWORD(NO_INHERITANCE), + Trustee: TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_USER, + ptstrName: + user.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + ) + ) + } + + if groupDenyRights != 0 { + eas.append( + EXPLICIT_ACCESS_W( + grfAccessPermissions: groupDenyRights, + grfAccessMode: DENY_ACCESS, + grfInheritance: DWORD(NO_INHERITANCE), + Trustee: TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + group.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + ) + ) + } + + var pACL: PACL? = nil + guard SetEntriesInAclW(ULONG(eas.count), + &eas, + nil, + &pACL) == ERROR_SUCCESS else { + return nil + } + defer { + LocalFree(pACL) + } + + // Create the security descriptor, making sure that inherited ACEs don't + // take effect, since that wouldn't match the behaviour of mode bits. + var descriptor = SECURITY_DESCRIPTOR() + + guard InitializeSecurityDescriptor(&descriptor, + DWORD(SECURITY_DESCRIPTOR_REVISION)) else { + return nil + } + + guard SetSecurityDescriptorControl(&descriptor, + SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED), + SECURITY_DESCRIPTOR_CONTROL(SE_DACL_PROTECTED)) + && SetSecurityDescriptorOwner(&descriptor, user, false) + && SetSecurityDescriptorGroup(&descriptor, group, false) + && SetSecurityDescriptorDacl(&descriptor, + true, + pACL, + false) else { + return nil + } + + // Make it self-contained (up to this point it uses pointers) + var dwRelativeSize = DWORD(0) + + guard !MakeSelfRelativeSD(&descriptor, nil, &dwRelativeSize) + && GetLastError() == ERROR_INSUFFICIENT_BUFFER else { + return nil + } + + let pDescriptor = UnsafeMutableRawPointer.allocate( + byteCount: Int(dwRelativeSize), + alignment: MemoryLayout.alignment + ).assumingMemoryBound(to: SECURITY_DESCRIPTOR.self) + + guard MakeSelfRelativeSD(&descriptor, pDescriptor, &dwRelativeSize) else { + pDescriptor.deallocate() + return nil + } + + return UnsafeMutableRawPointer(pDescriptor) +} + +fileprivate struct DecodedOpenFlags { + var dwDesiredAccess: DWORD + var dwCreationDisposition: DWORD + var bInheritHandle: WindowsBool + var dwFlagsAndAttributes: DWORD + + init(_ oflag: Int32) { + switch oflag & (_O_CREAT | _O_EXCL | _O_TRUNC) { + case _O_CREAT | _O_EXCL, _O_CREAT | _O_EXCL | _O_TRUNC: + dwCreationDisposition = DWORD(CREATE_NEW) + case _O_CREAT: + dwCreationDisposition = DWORD(OPEN_ALWAYS) + case _O_CREAT | _O_TRUNC: + dwCreationDisposition = DWORD(CREATE_ALWAYS) + case _O_TRUNC: + dwCreationDisposition = DWORD(TRUNCATE_EXISTING) + default: + dwCreationDisposition = DWORD(OPEN_EXISTING) + } + + // The _O_RDONLY, _O_WRONLY and _O_RDWR flags are non-overlapping + // on Windows; in particular, _O_RDONLY is zero, which means we can't + // test for it by AND-ing. + dwDesiredAccess = 0 + switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) { + case _O_RDONLY: + dwDesiredAccess |= DWORD(GENERIC_READ) + case _O_WRONLY: + dwDesiredAccess |= DWORD(GENERIC_WRITE) + case _O_RDWR: + dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE) + default: + break + } + + bInheritHandle = WindowsBool((oflag & _O_NOINHERIT) == 0) + + dwFlagsAndAttributes = 0 + if (oflag & _O_SEQUENTIAL) != 0 { + dwFlagsAndAttributes |= DWORD(FILE_FLAG_SEQUENTIAL_SCAN) + } + if (oflag & _O_RANDOM) != 0 { + dwFlagsAndAttributes |= DWORD(FILE_FLAG_RANDOM_ACCESS) + } + if (oflag & _O_TEMPORARY) != 0 { + dwFlagsAndAttributes |= DWORD(FILE_FLAG_DELETE_ON_CLOSE) + } + + if (oflag & _O_SHORT_LIVED) != 0 { + dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_TEMPORARY) + } else { + dwFlagsAndAttributes |= DWORD(FILE_ATTRIBUTE_NORMAL) + } + } +} + #endif diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 04d2cc5..62b5547 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -7,12 +7,14 @@ See https://swift.org/LICENSE.txt for license information */ -#if false && swift(>=5.8) && $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) +#if swift(>=5.9) && SYSTEM_PACKAGE_DARWIN import Darwin.Mach +@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public protocol MachPortRight {} +@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) @inlinable internal func _machPrecondition( file: StaticString = #file, @@ -27,6 +29,7 @@ internal func _machPrecondition( @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) @frozen public enum Mach { + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public struct Port: ~Copyable { @usableFromInline internal var _name: mach_port_name_t @@ -48,11 +51,15 @@ public enum Mach { /// /// This initializer makes a syscall to guard the right. public init(name: mach_port_name_t) { - precondition(name != mach_port_name_t(MACH_PORT_NULL), "Mach.Port cannot be initialized with MACH_PORT_NULL") + precondition(name != mach_port_name_t(MACH_PORT_NULL), + "Mach.Port cannot be initialized with MACH_PORT_NULL") self._name = name if RightType.self == ReceiveRight.self { - precondition(name != 0xFFFFFFFF /* MACH_PORT_DEAD */, "Receive rights cannot be dead names") + precondition( + _name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */, + "Receive rights cannot be dead names" + ) let secret = mach_port_context_t(arc4random()) _machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0)) @@ -81,17 +88,20 @@ public enum Mach { } deinit { - if _name == 0xFFFFFFFF /* MACH_PORT_DEAD */ { - precondition(RightType.self != ReceiveRight.self, "Receive rights cannot be dead names") - _machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_DEAD_NAME, -1)) + if RightType.self == ReceiveRight.self { + precondition( + _name != (0xFFFFFFFF as mach_port_name_t) /* MACH_PORT_DEAD */, + "Receive rights cannot be dead names" + ) + _machPrecondition( + mach_port_destruct(mach_task_self_, _name, 0, _context) + ) } else { - if RightType.self == ReceiveRight.self { - _machPrecondition(mach_port_destruct(mach_task_self_, _name, -1, _context)) - } else if RightType.self == SendRight.self { - _machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND, -1)) - } else if RightType.self == SendOnceRight.self { - _machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND_ONCE, -1)) - } + assert( + RightType.self == SendRight.self || + RightType.self == SendOnceRight.self + ) + _machPrecondition(mach_port_deallocate(mach_task_self_, _name)) } } } @@ -123,6 +133,7 @@ public enum Mach { public struct SendOnceRight: MachPortRight {} } +@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) extension Mach.Port where RightType == Mach.ReceiveRight { /// Transfer ownership of an existing, unmanaged, but already guarded, /// Mach port right into a Mach.Port by name. @@ -135,6 +146,8 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// The underlying port right will be automatically deallocated when /// the Mach.Port object is destroyed. public init(name: mach_port_name_t, context: mach_port_context_t) { + precondition(name != mach_port_name_t(MACH_PORT_NULL), + "Mach.Port cannot be initialized with MACH_PORT_NULL") self._name = name self._context = context } @@ -145,11 +158,12 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// This initializer will abort if the right could not be created. /// Callers may assert that a valid right is always returned. @inlinable + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public init() { var storage: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL) - withUnsafeMutablePointer(to: &storage) { storage in - _machPrecondition(mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage)) - } + _machPrecondition( + mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &storage) + ) // name-only init will guard ReceiveRights self.init(name: storage) @@ -167,9 +181,12 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// After this function completes, the Mach.Port is destroyed and no longer /// usable. @inlinable - public __consuming func relinquish( + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) + public consuming func relinquish( ) -> (name: mach_port_name_t, context: mach_port_context_t) { - return (name: _name, context: _context) + let destructured = (name: _name, context: _context) + discard self + return destructured } /// Remove guard and transfer ownership of the underlying port right to @@ -187,9 +204,11 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract /// the context value along with the port name. @inlinable - public __consuming func unguardAndRelinquish() -> mach_port_name_t { - _machPrecondition(mach_port_unguard(mach_task_self_, _name, _context)) - return _name + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) + public consuming func unguardAndRelinquish() -> mach_port_name_t { + let (name, context) = self.relinquish() + _machPrecondition(mach_port_unguard(mach_task_self_, name, context)) + return name } /// Borrow access to the port name in a block that can perform @@ -202,6 +221,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// The body block may optionally return something, which will then be /// returned to the caller of withBorrowedName. @inlinable + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public func withBorrowedName( body: (mach_port_name_t, mach_port_context_t) -> ReturnType ) -> ReturnType { @@ -215,22 +235,21 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// This function will abort if the right could not be created. /// Callers may assert that a valid right is always returned. @inlinable + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public func makeSendOnceRight() -> Mach.Port { // send once rights do not coalesce var newRight: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL) var newRightType: mach_port_type_t = MACH_PORT_TYPE_NONE - withUnsafeMutablePointer(to: &newRight) { newRight in - withUnsafeMutablePointer(to: &newRightType) { newRightType in - _machPrecondition( - mach_port_extract_right(mach_task_self_, - _name, - mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE), - newRight, - newRightType) - ) - } - } + _machPrecondition( + mach_port_extract_right( + mach_task_self_, + _name, + mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE), + &newRight, + &newRightType + ) + ) // The value of newRight is validated by the Mach.Port initializer precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) @@ -245,11 +264,16 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// This function will abort if the right could not be created. /// Callers may assert that a valid right is always returned. @inlinable + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public func makeSendRight() -> Mach.Port { let how = MACH_MSG_TYPE_MAKE_SEND // name is the same because send and recv rights are coalesced - _machPrecondition(mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how))) + _machPrecondition( + mach_port_insert_right( + mach_task_self_, _name, _name, mach_msg_type_name_t(how) + ) + ) return Mach.Port(name: _name) } @@ -258,14 +282,24 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// /// Each get/set of this property makes a syscall. @inlinable + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public var makeSendCount: mach_port_mscount_t { get { var status: mach_port_status = mach_port_status() - var size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) - withUnsafeMutablePointer(to: &size) { size in - withUnsafeMutablePointer(to: &status) { status in - let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1) - _machPrecondition(mach_port_get_attributes(mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, size)) + var size = mach_msg_type_number_t( + MemoryLayout.size / MemoryLayout.size + ) + + withUnsafeMutablePointer(to: &status) { + [ _name = self._name ] in + let status = UnsafeMutableBufferPointer(start: $0, count: 1) + status.withMemoryRebound(to: integer_t.self) { + let info = $0.baseAddress + _machPrecondition( + mach_port_get_attributes( + mach_task_self_, _name, MACH_PORT_RECEIVE_STATUS, info, &size + ) + ) } } return status.mps_mscount @@ -277,6 +311,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { } } +@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) extension Mach.Port where RightType == Mach.SendRight { /// Transfer ownership of the underlying port right to the caller. /// @@ -288,8 +323,10 @@ extension Mach.Port where RightType == Mach.SendRight { /// After this function completes, the Mach.Port is destroyed and no longer /// usable. @inlinable - public __consuming func relinquish() -> mach_port_name_t { - return _name + public consuming func relinquish() -> mach_port_name_t { + let name = _name + discard self + return name } /// Create another send right from a given send right. @@ -300,12 +337,15 @@ extension Mach.Port where RightType == Mach.SendRight { /// receiving side has been deallocated, then copySendRight() will throw /// a Mach.PortRightError.deadName error. @inlinable + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) public func copySendRight() throws -> Mach.Port { let how = MACH_MSG_TYPE_COPY_SEND // name is the same because send rights are coalesced - let kr = mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how)) - if kr == KERN_INVALID_CAPABILITY { + let kr = mach_port_insert_right( + mach_task_self_, _name, _name, mach_msg_type_name_t(how) + ) + if kr == KERN_INVALID_NAME || kr == KERN_INVALID_CAPABILITY { throw Mach.PortRightError.deadName } _machPrecondition(kr) @@ -314,7 +354,7 @@ extension Mach.Port where RightType == Mach.SendRight { } } - +@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) extension Mach.Port where RightType == Mach.SendOnceRight { /// Transfer ownership of the underlying port right to the caller. /// @@ -326,8 +366,11 @@ extension Mach.Port where RightType == Mach.SendOnceRight { /// After this function completes, the Mach.Port is destroyed and no longer /// usable. @inlinable - public __consuming func relinquish() -> mach_port_name_t { - return _name + @available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) + public consuming func relinquish() -> mach_port_name_t { + let name = _name + discard self + return name } } diff --git a/Sources/System/PlatformString.swift b/Sources/System/PlatformString.swift index 4e2e7dd..664a608 100644 --- a/Sources/System/PlatformString.swift +++ b/Sources/System/PlatformString.swift @@ -20,6 +20,7 @@ extension String { /// This means that, depending on the semantics of the specific platform, /// conversion to a string and back might result in a value that's different /// from the original platform string. + @_disfavoredOverload public init(platformString: UnsafePointer) { self.init(_errorCorrectingPlatformString: platformString) } diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 14651d5..57abc62 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -1,14 +1,15 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ // A platform-native character representation, currently used for file paths -internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable { +internal struct SystemChar: + RawRepresentable, Sendable, Comparable, Hashable, Codable { internal typealias RawValue = CInterop.PlatformChar internal var rawValue: RawValue @@ -61,7 +62,7 @@ extension SystemChar { // A platform-native string representation, currently for file paths // // Always null-terminated. -internal struct SystemString { +internal struct SystemString: Sendable { internal typealias Storage = [SystemChar] internal var nullTerminatedStorage: Storage } @@ -95,10 +96,18 @@ extension SystemString { } extension SystemString { + fileprivate func _invariantsSatisfied() -> Bool { + guard !nullTerminatedStorage.isEmpty else { return false } + guard nullTerminatedStorage.last! == .null else { return false } + guard nullTerminatedStorage.firstIndex(of: .null) == length else { + return false + } + return true + } + fileprivate func _invariantCheck() { #if DEBUG - precondition(nullTerminatedStorage.last! == .null) - precondition(nullTerminatedStorage.firstIndex(of: .null) == length) + precondition(_invariantsSatisfied()) #endif // DEBUG } } @@ -141,44 +150,67 @@ extension SystemString: RangeReplaceableCollection { nullTerminatedStorage.reserveCapacity(1 + n) } - // TODO: Below include null terminator, is this desired? - internal func withContiguousStorageIfAvailable( _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> R? { - try nullTerminatedStorage.withContiguousStorageIfAvailable(body) + // Do not include the null terminator, it is outside the Collection + try nullTerminatedStorage.withContiguousStorageIfAvailable { + try body(.init(start: $0.baseAddress, count: $0.count-1)) + } } internal mutating func withContiguousMutableStorageIfAvailable( _ body: (inout UnsafeMutableBufferPointer) throws -> R ) rethrows -> R? { defer { _invariantCheck() } - return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body) + // Do not include the null terminator, it is outside the Collection + return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable { + var buffer = UnsafeMutableBufferPointer( + start: $0.baseAddress, count: $0.count-1 + ) + return try body(&buffer) + } } } -extension SystemString: Hashable, Codable {} +extension SystemString: Hashable, Codable { + // Encoder is synthesized; it probably should have been explicit and used + // a single-value container, but making that change now is somewhat risky. + + // Decoder is written explicitly to ensure that we validate invariants on + // untrusted input. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.nullTerminatedStorage = try container.decode( + Storage.self, forKey: .nullTerminatedStorage + ) + guard _invariantsSatisfied() else { + throw DecodingError.dataCorruptedError( + forKey: .nullTerminatedStorage, + in: container, + debugDescription: + "Encoding does not satisfy the invariants of SystemString" + ) + } + } +} extension SystemString { - // TODO: Below include null terminator, is this desired? - internal func withSystemChars( + internal func withNullTerminatedSystemChars( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withContiguousStorageIfAvailable(f)! + try nullTerminatedStorage.withUnsafeBufferPointer(f) } + // withCodeUnits does not include the null terminator internal func withCodeUnits( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withSystemChars { chars in - let length = chars.count * MemoryLayout.stride - let count = length / MemoryLayout.stride - return try chars.baseAddress!.withMemoryRebound( - to: CInterop.PlatformUnicodeEncoding.CodeUnit.self, - capacity: count - ) { pointer in - try f(UnsafeBufferPointer(start: pointer, count: count)) + try withNullTerminatedSystemChars { + try $0.withMemoryRebound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self) { + assert($0.last == .zero) + return try f(.init(start: $0.baseAddress, count: $0.count&-1)) } } } @@ -194,7 +226,9 @@ extension Slice where Base == SystemString { } internal var string: String { - withCodeUnits { String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) } + withCodeUnits { + String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) + } } internal func withPlatformString( @@ -236,7 +270,11 @@ extension SystemString: ExpressibleByStringLiteral { } extension SystemString: CustomStringConvertible, CustomDebugStringConvertible { - internal var string: String { String(decoding: self) } + internal var string: String { + self.withCodeUnits { + String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) + } + } internal var description: String { string } internal var debugDescription: String { description.debugDescription } @@ -275,7 +313,7 @@ extension SystemString { internal func withPlatformString( _ f: (UnsafePointer) throws -> T ) rethrows -> T { - try withSystemChars { chars in + try withNullTerminatedSystemChars { chars in let length = chars.count * MemoryLayout.stride return try chars.baseAddress!.withMemoryRebound( to: CInterop.PlatformChar.self, @@ -288,11 +326,6 @@ extension SystemString { } } -#if compiler(>=5.5) && canImport(_Concurrency) -extension SystemChar: Sendable {} -extension SystemString: Sendable {} -#endif - // TODO: SystemString should use a COW-interchangable storage form rather // than array, so you could "borrow" the storage from a non-bridged String // or Data or whatever diff --git a/Tests/SystemTests/ErrnoTest.swift b/Tests/SystemTests/ErrnoTest.swift index 05cd518..80e3e84 100644 --- a/Tests/SystemTests/ErrnoTest.swift +++ b/Tests/SystemTests/ErrnoTest.swift @@ -106,7 +106,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(EHOSTUNREACH == Errno.noRouteToHost.rawValue) XCTAssert(ENOTEMPTY == Errno.directoryNotEmpty.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(EPROCLIM == Errno.tooManyProcesses.rawValue) #endif @@ -120,7 +120,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue) #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(EBADRPC == Errno.rpcUnsuccessful.rawValue) XCTAssert(ERPCMISMATCH == Errno.rpcVersionMismatch.rawValue) XCTAssert(EPROGUNAVAIL == Errno.rpcProgramUnavailable.rawValue) @@ -131,7 +131,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(ENOLCK == Errno.noLocks.rawValue) XCTAssert(ENOSYS == Errno.noFunction.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(EFTYPE == Errno.badFileTypeOrFormat.rawValue) XCTAssert(EAUTH == Errno.authenticationError.rawValue) XCTAssert(ENEEDAUTH == Errno.needAuthenticator.rawValue) @@ -143,7 +143,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(EOVERFLOW == Errno.overflow.rawValue) #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(EBADEXEC == Errno.badExecutable.rawValue) XCTAssert(EBADARCH == Errno.badCPUType.rawValue) XCTAssert(ESHLIBVERS == Errno.sharedLibraryVersionMismatch.rawValue) @@ -157,7 +157,7 @@ final class ErrnoTest: XCTestCase { #endif XCTAssert(EILSEQ == Errno.illegalByteSequence.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(ENOATTR == Errno.attributeNotFound.rawValue) #endif @@ -183,7 +183,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue) #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(ENOPOLICY == Errno.noSuchPolicy.rawValue) #endif @@ -192,7 +192,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue) #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(EQFULL == Errno.outputQueueFull.rawValue) XCTAssert(ELAST == Errno.lastErrnoValue.rawValue) #endif diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index 8062aed..ed05dcf 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -10,9 +10,9 @@ import XCTest #if SYSTEM_PACKAGE -import SystemPackage +@testable import SystemPackage #else -import System +@testable import System #endif @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) @@ -86,11 +86,70 @@ final class FileOperationsTest: XCTestCase { for test in syscallTestCases { test.runAllTests() } } + func testWriteFromEmptyBuffer() throws { + #if os(Windows) + let fd = try FileDescriptor.open(FilePath("NUL"), .writeOnly) + #else + let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly) + #endif + let written1 = try fd.write(toAbsoluteOffset: 0, .init(start: nil, count: 0)) + XCTAssertEqual(written1, 0) + + let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8) + defer { pointer.deallocate() } + let empty = UnsafeRawBufferPointer(start: pointer, count: 0) + let written2 = try fd.write(toAbsoluteOffset: 0, empty) + XCTAssertEqual(written2, 0) + } + + #if os(Windows) + // Generate a file containing random bytes; this should not be used + // for cryptography, it's just for testing. + func generateRandomData(at path: FilePath, count: Int) throws { + let fd = try FileDescriptor.open(path, .readWrite, + options: [.create, .truncate]) + defer { + try! fd.close() + } + let data = [UInt8]( + sequence(first: 0, + next: { + _ in UInt8.random(in: UInt8.min...UInt8.max) + }).dropFirst().prefix(count) + ) + + try data.withUnsafeBytes { + _ = try fd.write($0) + } + } + #endif + + func testReadToEmptyBuffer() throws { + try withTemporaryFilePath(basename: "testReadToEmptyBuffer") { path in + #if os(Windows) + // Windows doesn't have an equivalent to /dev/random, so generate + // some random bytes and write them to a file for the next step. + let randomPath = path.appending("random.txt") + try generateRandomData(at: randomPath, count: 16) + let fd = try FileDescriptor.open(randomPath, .readOnly) + #else // !os(Windows) + let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly) + #endif + let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0)) + XCTAssertEqual(read1, 0) + + let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8) + defer { pointer.deallocate() } + let empty = UnsafeMutableRawBufferPointer(start: pointer, count: 0) + let read2 = try fd.read(fromAbsoluteOffset: 0, into: empty) + XCTAssertEqual(read2, 0) + } + } + func testHelpers() { // TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter } - -#if !os(Windows) + func testAdHocPipe() throws { // Ad-hoc test testing `Pipe` functionality. // We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`. @@ -109,33 +168,34 @@ final class FileOperationsTest: XCTestCase { } } } -#endif func testAdHocOpen() { // Ad-hoc test touching a file system. do { // TODO: Test this against a virtual in-memory file system - let fd = try FileDescriptor.open("/tmp/b.txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) - try fd.closeAfter { - try fd.writeAll("abc".utf8) - var def = "def" - try def.withUTF8 { - _ = try fd.write(UnsafeRawBufferPointer($0)) - } - try fd.seek(offset: 1, from: .start) + try withTemporaryFilePath(basename: "testAdhocOpen") { path in + let fd = try FileDescriptor.open(path.appending("b.txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) + try fd.closeAfter { + try fd.writeAll("abc".utf8) + var def = "def" + try def.withUTF8 { + _ = try fd.write(UnsafeRawBufferPointer($0)) + } + try fd.seek(offset: 1, from: .start) - let readLen = 3 - let readBytes = try Array(unsafeUninitializedCapacity: readLen) { (buf, count) in - count = try fd.read(into: UnsafeMutableRawBufferPointer(buf)) - } - let preadBytes = try Array(unsafeUninitializedCapacity: readLen) { (buf, count) in - count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf)) - } + let readLen = 3 + let readBytes = try Array(unsafeUninitializedCapacity: readLen) { (buf, count) in + count = try fd.read(into: UnsafeMutableRawBufferPointer(buf)) + } + let preadBytes = try Array(unsafeUninitializedCapacity: readLen) { (buf, count) in + count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf)) + } - XCTAssertEqual(readBytes.first!, "b".utf8.first!) - XCTAssertEqual(readBytes, preadBytes) + XCTAssertEqual(readBytes.first!, "b".utf8.first!) + XCTAssertEqual(readBytes, preadBytes) - // TODO: seek + // TODO: seek + } } } catch let err as Errno { print("caught \(err))") @@ -161,48 +221,48 @@ final class FileOperationsTest: XCTestCase { } -#if !os(Windows) func testResizeFile() throws { - let fd = try FileDescriptor.open("/tmp/\(UUID().uuidString).txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) - try fd.closeAfter { - // File should be empty initially. - XCTAssertEqual(try fd.fileSize(), 0) - // Write 3 bytes. - try fd.writeAll("abc".utf8) - // File should now be 3 bytes. - XCTAssertEqual(try fd.fileSize(), 3) - // Resize to 6 bytes. - try fd.resize(to: 6) - // File should now be 6 bytes. - XCTAssertEqual(try fd.fileSize(), 6) - // Read in the 6 bytes. - let readBytes = try Array(unsafeUninitializedCapacity: 6) { (buf, count) in - try fd.seek(offset: 0, from: .start) - // Should have read all 6 bytes. - count = try fd.read(into: UnsafeMutableRawBufferPointer(buf)) - XCTAssertEqual(count, 6) + try withTemporaryFilePath(basename: "testResizeFile") { path in + let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) + try fd.closeAfter { + // File should be empty initially. + XCTAssertEqual(try fd.fileSize(), 0) + // Write 3 bytes. + try fd.writeAll("abc".utf8) + // File should now be 3 bytes. + XCTAssertEqual(try fd.fileSize(), 3) + // Resize to 6 bytes. + try fd.resize(to: 6) + // File should now be 6 bytes. + XCTAssertEqual(try fd.fileSize(), 6) + // Read in the 6 bytes. + let readBytes = try Array(unsafeUninitializedCapacity: 6) { (buf, count) in + try fd.seek(offset: 0, from: .start) + // Should have read all 6 bytes. + count = try fd.read(into: UnsafeMutableRawBufferPointer(buf)) + XCTAssertEqual(count, 6) + } + // First 3 bytes should be unaffected by resize. + XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8)) + // Extension should be padded with zeros. + XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3)) + // File should still be 6 bytes. + XCTAssertEqual(try fd.fileSize(), 6) + // Resize to 2 bytes. + try fd.resize(to: 2) + // File should now be 2 bytes. + XCTAssertEqual(try fd.fileSize(), 2) + // Read in file with a buffer big enough for 6 bytes. + let readBytesAfterTruncation = try Array(unsafeUninitializedCapacity: 6) { (buf, count) in + try fd.seek(offset: 0, from: .start) + count = try fd.read(into: UnsafeMutableRawBufferPointer(buf)) + // Should only have read 2 bytes. + XCTAssertEqual(count, 2) + } + // Written content was trunctated. + XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8)) } - // First 3 bytes should be unaffected by resize. - XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8)) - // Extension should be padded with zeros. - XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3)) - // File should still be 6 bytes. - XCTAssertEqual(try fd.fileSize(), 6) - // Resize to 2 bytes. - try fd.resize(to: 2) - // File should now be 2 bytes. - XCTAssertEqual(try fd.fileSize(), 2) - // Read in file with a buffer big enough for 6 bytes. - let readBytesAfterTruncation = try Array(unsafeUninitializedCapacity: 6) { (buf, count) in - try fd.seek(offset: 0, from: .start) - count = try fd.read(into: UnsafeMutableRawBufferPointer(buf)) - // Should only have read 2 bytes. - XCTAssertEqual(count, 2) - } - // Written content was trunctated. - XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8)) } } -#endif } diff --git a/Tests/SystemTests/FileOperationsTestWindows.swift b/Tests/SystemTests/FileOperationsTestWindows.swift new file mode 100644 index 0000000..8203051 --- /dev/null +++ b/Tests/SystemTests/FileOperationsTestWindows.swift @@ -0,0 +1,241 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +import XCTest + +#if os(Windows) + +#if SYSTEM_PACKAGE +@testable import SystemPackage +#else +@testable import System +#endif + +import WinSDK + +@available(iOS 8, *) +final class FileOperationsTestWindows: XCTestCase { + private let r = ACCESS_MASK( + FILE_READ_ATTRIBUTES + | FILE_READ_DATA + | FILE_READ_EA + | STANDARD_RIGHTS_READ + | SYNCHRONIZE + ) + private let w = ACCESS_MASK( + FILE_APPEND_DATA + | FILE_WRITE_ATTRIBUTES + | FILE_WRITE_DATA + | FILE_WRITE_EA + | STANDARD_RIGHTS_WRITE + | SYNCHRONIZE + ) + private let x = ACCESS_MASK( + FILE_EXECUTE + | FILE_READ_ATTRIBUTES + | STANDARD_RIGHTS_EXECUTE + | SYNCHRONIZE + ) + + private struct Test { + var permissions: CModeT + var ownerAccess: ACCESS_MASK + var groupAccess: ACCESS_MASK + var otherAccess: ACCESS_MASK + + init(_ permissions: CModeT, + _ ownerAccess: ACCESS_MASK, + _ groupAccess: ACCESS_MASK, + _ otherAccess: ACCESS_MASK) { + self.permissions = permissions + self.ownerAccess = ownerAccess + self.groupAccess = groupAccess + self.otherAccess = otherAccess + } + } + + /// Retrieve the owner, group and other access masks for a given file. + /// + /// - Parameters: + /// - path: The path to the file to inspect + /// - Returns: A tuple of ACCESS_MASK values. + func getAccessMasks( + path: FilePath + ) -> (ACCESS_MASK, ACCESS_MASK, ACCESS_MASK) { + var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1)) + var psidEveryone: PSID? = nil + + XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1, + DWORD(SECURITY_WORLD_RID), + 0, 0, 0, 0, 0, 0, 0, + &psidEveryone)) + defer { + FreeSid(psidEveryone) + } + + var everyone = TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + psidEveryone!.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + + return path.withPlatformString { objectName in + var psidOwner: PSID? = nil + var psidGroup: PSID? = nil + var pDacl: PACL? = nil + var pSD: PSECURITY_DESCRIPTOR? = nil + + XCTAssertEqual(GetNamedSecurityInfoW( + objectName, + SE_FILE_OBJECT, + SECURITY_INFORMATION( + DACL_SECURITY_INFORMATION + | GROUP_SECURITY_INFORMATION + | OWNER_SECURITY_INFORMATION + ), + &psidOwner, + &psidGroup, + &pDacl, + nil, + &pSD), DWORD(ERROR_SUCCESS)) + defer { + LocalFree(pSD) + } + + var owner = TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_USER, + ptstrName: + psidOwner!.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + var group = TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + psidGroup!.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + + var ownerAccess = ACCESS_MASK(0) + var groupAccess = ACCESS_MASK(0) + var otherAccess = ACCESS_MASK(0) + + XCTAssertEqual(GetEffectiveRightsFromAclW( + pDacl, + &owner, + &ownerAccess), DWORD(ERROR_SUCCESS)) + XCTAssertEqual(GetEffectiveRightsFromAclW( + pDacl, + &group, + &groupAccess), DWORD(ERROR_SUCCESS)) + XCTAssertEqual(GetEffectiveRightsFromAclW( + pDacl, + &everyone, + &otherAccess), DWORD(ERROR_SUCCESS)) + + return (ownerAccess, groupAccess, otherAccess) + } + } + + private func runTests(_ tests: [Test], at path: FilePath) throws { + for test in tests { + let octal = String(test.permissions, radix: 8) + let testPath = path.appending("test-\(octal).txt") + let fd = try FileDescriptor.open( + testPath, + .readWrite, + options: [.create, .truncate], + permissions: FilePermissions(rawValue: test.permissions) + ) + _ = try fd.closeAfter { + try fd.writeAll("Hello World".utf8) + } + + let (ownerAccess, groupAccess, otherAccess) + = getAccessMasks(path: testPath) + + XCTAssertEqual(ownerAccess, test.ownerAccess) + XCTAssertEqual(groupAccess, test.groupAccess) + XCTAssertEqual(otherAccess, test.otherAccess) + } + } + + /// Test that the umask works properly + func testUmask() throws { + // Default mask should be 0o022 + XCTAssertEqual(FilePermissions.creationMask, [.groupWrite, .otherWrite]) + + try withTemporaryFilePath(basename: "testUmask") { path in + let tests = [ + Test(0o000, 0, 0, 0), + Test(0o700, r|w|x, 0, 0), + Test(0o770, r|w|x, r|x, 0), + Test(0o777, r|w|x, r|x, r|x) + ] + + try runTests(tests, at: path) + } + + try FilePermissions.withCreationMask([.groupWrite, .groupExecute, + .otherWrite, .otherExecute]) { + try withTemporaryFilePath(basename: "testUmask") { path in + let tests = [ + Test(0o000, 0, 0, 0), + Test(0o700, r|w|x, 0, 0), + Test(0o770, r|w|x, r, 0), + Test(0o777, r|w|x, r, r) + ] + + try runTests(tests, at: path) + } + } + } + + /// Test that setting permissions on a file works as expected + func testPermissions() throws { + try FilePermissions.withCreationMask([]) { + try withTemporaryFilePath(basename: "testPermissions") { path in + let tests = [ + Test(0o000, 0, 0, 0), + + Test(0o400, r, 0, 0), + Test(0o200, w, 0, 0), + Test(0o100, x, 0, 0), + Test(0o040, 0, r, 0), + Test(0o020, 0, w, 0), + Test(0o010, 0, x, 0), + Test(0o004, 0, 0, r), + Test(0o002, 0, 0, w), + Test(0o001, 0, 0, x), + + Test(0o700, r|w|x, 0, 0), + Test(0o770, r|w|x, r|w|x, 0), + Test(0o777, r|w|x, r|w|x, r|w|x), + + Test(0o755, r|w|x, r|x, r|x), + Test(0o644, r|w, r, r), + + Test(0o007, 0, 0, r|w|x), + Test(0o070, 0, r|w|x, 0), + Test(0o077, 0, r|w|x, r|w|x), + ] + + try runTests(tests, at: path) + } + } + } +} + +#endif // os(Windows) diff --git a/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift b/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift index ad69cb4..e816bb5 100644 --- a/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift @@ -231,7 +231,7 @@ final class FilePathComponentsTest: XCTestCase { } func testCases() { - let testPaths: Array = [ + var testPaths: Array = [ TestPathComponents("", root: nil, []), TestPathComponents("/", root: "/", []), TestPathComponents("foo", root: nil, ["foo"]), @@ -240,16 +240,28 @@ final class FilePathComponentsTest: XCTestCase { TestPathComponents("foo/bar", root: nil, ["foo", "bar"]), TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]), TestPathComponents("/foo/bar", root: "/", ["foo", "bar"]), - TestPathComponents("///foo//", root: "/", ["foo"]), TestPathComponents("/foo///bar", root: "/", ["foo", "bar"]), TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]), TestPathComponents("foo///bar/baz/", root: nil, ["foo", "bar", "baz"]), - TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"]), TestPathComponents("./", root: nil, ["."]), TestPathComponents("./..", root: nil, [".", ".."]), TestPathComponents("/./..//", root: "/", [".", ".."]), ] - testPaths.forEach { $0.runAllTests() } +#if !os(Windows) + testPaths.append(contentsOf:[ + TestPathComponents("///foo//", root: "/", ["foo"]), + TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"]) + ]) +#else + // On Windows, these are UNC paths + testPaths.append(contentsOf:[ + TestPathComponents("///foo//", root: "///foo//", []), + TestPathComponents("//foo///bar/baz/", root: "//foo//", ["bar", "baz"]) + ]) +#endif + testPaths.forEach { + $0.runAllTests() + } } func testSeparatorNormalization() { diff --git a/Tests/SystemTests/FilePathTests/FilePathDecodable.swift b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift new file mode 100644 index 0000000..290bef2 --- /dev/null +++ b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift @@ -0,0 +1,129 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c)2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information + */ + +import XCTest + +#if SYSTEM_PACKAGE +@testable import SystemPackage +#else +@testable import System +#endif + +@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) +final class FilePathDecodableTest: XCTestCase { + func testInvalidFilePath() { + // _storage is a valid SystemString, but the invariants of FilePath are + // violated (specifically, _storage is not normal). + let input: [UInt8] = [ + 123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108, + 84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34, + 58, 91, 49, 48, 57, 44, 45, 55, 54, 44, 53, 53, 44, 55, 49, 44, 49, 52, + 44, 53, 57, 44, 45, 49, 49, 50, 44, 45, 56, 52, 44, 52, 50, 44, 45, 55, + 48, 44, 45, 49, 48, 52, 44, 55, 51, 44, 45, 54, 44, 50, 44, 53, 55, 44, + 54, 50, 44, 45, 56, 55, 44, 45, 53, 44, 45, 54, 53, 44, 45, 51, 57, 44, + 45, 49, 48, 57, 44, 45, 55, 54, 44, 51, 48, 44, 53, 50, 44, 45, 56, 50, + 44, 45, 54, 48, 44, 45, 50, 44, 56, 53, 44, 49, 50, 51, 44, 45, 56, 52, + 44, 45, 53, 56, 44, 49, 49, 52, 44, 49, 44, 45, 49, 49, 54, 44, 56, 48, + 44, 49, 48, 52, 44, 45, 55, 56, 44, 45, 52, 53, 44, 49, 54, 44, 45, 52, + 54, 44, 55, 44, 49, 49, 56, 44, 45, 50, 52, 44, 54, 50, 44, 54, 52, 44, + 45, 52, 49, 44, 45, 49, 48, 51, 44, 53, 44, 45, 55, 53, 44, 50, 50, 44, + 45, 49, 48, 53, 44, 45, 49, 54, 44, 52, 55, 44, 52, 55, 44, 49, 50, 52, + 44, 45, 53, 55, 44, 53, 51, 44, 49, 49, 49, 44, 49, 53, 44, 45, 50, 55, + 44, 54, 54, 44, 45, 49, 54, 44, 49, 48, 50, 44, 49, 48, 54, 44, 49, 51, + 44, 49, 48, 53, 44, 45, 49, 49, 50, 44, 55, 56, 44, 45, 53, 48, 44, 50, + 48, 44, 56, 44, 45, 50, 55, 44, 52, 52, 44, 52, 44, 56, 44, 54, 53, 44, + 50, 51, 44, 57, 55, 44, 45, 50, 56, 44, 56, 56, 44, 52, 50, 44, 45, 51, + 54, 44, 45, 50, 51, 44, 49, 48, 51, 44, 57, 57, 44, 45, 53, 56, 44, 45, + 49, 49, 48, 44, 45, 53, 52, 44, 45, 49, 49, 55, 44, 45, 57, 52, 44, 45, + 55, 50, 44, 50, 57, 44, 45, 50, 52, 44, 45, 56, 52, 44, 53, 55, 44, 45, + 49, 50, 54, 44, 52, 52, 44, 55, 53, 44, 55, 54, 44, 52, 57, 44, 45, 52, + 49, 44, 45, 50, 53, 44, 50, 52, 44, 45, 49, 50, 54, 44, 55, 44, 50, 56, + 44, 45, 52, 56, 44, 56, 55, 44, 51, 49, 44, 45, 49, 49, 53, 44, 55, 44, + 45, 54, 48, 44, 53, 57, 44, 49, 51, 44, 55, 57, 44, 53, 48, 44, 45, 57, + 54, 44, 45, 50, 44, 45, 50, 52, 44, 45, 57, 49, 44, 55, 49, 44, 45, 49, + 50, 53, 44, 52, 50, 44, 45, 56, 52, 44, 52, 44, 53, 57, 44, 49, 50, 53, + 44, 49, 50, 49, 44, 45, 50, 54, 44, 45, 49, 50, 44, 45, 49, 48, 53, 44, + 53, 54, 44, 49, 49, 48, 44, 49, 52, 44, 45, 49, 48, 52, 44, 45, 53, 50, + 44, 45, 53, 56, 44, 45, 54, 44, 45, 50, 54, 44, 45, 52, 55, 44, 53, 57, + 44, 52, 50, 44, 49, 50, 51, 44, 52, 52, 44, 45, 57, 50, 44, 45, 50, 57, + 44, 45, 51, 54, 44, 45, 54, 50, 44, 50, 54, 44, 45, 49, 55, 44, 45, 49, + 48, 44, 45, 56, 49, 44, 54, 49, 44, 52, 55, 44, 45, 57, 52, 44, 45, 49, + 48, 54, 44, 49, 53, 44, 49, 48, 48, 44, 45, 49, 50, 49, 44, 45, 49, 49, + 49, 44, 51, 44, 45, 57, 44, 52, 54, 44, 45, 55, 48, 44, 45, 49, 57, 44, + 52, 56, 44, 45, 49, 50, 44, 45, 57, 49, 44, 45, 50, 48, 44, 49, 51, 44, + 54, 53, 44, 45, 55, 48, 44, 52, 49, 44, 45, 57, 53, 44, 49, 48, 52, 44, + 45, 55, 53, 44, 45, 49, 49, 53, 44, 49, 48, 49, 44, 45, 57, 52, 44, 45, + 49, 50, 51, 44, 45, 51, 53, 44, 45, 50, 49, 44, 45, 52, 50, 44, 45, 51, + 48, 44, 45, 55, 49, 44, 45, 49, 49, 57, 44, 52, 52, 44, 49, 49, 49, 44, + 49, 48, 53, 44, 54, 54, 44, 45, 49, 50, 54, 44, 55, 50, 44, 45, 52, 48, + 44, 49, 50, 49, 44, 45, 50, 49, 44, 52, 50, 44, 45, 55, 56, 44, 49, 50, + 54, 44, 56, 49, 44, 45, 57, 52, 44, 55, 52, 44, 49, 49, 50, 44, 45, 56, + 54, 44, 51, 50, 44, 55, 54, 44, 49, 49, 55, 44, 45, 56, 44, 56, 54, 44, + 49, 48, 51, 44, 54, 50, 44, 49, 49, 55, 44, 54, 55, 44, 45, 56, 54, 44, + 45, 49, 48, 48, 44, 45, 49, 48, 57, 44, 45, 53, 52, 44, 45, 51, 49, 44, + 45, 56, 57, 44, 48, 93,125,125, + ] + + XCTAssertThrowsError(try JSONDecoder().decode( + FilePath.self, + from: Data(input) + )) + } + + func testInvalidSystemString() { + // _storage is a SystemString whose invariants are violated; it contains + // a non-terminating null byte. + let input: [UInt8] = [ + 123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108, + 84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34, + 58, 91, 49, 49, 49, 44, 48, 44, 45, 49, 54, 44, 57, 49, 44, 52, 54, 44, + 45, 49, 48, 50, 44, 49, 49, 53, 44, 45, 50, 49, 44, 45, 49, 49, 56, 44, + 52, 57, 44, 57, 50, 44, 45, 49, 48, 44, 53, 56, 44, 45, 55, 48, 44, 57, + 55, 44, 56, 44, 57, 57, 44, 48, 93,125, 125 + ] + + XCTAssertThrowsError(try JSONDecoder().decode( + FilePath.self, + from: Data(input) + )) + } + + func testInvalidExample() { + // Another misformed example from Johannes that violates FilePath's + // invariants by virtue of not being normalized. + let input: [UInt8] = [ + 123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108, + 84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34, + 58, 91, 56, 55, 44, 50, 52, 44, 45, 49, 49, 53, 44, 45, 49, 57, 44, 49, + 50, 50, 44, 45, 54, 56, 44, 57, 49, 44, 45, 49, 48, 54, 44, 45, 49, 48, + 48, 44, 45, 49, 49, 52, 44, 53, 54, 44, 45, 54, 53, 44, 49, 49, 56, 44, + 45, 54, 48, 44, 54, 54, 44, 45, 52, 50, 44, 55, 55, 44, 45, 54, 44, 45, + 52, 50, 44, 45, 56, 56, 44, 52, 55, 44, 48, 93,125, 125 + ] + + XCTAssertThrowsError(try JSONDecoder().decode( + FilePath.self, + from: Data(input) + )) + } + + func testEmptyString() { + // FilePath with an empty (and hence not null-terminated) SystemString. + let input: [UInt8] = [ + 123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108, + 84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34, + 58, 91, 93,125,125 + ] + + XCTAssertThrowsError(try JSONDecoder().decode( + FilePath.self, + from: Data(input) + )) + } +} diff --git a/Tests/SystemTests/FilePathTests/FilePathSyntaxTest.swift b/Tests/SystemTests/FilePathTests/FilePathSyntaxTest.swift index ccaa782..d23999a 100644 --- a/Tests/SystemTests/FilePathTests/FilePathSyntaxTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathSyntaxTest.swift @@ -1064,7 +1064,10 @@ final class FilePathSyntaxTest: XCTestCase { XCTAssert(path.lexicallyContains("usr")) XCTAssert(path.lexicallyContains("/usr")) XCTAssert(path.lexicallyContains("local/bin")) +#if !os(Windows) + // On Windows, this is a relative path and is still contained XCTAssert(!path.lexicallyContains("/local/bin")) +#endif path.append("..") XCTAssert(!path.lexicallyContains("local/bin")) XCTAssert(path.lexicallyContains("local/bin/..")) diff --git a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift new file mode 100644 index 0000000..30d5826 --- /dev/null +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -0,0 +1,58 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +import XCTest + +#if SYSTEM_PACKAGE +@testable import SystemPackage +#else +@testable import System +#endif + +final class TemporaryPathTest: XCTestCase { + #if SYSTEM_PACKAGE_DARWIN + func testNotInSlashTmp() throws { + try withTemporaryFilePath(basename: "NotInSlashTmp") { path in + // We shouldn't be using "/tmp" on Darwin + XCTAssertNotEqual(path.components.first!, "tmp") + } + } + #endif + + func testUnique() throws { + try withTemporaryFilePath(basename: "test") { path in + let strPath = String(decoding: path) + XCTAssert(strPath.contains("test")) + try withTemporaryFilePath(basename: "test") { path2 in + let strPath2 = String(decoding: path2) + XCTAssertNotEqual(strPath, strPath2) + } + } + } + + func testCleanup() throws { + var thePath: FilePath? = nil + + try withTemporaryFilePath(basename: "test") { path in + thePath = path.appending("foo.txt") + let fd = try FileDescriptor.open(thePath!, .readWrite, + options: [.create, .truncate], + permissions: .ownerReadWrite) + _ = try fd.closeAfter { + try fd.writeAll("Hello World".utf8) + } + } + + XCTAssertThrowsError(try FileDescriptor.open(thePath!, .readOnly)) { + error in + + XCTAssertEqual(error as! Errno, Errno.noSuchFileOrDirectory) + } + } +} diff --git a/Tests/SystemTests/FilePathTests/FilePathTest.swift b/Tests/SystemTests/FilePathTests/FilePathTest.swift index 1686faa..b50cc17 100644 --- a/Tests/SystemTests/FilePathTests/FilePathTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathTest.swift @@ -34,6 +34,16 @@ final class FilePathTest: XCTestCase { let filePath: FilePath let string: String let validString: Bool + + init(filePath: FilePath, string: String, validString: Bool) { + self.filePath = filePath + #if os(Windows) + self.string = string.replacingOccurrences(of: "/", with: "\\") + #else + self.string = string + #endif + self.validString = validString + } } #if os(Windows) diff --git a/Tests/SystemTests/FileTypesTest.swift b/Tests/SystemTests/FileTypesTest.swift index 4bddf41..620cfd7 100644 --- a/Tests/SystemTests/FileTypesTest.swift +++ b/Tests/SystemTests/FileTypesTest.swift @@ -42,7 +42,7 @@ final class FileDescriptorTest: XCTestCase { #endif // BSD only -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue) XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue) XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue) @@ -53,7 +53,7 @@ final class FileDescriptorTest: XCTestCase { XCTAssertEqual(SEEK_CUR, FileDescriptor.SeekOrigin.current.rawValue) XCTAssertEqual(SEEK_END, FileDescriptor.SeekOrigin.end.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssertEqual(SEEK_HOLE, FileDescriptor.SeekOrigin.nextHole.rawValue) XCTAssertEqual(SEEK_DATA, FileDescriptor.SeekOrigin.nextData.rawValue) #endif diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 31a654c..cba558b 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -7,7 +7,7 @@ See https://swift.org/LICENSE.txt for license information */ -#if false && swift(>=5.8) && $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) +#if swift(>=5.9) && SYSTEM_PACKAGE_DARWIN import XCTest import Darwin.Mach @@ -18,35 +18,40 @@ import SystemPackage import System #endif +@available(/*System 1.3.0: macOS 9999, iOS 9999, watchOS 9999, tvOS 9999*/iOS 8, *) final class MachPortTests: XCTestCase { func refCountForMachPortName(name:mach_port_name_t, kind:mach_port_right_t) -> mach_port_urefs_t { - var refCount:mach_port_urefs_t = 0 - withUnsafeMutablePointer(to: &refCount) { refCount in - let kr = mach_port_get_refs(mach_task_self_, name, kind, refCount) - assert(kr == KERN_SUCCESS) + var refCount:mach_port_urefs_t = .max + let kr = mach_port_get_refs(mach_task_self_, name, kind, &refCount) + if kr == KERN_INVALID_NAME { + refCount = 0 + } else { + XCTAssertEqual(kr, KERN_SUCCESS) } return refCount } func scopedReceiveRight(name:mach_port_name_t) -> mach_port_urefs_t { - _ = Mach.Port(name:name) // this should automatically deallocate when going out of scope + let right = Mach.Port(name:name) // this should automatically deallocate when going out of scope + defer { _ = right } return refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_RECEIVE) } - func testRecieveRightDeallocation() throws { - var name:mach_port_name_t = 0 // Never read - withUnsafeMutablePointer(to:&name) { name in - let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, name) - assert(kr == KERN_SUCCESS) - } + func testReceiveRightDeallocation() throws { + var name: mach_port_name_t = 0xFFFFFFFF + let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &name) + XCTAssertEqual(kr, KERN_SUCCESS) - XCTAssert(name != 0xFFFFFFFF) + XCTAssertNotEqual(name, 0xFFFFFFFF) - let one = scopedReceiveRight(name:name) - let zero = refCountForMachPortName(name:name, kind: MACH_PORT_RIGHT_RECEIVE) + let originalCount = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_RECEIVE) + XCTAssertEqual(originalCount, 1) - XCTAssert(one == 1); - XCTAssert(zero == 0); + let incrementedCount = scopedReceiveRight(name:name) + XCTAssertEqual(incrementedCount, 1); + + let deallocated = refCountForMachPortName(name:name, kind: MACH_PORT_RIGHT_RECEIVE) + XCTAssertEqual(deallocated, 0); } func consumeSendRightAutomatically(name:mach_port_name_t) -> mach_port_urefs_t { @@ -61,11 +66,11 @@ final class MachPortTests: XCTestCase { let recv = Mach.Port() recv.withBorrowedName { name in let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND)) - XCTAssert(kr == KERN_SUCCESS) + XCTAssertEqual(kr, KERN_SUCCESS) let one = consumeSendRightAutomatically(name:name) - XCTAssert(one == 1); + XCTAssertEqual(one, 1); let zero = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) - XCTAssert(zero == 0); + XCTAssertEqual(zero, 0); } } @@ -77,29 +82,70 @@ final class MachPortTests: XCTestCase { let one = send.withBorrowedName { name in return self.refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) } - XCTAssert(one == 1) + XCTAssertEqual(one, 1) return send.relinquish() })() let stillOne = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) - XCTAssert(stillOne == 1) + XCTAssertEqual(stillOne, 1) + + recv.withBorrowedName { + let alsoOne = refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE) + XCTAssertEqual(alsoOne, 1) + } + } + + func testSendOnceRightRelinquishment() throws { + let recv = Mach.Port() + + let name = ({ + let send = recv.makeSendOnceRight() + let one = send.withBorrowedName { name in + return self.refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_SEND_ONCE) + } + XCTAssertEqual(one, 1) + + return send.relinquish() + })() + + let stillOne = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_SEND_ONCE) + XCTAssertEqual(stillOne, 1) + + recv.withBorrowedName { + let alsoOne = refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE) + XCTAssertEqual(alsoOne, 1) + } + } + + func testReceiveRightRelinquishment() throws { + let recv = Mach.Port() + + let one = recv.withBorrowedName { + self.refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE) + } + XCTAssertEqual(one, 1) + + let name = recv.unguardAndRelinquish() + + let stillOne = refCountForMachPortName(name: name, kind: MACH_PORT_RIGHT_RECEIVE) + XCTAssertEqual(stillOne, 1) } func testMakeSendCountSettable() throws { var recv = Mach.Port() - XCTAssert(recv.makeSendCount == 0) + XCTAssertEqual(recv.makeSendCount, 0) recv.makeSendCount = 7 - XCTAssert(recv.makeSendCount == 7) + XCTAssertEqual(recv.makeSendCount, 7) } func makeSendRight() throws -> Mach.Port { let recv = Mach.Port() let zero = recv.makeSendCount - XCTAssert(zero == 0) + XCTAssertEqual(zero, 0) let send = recv.makeSendRight() let one = recv.makeSendCount - XCTAssert(one == 1) + XCTAssertEqual(one, 1) return send } @@ -110,10 +156,10 @@ final class MachPortTests: XCTestCase { func testMakeSendOnceDoesntIncrementMakeSendCount() throws { let recv = Mach.Port() let zero = recv.makeSendCount - XCTAssert(zero == 0) + XCTAssertEqual(zero, 0) _ = recv.makeSendOnceRight() let same = recv.makeSendCount - XCTAssert(same == zero) + XCTAssertEqual(same, zero) } func testMakeSendOnceIsUnique() throws { @@ -121,8 +167,7 @@ final class MachPortTests: XCTestCase { let once = recv.makeSendOnceRight() recv.withBorrowedName { rname in once.withBorrowedName { oname in - print(oname, rname) - XCTAssert(oname != rname) + XCTAssertNotEqual(oname, rname) } } } @@ -130,15 +175,68 @@ final class MachPortTests: XCTestCase { func testCopySend() throws { let recv = Mach.Port() let zero = recv.makeSendCount - XCTAssert(zero == 0) + XCTAssertEqual(zero, 0) let send = recv.makeSendRight() let one = recv.makeSendCount - XCTAssert(one == 1) + XCTAssertEqual(one, 1) _ = try send.copySendRight() let same = recv.makeSendCount - XCTAssert(same == one) + XCTAssertEqual(same, one) } + + func testCopyDeadName() throws { + let recv = Mach.Port() + let send = recv.makeSendRight() + _ = consume recv // and turn `send` into a dead name + XCTAssertThrowsError( + _ = try send.copySendRight(), + "Copying a dead name should throw" + ) { error in + XCTAssertEqual( + error as! Mach.PortRightError, Mach.PortRightError.deadName + ) + } + } + + func testCopyDeadName2() throws { + let send = Mach.Port(name: 0xffffffff) + XCTAssertThrowsError( + _ = try send.copySendRight(), + "Copying a dead name should throw" + ) { error in + XCTAssertEqual( + error as! Mach.PortRightError, Mach.PortRightError.deadName + ) + } + } + + func testMakeReceiveRightFromExistingName() throws { + var name = mach_port_name_t(MACH_PORT_NULL) + var kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &name) + XCTAssertEqual(kr, KERN_SUCCESS) + XCTAssertNotEqual(name, mach_port_name_t(MACH_PORT_NULL)) + let context = mach_port_context_t(arc4random()) + kr = mach_port_guard(mach_task_self_, name, context, 0) + XCTAssertEqual(kr, KERN_SUCCESS) + + let right = Mach.Port(name: name, context: context) + right.withBorrowedName { + XCTAssertEqual(name, $0) + XCTAssertEqual(context, $1) + } + } + + func testDeinitDeadSendRights() throws { + let recv = Mach.Port() + let send = recv.makeSendRight() + let send1 = recv.makeSendOnceRight() + + _ = consume recv + // `send` and `send1` have become dead names + _ = consume send + _ = consume send1 + } } #endif diff --git a/Tests/SystemTests/SystemStringTests.swift b/Tests/SystemTests/SystemStringTests.swift index a189171..48ca83c 100644 --- a/Tests/SystemTests/SystemStringTests.swift +++ b/Tests/SystemTests/SystemStringTests.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2024 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -101,7 +101,7 @@ struct StringTest: TestCase { // Test null insertion let rawChars = raw.lazy.map { SystemChar($0) } expectEqual(sysRaw, SystemString(rawChars.dropLast())) - sysRaw.withSystemChars { // TODO: assuming we want null in withSysChars + sysRaw.withNullTerminatedSystemChars { expectEqualSequence(rawChars, $0, "rawChars") } @@ -254,6 +254,11 @@ final class SystemStringTest: XCTestCase { XCTAssert(str == "abcd") } + func testStringProperty() { + let source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63] + let str = SystemString(platformString: source) + XCTAssertEqual(str.string, str[...].string) + } } extension SystemStringTest { diff --git a/Utilities/expand-availability.py b/Utilities/expand-availability.py index 81dd97d..26ec2de 100755 --- a/Utilities/expand-availability.py +++ b/Utilities/expand-availability.py @@ -54,7 +54,7 @@ import argparse versions = { "System 0.0.1": "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0", "System 0.0.2": "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0", - "System 1.1.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999", + "System 1.1.0": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4", "System 1.2.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999", "System 1.3.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999", } diff --git a/cmake/modules/SwiftSupport.cmake b/cmake/modules/SwiftSupport.cmake index a73a4e5..8f1e2c4 100644 --- a/cmake/modules/SwiftSupport.cmake +++ b/cmake/modules/SwiftSupport.cmake @@ -45,6 +45,8 @@ function(get_swift_host_arch result_var_name) set("${result_var_name}" "i686" PARENT_SCOPE) elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686") set("${result_var_name}" "i686" PARENT_SCOPE) + elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "riscv64") + set("${result_var_name}" "riscv64" PARENT_SCOPE) else() message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}") endif()