From af4544c86920634166223e4e3f6fe99db9e2dcaf Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 9 Jun 2023 17:56:36 -0700 Subject: [PATCH 01/83] Re-enable Mach.Port --- Sources/System/MachPort.swift | 2 +- Tests/SystemTests/MachPortTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 04d2cc5..f1d29b7 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.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) && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) import Darwin.Mach diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 31a654c..01855e3 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) && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) import XCTest import Darwin.Mach From 2df5b0b0315456a816bff29570fb160b6500b083 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Tue, 8 Aug 2023 17:36:20 -0700 Subject: [PATCH 02/83] srdelta argument to mach_port_destruct should be zero This should never have been -1, as there is no send right for it to balance when `RightType.self == ReceiveRight.self`. --- Sources/System/MachPort.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index f1d29b7..b1b2f1c 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -86,7 +86,7 @@ public enum Mach { _machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_DEAD_NAME, -1)) } else { if RightType.self == ReceiveRight.self { - _machPrecondition(mach_port_destruct(mach_task_self_, _name, -1, _context)) + _machPrecondition(mach_port_destruct(mach_task_self_, _name, 0, _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 { From bf16d3da30634886b7730b90d495b8f2c1fb022f Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 13:16:40 -0700 Subject: [PATCH 03/83] [test] use `XCTAssertEqual` or `XCTAssertNotEqual` --- Tests/SystemTests/MachPortTests.swift | 43 +++++++++++++-------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 01855e3..cf68cd6 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -23,7 +23,7 @@ final class MachPortTests: XCTestCase { 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) + XCTAssertEqual(kr, KERN_SUCCESS) } return refCount } @@ -33,20 +33,20 @@ final class MachPortTests: XCTestCase { return refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_RECEIVE) } - func testRecieveRightDeallocation() throws { + func testReceiveRightDeallocation() 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) + 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) - XCTAssert(one == 1); - XCTAssert(zero == 0); + XCTAssertEqual(one, 1); + XCTAssertEqual(zero, 0); } func consumeSendRightAutomatically(name:mach_port_name_t) -> mach_port_urefs_t { @@ -61,11 +61,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 +77,29 @@ 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) } 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 +110,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 +121,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,13 +129,13 @@ 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) } } From 9123120c08ec18e525d488080478c5c62b40099c Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 13:17:37 -0700 Subject: [PATCH 04/83] destroy Send rights with `mach_port_deallocate` --- Sources/System/MachPort.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index b1b2f1c..96dd992 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -88,7 +88,7 @@ public enum Mach { if RightType.self == ReceiveRight.self { _machPrecondition(mach_port_destruct(mach_task_self_, _name, 0, _context)) } else if RightType.self == SendRight.self { - _machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND, -1)) + _machPrecondition(mach_port_deallocate(mach_task_self_, _name)) } else if RightType.self == SendOnceRight.self { _machPrecondition(mach_port_mod_refs(mach_task_self_, _name, MACH_PORT_RIGHT_SEND_ONCE, -1)) } From 669dcf2c25f7f1c63612e55dc478f8837a50409a Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 13:48:55 -0700 Subject: [PATCH 05/83] ensure Mach.Port lives until the function returns --- Tests/SystemTests/MachPortTests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index cf68cd6..299809c 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -29,7 +29,8 @@ final class MachPortTests: XCTestCase { } 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) } From 0539daa364e2c006e1349369c2c4f7a164126933 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 14:17:43 -0700 Subject: [PATCH 06/83] fix test of receive-right deallocation --- Tests/SystemTests/MachPortTests.swift | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 299809c..41e28f6 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -23,7 +23,11 @@ final class MachPortTests: XCTestCase { var refCount:mach_port_urefs_t = 0 withUnsafeMutablePointer(to: &refCount) { refCount in let kr = mach_port_get_refs(mach_task_self_, name, kind, refCount) - XCTAssertEqual(kr, KERN_SUCCESS) + if kr == KERN_INVALID_NAME { + refCount.pointee = 0 + } else { + XCTAssertEqual(kr, KERN_SUCCESS) + } } return refCount } @@ -43,11 +47,14 @@ final class MachPortTests: XCTestCase { 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) - XCTAssertEqual(one, 1); - XCTAssertEqual(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 { From 6ee96ffdb5a1645cb6755367f86bb87c2e9bf996 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 14:52:35 -0700 Subject: [PATCH 07/83] modify consuming methods to call `discard self` --- Sources/System/MachPort.swift | 26 +++++++++++++++++--------- Tests/SystemTests/MachPortTests.swift | 5 +++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 96dd992..1ae99bf 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -167,9 +167,11 @@ 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( + 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 +189,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 + public consuming func unguardAndRelinquish() -> mach_port_name_t { + let (name, context) = (_name, _context) + discard self + _machPrecondition(mach_port_unguard(mach_task_self_, name, context)) + return name } /// Borrow access to the port name in a block that can perform @@ -288,8 +292,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. @@ -326,8 +332,10 @@ 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 + public consuming func relinquish() -> mach_port_name_t { + let name = _name + discard self + return name } } diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 41e28f6..7603761 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -92,6 +92,11 @@ final class MachPortTests: XCTestCase { let stillOne = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) XCTAssertEqual(stillOne, 1) + + recv.withBorrowedName { + let alsoOne = refCountForMachPortName(name: $0, kind: MACH_PORT_RIGHT_RECEIVE) + XCTAssertEqual(alsoOne, 1) + } } func testMakeSendCountSettable() throws { From e8bb779909f33f0df50ae8c08700409883c9bc44 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 15:24:03 -0700 Subject: [PATCH 08/83] use inout conversion - this is the situation where it is appropriate --- Sources/System/MachPort.swift | 26 ++++++++++++-------------- Tests/SystemTests/MachPortTests.swift | 22 +++++++++------------- 2 files changed, 21 insertions(+), 27 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 1ae99bf..0f8b8a4 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -147,9 +147,9 @@ extension Mach.Port where RightType == Mach.ReceiveRight { @inlinable 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) @@ -224,17 +224,15 @@ extension Mach.Port where RightType == Mach.ReceiveRight { 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) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 7603761..74ea55a 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -20,14 +20,12 @@ import System 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) - if kr == KERN_INVALID_NAME { - refCount.pointee = 0 - } else { - XCTAssertEqual(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 } @@ -39,11 +37,9 @@ final class MachPortTests: XCTestCase { } func testReceiveRightDeallocation() 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) - XCTAssertEqual(kr, KERN_SUCCESS) - } + var name: mach_port_name_t = 0xFFFFFFFF + let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &name) + XCTAssertEqual(kr, KERN_SUCCESS) XCTAssertNotEqual(name, 0xFFFFFFFF) From 40b5b3068b57e211a6245bcf599152d80ddfb4ca Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 16:18:06 -0700 Subject: [PATCH 09/83] test all the `relinquish()` methods --- Sources/System/MachPort.swift | 3 +-- Tests/SystemTests/MachPortTests.swift | 36 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 0f8b8a4..7fd98bf 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -190,8 +190,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// the context value along with the port name. @inlinable public consuming func unguardAndRelinquish() -> mach_port_name_t { - let (name, context) = (_name, _context) - discard self + let (name, context) = self.relinquish() _machPrecondition(mach_port_unguard(mach_task_self_, name, context)) return name } diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 74ea55a..7c80f0d 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -95,6 +95,42 @@ final class MachPortTests: XCTestCase { } } + 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() XCTAssertEqual(recv.makeSendCount, 0) From 5e03246e4eddb9836de18d114405b70cef44f584 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 17:24:49 -0700 Subject: [PATCH 10/83] test copies of dead mach port names --- Sources/System/MachPort.swift | 2 +- Tests/SystemTests/MachPortTests.swift | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 7fd98bf..9867ed8 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -308,7 +308,7 @@ extension Mach.Port where RightType == Mach.SendRight { // 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 { + if kr == KERN_INVALID_NAME { throw Mach.PortRightError.deadName } _machPrecondition(kr) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 7c80f0d..95d2f63 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -183,6 +183,17 @@ final class MachPortTests: XCTestCase { XCTAssertEqual(same, one) } + + func testCopyDeadName() throws { + let send = Mach.Port(name: 0xffffffff) + do { + let copy = try send.copySendRight() + _ = copy + } + catch Mach.PortRightError.deadName { + _ = send.relinquish() + } + } } #endif From d259ef476e1fffa2913c979eef98320eefd5eb56 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 17:51:54 -0700 Subject: [PATCH 11/83] test two-parameter `withBorrowedName` --- Sources/System/MachPort.swift | 1 + Tests/SystemTests/MachPortTests.swift | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 9867ed8..a67a01a 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -135,6 +135,7 @@ 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 } diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 95d2f63..bf1e118 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -194,6 +194,22 @@ final class MachPortTests: XCTestCase { _ = send.relinquish() } } + + func testMakeReceivedRightFromExistingName() 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) + } + } } #endif From e4d06ae3ea97ecc35311699e1895f61932e35499 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 9 Aug 2023 17:52:50 -0700 Subject: [PATCH 12/83] simplify deinit --- Sources/System/MachPort.swift | 20 ++++++++++---------- Tests/SystemTests/MachPortTests.swift | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index a67a01a..4ca3572 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -81,17 +81,17 @@ 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, "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, 0, _context)) - } else if RightType.self == SendRight.self { - _machPrecondition(mach_port_deallocate(mach_task_self_, _name)) - } 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)) } } } diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index bf1e118..3c64ce8 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -210,6 +210,20 @@ final class MachPortTests: XCTestCase { XCTAssertEqual(context, $1) } } + + func testDeinitDeadSendRight() throws { + let send = Mach.Port(name: 0xffffffff) + send.withBorrowedName { + XCTAssertEqual($0, .max) + } + _ = consume send + + let send1 = Mach.Port(name: 0xffffffff) + send1.withBorrowedName { + XCTAssertEqual($0, .max) + } + _ = consume send1 + } } #endif From 6189c1f553ea30bc64a59f27cc851d7daae03269 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 11 Aug 2023 14:09:44 -0700 Subject: [PATCH 13/83] fix `copySendRight()` for send rights that become dead names --- Sources/System/MachPort.swift | 2 +- Tests/SystemTests/MachPortTests.swift | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 4ca3572..0f58243 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -309,7 +309,7 @@ extension Mach.Port where RightType == Mach.SendRight { // name is the same because send rights are coalesced let kr = mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how)) - if kr == KERN_INVALID_NAME { + if kr == KERN_INVALID_NAME || kr == KERN_INVALID_CAPABILITY { throw Mach.PortRightError.deadName } _machPrecondition(kr) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 3c64ce8..082653e 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -185,13 +185,24 @@ final class MachPortTests: XCTestCase { } func testCopyDeadName() throws { + let recv = Mach.Port() + let send = recv.makeSendRight() + _ = consume recv // and turn `send` into a dead name + do { + let copy = try send.copySendRight() + _ = copy + } + catch Mach.PortRightError.deadName { + } + } + + func testCopyDeadName2() throws { let send = Mach.Port(name: 0xffffffff) do { let copy = try send.copySendRight() _ = copy } catch Mach.PortRightError.deadName { - _ = send.relinquish() } } From f5edd720bd7418cda0f4ee29e779eac74705e025 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 11 Aug 2023 18:03:24 -0700 Subject: [PATCH 14/83] clarify some tests --- Tests/SystemTests/MachPortTests.swift | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 082653e..07da8bb 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -193,6 +193,7 @@ final class MachPortTests: XCTestCase { _ = copy } catch Mach.PortRightError.deadName { + // success } } @@ -203,10 +204,11 @@ final class MachPortTests: XCTestCase { _ = copy } catch Mach.PortRightError.deadName { + // success } } - func testMakeReceivedRightFromExistingName() throws { + 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) @@ -222,17 +224,14 @@ final class MachPortTests: XCTestCase { } } - func testDeinitDeadSendRight() throws { - let send = Mach.Port(name: 0xffffffff) - send.withBorrowedName { - XCTAssertEqual($0, .max) - } - _ = consume send + func testDeinitDeadSendRights() throws { + let recv = Mach.Port() + let send = recv.makeSendRight() + let send1 = recv.makeSendOnceRight() - let send1 = Mach.Port(name: 0xffffffff) - send1.withBorrowedName { - XCTAssertEqual($0, .max) - } + _ = consume recv + // `send` and `send1` have become dead names + _ = consume send _ = consume send1 } } From 65693b8b808d013cab03055963989cbe97a145ba Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 14 Aug 2023 18:00:14 -0700 Subject: [PATCH 15/83] improve memory rebinding for `mach_port_get_attributes` call --- Sources/System/MachPort.swift | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 0f58243..5852146 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -263,11 +263,19 @@ extension Mach.Port where RightType == Mach.ReceiveRight { 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) { + 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 From 8730f2cf256694ae5cee761e2f687df064f0a480 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 15 Aug 2023 09:14:21 -0700 Subject: [PATCH 16/83] [gardening] 80-column enforcement --- Sources/System/MachPort.swift | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 5852146..223757b 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -48,11 +48,13 @@ 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 /* 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)) @@ -82,7 +84,8 @@ public enum Mach { deinit { if RightType.self == ReceiveRight.self { - precondition(_name != 0xffffffff, "Receive rights cannot be dead names") + precondition(_name != 0xFFFFFFFF /* MACH_PORT_DEAD */, + "Receive rights cannot be dead names") _machPrecondition( mach_port_destruct(mach_task_self_, _name, 0, _context) ) @@ -135,7 +138,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") + precondition(name != mach_port_name_t(MACH_PORT_NULL), + "Mach.Port cannot be initialized with MACH_PORT_NULL") self._name = name self._context = context } @@ -251,7 +255,11 @@ extension Mach.Port where RightType == Mach.ReceiveRight { 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) } @@ -316,7 +324,9 @@ extension Mach.Port where RightType == Mach.SendRight { let how = MACH_MSG_TYPE_COPY_SEND // name is the same because send rights are coalesced - let kr = mach_port_insert_right(mach_task_self_, _name, _name, mach_msg_type_name_t(how)) + 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 } From a3aff2f913c26cabbc3bbe40190fb27f9f738cd7 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 16 Aug 2023 11:01:36 -0700 Subject: [PATCH 17/83] require Swift 5.6 --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index b081a87..5f8efb0 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.2 +// swift-tools-version:5.6 // The swift-tools-version declares the minimum version of Swift required to build this package. /* From f32faad415ee97130b9aa7e6b3a79f5018514931 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 16 Aug 2023 11:02:51 -0700 Subject: [PATCH 18/83] remove code depending on Swift older than 5.6 --- .../FilePath/FilePathComponentView.swift | 25 ---- Tests/SystemTests/XCTestManifests.swift | 132 ------------------ 2 files changed, 157 deletions(-) delete mode 100644 Tests/SystemTests/XCTestManifests.swift diff --git a/Sources/System/FilePath/FilePathComponentView.swift b/Sources/System/FilePath/FilePathComponentView.swift index efdd084..1b9fd21 100644 --- a/Sources/System/FilePath/FilePathComponentView.swift +++ b/Sources/System/FilePath/FilePathComponentView.swift @@ -39,30 +39,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,7 +61,6 @@ extension FilePath { yield &comp } } - #endif } @available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *) diff --git a/Tests/SystemTests/XCTestManifests.swift b/Tests/SystemTests/XCTestManifests.swift deleted file mode 100644 index de99bd8..0000000 --- a/Tests/SystemTests/XCTestManifests.swift +++ /dev/null @@ -1,132 +0,0 @@ -#if !canImport(ObjectiveC) && swift(<5.5) -import XCTest - -extension ErrnoTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__ErrnoTest = [ - ("testConstants", testConstants), - ("testPatternMatching", testPatternMatching), - ] -} - -extension FileDescriptorTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FileDescriptorTest = [ - ("testConstants", testConstants), - ("testStandardDescriptors", testStandardDescriptors), - ] -} - -extension FileOperationsTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FileOperationsTest = [ - ("testAdHocOpen", testAdHocOpen), - ("testAdHocPipe", testAdHocPipe), - ("testGithubIssues", testGithubIssues), - ("testHelpers", testHelpers), - ("testSyscalls", testSyscalls), - ] -} - -extension FilePathComponentsTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathComponentsTest = [ - ("testAdHocRRC", testAdHocRRC), - ("testCases", testCases), - ("testSeparatorNormalization", testSeparatorNormalization), - ] -} - -extension FilePathParsingTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathParsingTest = [ - ("testNormalization", testNormalization), - ] -} - -extension FilePathSyntaxTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathSyntaxTest = [ - ("testAdHocMutations", testAdHocMutations), - ("testFailableStringInitializers", testFailableStringInitializers), - ("testLexicallyRelative", testLexicallyRelative), - ("testPartialWindowsRoots", testPartialWindowsRoots), - ("testPathSyntax", testPathSyntax), - ("testPrefixSuffix", testPrefixSuffix), - ] -} - -extension FilePathTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathTest = [ - ("testFilePath", testFilePath), - ] -} - -extension FilePermissionsTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePermissionsTest = [ - ("testPermissions", testPermissions), - ] -} - -extension MockingTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__MockingTest = [ - ("testMocking", testMocking), - ] -} - -extension SystemCharTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__SystemCharTest = [ - ("testIsLetter", testIsLetter), - ] -} - -extension SystemStringTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__SystemStringTest = [ - ("testAdHoc", testAdHoc), - ("testPlatformString", testPlatformString), - ] -} - -public func __allTests() -> [XCTestCaseEntry] { - return [ - testCase(ErrnoTest.__allTests__ErrnoTest), - testCase(FileDescriptorTest.__allTests__FileDescriptorTest), - testCase(FileOperationsTest.__allTests__FileOperationsTest), - testCase(FilePathComponentsTest.__allTests__FilePathComponentsTest), - testCase(FilePathParsingTest.__allTests__FilePathParsingTest), - testCase(FilePathSyntaxTest.__allTests__FilePathSyntaxTest), - testCase(FilePathTest.__allTests__FilePathTest), - testCase(FilePermissionsTest.__allTests__FilePermissionsTest), - testCase(MockingTest.__allTests__MockingTest), - testCase(SystemCharTest.__allTests__SystemCharTest), - testCase(SystemStringTest.__allTests__SystemStringTest), - ] -} -#endif From 87e68fca36465a17de7176c9e0267a4f5fd91591 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 16 Aug 2023 11:19:06 -0700 Subject: [PATCH 19/83] declare `Sendable` conformances along with the types - `Sendable` is fundamental, it is preferably not declared as an extension. --- Sources/System/FileDescriptor.swift | 20 ++++++------------- Sources/System/FilePath/FilePath.swift | 7 +------ .../FilePath/FilePathComponentView.swift | 15 +++++--------- .../System/FilePath/FilePathComponents.swift | 20 ++++++------------- Sources/System/FilePermissions.swift | 7 +------ Sources/System/SystemString.swift | 10 +++------- 6 files changed, 22 insertions(+), 57 deletions(-) diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 556e63e..eda4f11 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 @@ -311,7 +313,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 @@ -475,18 +478,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/FilePath/FilePath.swift b/Sources/System/FilePath/FilePath.swift index c1dfd7f..13064b5 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 @@ -67,8 +67,3 @@ 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 diff --git a/Sources/System/FilePath/FilePathComponentView.swift b/Sources/System/FilePath/FilePathComponentView.swift index 1b9fd21..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 @@ -66,7 +67,9 @@ extension FilePath { @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 @@ -214,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..6b8a940 100644 --- a/Sources/System/FilePath/FilePathComponents.swift +++ b/Sources/System/FilePath/FilePathComponents.swift @@ -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 @@ -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/FilePermissions.swift b/Sources/System/FilePermissions.swift index 9bd6c5f..2cdb32f 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 @@ -175,8 +175,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/SystemString.swift b/Sources/System/SystemString.swift index 14651d5..9bfef49 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -8,7 +8,8 @@ */ // 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 } @@ -288,11 +289,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 From faffb9a15a84f5194085d4c853f42651b683e5d0 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 16 Aug 2023 13:19:52 -0700 Subject: [PATCH 20/83] Apply suggestions from code review This better communicates the intention. Co-authored-by: loffgren <117697138+loffgren@users.noreply.github.com> --- Tests/SystemTests/MachPortTests.swift | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 07da8bb..8a6ade6 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -188,23 +188,15 @@ final class MachPortTests: XCTestCase { let recv = Mach.Port() let send = recv.makeSendRight() _ = consume recv // and turn `send` into a dead name - do { - let copy = try send.copySendRight() - _ = copy - } - catch Mach.PortRightError.deadName { - // success + XCTAssertThrowsError(try send.copySendRight(), "Copying a dead name should throw") { error in + XCTAssertEqual(error, Mach.PortRightError.deadName) } } func testCopyDeadName2() throws { let send = Mach.Port(name: 0xffffffff) - do { - let copy = try send.copySendRight() - _ = copy - } - catch Mach.PortRightError.deadName { - // success + XCTAssertThrowsError(try send.copySendRight(), "Copying a dead name should throw") { error in + XCTAssertEqual(error, Mach.PortRightError.deadName) } } From ad407249fec4293dbf8b2578ac54b65f98060313 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 16 Aug 2023 13:34:41 -0700 Subject: [PATCH 21/83] make test expression return `Void` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - It can’t return `Mach.Port`, because a noncopyable type cannot currently be a generic type argument. --- Tests/SystemTests/MachPortTests.swift | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 8a6ade6..07b7410 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -188,15 +188,25 @@ final class MachPortTests: XCTestCase { 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, Mach.PortRightError.deadName) + 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, Mach.PortRightError.deadName) + XCTAssertThrowsError( + _ = try send.copySendRight(), + "Copying a dead name should throw" + ) { error in + XCTAssertEqual( + error as! Mach.PortRightError, Mach.PortRightError.deadName + ) } } From 1ccaee141c106584962f208c45a35892cd1db4fc Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Tue, 5 Sep 2023 11:36:08 -0700 Subject: [PATCH 22/83] Fix typos in renaming message for Errno --- Sources/System/Errno.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index d55e52b..15d9fdd 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -142,7 +142,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { public static var execFormatError: Errno { Errno(_ENOEXEC) } @_alwaysEmitIntoClient - @available(*, unavailable, renamed: "noExec") + @available(*, unavailable, renamed: "execFormatError") public static var ENOEXEC: Errno { execFormatError } /// Bad file descriptor. @@ -529,7 +529,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { public static var nowInProgress: Errno { Errno(_EINPROGRESS) } @_alwaysEmitIntoClient - @available(*, unavailable, renamed: "nowInProcess") + @available(*, unavailable, renamed: "nowInProgress") public static var EINPROGRESS: Errno { nowInProgress } /// Operation already in progress. From 7654f14f8cd905933ea55048a919c593aeec8a84 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 11 Oct 2023 14:28:43 -0700 Subject: [PATCH 23/83] [gardening] add some more availability annotations --- Sources/System/MachPort.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 223757b..9eb47f8 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -11,8 +11,10 @@ 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 From 495f72934758a1c4b2e3fcaa385b67de57e09646 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 11 Oct 2023 16:08:59 -0700 Subject: [PATCH 24/83] [noncopyability] explicitly prevent a capture This may be needed because of a bug involving resilient structs. --- Sources/System/MachPort.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 9eb47f8..51dbda6 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -279,6 +279,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { ) withUnsafeMutablePointer(to: &status) { + [ _name = self._name ] in let status = UnsafeMutableBufferPointer(start: $0, count: 1) status.withMemoryRebound(to: integer_t.self) { let info = $0.baseAddress From fb0efe832cb0f0480420ba15005ff47281021cd4 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 12 Oct 2023 15:02:31 -0700 Subject: [PATCH 25/83] [gardening] finish cleaning up old test files This should have been removed alongside XCTestManifests.swift --- Tests/LinuxMain.swift | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 Tests/LinuxMain.swift diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift deleted file mode 100644 index 695f4e5..0000000 --- a/Tests/LinuxMain.swift +++ /dev/null @@ -1,8 +0,0 @@ -import XCTest - -import SystemTests - -var tests = [XCTestCaseEntry]() -tests += SystemTests.__allTests() - -XCTMain(tests) From b92be8a02adda71c03576d28a8b4b58b1b6c2edc Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 13 Oct 2023 10:21:57 -0700 Subject: [PATCH 26/83] Update availability declarations for swift-system 1.1.0 API --- Sources/System/FileOperations.swift | 6 +++--- Utilities/expand-availability.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index 2297aeb..ada80cf 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -435,7 +435,7 @@ extension FileDescriptor { } #if !os(Windows) -@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, *) 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) 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", } From 882466a7300b15019fac5accf6b661683a6b9274 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 13 Oct 2023 18:55:23 -0700 Subject: [PATCH 27/83] apply missing availability attributes to Mach.Port --- Sources/System/MachPort.swift | 13 ++++++++++++- Tests/SystemTests/MachPortTests.swift | 1 + 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 51dbda6..10538bc 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -129,6 +129,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. @@ -153,6 +154,7 @@ 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) _machPrecondition( @@ -175,6 +177,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// After this function completes, the Mach.Port is destroyed and no longer /// usable. @inlinable + @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) { let destructured = (name: _name, context: _context) @@ -197,6 +200,7 @@ 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 + @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)) @@ -213,6 +217,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 { @@ -226,6 +231,7 @@ 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) @@ -254,6 +260,7 @@ 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 @@ -271,6 +278,7 @@ 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() @@ -299,6 +307,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. /// @@ -324,6 +333,7 @@ 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 @@ -340,7 +350,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. /// @@ -352,6 +362,7 @@ extension Mach.Port where RightType == Mach.SendOnceRight { /// After this function completes, the Mach.Port is destroyed and no longer /// usable. @inlinable + @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 diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 07b7410..7129a50 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -18,6 +18,7 @@ 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 = .max From 5c3617b9e9088ecd9b81b02095ba7b41d6766edc Mon Sep 17 00:00:00 2001 From: Finagolfin Date: Fri, 24 Nov 2023 18:59:06 +0530 Subject: [PATCH 28/83] Android: update pread/pwrite for nullability annotations in NDK 26 --- Sources/System/Internals/Syscalls.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 9fcb2f9..3d375a5 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -71,7 +71,7 @@ internal func system_pread( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif - return pread(fd, buf, nbyte, offset) + return pread(fd, buf!, nbyte, offset) } // lseek @@ -101,7 +101,7 @@ internal func system_pwrite( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif - return pwrite(fd, buf, nbyte, offset) + return pwrite(fd, buf!, nbyte, offset) } internal func system_dup(_ fd: Int32) -> Int32 { From c2e8f24c7c81c1842af8a556f7940abf96ec3a5f Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 4 Jan 2024 17:48:48 -0800 Subject: [PATCH 29/83] avoid passing null pointer to pread() or pwrite() --- Sources/System/Internals/Syscalls.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 3d375a5..d454907 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -71,7 +71,7 @@ internal func system_pread( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif - return pread(fd, buf!, nbyte, offset) + return buf.map({ pread(fd, $0, nbyte, offset) }) ?? 0 } // lseek @@ -101,7 +101,7 @@ internal func system_pwrite( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif - return pwrite(fd, buf!, nbyte, offset) + return buf.map({ pwrite(fd, $0, nbyte, offset) }) ?? 0 } internal func system_dup(_ fd: Int32) -> Int32 { From c6b2119c816e16d161f077a8fb9b8be29b3bc8e1 Mon Sep 17 00:00:00 2001 From: Kyle Date: Mon, 22 Jan 2024 17:00:46 +0800 Subject: [PATCH 30/83] Enable SPI documentation and add API doc link --- .spi.yml | 4 ++++ README.md | 2 ++ 2 files changed, 6 insertions(+) create mode 100644 .spi.yml diff --git a/.spi.yml b/.spi.yml new file mode 100644 index 0000000..7535f52 --- /dev/null +++ b/.spi.yml @@ -0,0 +1,4 @@ +version: 1 +builder: + configs: + - documentation_targets: [SystemPackage] \ No newline at end of file diff --git a/README.md b/README.md index 11e57eb..14edea0 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ 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, From e49d2b9bd2558fc0ef7780e965cd747f8c7a84e7 Mon Sep 17 00:00:00 2001 From: Kyle Date: Mon, 22 Jan 2024 17:23:31 +0800 Subject: [PATCH 31/83] Update .spi.yml Co-authored-by: Max Desiatov --- .spi.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.spi.yml b/.spi.yml index 7535f52..b9cbb71 100644 --- a/.spi.yml +++ b/.spi.yml @@ -1,4 +1,4 @@ version: 1 builder: configs: - - documentation_targets: [SystemPackage] \ No newline at end of file + - documentation_targets: [SystemPackage] From 6b156898138b65d49f40ddc04e2090c88d9cbaaa Mon Sep 17 00:00:00 2001 From: Hiroshi Yamauchi Date: Tue, 13 Feb 2024 10:32:39 -0800 Subject: [PATCH 32/83] Support Windows ARM64 --- cmake/modules/SwiftSupport.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/SwiftSupport.cmake b/cmake/modules/SwiftSupport.cmake index 82961db..a73a4e5 100644 --- a/cmake/modules/SwiftSupport.cmake +++ b/cmake/modules/SwiftSupport.cmake @@ -17,7 +17,7 @@ See https://swift.org/LICENSE.txt for license information function(get_swift_host_arch result_var_name) if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") set("${result_var_name}" "x86_64" PARENT_SCOPE) - elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64") + elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64|ARM64") if(CMAKE_SYSTEM_NAME MATCHES Darwin) set("${result_var_name}" "arm64" PARENT_SCOPE) else() From adca1f70b1f67bed7431bdfb8cebc3b544e80d28 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 6 Mar 2024 17:45:23 -0800 Subject: [PATCH 33/83] Fix `SystemString.withCSIA()` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The original implementation simply forwarded to the underlying `nullTerminatedStorage`, which contains one element – a null terminator – more than the actual `String`. - This isn’t in keeping with the sperit of `withContiguousStorageIfAvailable()`, which should present exactly the elements of the collection. --- Sources/System/SystemString.swift | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 9bfef49..8ca643b 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -142,31 +142,38 @@ 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 { - // TODO: Below include null terminator, is this desired? + // withSystemChars includes the null terminator internal func withSystemChars( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withContiguousStorageIfAvailable(f)! + try nullTerminatedStorage.withContiguousStorageIfAvailable(f)! } internal func withCodeUnits( From f59a0b73ce66bf5277acbf7f6a02c1e298bebd9b Mon Sep 17 00:00:00 2001 From: Sketch <75850871+SketchMaster2001@users.noreply.github.com> Date: Mon, 19 Feb 2024 23:19:22 -0500 Subject: [PATCH 34/83] Add support for visionOS --- Package.swift | 2 ++ Sources/System/Errno.swift | 20 +++++++++--------- Sources/System/FileDescriptor.swift | 10 ++++----- Sources/System/Internals/CInterop.swift | 2 +- Sources/System/Internals/Constants.swift | 26 ++++++++++++------------ Sources/System/Internals/Exports.swift | 4 ++-- Sources/System/Internals/Syscalls.swift | 2 +- Sources/System/MachPort.swift | 2 +- Tests/SystemTests/ErrnoTest.swift | 14 ++++++------- Tests/SystemTests/FileTypesTest.swift | 4 ++-- Tests/SystemTests/MachPortTests.swift | 2 +- 11 files changed, 45 insertions(+), 43 deletions(-) diff --git a/Package.swift b/Package.swift index 5f8efb0..7511a8b 100644 --- a/Package.swift +++ b/Package.swift @@ -30,6 +30,7 @@ let package = Package( .define("_CRT_SECURE_NO_WARNINGS") ], swiftSettings: [ + .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS, .visionOS])), .define("SYSTEM_PACKAGE"), .define("ENABLE_MOCKING", .when(configuration: .debug)) ]), @@ -37,6 +38,7 @@ let package = Package( name: "SystemTests", dependencies: ["SystemPackage"], swiftSettings: [ + .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS, .visionOS])), .define("SYSTEM_PACKAGE") ]), ] diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index 15d9fdd..7f0aabe 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -23,7 +23,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_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) } @@ -911,7 +911,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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`. @@ -968,7 +968,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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. /// @@ -1060,7 +1060,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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, @@ -1075,7 +1075,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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. @@ -1102,7 +1102,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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`. @@ -1142,7 +1142,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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. @@ -1246,7 +1246,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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. @@ -1413,7 +1413,7 @@ extension Errno { @available(*, unavailable, renamed: "tooManyRemoteLevels") public static var EREMOTE: Errno { tooManyRemoteLevels } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// No such policy registered. /// /// The corresponding C error is `ENOPOLICY`. @@ -1447,7 +1447,7 @@ extension Errno { 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`. diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index eda4f11..0ac7f4f 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -185,7 +185,7 @@ extension FileDescriptor { @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. /// @@ -253,7 +253,7 @@ extension FileDescriptor { 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. /// @@ -357,7 +357,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. /// @@ -419,7 +419,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 @@ -438,7 +438,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"), diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index a71ef12..3b4792e 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -7,7 +7,7 @@ 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 diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 592e38c..8d4e4bb 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -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 @@ -26,7 +26,7 @@ import Musl #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 @@ -272,7 +272,7 @@ 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 @@ -313,7 +313,7 @@ internal var _EREMOTE: CInt { #endif } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EBADRPC: CInt { EBADRPC } @@ -336,7 +336,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 +358,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 +386,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 @@ -424,7 +424,7 @@ internal var _ETIME: CInt { ETIME } @_alwaysEmitIntoClient internal var _EOPNOTSUPP: CInt { EOPNOTSUPP } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _ENOPOLICY: CInt { ENOPOLICY } #endif @@ -437,7 +437,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 } @@ -472,7 +472,7 @@ internal var _O_NONBLOCK: CInt { O_NONBLOCK } @_alwaysEmitIntoClient internal var _O_APPEND: CInt { O_APPEND } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_SHLOCK: CInt { O_SHLOCK } @@ -498,7 +498,7 @@ internal var _O_TRUNC: CInt { O_TRUNC } @_alwaysEmitIntoClient internal var _O_EXCL: CInt { O_EXCL } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_EVTONLY: CInt { O_EVTONLY } #endif @@ -512,7 +512,7 @@ internal var _O_NOCTTY: CInt { O_NOCTTY } internal var _O_DIRECTORY: CInt { O_DIRECTORY } #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 +531,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..e20454e 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -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 @@ -31,7 +31,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 } diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 9fcb2f9..7c417e0 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -7,7 +7,7 @@ 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 diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 10538bc..b3eb0a9 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -7,7 +7,7 @@ See https://swift.org/LICENSE.txt for license information */ -#if swift(>=5.9) && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) +#if swift(>=5.9) && SYSTEM_PACKAGE_DARWIN import Darwin.Mach 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/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 7129a50..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 swift(>=5.9) && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) +#if swift(>=5.9) && SYSTEM_PACKAGE_DARWIN import XCTest import Darwin.Mach From afb7fa4eef3d709a72c84e108efe7e214fd8e2fe Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 7 Mar 2024 16:51:12 -0800 Subject: [PATCH 35/83] Generate SystemString.string consistently - SystemString.string and Slice.string should be generated in the same manner. Now they are. --- Sources/System/SystemString.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 8ca643b..f5c558d 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -202,7 +202,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( @@ -244,7 +246,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 } From c86758849a80ea7f04b2d969aa0c9d2d5cc55d48 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 7 Mar 2024 16:53:49 -0800 Subject: [PATCH 36/83] Test SystemString.string property consistency --- Tests/SystemTests/SystemStringTests.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Tests/SystemTests/SystemStringTests.swift b/Tests/SystemTests/SystemStringTests.swift index a189171..c929171 100644 --- a/Tests/SystemTests/SystemStringTests.swift +++ b/Tests/SystemTests/SystemStringTests.swift @@ -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 { From def7b1a70c2fb303693c12eb6852d2e5560deeb5 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 7 Mar 2024 16:31:54 -0800 Subject: [PATCH 37/83] Fix behaviour of `withCodeUnits()` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The original implementation includes a trailing zero with the full collection, but the implementation for a slice does not. As a result, given a `let s: SystemString`, `s.string` was not equal to `s[…].string` --- Sources/System/SystemString.swift | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index f5c558d..67a7ffb 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -176,17 +176,14 @@ extension SystemString { try nullTerminatedStorage.withContiguousStorageIfAvailable(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 withSystemChars { + try $0.withMemoryRebound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self) { + assert($0.last == .zero) + return try f(.init(start: $0.baseAddress, count: $0.count&-1)) } } } From 17e97907923f650cff90c501ffcf8c5654b14165 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 7 Mar 2024 17:00:47 -0800 Subject: [PATCH 38/83] Rename `withSystemChars` - `withNullTerminatedSystemChars` makes it clear that the null-termination is included. Operations where the null-termination is included should be obvious. --- Sources/System/FilePath/FilePathComponents.swift | 2 +- Sources/System/SystemString.swift | 9 ++++----- Tests/SystemTests/SystemStringTests.swift | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Sources/System/FilePath/FilePathComponents.swift b/Sources/System/FilePath/FilePathComponents.swift index 6b8a940..a19526f 100644 --- a/Sources/System/FilePath/FilePathComponents.swift +++ b/Sources/System/FilePath/FilePathComponents.swift @@ -146,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])) } } diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 67a7ffb..9a974d5 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -169,18 +169,17 @@ extension SystemString: Hashable, Codable {} extension SystemString { - // withSystemChars includes the null terminator - internal func withSystemChars( + internal func withNullTerminatedSystemChars( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try nullTerminatedStorage.withContiguousStorageIfAvailable(f)! + try nullTerminatedStorage.withUnsafeBufferPointer(f) } // withCodeUnits does not include the null terminator internal func withCodeUnits( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withSystemChars { + 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)) @@ -286,7 +285,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, diff --git a/Tests/SystemTests/SystemStringTests.swift b/Tests/SystemTests/SystemStringTests.swift index c929171..1815392 100644 --- a/Tests/SystemTests/SystemStringTests.swift +++ b/Tests/SystemTests/SystemStringTests.swift @@ -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") } From 6609a401b93116020590662cfd970480fc59de8d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 7 Mar 2024 17:05:54 -0800 Subject: [PATCH 39/83] Update copyright notices --- Sources/System/FilePath/FilePathComponents.swift | 2 +- Sources/System/SystemString.swift | 2 +- Tests/SystemTests/SystemStringTests.swift | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/System/FilePath/FilePathComponents.swift b/Sources/System/FilePath/FilePathComponents.swift index a19526f..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 diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 9a974d5..36b6850 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.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 diff --git a/Tests/SystemTests/SystemStringTests.swift b/Tests/SystemTests/SystemStringTests.swift index 1815392..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 From 14597334dcdad2f0e669909882bddbb6f2762034 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 5 Jan 2024 17:57:14 -0800 Subject: [PATCH 40/83] [test] test reading and writing empty, nil-based buffers --- Tests/SystemTests/FileOperationsTest.swift | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index 8062aed..ca178ba 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -86,6 +86,30 @@ final class FileOperationsTest: XCTestCase { for test in syscallTestCases { test.runAllTests() } } + func testWriteFromEmptyBuffer() throws { + let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly) + 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) + } + + func testReadToEmptyBuffer() throws { + let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly) + 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 } From 5ca37e7d3997b00e19d4a77d45db7830b18b6f56 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 8 Mar 2024 12:58:48 -0800 Subject: [PATCH 41/83] Android: more targeted approach to unusual nullabilities --- Sources/System/Internals/Syscalls.swift | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index d454907..236ee6c 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -71,7 +71,15 @@ internal func system_pread( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif - return buf.map({ pread(fd, $0, nbyte, offset) }) ?? 0 +#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,7 +109,15 @@ internal func system_pwrite( #if ENABLE_MOCKING if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) } #endif - return buf.map({ pwrite(fd, $0, nbyte, offset) }) ?? 0 +#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 } internal func system_dup(_ fd: Int32) -> Int32 { From 40b6b0ef8c2e21db12180036627b3cdc09a68bbf Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Tue, 30 Apr 2024 17:11:39 +0100 Subject: [PATCH 42/83] Add support for `WASILibc` module (#159) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quoting the [wasi.dev landing page](https://wasi.dev): > The WebAssembly System Interface (WASI) is a group of standard API specifications for software compiled to the W3C WebAssembly (Wasm) standard. WASI is designed to provide a secure standard interface for applications that can be compiled to Wasm from any language, and that may run anywhere—from browsers to clouds to embedded devices. Currently support for WASI in Swift is based on [`wasi-libc`](https://github.com/WebAssembly/wasi-libc). Adding support for `wasi-libc` mostly amounted to excluding unsupported errnos, adding TLS dictionary storage shim for single-threaded environment, and adding constants in C headers for macros that Clang importer currently doesn't support. Co-authored-by: Guillaume Lessard --- Sources/CSystem/include/CSystemWASI.h | 31 +++++++ Sources/CSystem/include/module.modulemap | 1 + Sources/System/Errno.swift | 23 +++++- Sources/System/FileOperations.swift | 6 +- Sources/System/Internals/CInterop.swift | 4 +- Sources/System/Internals/Constants.swift | 100 ++++++++++++++++++++--- Sources/System/Internals/Exports.swift | 29 ++++++- Sources/System/Internals/Syscalls.swift | 8 +- 8 files changed, 180 insertions(+), 22 deletions(-) create mode 100644 Sources/CSystem/include/CSystemWASI.h diff --git a/Sources/CSystem/include/CSystemWASI.h b/Sources/CSystem/include/CSystemWASI.h new file mode 100644 index 0000000..9877853 --- /dev/null +++ b/Sources/CSystem/include/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/include/module.modulemap b/Sources/CSystem/include/module.modulemap index 776f776..6e8b89e 100644 --- a/Sources/CSystem/include/module.modulemap +++ b/Sources/CSystem/include/module.modulemap @@ -1,5 +1,6 @@ module CSystem { header "CSystemLinux.h" + header "CSystemWASI.h" header "CSystemWindows.h" export * } diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index 7f0aabe..1305593 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 @@ -229,7 +229,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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. @@ -621,6 +621,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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 @@ -633,6 +634,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "socketTypeNotSupported") public static var ESOCKTNOSUPPORT: Errno { socketTypeNotSupported } +#endif /// Not supported. /// @@ -647,6 +649,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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 @@ -659,6 +662,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "protocolFamilyNotSupported") public static var EPFNOSUPPORT: Errno { protocolFamilyNotSupported } +#endif /// The address family isn't supported by the protocol family. /// @@ -805,6 +809,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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 @@ -818,6 +823,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "socketShutdown") public static var ESHUTDOWN: Errno { socketShutdown } +#endif /// Operation timed out. /// @@ -874,6 +880,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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. @@ -885,6 +892,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "hostIsDown") public static var EHOSTDOWN: Errno { hostIsDown } +#endif /// No route to host. /// @@ -923,6 +931,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { public static var EPROCLIM: Errno { tooManyProcesses } #endif +#if !os(WASI) /// Too many users. /// /// The quota system ran out of table entries. @@ -934,6 +943,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyUsers") public static var EUSERS: Errno { tooManyUsers } +#endif /// Disk quota exceeded. /// @@ -1287,6 +1297,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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. @@ -1298,6 +1309,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "noData") public static var ENODATA: Errno { noData } +#endif /// Reserved. /// @@ -1311,6 +1323,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @available(*, unavailable, renamed: "noLink") public static var ENOLINK: Errno { noLink } +#if !os(WASI) /// Reserved. /// /// This error is reserved for future use. @@ -1334,6 +1347,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "notStream") public static var ENOSTR: Errno { notStream } +#endif #endif /// Protocol error. @@ -1350,7 +1364,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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. @@ -1382,7 +1396,6 @@ 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`. @@ -1393,6 +1406,7 @@ extension Errno { @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`. @@ -1412,6 +1426,7 @@ extension Errno { @_alwaysEmitIntoClient @available(*, unavailable, renamed: "tooManyRemoteLevels") public static var EREMOTE: Errno { tooManyRemoteLevels } +#endif #if SYSTEM_PACKAGE_DARWIN /// No such policy registered. diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index ada80cf..a322a9b 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 @@ -369,6 +369,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,8 +434,9 @@ extension FileDescriptor { fatalError("Not implemented") } } +#endif -#if !os(Windows) +#if !os(Windows) && !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. diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index 3b4792e..19cf4d5 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.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 @@ -18,6 +18,8 @@ import Glibc #elseif canImport(Musl) @_implementationOnly import CSystem import Musl +#elseif canImport(WASILibc) +import WASILibc #else #error("Unsupported Platform") #endif diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 8d4e4bb..27a145f 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 @@ -21,6 +21,9 @@ import Glibc #elseif canImport(Musl) import CSystem import Musl +#elseif canImport(WASILibc) +import CSystem +import WASILibc #else #error("Unsupported Platform") #endif @@ -73,7 +76,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 +144,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 +176,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 +185,7 @@ internal var _ESOCKTNOSUPPORT: CInt { return ESOCKTNOSUPPORT #endif } +#endif @_alwaysEmitIntoClient internal var _ENOTSUP: CInt { @@ -185,6 +196,7 @@ internal var _ENOTSUP: CInt { #endif } +#if !os(WASI) @_alwaysEmitIntoClient internal var _EPFNOSUPPORT: CInt { #if os(Windows) @@ -193,6 +205,7 @@ internal var _EPFNOSUPPORT: CInt { return EPFNOSUPPORT #endif } +#endif @_alwaysEmitIntoClient internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT } @@ -227,6 +240,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 +258,7 @@ internal var _ETOOMANYREFS: CInt { return ETOOMANYREFS #endif } +#endif @_alwaysEmitIntoClient internal var _ETIMEDOUT: CInt { ETIMEDOUT } @@ -257,6 +272,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 +281,7 @@ internal var _EHOSTDOWN: CInt { return EHOSTDOWN #endif } +#endif @_alwaysEmitIntoClient internal var _EHOSTUNREACH: CInt { EHOSTUNREACH } @@ -277,6 +294,7 @@ internal var _ENOTEMPTY: CInt { ENOTEMPTY } internal var _EPROCLIM: CInt { EPROCLIM } #endif +#if !os(WASI) @_alwaysEmitIntoClient internal var _EUSERS: CInt { #if os(Windows) @@ -285,6 +303,7 @@ internal var _EUSERS: CInt { return EUSERS #endif } +#endif @_alwaysEmitIntoClient internal var _EDQUOT: CInt { @@ -304,6 +323,7 @@ internal var _ESTALE: CInt { #endif } +#if !os(WASI) @_alwaysEmitIntoClient internal var _EREMOTE: CInt { #if os(Windows) @@ -312,6 +332,7 @@ internal var _EREMOTE: CInt { return EREMOTE #endif } +#endif #if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient @@ -399,30 +420,41 @@ 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 } +internal var _EOPNOTSUPP: CInt { +#if os(WASI) + _getConst_EOPNOTSUPP() +#else + EOPNOTSUPP +#endif +} #if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient @@ -462,15 +494,33 @@ 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 SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient @@ -481,22 +531,42 @@ 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 SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient @@ -509,7 +579,13 @@ 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 SYSTEM_PACKAGE_DARWIN diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index e20454e..f4358c5 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 @@ -23,6 +23,8 @@ import Glibc #elseif canImport(Musl) @_implementationOnly import CSystem import Musl +#elseif canImport(WASILibc) +import WASILibc #else #error("Unsupported Platform") #endif @@ -58,6 +60,11 @@ 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 } +} #endif // MARK: C stdlib decls @@ -149,6 +156,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 +185,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/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 793fdfd..69931b3 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 - 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 @@ -13,6 +13,8 @@ import Darwin import Glibc #elseif canImport(Musl) import Musl +#elseif canImport(WASILibc) +import WASILibc #elseif os(Windows) import ucrt #else @@ -120,6 +122,7 @@ internal func system_pwrite( #endif } +#if !os(WASI) internal func system_dup(_ fd: Int32) -> Int32 { #if ENABLE_MOCKING if mockingEnabled { return _mock(fd) } @@ -133,8 +136,9 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 { #endif return dup2(fd, fd2) } +#endif -#if !os(Windows) +#if !os(Windows) && !os(WASI) internal func system_pipe(_ fds: UnsafeMutablePointer) -> CInt { #if ENABLE_MOCKING if mockingEnabled { return _mock(fds) } From dd45c800623379ac6b1c2a6eff79ada5fd5e225a Mon Sep 17 00:00:00 2001 From: Jeremy Schonfeld Date: Thu, 2 May 2024 13:07:27 -0700 Subject: [PATCH 43/83] Disfavor String.init(platformString: UnsafePointer) --- Sources/System/PlatformString.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/PlatformString.swift b/Sources/System/PlatformString.swift index 35fab59..3aecf97 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) } From cfd3f9da906cf62efafd162d524df6334cc85da6 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 20 Mar 2024 14:46:10 +0000 Subject: [PATCH 44/83] Fix swift-system to work on Windows. The swift-system tests were not passing, for various reasons, mostly to do with path related confusion. As part of this, add a function to create a temporary directory, as that was one of the problems. Also add Windows support for pipe() and ftruncate(), which was missing. rdar://125087707 --- Package.swift | 4 +- Sources/System/ErrnoWindows.swift | 20 ++ Sources/System/FileOperations.swift | 4 +- Sources/System/FilePath/FilePathParsing.swift | 10 +- Sources/System/FilePath/FilePathTemp.swift | 256 ++++++++++++++++++ Sources/System/Internals/Mocking.swift | 16 +- Sources/System/Internals/Syscalls.swift | 76 +++++- .../Internals/WindowsSyscallAdapters.swift | 133 ++++++++- Tests/SystemTests/FileOperationsTest.swift | 120 ++++---- .../FilePathComponentsTest.swift | 20 +- .../FilePathTests/FilePathSyntaxTest.swift | 3 + .../FilePathTests/FilePathTempTest.swift | 49 ++++ .../FilePathTests/FilePathTest.swift | 10 + 13 files changed, 633 insertions(+), 88 deletions(-) create mode 100644 Sources/System/ErrnoWindows.swift create mode 100644 Sources/System/FilePath/FilePathTemp.swift create mode 100644 Tests/SystemTests/FilePathTests/FilePathTempTest.swift diff --git a/Package.swift b/Package.swift index 7511a8b..26bd4e6 100644 --- a/Package.swift +++ b/Package.swift @@ -15,7 +15,7 @@ import PackageDescription let package = Package( name: "swift-system", products: [ - .library(name: "SystemPackage", targets: ["SystemPackage"]), + .library(name: "SystemPackage", targets: ["SystemPackage"]) ], dependencies: [], targets: [ @@ -40,6 +40,6 @@ let package = Package( swiftSettings: [ .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS, .visionOS])), .define("SYSTEM_PACKAGE") - ]), + ]) ] ) diff --git a/Sources/System/ErrnoWindows.swift b/Sources/System/ErrnoWindows.swift new file mode 100644 index 0000000..98fda43 --- /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 { + public init(windowsError: DWORD) { + self.init(rawValue: mapWindowsErrorToErrno(windowsError)) + } +} + +#endif diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index a322a9b..d2e8d65 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -436,7 +436,7 @@ extension FileDescriptor { } #endif -#if !os(Windows) && !os(WASI) +#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. @@ -465,7 +465,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. @@ -511,4 +510,3 @@ extension FileDescriptor { } } } -#endif diff --git a/Sources/System/FilePath/FilePathParsing.swift b/Sources/System/FilePath/FilePathParsing.swift index 6d01477..0ab4f7e 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 } diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift new file mode 100644 index 0000000..9aa65ff --- /dev/null +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -0,0 +1,256 @@ +/* + 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 + +public func withTemporaryPath(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 + +#if os(Windows) +import WinSDK + +internal func getTemporaryDirectory() throws -> FilePath { + return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self, + capacity: Int(MAX_PATH) + 1) { + buffer in + + let count = GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) + if count == 0 { + throw Errno(windowsError: GetLastError()) + } + + return FilePath(SystemString(platformString: buffer.baseAddress!)) + } +} + +internal 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) + } +} + +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()) + } + } +} + +#else +internal func getTemporaryDirectory() throws -> FilePath { + return "/tmp" +} + +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, + path: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress! + ) + } + + try path.withPlatformString { + if system_rmdir($0) != 0 { + throw Errno.current + } + } +} + +fileprivate func impl_opendirat( + _ dirfd: CInt, + _ path: UnsafePointer +) -> UnsafeMutablePointer? { + let fd = system_openat(dirfd, path, + FileDescriptor.AccessMode.readOnly.rawValue + | FileDescriptor.OpenOptions.directory.rawValue) + if fd < 0 { + return nil + } + return system_fdopendir(fd) +} + +internal func forEachFile( + in dirfd: CInt, path: UnsafePointer, + _ body: (system_dirent) throws -> () +) throws { + guard let dir = impl_opendirat(dirfd, path) 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) + } +} + +internal func recursiveRemove( + in dirfd: CInt, + path: UnsafePointer +) throws { + // First, deal with subdirectories + try forEachFile(in: dirfd, path: path) { dirent in + if dirent.d_type == SYSTEM_DT_DIR { + try withUnsafeBytes(of: dirent.d_name) { + try recursiveRemove( + in: dirfd, + path: $0.assumingMemoryBound(to: CInterop.PlatformChar.self) + .baseAddress! + ) + } + } + } + + // Now delete the contents of this directory + try forEachFile(in: dirfd, path: path) { 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 + +internal let base64 = Array( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8 +) + +internal func makeDirectory(at: FilePath) throws -> Bool { + return try at.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) + } + } +} + +internal 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 makeDirectory(at: tempDir) { + return tempDir + } + } +} diff --git a/Sources/System/Internals/Mocking.swift b/Sources/System/Internals/Mocking.swift index 405dc34..08c0f71 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: Optional { + currentMockingDriver?.forceWindowsSyntaxForPaths } } @@ -128,7 +128,7 @@ internal var mockingEnabled: Bool { } @inline(__always) -internal var forceWindowsPaths: Bool { +internal var forceWindowsPaths: Optional { #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 69931b3..4669141 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -138,7 +138,7 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 { } #endif -#if !os(Windows) && !os(WASI) +#if !os(WASI) internal func system_pipe(_ fds: UnsafeMutablePointer) -> CInt { #if ENABLE_MOCKING if mockingEnabled { return _mock(fds) } @@ -147,11 +147,83 @@ 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 !os(Windows) +internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR +internal let SYSTEM_DT_DIR = DT_DIR +internal typealias system_dirent = dirent +internal typealias system_DIR = DIR + +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 +) -> UnsafeMutablePointer? { + return fdopendir(fd) +} + +internal func system_readdir( + _ dir: UnsafeMutablePointer +) -> UnsafeMutablePointer? { + return readdir(dir) +} + +internal func system_rewinddir( + _ dir: UnsafeMutablePointer +) { + return rewinddir(dir) +} + +internal func system_closedir( + _ dir: UnsafeMutablePointer +) -> 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 diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index 2f3851b..bc83782 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -80,7 +80,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 +91,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 +102,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 +114,133 @@ 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 { + return _wmkdir(path) +} + +@inline(__always) +internal func rmdir( + _ path: UnsafePointer +) -> CInt { + return _wrmdir(path) +} + +@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 + } +} + #endif diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index ca178ba..ee82128 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -113,8 +113,7 @@ final class FileOperationsTest: XCTestCase { 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`. @@ -133,33 +132,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 withTemporaryPath(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))") @@ -185,48 +185,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 withTemporaryPath(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/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/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..0948f78 --- /dev/null +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -0,0 +1,49 @@ +/* + 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 +import SystemPackage +#else +import System +#endif + +final class TemporaryPathTest: XCTestCase { + func testUnique() throws { + try withTemporaryPath(basename: "test") { path in + let strPath = String(decoding: path) + XCTAssert(strPath.contains("test")) + try withTemporaryPath(basename: "test") { path2 in + let strPath2 = String(decoding: path2) + XCTAssertNotEqual(strPath, strPath2) + } + } + } + + func testCleanup() throws { + var thePath: FilePath? = nil + + try withTemporaryPath(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) From c6456a9c03b191677f09828ec1ee492b6fbed026 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 20 Mar 2024 17:10:30 +0000 Subject: [PATCH 45/83] Use the proper temporary directory on Darwin. It seems we can get the temporary directory from confstr(). rdar://125087707 --- Sources/System/FilePath/FilePathTemp.swift | 26 +++++++++++++++++++ Sources/System/Internals/Syscalls.swift | 12 +++++++++ .../FilePathTests/FilePathTempTest.swift | 9 +++++++ 3 files changed, 47 insertions(+) diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index 9aa65ff..0028671 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -111,7 +111,33 @@ internal func recursiveRemove(at path: FilePath) throws { #else internal func getTemporaryDirectory() throws -> FilePath { + #if SYSTEM_PACKAGE_DARWIN + var capacity = 1024 + while true { + let path: FilePath? = withUnsafeTemporaryAllocation( + of: CInterop.PlatformChar.self, + capacity: 1024) { buffer in + let len = system_confstr(SYSTEM_CS_DARWIN_USER_TEMP_DIR, + buffer.baseAddress!, + buffer.count) + if len == 0 { + // Fall back to "/tmp" if we can't read the temp directory + return "/tmp" + } + // If it was truncated, increase capaciy and try again + if len > buffer.count { + capacity = len + return nil + } + return FilePath(SystemString(platformString: buffer.baseAddress!)) + } + if let path = path { + return path + } + } + #else return "/tmp" + #endif } internal func recursiveRemove(at path: FilePath) throws { diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 4669141..cec8413 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -173,6 +173,18 @@ internal func system_rmdir( 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 diff --git a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift index 0948f78..b2b1fa2 100644 --- a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -16,6 +16,15 @@ import System #endif final class TemporaryPathTest: XCTestCase { + #if SYSTEM_PACKAGE_DARWIN + func testNotInSlashTmp() throws { + try withTemporaryPath(basename: "NotInSlashTmp") { path in + // We shouldn't be using "/tmp" on Darwin + XCTAssertNotEqual(path.components.first!, "tmp") + } + } + #endif + func testUnique() throws { try withTemporaryPath(basename: "test") { path in let strPath = String(decoding: path) From ec7d406cd4c2ac56ec3cb7c859dd56f87e7808f5 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 20 Mar 2024 17:27:38 +0000 Subject: [PATCH 46/83] Changes after comments from Saleem. Use idiomatic Swift notation, not `Optional`. Prefer Win32 APIs to UCRT APIs. rdar://125087707 --- Sources/System/FilePath/FilePathTemp.swift | 5 ++--- Sources/System/Internals/Mocking.swift | 4 ++-- .../System/Internals/WindowsSyscallAdapters.swift | 15 +++++++++++++-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index 0028671..437d233 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -29,8 +29,7 @@ internal func getTemporaryDirectory() throws -> FilePath { capacity: Int(MAX_PATH) + 1) { buffer in - let count = GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) - if count == 0 { + guard GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) != 0 else { throw Errno(windowsError: GetLastError()) } @@ -116,7 +115,7 @@ internal func getTemporaryDirectory() throws -> FilePath { while true { let path: FilePath? = withUnsafeTemporaryAllocation( of: CInterop.PlatformChar.self, - capacity: 1024) { buffer in + capacity: capacity) { buffer in let len = system_confstr(SYSTEM_CS_DARWIN_USER_TEMP_DIR, buffer.baseAddress!, buffer.count) diff --git a/Sources/System/Internals/Mocking.swift b/Sources/System/Internals/Mocking.swift index 08c0f71..2945651 100644 --- a/Sources/System/Internals/Mocking.swift +++ b/Sources/System/Internals/Mocking.swift @@ -110,7 +110,7 @@ private var contextualMockingEnabled: Bool { extension MockingDriver { internal static var enabled: Bool { mockingEnabled } - internal static var forceWindowsPaths: Optional { + internal static var forceWindowsPaths: Bool? { currentMockingDriver?.forceWindowsSyntaxForPaths } } @@ -128,7 +128,7 @@ internal var mockingEnabled: Bool { } @inline(__always) -internal var forceWindowsPaths: Optional { +internal var forceWindowsPaths: Bool? { #if !ENABLE_MOCKING return false #else diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index bc83782..6d5c755 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -160,14 +160,25 @@ internal func mkdir( _ path: UnsafePointer, _ mode: CInterop.Mode ) -> CInt { - return _wmkdir(path) + // TODO: Read/write permissions (these need mapping to a SECURITY_DESCRIPTOR). + if !CreateDirectoryW(path, nil) { + ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return 0; } @inline(__always) internal func rmdir( _ path: UnsafePointer ) -> CInt { - return _wrmdir(path) + if !RemoveDirectoryW(path) { + ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + return -1 + } + + return 0; } @usableFromInline From 21638a06b17f5872fe4f2035a5f52e175c05aaf3 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Thu, 21 Mar 2024 16:15:19 +0000 Subject: [PATCH 47/83] Map mode bits to Windows ACLs. This adds support for mapping POSIX-style mode bits to Windows ACLs when calling `open()` or `mkdir()`. rdar://125087707 --- Sources/System/FilePath/FilePathTemp.swift | 23 +- .../Internals/WindowsSyscallAdapters.swift | 392 +++++++++++++++++- 2 files changed, 395 insertions(+), 20 deletions(-) diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index 437d233..23a0816 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -24,7 +24,7 @@ public func withTemporaryPath(basename: FilePath.Component, #if os(Windows) import WinSDK -internal func getTemporaryDirectory() throws -> FilePath { +fileprivate func getTemporaryDirectory() throws -> FilePath { return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self, capacity: Int(MAX_PATH) + 1) { buffer in @@ -37,7 +37,7 @@ internal func getTemporaryDirectory() throws -> FilePath { } } -internal func forEachFile( +fileprivate func forEachFile( at path: FilePath, _ body: (WIN32_FIND_DATAW) throws -> () ) rethrows { @@ -67,7 +67,7 @@ internal func forEachFile( } } -internal func recursiveRemove(at path: FilePath) throws { +fileprivate func recursiveRemove(at path: FilePath) throws { // First, deal with subdirectories try forEachFile(at: path) { findData in if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 { @@ -109,13 +109,14 @@ internal func recursiveRemove(at path: FilePath) throws { } #else -internal func getTemporaryDirectory() throws -> FilePath { +fileprivate func getTemporaryDirectory() throws -> FilePath { #if SYSTEM_PACKAGE_DARWIN var capacity = 1024 while true { let path: FilePath? = withUnsafeTemporaryAllocation( of: CInterop.PlatformChar.self, - capacity: capacity) { buffer in + capacity: capacity + ) { buffer in let len = system_confstr(SYSTEM_CS_DARWIN_USER_TEMP_DIR, buffer.baseAddress!, buffer.count) @@ -139,7 +140,7 @@ internal func getTemporaryDirectory() throws -> FilePath { #endif } -internal func recursiveRemove(at path: FilePath) throws { +fileprivate func recursiveRemove(at path: FilePath) throws { let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory) defer { try? dirfd.close() @@ -173,7 +174,7 @@ fileprivate func impl_opendirat( return system_fdopendir(fd) } -internal func forEachFile( +fileprivate func forEachFile( in dirfd: CInt, path: UnsafePointer, _ body: (system_dirent) throws -> () ) throws { @@ -238,11 +239,11 @@ internal func recursiveRemove( } #endif -internal let base64 = Array( +fileprivate let base64 = Array( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8 ) -internal func makeDirectory(at: FilePath) throws -> Bool { +fileprivate func makeTempDirectory(at: FilePath) throws -> Bool { return try at.withPlatformString { if system_mkdir($0, 0o700) == 0 { return true @@ -256,7 +257,7 @@ internal func makeDirectory(at: FilePath) throws -> Bool { } } -internal func createRandomString(length: Int) -> String { +fileprivate func createRandomString(length: Int) -> String { return String( decoding: (0.., _ oflag: Int32 ) -> CInt { - var fh: CInt = -1 - _ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE) - return fh + if (oflag & _O_CREAT) != 0 { + ucrt._set_errno(EINVAL) + return -1 + } + + 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 +52,39 @@ 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 + guard let pSD = createSecurityDescriptor(from: mode) 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) @@ -160,8 +215,21 @@ internal func mkdir( _ path: UnsafePointer, _ mode: CInterop.Mode ) -> CInt { - // TODO: Read/write permissions (these need mapping to a SECURITY_DESCRIPTOR). - if !CreateDirectoryW(path, nil) { + guard let pSD = createSecurityDescriptor(from: mode) 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 } @@ -254,4 +322,310 @@ internal func mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { } } +fileprivate func rightsFromModeBits( + _ bits: Int, sticky: Bool = false +) -> 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 !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 +} + +/// 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) + -> PSECURITY_DESCRIPTOR? { + let ownerPerm = (Int(mode) >> 6) & 0o7 + let groupPerm = (Int(mode) >> 3) & 0o7 + let otherPerm = Int(mode) & 0o7 + + let ownerRights = rightsFromModeBits(ownerPerm) + let groupRights = rightsFromModeBits(groupPerm, sticky: (mode & 0o1000) != 0) + let otherRights = rightsFromModeBits(otherPerm, sticky: (mode & 0o1000) != 0) + + // 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) + } + + dwDesiredAccess = 0 + if (oflag & _O_RDONLY) != 0 { + dwDesiredAccess |= DWORD(GENERIC_READ) + } + if (oflag & _O_WRONLY) != 0 { + dwDesiredAccess |= DWORD(GENERIC_WRITE) + } + if (oflag & _O_RDWR) != 0 { + dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE) + } + + 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 From 33773a8eb9b9da85bae0e86fd21342482de593a0 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Thu, 21 Mar 2024 16:32:19 +0000 Subject: [PATCH 48/83] Update Sources/System/FilePath/FilePathTemp.swift Co-authored-by: Karoy Lorentey --- Sources/System/FilePath/FilePathTemp.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index 23a0816..ea67428 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -9,8 +9,10 @@ // MARK: - API -public func withTemporaryPath(basename: FilePath.Component, - _ body: (FilePath) throws -> R) throws -> R { +public func withTemporaryPath( + basename: FilePath.Component, + _ body: (FilePath) throws -> R +) throws -> R { let temporaryDir = try createUniqueTemporaryDirectory(basename: basename) defer { try? recursiveRemove(at: temporaryDir) From 2357d6932c9f8058562a84ca2146e2519809997e Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Mon, 25 Mar 2024 18:28:18 +0000 Subject: [PATCH 49/83] Refactor FilePathTemp, add tests for permission code. Broke `FilePathTemp.swift` into separate files for POSIX and Windows. Added tests for permissions code on Windows. Added leading underscores to some function names. Made some other functions `fileprivate`. rdar://125087707 --- Sources/System/ErrnoWindows.swift | 2 +- Sources/System/FileOperations.swift | 46 ++- Sources/System/FilePath/FilePathTemp.swift | 263 +++--------------- .../System/FilePath/FilePathTempPosix.swift | 153 ++++++++++ .../System/FilePath/FilePathTempWindows.swift | 114 ++++++++ Sources/System/Internals/Syscalls.swift | 12 + .../Internals/WindowsSyscallAdapters.swift | 72 +++-- Tests/SystemTests/FileOperationsTest.swift | 4 +- .../FileOperationsTestWindows.swift | 241 ++++++++++++++++ .../FilePathTests/FilePathTempTest.swift | 8 +- 10 files changed, 657 insertions(+), 258 deletions(-) create mode 100644 Sources/System/FilePath/FilePathTempPosix.swift create mode 100644 Sources/System/FilePath/FilePathTempWindows.swift create mode 100644 Tests/SystemTests/FileOperationsTestWindows.swift diff --git a/Sources/System/ErrnoWindows.swift b/Sources/System/ErrnoWindows.swift index 98fda43..b94b577 100644 --- a/Sources/System/ErrnoWindows.swift +++ b/Sources/System/ErrnoWindows.swift @@ -13,7 +13,7 @@ import WinSDK extension Errno { public init(windowsError: DWORD) { - self.init(rawValue: mapWindowsErrorToErrno(windowsError)) + self.init(rawValue: _mapWindowsErrorToErrno(windowsError)) } } diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index d2e8d65..ba70e87 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -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) } @@ -510,3 +508,47 @@ extension FileDescriptor { } } } + +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 + public 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 + public 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/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index ea67428..7b41d0b 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -9,13 +9,22 @@ // MARK: - API -public func withTemporaryPath( +/// 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. +public func withTemporaryFilePath( basename: FilePath.Component, _ body: (FilePath) throws -> R ) throws -> R { let temporaryDir = try createUniqueTemporaryDirectory(basename: basename) defer { - try? recursiveRemove(at: temporaryDir) + try? _recursiveRemove(at: temporaryDir) } return try body(temporaryDir) @@ -23,230 +32,20 @@ public func withTemporaryPath( // MARK: - Internals -#if os(Windows) -import WinSDK - -fileprivate 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!)) - } -} - -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) - } -} - -fileprivate 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()) - } - } -} - -#else -fileprivate func getTemporaryDirectory() throws -> FilePath { - #if SYSTEM_PACKAGE_DARWIN - var capacity = 1024 - while true { - let path: FilePath? = withUnsafeTemporaryAllocation( - of: CInterop.PlatformChar.self, - capacity: capacity - ) { buffer in - let len = system_confstr(SYSTEM_CS_DARWIN_USER_TEMP_DIR, - buffer.baseAddress!, - buffer.count) - if len == 0 { - // Fall back to "/tmp" if we can't read the temp directory - return "/tmp" - } - // If it was truncated, increase capaciy and try again - if len > buffer.count { - capacity = len - return nil - } - return FilePath(SystemString(platformString: buffer.baseAddress!)) - } - if let path = path { - return path - } - } - #else - return "/tmp" - #endif -} - -fileprivate 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, - path: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress! - ) - } - - try path.withPlatformString { - if system_rmdir($0) != 0 { - throw Errno.current - } - } -} - -fileprivate func impl_opendirat( - _ dirfd: CInt, - _ path: UnsafePointer -) -> UnsafeMutablePointer? { - let fd = system_openat(dirfd, path, - FileDescriptor.AccessMode.readOnly.rawValue - | FileDescriptor.OpenOptions.directory.rawValue) - if fd < 0 { - return nil - } - return system_fdopendir(fd) -} - -fileprivate func forEachFile( - in dirfd: CInt, path: UnsafePointer, - _ body: (system_dirent) throws -> () -) throws { - guard let dir = impl_opendirat(dirfd, path) 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) - } -} - -internal func recursiveRemove( - in dirfd: CInt, - path: UnsafePointer -) throws { - // First, deal with subdirectories - try forEachFile(in: dirfd, path: path) { dirent in - if dirent.d_type == SYSTEM_DT_DIR { - try withUnsafeBytes(of: dirent.d_name) { - try recursiveRemove( - in: dirfd, - path: $0.assumingMemoryBound(to: CInterop.PlatformChar.self) - .baseAddress! - ) - } - } - } - - // Now delete the contents of this directory - try forEachFile(in: dirfd, path: path) { 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 - fileprivate let base64 = Array( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8 ) -fileprivate func makeTempDirectory(at: FilePath) throws -> Bool { - return try at.withPlatformString { +/// 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 } @@ -259,6 +58,11 @@ fileprivate func makeTempDirectory(at: FilePath) throws -> Bool { } } +/// 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.. String { ) } -internal func createUniqueTemporaryDirectory( +/// Given a base name, create a uniquely named temporary directory. +/// +/// - Parameters: +/// - basename: The base name for the new directory. +/// - Returns: The path to the new directory. +/// +/// Creates a directory in the system temporary directory whose name +/// starts with `basename`, followed by a `.` and then a random +/// string of characters. +fileprivate func createUniqueTemporaryDirectory( basename: FilePath.Component ) throws -> FilePath { - var tempDir = try getTemporaryDirectory() + var tempDir = try _getTemporaryDirectory() tempDir.append(basename) while true { tempDir.extension = createRandomString(length: 16) - if try makeTempDirectory(at: tempDir) { + 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..623ccae --- /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 +) -> UnsafeMutablePointer? { + 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/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index cec8413..1c6ed72 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -239,3 +239,15 @@ internal func system_openat( 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 fa88cbe..3e3f9c6 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -12,15 +12,21 @@ 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 { - if (oflag & _O_CREAT) != 0 { - ucrt._set_errno(EINVAL) - return -1 - } - let decodedFlags = DecodedOpenFlags(oflag) var saAttrs = SECURITY_ATTRIBUTES( @@ -40,7 +46,7 @@ internal func open( nil) if hFile == INVALID_HANDLE_VALUE { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -52,8 +58,10 @@ internal func open( _ path: UnsafePointer, _ oflag: Int32, _ mode: CInterop.Mode ) -> CInt { - guard let pSD = createSecurityDescriptor(from: mode) else { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + let actualMode = mode & ~_umask + + guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -80,7 +88,7 @@ internal func open( nil) if hFile == INVALID_HANDLE_VALUE { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -146,7 +154,7 @@ internal func pread( var nNumberOfBytesRead: DWORD = 0 if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return Int(-1) } return Int(nNumberOfBytesRead) @@ -169,7 +177,7 @@ internal func pwrite( var nNumberOfBytesWritten: DWORD = 0 if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten, &ovlOverlapped) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return Int(-1) } return Int(nNumberOfBytesWritten) @@ -193,7 +201,7 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { // Save the current position and restore it when we're done if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset, DWORD(FILE_CURRENT)) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } defer { @@ -203,7 +211,7 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { // Truncate (or extend) the file if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN)) || !SetEndOfFile(hFile) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -215,8 +223,11 @@ internal func mkdir( _ path: UnsafePointer, _ mode: CInterop.Mode ) -> CInt { - guard let pSD = createSecurityDescriptor(from: mode) else { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + let actualMode = mode & ~_umask + + guard let pSD = _createSecurityDescriptor(from: actualMode, + for: .directory) else { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } defer { @@ -230,7 +241,7 @@ internal func mkdir( ) if !CreateDirectoryW(path, &saAttrs) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -242,7 +253,7 @@ internal func rmdir( _ path: UnsafePointer ) -> CInt { if !RemoveDirectoryW(path) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -250,7 +261,7 @@ internal func rmdir( } @usableFromInline -internal func mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { +internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { switch Int32(errorCode) { case ERROR_SUCCESS: return 0 @@ -323,7 +334,9 @@ internal func mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { } fileprivate func rightsFromModeBits( - _ bits: Int, sticky: Bool = false + _ bits: Int, + sticky: Bool = false, + for fileOrDirectory: _FileOrDirectory ) -> DWORD { var rights: DWORD = 0 @@ -341,7 +354,7 @@ fileprivate func rightsFromModeBits( | FILE_WRITE_EA | STANDARD_RIGHTS_WRITE | SYNCHRONIZE) - if !sticky { + if fileOrDirectory == .directory && !sticky { rights |= DWORD(FILE_DELETE_CHILD) } } @@ -384,19 +397,30 @@ fileprivate func getTokenInformation( 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) +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) - let groupRights = rightsFromModeBits(groupPerm, sticky: (mode & 0o1000) != 0) - let otherRights = rightsFromModeBits(otherPerm, sticky: (mode & 0o1000) != 0) + 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 diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index ee82128..be5a67d 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -137,7 +137,7 @@ final class FileOperationsTest: XCTestCase { // Ad-hoc test touching a file system. do { // TODO: Test this against a virtual in-memory file system - try withTemporaryPath(basename: "testAdhocOpen") { path in + 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) @@ -186,7 +186,7 @@ final class FileOperationsTest: XCTestCase { } func testResizeFile() throws { - try withTemporaryPath(basename: "testResizeFile") { path in + 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. diff --git a/Tests/SystemTests/FileOperationsTestWindows.swift b/Tests/SystemTests/FileOperationsTestWindows.swift new file mode 100644 index 0000000..35df731 --- /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 +import SystemPackage +#else +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/FilePathTempTest.swift b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift index b2b1fa2..dc8597b 100644 --- a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -18,7 +18,7 @@ import System final class TemporaryPathTest: XCTestCase { #if SYSTEM_PACKAGE_DARWIN func testNotInSlashTmp() throws { - try withTemporaryPath(basename: "NotInSlashTmp") { path in + try withTemporaryFilePath(basename: "NotInSlashTmp") { path in // We shouldn't be using "/tmp" on Darwin XCTAssertNotEqual(path.components.first!, "tmp") } @@ -26,10 +26,10 @@ final class TemporaryPathTest: XCTestCase { #endif func testUnique() throws { - try withTemporaryPath(basename: "test") { path in + try withTemporaryFilePath(basename: "test") { path in let strPath = String(decoding: path) XCTAssert(strPath.contains("test")) - try withTemporaryPath(basename: "test") { path2 in + try withTemporaryFilePath(basename: "test") { path2 in let strPath2 = String(decoding: path2) XCTAssertNotEqual(strPath, strPath2) } @@ -39,7 +39,7 @@ final class TemporaryPathTest: XCTestCase { func testCleanup() throws { var thePath: FilePath? = nil - try withTemporaryPath(basename: "test") { path in + try withTemporaryFilePath(basename: "test") { path in thePath = path.appending("foo.txt") let fd = try FileDescriptor.open(thePath!, .readWrite, options: [.create, .truncate], From f5ad5e57fb7f600d6f644d8b3836ee6dfbcfdd9a Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Mon, 8 Apr 2024 17:01:42 +0100 Subject: [PATCH 50/83] [Linux] Glibc's DIR doesn't get imported into Swift. Swift ends up with OpaquePointer instead of a typed pointer. rdar://125087707 --- Sources/System/FilePath/FilePathTempPosix.swift | 2 +- Sources/System/Internals/Syscalls.swift | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/Sources/System/FilePath/FilePathTempPosix.swift b/Sources/System/FilePath/FilePathTempPosix.swift index 623ccae..e8713c2 100644 --- a/Sources/System/FilePath/FilePathTempPosix.swift +++ b/Sources/System/FilePath/FilePathTempPosix.swift @@ -60,7 +60,7 @@ internal func _recursiveRemove( fileprivate func impl_opendirat( _ dirfd: CInt, _ name: UnsafePointer -) -> UnsafeMutablePointer? { +) -> system_DIRPtr? { let fd = system_openat(dirfd, name, FileDescriptor.AccessMode.readOnly.rawValue | FileDescriptor.OpenOptions.directory.rawValue) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 1c6ed72..3794d6e 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -189,7 +189,11 @@ internal func system_confstr( internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR internal let SYSTEM_DT_DIR = DT_DIR internal typealias system_dirent = dirent -internal typealias system_DIR = DIR +#if os(Linux) +internal typealias system_DIRPtr = OpaquePointer +#else +internal typealias system_DIRPtr = UnsafeMutablePointer +#endif internal func system_unlinkat( _ fd: CInt, @@ -204,24 +208,24 @@ return unlinkat(fd, path, flag) internal func system_fdopendir( _ fd: CInt -) -> UnsafeMutablePointer? { +) -> system_DIRPtr? { return fdopendir(fd) } internal func system_readdir( - _ dir: UnsafeMutablePointer + _ dir: system_DIRPtr ) -> UnsafeMutablePointer? { return readdir(dir) } internal func system_rewinddir( - _ dir: UnsafeMutablePointer + _ dir: system_DIRPtr ) { return rewinddir(dir) } internal func system_closedir( - _ dir: UnsafeMutablePointer + _ dir: system_DIRPtr ) -> CInt { return closedir(dir) } From 84077b3b4bbfb372789622df91173484f33b4e3c Mon Sep 17 00:00:00 2001 From: Mishal Shah Date: Wed, 8 May 2024 15:21:09 -0700 Subject: [PATCH 51/83] Add Swift CI Support --- .swiftci/5_10_ubuntu2204 | 5 +++++ .swiftci/5_7_ubuntu2204 | 5 +++++ .swiftci/5_8_ubuntu2204 | 5 +++++ .swiftci/5_9_ubuntu2204 | 5 +++++ .swiftci/nightly_6_0_macos | 5 +++++ .swiftci/nightly_6_0_ubuntu2204 | 5 +++++ .swiftci/nightly_main_macos | 5 +++++ .swiftci/nightly_main_ubuntu2204 | 5 +++++ .swiftci/nightly_main_windows | 7 +++++++ 9 files changed, 47 insertions(+) create mode 100644 .swiftci/5_10_ubuntu2204 create mode 100644 .swiftci/5_7_ubuntu2204 create mode 100644 .swiftci/5_8_ubuntu2204 create mode 100644 .swiftci/5_9_ubuntu2204 create mode 100644 .swiftci/nightly_6_0_macos create mode 100644 .swiftci/nightly_6_0_ubuntu2204 create mode 100644 .swiftci/nightly_main_macos create mode 100644 .swiftci/nightly_main_ubuntu2204 create mode 100644 .swiftci/nightly_main_windows 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_7_ubuntu2204 b/.swiftci/5_7_ubuntu2204 new file mode 100644 index 0000000..8550458 --- /dev/null +++ b/.swiftci/5_7_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.7-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" +} From 7fe8e6cfc2e9b6df649d3968a394db0609e867c8 Mon Sep 17 00:00:00 2001 From: Finagolfin Date: Thu, 9 May 2024 19:29:36 +0530 Subject: [PATCH 52/83] Android: DIR* is an OpaquePointer in Bionic too --- Sources/System/Internals/Syscalls.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 3794d6e..f40b168 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -189,7 +189,7 @@ internal func system_confstr( internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR internal let SYSTEM_DT_DIR = DT_DIR internal typealias system_dirent = dirent -#if os(Linux) +#if os(Linux) || os(Android) internal typealias system_DIRPtr = OpaquePointer #else internal typealias system_DIRPtr = UnsafeMutablePointer From e5a56da50e50f0aabf1778f08be679617ef328f7 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 9 May 2024 15:57:29 -0700 Subject: [PATCH 53/83] Cherry-pick changes from PR154 --- Sources/System/SystemString.swift | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index a918a92..c26d904 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -141,31 +141,38 @@ 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 { - // TODO: Below include null terminator, is this desired? + // withSystemChars includes the null terminator internal func withSystemChars( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withContiguousStorageIfAvailable(f)! + try nullTerminatedStorage.withContiguousStorageIfAvailable(f)! } internal func withCodeUnits( From c3a7235bf7cf5e92e8286e82773c91118734cfcf Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 9 May 2024 15:32:45 -0700 Subject: [PATCH 54/83] Cherry-pick changes from PR133 Co-authored-by: Max Desiatov --- Sources/System/Internals/CInterop.swift | 9 ++++++--- Sources/System/Internals/Constants.swift | 11 +++++++++-- Sources/System/Internals/Exports.swift | 16 ++++++++++++---- Sources/System/Internals/Syscalls.swift | 4 +++- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index cb84a59..e3cb3f2 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -16,12 +16,15 @@ public typealias CModeT = CInterop.Mode #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin -#elseif os(Linux) || os(FreeBSD) || os(Android) -@_implementationOnly import CSystem -import Glibc #elseif os(Windows) import CSystem import ucrt +#elseif canImport(Glibc) +@_implementationOnly import CSystem +import Glibc +#elseif canImport(Musl) +@_implementationOnly import CSystem +import Musl #else #error("Unsupported Platform") #endif diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 5489a55..12e42be 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -13,11 +13,14 @@ #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin -#elseif os(Linux) || os(FreeBSD) || os(Android) -import Glibc #elseif os(Windows) import CSystem import ucrt +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import CSystem +import Musl #else #error("Unsupported Platform") #endif @@ -450,9 +453,13 @@ internal var _O_WRONLY: CInt { O_WRONLY } internal var _O_RDWR: CInt { O_RDWR } #if !os(Windows) +#if canImport(Musl) +internal var _O_ACCMODE: CInt { 0x03|O_SEARCH } +#else // TODO: API? @_alwaysEmitIntoClient internal var _O_ACCMODE: CInt { O_ACCMODE } +#endif @_alwaysEmitIntoClient internal var _O_NONBLOCK: CInt { O_NONBLOCK } diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 5c0a58a..2879e13 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -14,12 +14,15 @@ #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin -#elseif os(Linux) || os(FreeBSD) || os(Android) -@_implementationOnly import CSystem -import Glibc #elseif os(Windows) import CSystem import ucrt +#elseif canImport(Glibc) +@_implementationOnly import CSystem +import Glibc +#elseif canImport(Musl) +@_implementationOnly import CSystem +import Musl #else #error("Unsupported Platform") #endif @@ -45,11 +48,16 @@ internal var system_errno: CInt { _ = ucrt._set_errno(newValue) } } -#else +#elseif canImport(Glibc) internal var system_errno: CInt { get { Glibc.errno } set { Glibc.errno = newValue } } +#elseif canImport(Musl) +internal var system_errno: CInt { + get { Musl.errno } + set { Musl.errno = newValue } +} #endif // MARK: C stdlib decls diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index b22d6a3..85d0e1c 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -9,8 +9,10 @@ #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin -#elseif os(Linux) || os(FreeBSD) || os(Android) +#elseif canImport(Glibc) import Glibc +#elseif canImport(Musl) +import Musl #elseif os(Windows) import ucrt #else From c7259554b5d70f2474d9495b256023a8dec50b89 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 9 May 2024 22:00:27 -0700 Subject: [PATCH 55/83] Cherry-pick changes from PR151 Co-authored-by: Hiroshi Yamauchi --- cmake/modules/SwiftSupport.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/SwiftSupport.cmake b/cmake/modules/SwiftSupport.cmake index 82961db..a73a4e5 100644 --- a/cmake/modules/SwiftSupport.cmake +++ b/cmake/modules/SwiftSupport.cmake @@ -17,7 +17,7 @@ See https://swift.org/LICENSE.txt for license information function(get_swift_host_arch result_var_name) if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") set("${result_var_name}" "x86_64" PARENT_SCOPE) - elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64") + elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64|ARM64") if(CMAKE_SYSTEM_NAME MATCHES Darwin) set("${result_var_name}" "arm64" PARENT_SCOPE) else() From 9620c1d30eb666e4b1d15f7c5efa8dfc0bd33b77 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 9 May 2024 22:24:04 -0700 Subject: [PATCH 56/83] Cherry-pick changes from PR148 Co-authored-by: Finagolfin --- Sources/System/Internals/Syscalls.swift | 16 +++++++++++++++ Tests/SystemTests/FileOperationsTest.swift | 24 ++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 85d0e1c..04d12db 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -71,7 +71,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,7 +109,15 @@ 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 } internal func system_dup(_ fd: Int32) -> Int32 { diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index 419e1c9..fce119f 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -86,6 +86,30 @@ final class FileOperationsTest: XCTestCase { for test in syscallTestCases { test.runAllTests() } } + func testWriteFromEmptyBuffer() throws { + let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly) + 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) + } + + func testReadToEmptyBuffer() throws { + let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly) + 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 } From b0e2a510edc693e65dd021ad5033bf16f18521b9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 10 May 2024 15:28:43 -0700 Subject: [PATCH 57/83] Make a platform-specific flag explicitly platform-specific --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 26bd4e6..fee91e0 100644 --- a/Package.swift +++ b/Package.swift @@ -27,7 +27,7 @@ let package = Package( dependencies: ["CSystem"], path: "Sources/System", cSettings: [ - .define("_CRT_SECURE_NO_WARNINGS") + .define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [.windows])) ], swiftSettings: [ .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS, .visionOS])), From 63b05e24e8dac45d075aa4897251918559b53477 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 10 May 2024 15:35:29 -0700 Subject: [PATCH 58/83] Improved compatibility for visionOS support --- Package.swift | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index 26bd4e6..4a3c2c4 100644 --- a/Package.swift +++ b/Package.swift @@ -12,6 +12,13 @@ import PackageDescription +let DarwinPlatforms: [Platform] +#if swift(<5.9) +DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS] +#else +DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS, .visionOS] +#endif + let package = Package( name: "swift-system", products: [ @@ -30,16 +37,16 @@ let package = Package( .define("_CRT_SECURE_NO_WARNINGS") ], swiftSettings: [ - .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS, .visionOS])), .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_DARWIN", .when(platforms: [.macOS, .iOS, .watchOS, .tvOS, .visionOS])), - .define("SYSTEM_PACKAGE") + .define("SYSTEM_PACKAGE"), + .define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)), ]) ] ) From 37a5bbb965369c2e1f236729db69b195867fc8f0 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 May 2024 15:54:56 -0700 Subject: [PATCH 59/83] Require Swift 5.8 or better --- Package.swift | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index b081a87..60976ce 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 From f1f59e148f1706caac25341123af4c45c617b1cc Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 May 2024 15:55:04 -0700 Subject: [PATCH 60/83] Update gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 36bbb6f..3ca0750 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ /*.xcodeproj xcuserdata/ .*.sw? +/.swiftpm From c456f4186e21b43e9a9f39f1a3231d5ffd44492e Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 10 May 2024 16:01:36 -0700 Subject: [PATCH 61/83] Change the package manifest to support visionOS --- Package.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 60976ce..e902aaa 100644 --- a/Package.swift +++ b/Package.swift @@ -11,6 +11,13 @@ import PackageDescription +let DarwinPlatforms: [Platform] +#if swift(<5.9) +DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS] +#else +DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS, .visionOS] +#endif + let package = Package( name: "swift-system", products: [ @@ -30,13 +37,15 @@ let package = Package( ], 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)), ]), ] ) From 7b14e48d0dc485b114efaa4129a33cb97286cdd9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 10 May 2024 16:09:22 -0700 Subject: [PATCH 62/83] Remove the repeated list of Darwin-based platforms Replaced with a constant defined in the package manifest. --- Sources/System/Errno.swift | 20 +++++++++--------- Sources/System/FileDescriptor.swift | 10 ++++----- Sources/System/Internals/CInterop.swift | 2 +- Sources/System/Internals/Constants.swift | 26 ++++++++++++------------ Sources/System/Internals/Exports.swift | 4 ++-- Sources/System/Internals/Syscalls.swift | 2 +- Tests/SystemTests/ErrnoTest.swift | 14 ++++++------- Tests/SystemTests/FileTypesTest.swift | 4 ++-- 8 files changed, 41 insertions(+), 41 deletions(-) diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index e2ebadb..0000f50 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -23,7 +23,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @_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) } @@ -911,7 +911,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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`. @@ -968,7 +968,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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. /// @@ -1060,7 +1060,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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, @@ -1075,7 +1075,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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. @@ -1102,7 +1102,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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`. @@ -1142,7 +1142,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { 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. @@ -1246,7 +1246,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { @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. @@ -1409,7 +1409,7 @@ extension Errno { @available(*, unavailable, renamed: "tooManyRemoteLevels") public static var EREMOTE: Errno { tooManyRemoteLevels } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN /// No such policy registered. /// /// The corresponding C error is `ENOPOLICY`. @@ -1443,7 +1443,7 @@ extension Errno { 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`. diff --git a/Sources/System/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index fbb7df3..5ef5ad8 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -182,7 +182,7 @@ extension FileDescriptor { @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. /// @@ -250,7 +250,7 @@ extension FileDescriptor { 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. /// @@ -353,7 +353,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. /// @@ -415,7 +415,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 @@ -434,7 +434,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"), diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index e3cb3f2..13abc75 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -14,7 +14,7 @@ @available(*, deprecated, renamed: "CInterop.Mode") public typealias CModeT = CInterop.Mode -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN import Darwin #elseif os(Windows) import CSystem diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 12e42be..53e215f 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -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 @@ -26,7 +26,7 @@ import Musl #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 @@ -272,7 +272,7 @@ 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 @@ -313,7 +313,7 @@ internal var _EREMOTE: CInt { #endif } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _EBADRPC: CInt { EBADRPC } @@ -336,7 +336,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 +358,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 +386,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 @@ -420,7 +420,7 @@ internal var _ETIME: CInt { ETIME } @_alwaysEmitIntoClient internal var _EOPNOTSUPP: CInt { EOPNOTSUPP } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _ENOPOLICY: CInt { ENOPOLICY } #endif @@ -433,7 +433,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 } @@ -468,7 +468,7 @@ internal var _O_NONBLOCK: CInt { O_NONBLOCK } @_alwaysEmitIntoClient internal var _O_APPEND: CInt { O_APPEND } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_SHLOCK: CInt { O_SHLOCK } @@ -494,7 +494,7 @@ internal var _O_TRUNC: CInt { O_TRUNC } @_alwaysEmitIntoClient internal var _O_EXCL: CInt { O_EXCL } -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_EVTONLY: CInt { O_EVTONLY } #endif @@ -508,7 +508,7 @@ internal var _O_NOCTTY: CInt { O_NOCTTY } internal var _O_DIRECTORY: CInt { O_DIRECTORY } #endif -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient internal var _O_SYMLINK: CInt { O_SYMLINK } #endif @@ -527,7 +527,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 2879e13..5b08725 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -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 @@ -31,7 +31,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 } diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 04d12db..555f63b 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -7,7 +7,7 @@ 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 diff --git a/Tests/SystemTests/ErrnoTest.swift b/Tests/SystemTests/ErrnoTest.swift index 4bbe88f..96e7df3 100644 --- a/Tests/SystemTests/ErrnoTest.swift +++ b/Tests/SystemTests/ErrnoTest.swift @@ -84,7 +84,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 @@ -92,7 +92,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(EDQUOT == Errno.diskQuotaExceeded.rawValue) XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(EBADRPC == Errno.rpcUnsuccessful.rawValue) XCTAssert(ERPCMISMATCH == Errno.rpcVersionMismatch.rawValue) XCTAssert(EPROGUNAVAIL == Errno.rpcProgramUnavailable.rawValue) @@ -103,7 +103,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) @@ -113,7 +113,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(EOVERFLOW == Errno.overflow.rawValue) -#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) @@ -125,7 +125,7 @@ final class ErrnoTest: XCTestCase { XCTAssert(ENOMSG == Errno.noMessage.rawValue) XCTAssert(EILSEQ == Errno.illegalByteSequence.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(ENOATTR == Errno.attributeNotFound.rawValue) #endif @@ -144,14 +144,14 @@ final class ErrnoTest: XCTestCase { XCTAssert(ETOOMANYREFS == Errno.tooManyReferences.rawValue) XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssert(ENOPOLICY == Errno.noSuchPolicy.rawValue) #endif XCTAssert(ENOTRECOVERABLE == Errno.notRecoverable.rawValue) XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue) -#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/FileTypesTest.swift b/Tests/SystemTests/FileTypesTest.swift index b8cf496..8498cf5 100644 --- a/Tests/SystemTests/FileTypesTest.swift +++ b/Tests/SystemTests/FileTypesTest.swift @@ -38,7 +38,7 @@ final class FileDescriptorTest: XCTestCase { XCTAssertEqual(O_CLOEXEC, FileDescriptor.OpenOptions.closeOnExec.rawValue) // BSD only -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if SYSTEM_PACKAGE_DARWIN XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue) XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue) XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue) @@ -49,7 +49,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 From 0368ce547bf0193955fe538eea624233e7815cd1 Mon Sep 17 00:00:00 2001 From: Mishal Shah Date: Fri, 10 May 2024 16:18:08 -0700 Subject: [PATCH 63/83] Add support for Swift CI on release/1.3.0 --- .swiftci/5_10_ubuntu2204 | 5 +++++ .swiftci/5_7_ubuntu2204 | 5 +++++ .swiftci/5_8_ubuntu2204 | 5 +++++ .swiftci/5_9_ubuntu2204 | 5 +++++ .swiftci/nightly_6_0_macos | 5 +++++ .swiftci/nightly_6_0_ubuntu2204 | 5 +++++ .swiftci/nightly_main_macos | 5 +++++ .swiftci/nightly_main_ubuntu2204 | 5 +++++ .swiftci/nightly_main_windows | 7 +++++++ 9 files changed, 47 insertions(+) create mode 100644 .swiftci/5_10_ubuntu2204 create mode 100644 .swiftci/5_7_ubuntu2204 create mode 100644 .swiftci/5_8_ubuntu2204 create mode 100644 .swiftci/5_9_ubuntu2204 create mode 100644 .swiftci/nightly_6_0_macos create mode 100644 .swiftci/nightly_6_0_ubuntu2204 create mode 100644 .swiftci/nightly_main_macos create mode 100644 .swiftci/nightly_main_ubuntu2204 create mode 100644 .swiftci/nightly_main_windows diff --git a/.swiftci/5_10_ubuntu2204 b/.swiftci/5_10_ubuntu2204 new file mode 100644 index 0000000..0554635 --- /dev/null +++ b/.swiftci/5_10_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.10-jammy" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/5_7_ubuntu2204 b/.swiftci/5_7_ubuntu2204 new file mode 100644 index 0000000..b1568a3 --- /dev/null +++ b/.swiftci/5_7_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.7-jammy" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/5_8_ubuntu2204 b/.swiftci/5_8_ubuntu2204 new file mode 100644 index 0000000..141a58e --- /dev/null +++ b/.swiftci/5_8_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.8-jammy" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/5_9_ubuntu2204 b/.swiftci/5_9_ubuntu2204 new file mode 100644 index 0000000..e834c95 --- /dev/null +++ b/.swiftci/5_9_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + swift_version_tag = "5.9-jammy" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/nightly_6_0_macos b/.swiftci/nightly_6_0_macos new file mode 100644 index 0000000..62683c2 --- /dev/null +++ b/.swiftci/nightly_6_0_macos @@ -0,0 +1,5 @@ +macOSSwiftPackageJob { + swift_version = "6.0" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/nightly_6_0_ubuntu2204 b/.swiftci/nightly_6_0_ubuntu2204 new file mode 100644 index 0000000..431f07c --- /dev/null +++ b/.swiftci/nightly_6_0_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + nightly_docker_tag = "nightly-6.0-jammy" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/nightly_main_macos b/.swiftci/nightly_main_macos new file mode 100644 index 0000000..7b3dcd7 --- /dev/null +++ b/.swiftci/nightly_main_macos @@ -0,0 +1,5 @@ +macOSSwiftPackageJob { + swift_version = "main" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/nightly_main_ubuntu2204 b/.swiftci/nightly_main_ubuntu2204 new file mode 100644 index 0000000..58c94d5 --- /dev/null +++ b/.swiftci/nightly_main_ubuntu2204 @@ -0,0 +1,5 @@ +LinuxSwiftPackageJob { + nightly_docker_tag = "nightly-jammy" + repo = "swift-system" + branch = "release/1.3.0" +} diff --git a/.swiftci/nightly_main_windows b/.swiftci/nightly_main_windows new file mode 100644 index 0000000..e2d3bf2 --- /dev/null +++ b/.swiftci/nightly_main_windows @@ -0,0 +1,7 @@ +WindowsSwiftPackageWithDockerImageJob { + docker_image = "swiftlang/swift:nightly-windowsservercore-1809" + repo = "swift-system" + branch = "release/1.3.0" + sub_dir = "swift-system" + label = "windows-server-2019" +} From 52f603c6b38d924d63a950aacb6d630979f4b258 Mon Sep 17 00:00:00 2001 From: Mishal Shah Date: Fri, 10 May 2024 16:31:13 -0700 Subject: [PATCH 64/83] [CI] Remove support for Swift 5.7 --- .swiftci/5_7_ubuntu2204 | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .swiftci/5_7_ubuntu2204 diff --git a/.swiftci/5_7_ubuntu2204 b/.swiftci/5_7_ubuntu2204 deleted file mode 100644 index b1568a3..0000000 --- a/.swiftci/5_7_ubuntu2204 +++ /dev/null @@ -1,5 +0,0 @@ -LinuxSwiftPackageJob { - swift_version_tag = "5.7-jammy" - repo = "swift-system" - branch = "release/1.3.0" -} From 3433699e6e75dc3a8973f687be99f64ef01a11f2 Mon Sep 17 00:00:00 2001 From: Mishal Shah Date: Fri, 10 May 2024 16:32:21 -0700 Subject: [PATCH 65/83] [CI] Remove support for Swift 5.7 --- .swiftci/5_7_ubuntu2204 | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .swiftci/5_7_ubuntu2204 diff --git a/.swiftci/5_7_ubuntu2204 b/.swiftci/5_7_ubuntu2204 deleted file mode 100644 index 8550458..0000000 --- a/.swiftci/5_7_ubuntu2204 +++ /dev/null @@ -1,5 +0,0 @@ -LinuxSwiftPackageJob { - swift_version_tag = "5.7-jammy" - repo = "swift-system" - branch = "main" -} From 0cf079efeaf1889534f0366546a7fe2116d7918d Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 May 2024 17:05:37 -0700 Subject: [PATCH 66/83] Add CODEOWNERS --- .github/CODEOWNERS | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/CODEOWNERS 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 From a6fd8ba9baeac821c711015fbedc8f21a4b507b6 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 10 May 2024 17:05:37 -0700 Subject: [PATCH 67/83] Add CODEOWNERS --- .github/CODEOWNERS | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/CODEOWNERS 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 From 7d45e0dd46dc505cff02b9a44e24243d2b4354a3 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sun, 12 May 2024 11:40:14 -0700 Subject: [PATCH 68/83] Update README.md to refer to 1.3.0 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 11e57eb..4c74e3b 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ 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 +37,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: [ From 25c4b1ad75f842680346035ea42ccabf46fccd2e Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sun, 12 May 2024 14:07:11 -0700 Subject: [PATCH 69/83] fix a 32-bit overflow issue - ensures compatibility with watchOS --- Sources/System/MachPort.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index b3eb0a9..62b5547 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -56,8 +56,10 @@ public enum Mach { 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)) @@ -87,8 +89,10 @@ public enum Mach { deinit { 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" + ) _machPrecondition( mach_port_destruct(mach_task_self_, _name, 0, _context) ) From 8e09ede76d975ff5aa5edde7043c017c43b20b84 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Mon, 13 May 2024 11:19:43 +0100 Subject: [PATCH 70/83] Remove accidentally public functions. These can't be new API as they haven't been reviewed. --- Sources/System/ErrnoWindows.swift | 2 +- Sources/System/FileOperations.swift | 4 ++-- Sources/System/FilePath/FilePathTemp.swift | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/System/ErrnoWindows.swift b/Sources/System/ErrnoWindows.swift index b94b577..cc481cb 100644 --- a/Sources/System/ErrnoWindows.swift +++ b/Sources/System/ErrnoWindows.swift @@ -12,7 +12,7 @@ import WinSDK extension Errno { - public init(windowsError: DWORD) { + internal init(windowsError: DWORD) { self.init(rawValue: _mapWindowsErrorToErrno(windowsError)) } } diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index ba70e87..3412834 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -516,7 +516,7 @@ extension FilePermissions { /// files or directories. Note that this mask is process-wide, and that /// *getting* it is not thread safe. @_alwaysEmitIntoClient - public static var creationMask: FilePermissions { + internal static var creationMask: FilePermissions { get { let oldMask = _umask(0o22) _ = _umask(oldMask) @@ -536,7 +536,7 @@ extension FilePermissions { /// This is more efficient than reading `creationMask` and restoring it /// afterwards, because of the way reading the creation mask works. @_alwaysEmitIntoClient - public static func withCreationMask( + internal static func withCreationMask( _ permissions: FilePermissions, body: () throws -> R ) rethrows -> R { diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index 7b41d0b..c0edf95 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -18,7 +18,7 @@ /// 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. -public func withTemporaryFilePath( +internal func withTemporaryFilePath( basename: FilePath.Component, _ body: (FilePath) throws -> R ) throws -> R { From c3559ecd6184216b77f46c472b7d247573d42371 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Mon, 13 May 2024 14:18:17 +0100 Subject: [PATCH 71/83] [Windows] Fix a problem with opening files read only. `_O_RDONLY` is zero, so we can't test for it by AND-ing. --- Sources/System/Internals/WindowsSyscallAdapters.swift | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index 3e3f9c6..1e35ee9 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -621,14 +621,15 @@ fileprivate struct DecodedOpenFlags { } dwDesiredAccess = 0 - if (oflag & _O_RDONLY) != 0 { + switch (oflag & (_O_RDONLY|_O_WRONLY|_O_RDWR)) { + case _O_RDONLY: dwDesiredAccess |= DWORD(GENERIC_READ) - } - if (oflag & _O_WRONLY) != 0 { + case _O_WRONLY: dwDesiredAccess |= DWORD(GENERIC_WRITE) - } - if (oflag & _O_RDWR) != 0 { + case _O_RDWR: dwDesiredAccess |= DWORD(GENERIC_READ) | DWORD(GENERIC_WRITE) + default: + break } bInheritHandle = WindowsBool((oflag & _O_NOINHERIT) == 0) From abc0a6d26ffb34d3d4a71244f300648f34f64313 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Mon, 13 May 2024 14:19:33 +0100 Subject: [PATCH 72/83] [Windows] Fix tests. We need to use `@testable` when importing `SystemPackage` in order to let us test the `internal` functions. Also, use `NUL` instead of `/dev/null`, and generate random bytes in a file instead of reading from `/dev/random`. --- Tests/SystemTests/FileOperationsTest.swift | 58 +++++++++++++++---- .../FileOperationsTestWindows.swift | 4 +- .../FilePathTests/FilePathTempTest.swift | 4 +- 3 files changed, 51 insertions(+), 15 deletions(-) diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index be5a67d..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, *) @@ -87,7 +87,11 @@ final class FileOperationsTest: XCTestCase { } 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) @@ -98,16 +102,48 @@ final class FileOperationsTest: XCTestCase { XCTAssertEqual(written2, 0) } - func testReadToEmptyBuffer() throws { - let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly) - let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0)) - XCTAssertEqual(read1, 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) + ) - 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) + 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() { diff --git a/Tests/SystemTests/FileOperationsTestWindows.swift b/Tests/SystemTests/FileOperationsTestWindows.swift index 35df731..8203051 100644 --- a/Tests/SystemTests/FileOperationsTestWindows.swift +++ b/Tests/SystemTests/FileOperationsTestWindows.swift @@ -12,9 +12,9 @@ import XCTest #if os(Windows) #if SYSTEM_PACKAGE -import SystemPackage +@testable import SystemPackage #else -import System +@testable import System #endif import WinSDK diff --git a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift index dc8597b..30d5826 100644 --- a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -10,9 +10,9 @@ import XCTest #if SYSTEM_PACKAGE -import SystemPackage +@testable import SystemPackage #else -import System +@testable import System #endif final class TemporaryPathTest: XCTestCase { From 082adfe732db95083b238e6eb787a68a4141f593 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Tue, 14 May 2024 14:42:57 +0100 Subject: [PATCH 73/83] [Windows] Add a comment to explain the O_RDONLY/O_WRONLY/O_RDWR logic. The values of these flags on Windows do not overlap, and more particularly, `O_RDONLY` is actually zero on Windows, which means we cannot test for it by AND-ing. --- Sources/System/Internals/WindowsSyscallAdapters.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index 1e35ee9..048377b 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -620,6 +620,9 @@ fileprivate struct DecodedOpenFlags { 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: From b7dc8e8e41b30079ec09602e44088295599645bd Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 15 May 2024 14:30:14 -0700 Subject: [PATCH 74/83] [CMake] Restore to working order on Apple platforms --- Sources/System/CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 43958d3..4335200 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -37,6 +37,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) From 9c17c8562d0d05b08de19285797c312d6ab8cd3d Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Mon, 3 Jun 2024 02:15:05 +0000 Subject: [PATCH 75/83] Suppress unhandled CMakeLists.txt warning by SwiftPM --- Package.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 4a3c2c4..5c1e260 100644 --- a/Package.swift +++ b/Package.swift @@ -28,11 +28,13 @@ let package = Package( targets: [ .target( name: "CSystem", - dependencies: []), + dependencies: [], + exclude: ["CMakeLists.txt"]), .target( name: "SystemPackage", dependencies: ["CSystem"], path: "Sources/System", + exclude: ["CMakeLists.txt"], cSettings: [ .define("_CRT_SECURE_NO_WARNINGS") ], From c1789e0525dfd8f7a1512fcaa0c6917184f136ba Mon Sep 17 00:00:00 2001 From: Neil Jones Date: Tue, 18 Jun 2024 10:45:08 +0900 Subject: [PATCH 76/83] add support for riscv64 --- cmake/modules/SwiftSupport.cmake | 2 ++ 1 file changed, 2 insertions(+) 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() From 02811ea6b428b82523a42e6deb8abce5011ec582 Mon Sep 17 00:00:00 2001 From: Finagolfin Date: Thu, 4 Jul 2024 23:37:25 +0530 Subject: [PATCH 77/83] Import new Android overlay Use Bionic module instead where possible --- Sources/System/Internals/CInterop.swift | 3 +++ Sources/System/Internals/Constants.swift | 2 ++ Sources/System/Internals/Exports.swift | 8 ++++++++ Sources/System/Internals/Syscalls.swift | 2 ++ 4 files changed, 15 insertions(+) diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index 19cf4d5..80d37d0 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -20,6 +20,9 @@ import Glibc 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 27a145f..904e5b2 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -24,6 +24,8 @@ import Musl #elseif canImport(WASILibc) import CSystem import WASILibc +#elseif canImport(Android) +import Android #else #error("Unsupported Platform") #endif diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index f4358c5..d18102a 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -25,6 +25,9 @@ import Glibc import Musl #elseif canImport(WASILibc) import WASILibc +#elseif canImport(Android) +@_implementationOnly import CSystem +import Android #else #error("Unsupported Platform") #endif @@ -65,6 +68,11 @@ 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 diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index f40b168..6f885be 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -17,6 +17,8 @@ import Musl import WASILibc #elseif os(Windows) import ucrt +#elseif canImport(Android) +import Android #else #error("Unsupported Platform") #endif From 4c96faa6d8c34dcca54944ba37a0582867f358d5 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 17 Jul 2024 12:14:43 -0400 Subject: [PATCH 78/83] Insure that FilePath and SystemString's invariants are enforced when decoding. --- Sources/System/FilePath/FilePath.swift | 24 +++- Sources/System/FilePath/FilePathParsing.swift | 15 ++- Sources/System/SystemString.swift | 28 ++++- .../FilePathTests/FilePathDecodable.swift | 114 ++++++++++++++++++ 4 files changed, 172 insertions(+), 9 deletions(-) create mode 100644 Tests/SystemTests/FilePathTests/FilePathDecodable.swift diff --git a/Sources/System/FilePath/FilePath.swift b/Sources/System/FilePath/FilePath.swift index 13064b5..1b9dfc2 100644 --- a/Sources/System/FilePath/FilePath.swift +++ b/Sources/System/FilePath/FilePath.swift @@ -59,6 +59,15 @@ public struct FilePath: Sendable { } } +/* + extension FilePath: Hashable, Codable { + + + precondition(_hasRoot == (self.root != nil)) + } + } + */ + @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) extension FilePath { /// The length of the file path, excluding the null terminator. @@ -66,4 +75,17 @@ 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 {} +extension FilePath: Hashable, Codable { + 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/FilePathParsing.swift b/Sources/System/FilePath/FilePathParsing.swift index 0ab4f7e..c31e6a5 100644 --- a/Sources/System/FilePath/FilePathParsing.swift +++ b/Sources/System/FilePath/FilePathParsing.swift @@ -375,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/SystemString.swift b/Sources/System/SystemString.swift index 36b6850..7b629e3 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -96,10 +96,17 @@ extension SystemString { } extension SystemString { + fileprivate func _invariantsSatisfied() -> Bool { + 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 } } @@ -165,7 +172,22 @@ extension SystemString: RangeReplaceableCollection { } } -extension SystemString: Hashable, Codable {} +extension SystemString: Hashable, Codable { + 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 { diff --git a/Tests/SystemTests/FilePathTests/FilePathDecodable.swift b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift new file mode 100644 index 0000000..a1a46d9 --- /dev/null +++ b/Tests/SystemTests/FilePathTests/FilePathDecodable.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 + */ + +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. + 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 + 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 + 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) + )) + } +} From c64775ef71100699f67aac928b3ec487d9f1a06f Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 17 Jul 2024 12:25:34 -0400 Subject: [PATCH 79/83] Another invariant to check --- Sources/System/SystemString.swift | 1 + .../FilePathTests/FilePathDecodable.swift | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 7b629e3..ab70334 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -97,6 +97,7 @@ 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 diff --git a/Tests/SystemTests/FilePathTests/FilePathDecodable.swift b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift index a1a46d9..a9d687d 100644 --- a/Tests/SystemTests/FilePathTests/FilePathDecodable.swift +++ b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift @@ -111,4 +111,17 @@ final class FilePathDecodableTest: XCTestCase { from: Data(input) )) } + + func testEmptyString() { + 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) + )) + } } From 3b43b391b5b9a2bf86f14aa8d4b34d37fbbbd0d1 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 17 Jul 2024 12:49:37 -0400 Subject: [PATCH 80/83] Add some comments and remove leftover WIP noise. --- Sources/System/FilePath/FilePath.swift | 14 +++++--------- Sources/System/SystemString.swift | 5 +++++ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Sources/System/FilePath/FilePath.swift b/Sources/System/FilePath/FilePath.swift index 1b9dfc2..67752c0 100644 --- a/Sources/System/FilePath/FilePath.swift +++ b/Sources/System/FilePath/FilePath.swift @@ -59,15 +59,6 @@ public struct FilePath: Sendable { } } -/* - extension FilePath: Hashable, Codable { - - - precondition(_hasRoot == (self.root != nil)) - } - } - */ - @available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *) extension FilePath { /// The length of the file path, excluding the null terminator. @@ -76,6 +67,11 @@ 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 { + // 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) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index ab70334..57abc62 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -174,6 +174,11 @@ extension SystemString: RangeReplaceableCollection { } 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( From 3841a7531f8a1f177dc6825fee207fcf83ff69fc Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 17 Jul 2024 13:49:15 -0400 Subject: [PATCH 81/83] Add some notes explaining what invariants are violated. --- Tests/SystemTests/FilePathTests/FilePathDecodable.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Tests/SystemTests/FilePathTests/FilePathDecodable.swift b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift index a9d687d..290bef2 100644 --- a/Tests/SystemTests/FilePathTests/FilePathDecodable.swift +++ b/Tests/SystemTests/FilePathTests/FilePathDecodable.swift @@ -19,7 +19,7 @@ import XCTest final class FilePathDecodableTest: XCTestCase { func testInvalidFilePath() { // _storage is a valid SystemString, but the invariants of FilePath are - // violated. + // 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, @@ -77,7 +77,8 @@ final class FilePathDecodableTest: XCTestCase { } func testInvalidSystemString() { - // _storage is a SystemString whose invariants are violated + // _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, @@ -95,7 +96,7 @@ final class FilePathDecodableTest: XCTestCase { func testInvalidExample() { // Another misformed example from Johannes that violates FilePath's - // invariants + // 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, @@ -113,6 +114,7 @@ final class FilePathDecodableTest: XCTestCase { } 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, From edbc9e4fdc7a4d2706e7ada7626622c21453ef52 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 31 Jul 2024 14:56:04 -0700 Subject: [PATCH 82/83] Remove private-and-@_aEIC initializers These were just passthroughs. --- Sources/System/Errno.swift | 221 +++++++++++++-------------- Sources/System/FileDescriptor.swift | 27 ++-- Sources/System/FilePermissions.swift | 51 +++---- 3 files changed, 145 insertions(+), 154 deletions(-) diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index 1305593..093023d 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -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 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,7 +136,7 @@ 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: "execFormatError") @@ -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,7 +220,7 @@ 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") @@ -236,7 +233,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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,7 +523,7 @@ 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: "nowInProgress") @@ -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,7 +612,7 @@ 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") @@ -629,7 +626,7 @@ 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") @@ -643,7 +640,7 @@ 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") @@ -657,7 +654,7 @@ 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") @@ -672,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") @@ -684,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") @@ -697,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") @@ -709,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") @@ -721,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") @@ -733,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") @@ -745,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") @@ -759,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") @@ -773,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") @@ -788,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") @@ -803,7 +800,7 @@ 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") @@ -818,7 +815,7 @@ 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") @@ -834,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") @@ -849,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") @@ -861,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") @@ -874,7 +871,7 @@ 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") @@ -887,7 +884,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -900,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") @@ -913,7 +910,7 @@ 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") @@ -924,7 +921,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -938,7 +935,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -956,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") @@ -971,7 +968,7 @@ 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") @@ -986,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") @@ -999,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") @@ -1011,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") @@ -1024,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") @@ -1037,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") @@ -1051,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") @@ -1063,7 +1060,7 @@ 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") @@ -1078,7 +1075,7 @@ 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") @@ -1092,7 +1089,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1105,7 +1102,7 @@ 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") @@ -1117,7 +1114,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1130,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") @@ -1145,7 +1142,7 @@ 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") @@ -1159,7 +1156,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1171,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") @@ -1184,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") @@ -1196,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") @@ -1209,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") @@ -1222,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") @@ -1235,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") @@ -1250,7 +1247,7 @@ 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") @@ -1263,7 +1260,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1278,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") @@ -1291,7 +1288,7 @@ 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") @@ -1304,7 +1301,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1317,7 +1314,7 @@ 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") @@ -1330,7 +1327,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1342,7 +1339,7 @@ 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") @@ -1358,7 +1355,7 @@ 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") @@ -1371,7 +1368,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable { /// /// 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") @@ -1386,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") @@ -1400,7 +1397,7 @@ extension Errno { /// /// 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") @@ -1411,7 +1408,7 @@ extension Errno { /// /// 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") @@ -1421,7 +1418,7 @@ 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") @@ -1433,7 +1430,7 @@ extension Errno { /// /// 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") @@ -1445,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") @@ -1455,7 +1452,7 @@ 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") @@ -1467,7 +1464,7 @@ extension Errno { /// /// 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") @@ -1481,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/FileDescriptor.swift b/Sources/System/FileDescriptor.swift index 0ac7f4f..d7b931e 100644 --- a/Sources/System/FileDescriptor.swift +++ b/Sources/System/FileDescriptor.swift @@ -98,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. @@ -117,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") @@ -133,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") @@ -143,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") @@ -157,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") @@ -179,7 +176,7 @@ 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") @@ -197,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") @@ -214,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") @@ -232,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") @@ -246,7 +243,7 @@ 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") @@ -265,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") @@ -281,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") @@ -303,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") diff --git a/Sources/System/FilePermissions.swift b/Sources/System/FilePermissions.swift index 2cdb32f..918246e 100644 --- a/Sources/System/FilePermissions.swift +++ b/Sources/System/FilePermissions.swift @@ -27,104 +27,101 @@ public struct FilePermissions: OptionSet, Sendable, 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, Sendable, 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, *) From 2662793bd69ff7bcda6975c36e86a8ae5127deb7 Mon Sep 17 00:00:00 2001 From: George Barnett Date: Mon, 19 Aug 2024 10:18:30 +0100 Subject: [PATCH 83/83] Add support for macCatalyst Building swift-system for macCatalyst fails as there is no import of the Darwin module. --- Package.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index 3d30cd9..c0847e4 100644 --- a/Package.swift +++ b/Package.swift @@ -13,9 +13,9 @@ import PackageDescription let DarwinPlatforms: [Platform] #if swift(<5.9) -DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS] +DarwinPlatforms = [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS] #else -DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS, .visionOS] +DarwinPlatforms = [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS] #endif let package = Package(