From c0e8ef346b5cfc350dbc27aa7d74c9bcc6afea26 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Dec 2021 17:20:15 -0800 Subject: [PATCH 1/5] Update package with changes from recent ABI stable releases This brings the contents of this package up to date with versions of the ABI stable `System` module that shipped in recent iOS/macOS releases. Most changes only touch internal implementation details, but some ABI-related fixes also affect the public API. There are no source-incompatible changes. - ABI stability fixes (un-deprecate CModeT, don't use PlatformChar in inlinable contexts that need to deploy to iOS 14) - New utilities: `_RawBuffer`, `Array._withCStringArray`, `_withOptionalUnsafePointerOrNull`, `_withStackBuffer`, `system_memset` - Prefer using explicit optionals to implicitly-unwrapped ones - Add support for wildcard matching in mocking tests - A bunch of new availability annotations. (I expect there will be more of these coming in future PRs.) --- .gitignore | 2 +- Sources/System/CMakeLists.txt | 2 + Sources/System/FileDescriptor.swift | 3 +- Sources/System/FileOperations.swift | 11 +- .../FilePath/FilePathComponentView.swift | 4 +- .../System/FilePath/FilePathComponents.swift | 12 +- Sources/System/FilePath/FilePathParsing.swift | 8 ++ Sources/System/FilePath/FilePathString.swift | 25 +++- Sources/System/FilePermissions.swift | 6 +- Sources/System/Internals/Backcompat.swift | 29 +++++ Sources/System/Internals/CInterop.swift | 23 ++-- Sources/System/Internals/Constants.swift | 3 +- Sources/System/Internals/Exports.swift | 16 ++- Sources/System/Internals/Mocking.swift | 7 +- Sources/System/Internals/RawBuffer.swift | 102 +++++++++++++++ Sources/System/Internals/Syscalls.swift | 10 +- Sources/System/PlatformString.swift | 3 + Sources/System/Util+StringArray.swift | 117 ++++++++++++++++++ Sources/System/Util.swift | 37 +++++- Tests/SystemTests/TestingInfrastructure.swift | 62 ++++++++-- Tests/SystemTests/UtilTests.swift | 89 +++++++++++++ 21 files changed, 524 insertions(+), 47 deletions(-) create mode 100644 Sources/System/Internals/Backcompat.swift create mode 100644 Sources/System/Internals/RawBuffer.swift create mode 100644 Sources/System/Util+StringArray.swift create mode 100644 Tests/SystemTests/UtilTests.swift diff --git a/.gitignore b/.gitignore index 36bbb6f..2196fff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ .DS_Store /.build /Packages -/*.xcodeproj +swift-system.xcodeproj xcuserdata/ .*.sw? diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 43958d3..990f1c6 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -16,6 +16,7 @@ add_library(SystemPackage PlatformString.swift SystemString.swift Util.swift + Util+StringArray.swift UtilConsumers.swift) set_target_properties(SystemPackage PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) @@ -32,6 +33,7 @@ target_sources(SystemPackage PRIVATE Internals/Constants.swift Internals/Exports.swift Internals/Mocking.swift + Internals/RawBuffer.swift Internals/Syscalls.swift Internals/WindowsSyscallAdapters.swift) target_link_libraries(SystemPackage PUBLIC diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 9a7d319..ba60696 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -25,7 +25,8 @@ public struct FileDescriptor: RawRepresentable, Hashable, Codable { public init(rawValue: CInt) { self.rawValue = rawValue } } -// Standard file descriptors +// Standard file descriptors. +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FileDescriptor { /// The standard input file descriptor, with a numeric value of 0. @_alwaysEmitIntoClient diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index 0102563..e90a494 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -31,7 +31,7 @@ extension FileDescriptor { permissions: FilePermissions? = nil, retryOnInterrupt: Bool = true ) throws -> FileDescriptor { - try path.withPlatformString { + try path.withCString { try FileDescriptor.open( $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) } @@ -53,7 +53,7 @@ extension FileDescriptor { /// The corresponding C function is `open`. @_alwaysEmitIntoClient public static func open( - _ path: UnsafePointer, + _ path: UnsafePointer, _ mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, @@ -66,7 +66,7 @@ extension FileDescriptor { @usableFromInline internal static func _open( - _ path: UnsafePointer, + _ path: UnsafePointer, _ mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions, permissions: FilePermissions?, @@ -308,7 +308,10 @@ extension FileDescriptor { buffer, retryOnInterrupt: retryOnInterrupt) } +} +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ +extension FileDescriptor { /// Duplicate this file descriptor and return the newly created copy. /// /// - Parameters: @@ -385,7 +388,7 @@ extension FileDescriptor { public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) { try _pipe().get() } - + /*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/ @usableFromInline internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> { diff --git a/Sources/System/FilePath/FilePathComponentView.swift b/Sources/System/FilePath/FilePathComponentView.swift index 959ff64..acbc8f3 100644 --- a/Sources/System/FilePath/FilePathComponentView.swift +++ b/Sources/System/FilePath/FilePathComponentView.swift @@ -40,7 +40,7 @@ extension FilePath { } } - #if SYSTEM_PACKAGE + #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) } @@ -202,6 +202,7 @@ extension FilePath { // MARK: - Internals +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.ComponentView: _PathSlice { internal var _range: Range { _start ..< _path._storage.endIndex @@ -214,6 +215,7 @@ extension FilePath.ComponentView: _PathSlice { // MARK: - Invariants +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.ComponentView { internal func _invariantCheck() { #if DEBUG diff --git a/Sources/System/FilePath/FilePathComponents.swift b/Sources/System/FilePath/FilePathComponents.swift index d6b043f..9d57a0b 100644 --- a/Sources/System/FilePath/FilePathComponents.swift +++ b/Sources/System/FilePath/FilePathComponents.swift @@ -98,6 +98,7 @@ extension FilePath.Component { } } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Root { // TODO: Windows analysis APIs } @@ -183,15 +184,18 @@ extension _PathSlice { internal var _storage: SystemString { _path._storage } } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Component: _PathSlice { } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Root: _PathSlice { internal var _range: Range { (..<_rootEnd).relative(to: _path._storage) } } + +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath: _PlatformStringable { - @usableFromInline func _withPlatformString(_ body: (UnsafePointer) throws -> Result) rethrows -> Result { try _storage.withPlatformString(body) } @@ -202,6 +206,7 @@ extension FilePath: _PlatformStringable { } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Component { // The index of the `.` denoting an extension internal func _extensionIndex() -> SystemString.Index? { @@ -230,6 +235,7 @@ internal func _makeExtension(_ ext: String) -> SystemString { return result } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Component { internal init?(_ str: SystemString) { // FIXME: explicit null root? Or something else? @@ -242,6 +248,7 @@ extension FilePath.Component { } } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Root { internal init?(_ str: SystemString) { // FIXME: explicit null root? Or something else? @@ -256,6 +263,7 @@ extension FilePath.Root { // MARK: - Invariants +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Component { // TODO: ensure this all gets easily optimized away in release... internal func _invariantCheck() { @@ -267,6 +275,8 @@ extension FilePath.Component { #endif // DEBUG } } + +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Root { internal func _invariantCheck() { #if DEBUG diff --git a/Sources/System/FilePath/FilePathParsing.swift b/Sources/System/FilePath/FilePathParsing.swift index 2675398..bbfd066 100644 --- a/Sources/System/FilePath/FilePathParsing.swift +++ b/Sources/System/FilePath/FilePathParsing.swift @@ -111,6 +111,7 @@ extension SystemString { } } +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath { internal mutating func _removeTrailingSeparator() { _storage._removeTrailingSeparator() @@ -191,6 +192,7 @@ extension SystemString { } } +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath { internal var _relativeStart: SystemString.Index { _storage._relativePathStart @@ -202,6 +204,7 @@ extension FilePath { // Parse separators +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath { internal typealias _Index = SystemString.Index @@ -265,6 +268,7 @@ extension FilePath { } } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.ComponentView { // TODO: Store this... internal var _relativeStart: SystemString.Index { @@ -289,6 +293,7 @@ extension SystemString { } } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension FilePath.Root { // Asserting self is a root, returns whether this is an // absolute root. @@ -313,6 +318,7 @@ extension FilePath.Root { } } +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath { internal var _portableDescription: String { guard _windowsPaths else { return description } @@ -331,6 +337,7 @@ internal var _windowsPaths: Bool { #endif } +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath { // Whether we should add a separator when doing an append internal var _needsSeparatorForAppend: Bool { @@ -358,6 +365,7 @@ extension FilePath { } // MARK: - Invariants +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePath { internal func _invariantCheck() { #if DEBUG diff --git a/Sources/System/FilePath/FilePathString.swift b/Sources/System/FilePath/FilePathString.swift index 2c245e9..2dd2cce 100644 --- a/Sources/System/FilePath/FilePathString.swift +++ b/Sources/System/FilePath/FilePathString.swift @@ -20,6 +20,7 @@ extension FilePath { self.init(_platformString: platformString) } +#if !os(Windows) // Availability workaround /// Calls the given closure with a pointer to the contents of the file path, /// represented as a null-terminated platform string. /// @@ -37,12 +38,28 @@ extension FilePath { _ body: (UnsafePointer) throws -> Result ) rethrows -> Result { // For backwards deployment, call withCString if available. - #if !os(Windows) return try withCString(body) - #else - return try _withPlatformString(body) - #endif } +#else + /// Calls the given closure with a pointer to the contents of the file path, + /// represented as a null-terminated platform string. + /// + /// - Parameter body: A closure with a pointer parameter + /// that points to a null-terminated platform string. + /// If `body` has a return value, + /// that value is also used as the return value for this method. + /// - Returns: The return value, if any, of the `body` closure parameter. + /// + /// The pointer passed as an argument to `body` is valid + /// only during the execution of this method. + /// Don't try to store the pointer for later use. + public func withPlatformString( + _ body: (UnsafePointer) throws -> Result + ) rethrows -> Result { + // For backwards deployment, call withCString if available. + return try _withPlatformString(body) + } +#endif } /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ diff --git a/Sources/System/FilePermissions.swift b/Sources/System/FilePermissions.swift index 0780ee0..238ba15 100644 --- a/Sources/System/FilePermissions.swift +++ b/Sources/System/FilePermissions.swift @@ -21,14 +21,14 @@ public struct FilePermissions: OptionSet, Hashable, Codable { /// The raw C file permissions. @_alwaysEmitIntoClient - public let rawValue: CInterop.Mode + public let rawValue: CModeT /// Create a strongly-typed file permission from a raw C value. @_alwaysEmitIntoClient - public init(rawValue: CInterop.Mode) { self.rawValue = rawValue } + public init(rawValue: CModeT) { self.rawValue = rawValue } @_alwaysEmitIntoClient - private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) } + private init(_ raw: CModeT) { self.init(rawValue: raw) } /// Indicates that other users have read-only permission. @_alwaysEmitIntoClient diff --git a/Sources/System/Internals/Backcompat.swift b/Sources/System/Internals/Backcompat.swift new file mode 100644 index 0000000..a376dd2 --- /dev/null +++ b/Sources/System/Internals/Backcompat.swift @@ -0,0 +1,29 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2021 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +extension String { + internal init( + _unsafeUninitializedCapacity capacity: Int, + initializingUTF8With body: (UnsafeMutableBufferPointer) throws -> Int + ) rethrows { + if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { + self = try String( + unsafeUninitializedCapacity: capacity, + initializingUTF8With: body) + return + } + + let array = try Array( + unsafeUninitializedCapacity: capacity + ) { buffer, count in + count = try body(buffer) + } + self = String(decoding: array, as: UTF8.self) + } +} diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index 2a9832e..5898813 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -1,19 +1,12 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ -// MARK: - Public typealiases - -/// The C `mode_t` type. -/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ -@available(*, deprecated, renamed: "CInterop.Mode") -public typealias CModeT = CInterop.Mode - #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(Android) @@ -26,6 +19,20 @@ import ucrt #error("Unsupported Platform") #endif +// MARK: - Public typealiases + +// FIXME: `CModeT` ought to be deprecated and replaced with `CInterop.Mode` +// if/when the compiler becomes less strict about availability checking +// of "namespaced" typealiases. (rdar://81722893) +#if os(Windows) +/// The C `mode_t` type. +public typealias CModeT = CInt +#else +/// The C `mode_t` type. +/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ +public typealias CModeT = mode_t +#endif + /// A namespace for C and platform types /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ public enum CInterop { diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index a4dbb89..e691676 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 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -528,4 +528,3 @@ internal var _SEEK_HOLE: CInt { SEEK_HOLE } @_alwaysEmitIntoClient internal var _SEEK_DATA: CInt { SEEK_DATA } #endif - diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 2b4ae3b..0a5a26e 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 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -60,7 +60,10 @@ internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer! strerror(__errnum) } -internal func system_strlen(_ s: UnsafePointer) -> Int { +internal func system_strlen(_ s: UnsafePointer) -> Int { + strlen(s) +} +internal func system_strlen(_ s: UnsafeMutablePointer) -> Int { strlen(s) } @@ -78,6 +81,15 @@ internal func system_platform_strlen(_ s: UnsafePointer) #endif } +// memset for raw buffers +// FIXME: Do we really not have something like this in the stdlib already? +internal func system_memset( + _ buffer: UnsafeMutableRawBufferPointer, + to byte: UInt8 +) { + memset(buffer.baseAddress, CInt(byte), buffer.count) +} + // Interop between String and platfrom string extension String { internal func _withPlatformString( diff --git a/Sources/System/Internals/Mocking.swift b/Sources/System/Internals/Mocking.swift index eb1fe83..405dc34 100644 --- a/Sources/System/Internals/Mocking.swift +++ b/Sources/System/Internals/Mocking.swift @@ -19,9 +19,10 @@ #if ENABLE_MOCKING internal struct Trace { - internal struct Entry: Hashable { - private var name: String - private var arguments: [AnyHashable] + internal struct Entry { + + internal var name: String + internal var arguments: [AnyHashable] internal init(name: String, _ arguments: [AnyHashable]) { self.name = name diff --git a/Sources/System/Internals/RawBuffer.swift b/Sources/System/Internals/RawBuffer.swift new file mode 100644 index 0000000..7f9461c --- /dev/null +++ b/Sources/System/Internals/RawBuffer.swift @@ -0,0 +1,102 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2021 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +// A copy-on-write fixed-size buffer of raw memory. +internal struct _RawBuffer { + internal var _storage: Storage? + + internal init() { + self._storage = nil + } + + internal init(minimumCapacity: Int) { + if minimumCapacity > 0 { + self._storage = Storage.create(minimumCapacity: minimumCapacity) + } else { + self._storage = nil + } + } +} + +extension _RawBuffer { + internal var capacity: Int { + _storage?.header ?? 0 // Note: not capacity! + } + + internal mutating func ensureUnique() { + guard _storage != nil else { return } + let unique = isKnownUniquelyReferenced(&_storage) + if !unique { + _storage = _copy(capacity: capacity) + } + } + + internal func _grow(desired: Int) -> Int { + let next = Int(1.75 * Double(self.capacity)) + return Swift.max(next, desired) + } + + internal mutating func ensureUnique(capacity: Int) { + let unique = isKnownUniquelyReferenced(&_storage) + if !unique || self.capacity < capacity { + _storage = _copy(capacity: _grow(desired: capacity)) + } + } + + internal func withUnsafeBytes( + _ body: (UnsafeRawBufferPointer) throws -> R + ) rethrows -> R { + guard let storage = _storage else { + return try body(UnsafeRawBufferPointer(start: nil, count: 0)) + } + return try storage.withUnsafeMutablePointers { count, bytes in + let buffer = UnsafeRawBufferPointer(start: bytes, count: count.pointee) + return try body(buffer) + } + } + + internal mutating func withUnsafeMutableBytes( + _ body: (UnsafeMutableRawBufferPointer) throws -> R + ) rethrows -> R { + guard _storage != nil else { + return try body(UnsafeMutableRawBufferPointer(start: nil, count: 0)) + } + ensureUnique() + return try _storage!.withUnsafeMutablePointers { count, bytes in + let buffer = UnsafeMutableRawBufferPointer(start: bytes, count: count.pointee) + return try body(buffer) + } + } +} + +extension _RawBuffer { + internal class Storage: ManagedBuffer { + internal static func create(minimumCapacity: Int) -> Storage { + Storage.create( + minimumCapacity: minimumCapacity, + makingHeaderWith: { $0.capacity } + ) as! Storage + } + } + + internal func _copy(capacity: Int) -> Storage { + let copy = Storage.create(minimumCapacity: capacity) + copy.withUnsafeMutablePointers { dstlen, dst in + self.withUnsafeBytes { src in + guard src.count > 0 else { return } + assert(src.count <= dstlen.pointee) + UnsafeMutableRawPointer(dst) + .copyMemory( + from: src.baseAddress!, + byteCount: Swift.min(src.count, dstlen.pointee)) + } + } + return copy + } +} diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 453c02f..6db3ad4 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.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 - 2021 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -54,7 +54,7 @@ internal func system_close(_ fd: Int32) -> Int32 { // read internal func system_read( - _ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int + _ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int ) -> Int { #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte) } @@ -64,7 +64,7 @@ internal func system_read( // pread internal func system_pread( - _ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t + _ fd: Int32, _ buf: UnsafeMutableRawPointer?, _ nbyte: Int, _ offset: off_t ) -> Int { #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } @@ -84,7 +84,7 @@ internal func system_lseek( // write internal func system_write( - _ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int + _ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int ) -> Int { #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte) } @@ -94,7 +94,7 @@ internal func system_write( // pwrite internal func system_pwrite( - _ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t + _ fd: Int32, _ buf: UnsafeRawPointer?, _ nbyte: Int, _ offset: off_t ) -> Int { #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } diff --git a/Sources/System/PlatformString.swift b/Sources/System/PlatformString.swift index 358f349..9fe398a 100644 --- a/Sources/System/PlatformString.swift +++ b/Sources/System/PlatformString.swift @@ -58,6 +58,7 @@ extension String { } +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension CInterop.PlatformChar { internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit { #if os(Windows) @@ -67,6 +68,8 @@ extension CInterop.PlatformChar { #endif } } + +/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ extension CInterop.PlatformUnicodeEncoding.CodeUnit { internal var _platformChar: CInterop.PlatformChar { #if os(Windows) diff --git a/Sources/System/Util+StringArray.swift b/Sources/System/Util+StringArray.swift new file mode 100644 index 0000000..2a8ba28 --- /dev/null +++ b/Sources/System/Util+StringArray.swift @@ -0,0 +1,117 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2021 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +extension Array where Element == String { + internal typealias CStr = UnsafePointer? + + /// Call `body` with a buffer of `UnsafePointer?` values, + /// suitable for passing to a C function that expects a C string array. + /// The buffer is guaranteed to be followed by an extra storage slot + /// containing a null pointer. (For C functions that expect an array + /// terminated with a null pointer.) + /// + /// This function is careful not to heap allocate memory unless there are + /// too many strings, or if it needs to copy too much character data. + internal func _withCStringArray( + _ body: (UnsafeBufferPointer?>) throws -> R + ) rethrows -> R { + if self.count == 0 { + // Fast path: empty array. + let p: CStr = nil + return try Swift.withUnsafePointer(to: p) { array in + try body(UnsafeBufferPointer(start: array, count: 0)) + } + } + #if SYSTEM_OS_BUILD // String._guts isn't accessible from SwiftPM or CMake + if self.count == 1, self[0]._guts._isLargeZeroTerminatedContiguousUTF8 { + // Fast path: Single fast string. + let start = self[0]._guts._largeContiguousUTF8CodeUnits.baseAddress! + var p: (CStr, CStr) = ( + UnsafeRawPointer(start).assumingMemoryBound(to: CChar.self), + nil + ) + return try Swift.withUnsafeBytes(of: &p) { buffer in + let start = buffer.baseAddress!.assumingMemoryBound(to: CStr.self) + return try body(UnsafeBufferPointer(start: start, count: 1)) + } + } + #endif + // We need to create a buffer for the C array. + return try _withStackBuffer( + capacity: (self.count + 1) * MemoryLayout.stride + ) { array in + let array = array.bindMemory(to: CStr.self) + // Calculate number of bytes we need for character storage + let bytes = self.reduce(into: 0) { count, string in + #if SYSTEM_OS_BUILD + if string._guts._isLargeZeroTerminatedContiguousUTF8 { return } + #endif + count += string.utf8.count + 1 // Plus one for terminating NUL + } + #if SYSTEM_OS_BUILD + if bytes == 0 { + // Fast path: we only contain strings with stable null-terminated storage + for i in self.indices { + let string = self[i] + precondition(string._guts._isLargeZeroTerminatedContiguousUTF8) + let address = string._guts._largeContiguousUTF8CodeUnits.baseAddress! + array[i] = UnsafeRawPointer(address).assumingMemoryBound(to: CChar.self) + } + array[self.count] = nil + return try body(UnsafeBufferPointer(rebasing: array.dropLast())) + } + #endif + return try _withStackBuffer(capacity: bytes) { chars in + var chars = chars + for i in self.indices { + let (cstr, scratchUsed) = self[i]._getCStr(with: chars) + array[i] = cstr.assumingMemoryBound(to: CChar.self) + chars = .init(rebasing: chars[scratchUsed...]) + } + array[self.count] = nil + return try body(UnsafeBufferPointer(rebasing: array.dropLast())) + } + } + } +} + +extension String { + fileprivate func _getCStr( + with scratch: UnsafeMutableRawBufferPointer + ) -> (cstr: UnsafeRawPointer, scratchUsed: Int) { + #if SYSTEM_OS_BUILD + if _guts._isLargeZeroTerminatedContiguousUTF8 { + // This is a wonderful string, we can just use its storage address. + let address = _guts._largeContiguousUTF8CodeUnits.baseAddress! + return (UnsafeRawPointer(address), 0) + } + #endif + let r: (UnsafeRawPointer, Int)? = self.utf8.withContiguousStorageIfAvailable { source in + // This is a somewhat okay string -- we need to use memcpy. + precondition(source.count <= scratch.count) + let start = scratch.baseAddress! + start.copyMemory(from: source.baseAddress!, byteCount: source.count) + start.storeBytes(of: 0, toByteOffset: source.count, as: UInt8.self) + return (UnsafeRawPointer(start), source.count + 1) + } + if let r = r { return r } + + // What a horrible string; we need to copy individual bytes. + precondition(self.utf8.count <= scratch.count) + var c = 0 + for byte in self.utf8 { + scratch[c] = byte + c += 1 + } + scratch[c] = 0 + c += 1 + return (UnsafeRawPointer(scratch.baseAddress!), c) + } +} + diff --git a/Sources/System/Util.swift b/Sources/System/Util.swift index ac25830..a119576 100644 --- a/Sources/System/Util.swift +++ b/Sources/System/Util.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 - 2021 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -127,3 +127,38 @@ extension MutableCollection where Element: Equatable { } } } + +internal func _withOptionalUnsafePointerOrNull( + to value: T?, + _ body: (UnsafePointer?) throws -> R +) rethrows -> R { + guard let value = value else { + return try body(nil) + } + return try withUnsafePointer(to: value, body) +} + +/// Calls `body` with a temporary buffer of the indicated size, +/// possibly stack-allocated. +internal func _withStackBuffer( + capacity: Int, + _ body: (UnsafeMutableRawBufferPointer) throws -> R +) rethrows -> R { + typealias StackStorage = ( + UInt64, UInt64, UInt64, UInt64, + UInt64, UInt64, UInt64, UInt64, + UInt64, UInt64, UInt64, UInt64, + UInt64, UInt64, UInt64, UInt64 + ) + if capacity > MemoryLayout.size { + var buffer = _RawBuffer(minimumCapacity: capacity) + return try buffer.withUnsafeMutableBytes { buffer in + try body(.init(rebasing: buffer[.. Bool { + guard self.name == other.name else { return false } + guard self.arguments.count == other.arguments.count else { return false } + for i in self.arguments.indices { + if self.arguments[i] is Wildcard || other.arguments[i] is Wildcard { + continue + } + guard self.arguments[i] == other.arguments[i] else { return false } + } + return true + } +} + // To aid debugging, force failures to fatal error internal var forceFatalFailures = false @@ -40,7 +59,7 @@ extension TestCase { _ message: String? = nil ) where S1.Element: Equatable, S1.Element == S2.Element { if !expected.elementsEqual(actual) { - defer { print("expected: \(expected), actual: \(actual)") } + defer { print("expected: \(expected)\n actual: \(actual)") } fail(message) } } @@ -49,7 +68,7 @@ extension TestCase { _ message: String? = nil ) { if actual != expected { - defer { print("expected: \(expected), actual: \(actual)") } + defer { print("expected: \(expected)\n actual: \(actual)") } fail(message) } } @@ -62,6 +81,27 @@ extension TestCase { fail(message) } } + func expectMatch( + _ expected: Trace.Entry?, _ actual: Trace.Entry?, + _ message: String? = nil + ) { + func check() -> Bool { + switch (expected, actual) { + case let (expected?, actual?): + return expected.matches(actual) + case (nil, nil): + return true + default: + return false + } + } + if !check() { + let e = expected.map { "\($0)" } ?? "nil" + let a = actual.map { "\($0)" } ?? "nil" + defer { print("expected: \(e)\n actual: \(a)") } + fail(message) + } + } func expectNil( _ actual: T?, _ message: String? = nil @@ -149,7 +189,7 @@ internal struct MockTestCase: TestCase { // Test our API mappings to the lower-level syscall invocation do { try body(true) - self.expectEqual(self.expected, mocking.trace.dequeue()) + self.expectMatch(self.expected, mocking.trace.dequeue()) } catch { self.fail() } @@ -158,9 +198,9 @@ internal struct MockTestCase: TestCase { guard interruptBehavior != .noError else { do { try body(interruptable) - self.expectEqual(self.expected, mocking.trace.dequeue()) + self.expectMatch(self.expected, mocking.trace.dequeue()) try body(!interruptable) - self.expectEqual(self.expected, mocking.trace.dequeue()) + self.expectMatch(self.expected, mocking.trace.dequeue()) } catch { self.fail() } @@ -177,7 +217,7 @@ internal struct MockTestCase: TestCase { self.fail() } catch Errno.interrupted { // Success! - self.expectEqual(self.expected, mocking.trace.dequeue()) + self.expectMatch(self.expected, mocking.trace.dequeue()) } catch { self.fail() } @@ -188,13 +228,13 @@ internal struct MockTestCase: TestCase { mocking.forceErrno = .counted(errno: EINTR, count: 3) try body(interruptable) - self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR - self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR - self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR - self.expectEqual(self.expected, mocking.trace.dequeue()) // Success + self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR + self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR + self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR + self.expectMatch(self.expected, mocking.trace.dequeue()) // Success } catch Errno.interrupted { self.expectFalse(interruptable) - self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR + self.expectMatch(self.expected, mocking.trace.dequeue()) // EINTR } catch { self.fail() } diff --git a/Tests/SystemTests/UtilTests.swift b/Tests/SystemTests/UtilTests.swift new file mode 100644 index 0000000..bfd2134 --- /dev/null +++ b/Tests/SystemTests/UtilTests.swift @@ -0,0 +1,89 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2021 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +import XCTest + +#if SYSTEM_PACKAGE +@testable import SystemPackage +#else +@testable import System +#endif + +class UtilTests: XCTestCase { + func testStackBuffer() { + // Exercises _withStackBuffer a bit, in hopes any bugs will + // show up as ASan failures. + for size in stride(from: 0, to: 1000, by: 5) { + var called = false + _withStackBuffer(capacity: size) { buffer in + XCTAssertFalse(called) + called = true + + buffer.initializeMemory(as: UInt8.self, repeating: 42) + } + XCTAssertTrue(called) + } + } + + func testCStringArray() { + func check( + _ array: [String], + file: StaticString = #file, + line: UInt = #line + ) { + array._withCStringArray { carray in + let actual = carray.map { $0.map { String(cString: $0) } ?? "" } + XCTAssertEqual(actual, array, file: file, line: line) + // Verify that there is a null pointer following the last item in + // carray. (Note: this is intentionally addressing beyond the + // end of the buffer, as the function promises that is going to be okay.) + XCTAssertNil((carray.baseAddress! + carray.count).pointee) + } + } + + check([]) + check([""]) + check(["", ""]) + check(["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]) + // String literals of various sizes and counts + check(["hello"]) + check(["hello", "world"]) + check(["This is a rather large string literal"]) + check([ + "This is a rather large string literal", + "This is small", + "This one is not that small -- it's even longer than the first", + ]) + check([ + "This is a rather large string literal", + "This one is not that small -- it's even longer than the first", + "And this is the largest of them all. I wonder if it even fits on a line" + ]) + check(Array(repeating: "", count: 100)) + check(Array(repeating: "Hiii", count: 100)) + check(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]) + check(["", "b", "", "d", "", "f", "", "h", "", "j", "", "👨‍👨‍👧‍👦👩‍❤️‍💋‍👨", "m"]) + + var girls = ["Dörothy", "Róse", "Blánche", "Sőphia"] + check(girls) // Small strings + for i in girls.indices { + // Convert to native + girls[i] = "\(girls[i]) \(girls[i]) \(girls[i])" + } + check(girls) // Native large strings + for i in girls.indices { + let data = girls[i].data(using: .utf16)! + girls[i] = NSString( + data: data, + encoding: String.Encoding.utf16.rawValue + )! as String + } + check(girls) // UTF-16 Cocoa strings + } +} From 6469433909b273fe7d24bc268f7184ba9a7be60d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Dec 2021 17:39:44 -0800 Subject: [PATCH 2/5] Work around `memset` taking a non-optional pointer on Linux --- Sources/System/Internals/Exports.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 0a5a26e..01650a7 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -87,7 +87,8 @@ internal func system_memset( _ buffer: UnsafeMutableRawBufferPointer, to byte: UInt8 ) { - memset(buffer.baseAddress, CInt(byte), buffer.count) + guard buffer.count > 0 else { return } + memset(buffer.baseAddress!, CInt(byte), buffer.count) } // Interop between String and platfrom string From 915070e00671074fd1ac8f07042719151643b378 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 21 Dec 2021 18:40:27 -0800 Subject: [PATCH 3/5] Add Internals/Backcompat.swift to CMake config --- Sources/System/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 990f1c6..33fb46b 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -29,6 +29,7 @@ target_sources(SystemPackage PRIVATE FilePath/FilePathSyntax.swift FilePath/FilePathWindows.swift) target_sources(SystemPackage PRIVATE + Internals/Backcompat.swift Internals/CInterop.swift Internals/Constants.swift Internals/Exports.swift From 81d78be49904c51d55c737c04a24604b015ae262 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 26 Dec 2021 21:53:28 -0800 Subject: [PATCH 4/5] Fix Windows build --- Sources/System/FileOperations.swift | 59 ++++++++++++++++++++ Sources/System/FilePath/FilePathString.swift | 10 +++- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index e90a494..368d4d1 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -31,12 +31,23 @@ extension FileDescriptor { permissions: FilePermissions? = nil, retryOnInterrupt: Bool = true ) throws -> FileDescriptor { + #if !os(Windows) try path.withCString { try FileDescriptor.open( $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) } + #else + try path.withPlatformString { + try FileDescriptor.open( + $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) + } + #endif } + #if !os(Windows) + // On Darwin, `CInterop.PlatformChar` is less available than + // `FileDescriptor.open`, so we need to use `CChar` instead. + /// Opens or creates a file for reading or writing. /// /// - Parameters: @@ -83,6 +94,54 @@ extension FileDescriptor { } return descOrError.map { FileDescriptor(rawValue: $0) } } + #else + /// Opens or creates a file for reading or writing. + /// + /// - Parameters: + /// - path: The location of the file to open. + /// - mode: The read and write access to use. + /// - options: The behavior for opening the file. + /// - permissions: The file permissions to use for created files. + /// - retryOnInterrupt: Whether to retry the open operation + /// if it throws ``Errno/interrupted``. + /// The default is `true`. + /// Pass `false` to try only once and throw an error upon interruption. + /// - Returns: A file descriptor for the open file + /// + /// The corresponding C function is `open`. + @_alwaysEmitIntoClient + public static func open( + _ path: UnsafePointer, + _ mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + retryOnInterrupt: Bool = true + ) throws -> FileDescriptor { + try FileDescriptor._open( + path, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt + ).get() + } + + @usableFromInline + internal static func _open( + _ path: UnsafePointer, + _ mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions, + permissions: FilePermissions?, + retryOnInterrupt: Bool + ) -> Result { + let oFlag = mode.rawValue | options.rawValue + let descOrError: Result = valueOrErrno(retryOnInterrupt: retryOnInterrupt) { + if let permissions = permissions { + return system_open(path, oFlag, permissions.rawValue) + } + precondition(!options.contains(.create), + "Create must be given permissions") + return system_open(path, oFlag) + } + return descOrError.map { FileDescriptor(rawValue: $0) } + } + #endif /// Deletes a file descriptor. /// diff --git a/Sources/System/FilePath/FilePathString.swift b/Sources/System/FilePath/FilePathString.swift index 2dd2cce..21f3548 100644 --- a/Sources/System/FilePath/FilePathString.swift +++ b/Sources/System/FilePath/FilePathString.swift @@ -20,7 +20,13 @@ extension FilePath { self.init(_platformString: platformString) } -#if !os(Windows) // Availability workaround + #if !os(Windows) + // Note: This function should have been opaque, but it shipped as + // `@_alwaysEmitIntoClient` in macOS 12/iOS 15, and now it is stuck + // this way forever. (Or until the language provides a way for us + // to declare separate availability for a function's exported symbol + // and its inlinable body.) + /// Calls the given closure with a pointer to the contents of the file path, /// represented as a null-terminated platform string. /// @@ -37,7 +43,6 @@ extension FilePath { public func withPlatformString( _ body: (UnsafePointer) throws -> Result ) rethrows -> Result { - // For backwards deployment, call withCString if available. return try withCString(body) } #else @@ -56,7 +61,6 @@ extension FilePath { public func withPlatformString( _ body: (UnsafePointer) throws -> Result ) rethrows -> Result { - // For backwards deployment, call withCString if available. return try _withPlatformString(body) } #endif From ca700460b1bc23e6e46c2021b7d80f1442b4fd3a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 26 Dec 2021 22:00:07 -0800 Subject: [PATCH 5/5] Fix compatibility with Swift 5.3.3 --- Sources/System/FileOperations.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index 368d4d1..e081278 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -32,12 +32,12 @@ extension FileDescriptor { retryOnInterrupt: Bool = true ) throws -> FileDescriptor { #if !os(Windows) - try path.withCString { + return try path.withCString { try FileDescriptor.open( $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) } #else - try path.withPlatformString { + return try path.withPlatformString { try FileDescriptor.open( $0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt) }