From 304ccc3abbd4bdfcd42b84cf4aace5e1a1dbf51d Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 7 Dec 2022 17:19:36 -0800 Subject: [PATCH 01/15] Add Mach.Port --- Sources/System/CMakeLists.txt | 1 + Sources/System/MachPort.swift | 318 ++++++++++++++++++++++++++ Tests/SystemTests/MachPortTests.swift | 140 ++++++++++++ 3 files changed, 459 insertions(+) create mode 100644 Sources/System/MachPort.swift create mode 100644 Tests/SystemTests/MachPortTests.swift diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 43958d3..4d46dc4 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -13,6 +13,7 @@ add_library(SystemPackage FileHelpers.swift FileOperations.swift FilePermissions.swift + MachPort.swift PlatformString.swift SystemString.swift Util.swift diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift new file mode 100644 index 0000000..dcd9831 --- /dev/null +++ b/Sources/System/MachPort.swift @@ -0,0 +1,318 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2022 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 $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) + +import Darwin.Mach + +protocol MachPortRight {} + +enum Mach { + @_moveOnly + struct Port { + internal var name:mach_port_name_t + internal var context:mach_port_context_t + + /// Transfer ownership of an existing unmanaged Mach port right into a + /// Mach.Port by name. + /// + /// This initializer aborts if name is MACH_PORT_NULL. + /// + /// If the type of the right does not match the type T of Mach.Port + /// being constructed, behavior is undefined. + /// + /// The underlying port right will be automatically deallocated at the + /// end of the Mach.Port instance's lifetime. + /// + /// This initializer makes a syscall to guard the right. + init(name:mach_port_name_t) { + assert(name != mach_port_name_t(MACH_PORT_NULL)) + self.name = name + + if (RightType.self == ReceiveRight.self) { + let secret = mach_port_context_t(arc4random()) + let kr = mach_port_guard(mach_task_self_, name, secret, 0) + assert(kr == KERN_SUCCESS) + self.context = secret + } + else { + self.context = 0 + } + } + + /// Borrow access to the port name in a block that can perform + /// non-consuming operations. + /// + /// Take care when using this function; many operations consume rights, + /// and send-once rights are easily consumed. + /// + /// If the right is consumed, behavior is undefined. + /// + /// The body block may optionally return something, which will then be + /// returned to the caller of withBorrowedName. + func withBorrowedName(body:(mach_port_name_t) -> ReturnType) -> ReturnType { + return body(name) + } + + deinit { + if name != 0xFFFFFFFF /* MACH_PORT_DEAD */ { + if RightType.self == ReceiveRight.self { + // recv rights must be mod ref'ed instead of deallocated + let kr = mach_port_unguard(mach_task_self_, name, context) + assert(kr == KERN_SUCCESS) + + let kr2 = mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_RECEIVE, -1) + assert(kr2 == KERN_SUCCESS) + } else { + mach_port_deallocate(mach_task_self_, name) + } + } + } + } + + /// Possible errors that can be thrown by Mach.Port operations. + enum PortRightError : Error { + /// Returned when an operation cannot be completed, because the Mach + /// port right has become a dead name. This is caused by deallocation of the + /// receive right on the other end. + case deadName + } + + /// The MachPortRight type used to manage a receive right. + struct ReceiveRight : MachPortRight {} + + /// The MachPortRight type used to manage a send right. + struct SendRight : MachPortRight {} + + /// The MachPortRight type used to manage a send-once right. + /// + /// Send-once rights are the most restrictive type of Mach port rights. + /// They cannot create other rights, and are consumed upon use. + /// + /// Upon destruction a send-once notification will be sent to the + /// receiving end. + struct SendOnceRight : MachPortRight {} + + /// Create a connected pair of rights, one receive, and one send. + /// + /// This function will abort if the rights could not be created. + /// Callers may assert that valid rights are always returned. + static func allocatePortRightPair() -> (Mach.Port, Mach.Port) { + var name = mach_port_name_t(MACH_PORT_NULL) + let secret = mach_port_context_t(arc4random()) + withUnsafeMutablePointer(to: &name) { name in + var options = mach_port_options_t() + options.flags = UInt32(MPO_INSERT_SEND_RIGHT); + withUnsafeMutablePointer(to: &options) { options in + let kr = mach_port_construct(mach_task_self_, options, secret, name) + assert(kr == KERN_SUCCESS) + } + } + return (Mach.Port(name: name, context: secret), Mach.Port(name: name)) + } +} + +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. + /// + /// This initializer aborts if name is MACH_PORT_NULL. + /// + /// If the type of the right does not match the type T of Mach.Port + /// being constructed, the behavior is undefined. + /// + /// The underlying port right will be automatically deallocated when + /// the Mach.Port object is destroyed. + init(name:mach_port_name_t, context:mach_port_context_t) { + self.name = name + self.context = context + } + + /// Allocate a new Mach port with a receive right, creating a + /// Mach.Port to manage it. + /// + /// This initializer will abort if the right could not be created. + /// Callers may assert that a valid right is always returned. + init() { + var storage:mach_port_name_t = 0 + withUnsafeMutablePointer(to:&storage) { storage in + let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage) + assert(kr == KERN_SUCCESS) + } + + // name-only init will guard ReceiveRights + self.init(name:storage) + } + + + /// Transfer ownership of the underlying port right to the caller. + /// + /// Returns a tuple containing the Mach port name representing the right, + /// and the context value used to guard the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + __consuming func relinquish() -> (mach_port_name_t, mach_port_context_t) { + return (name, context) + } + + /// Remove guard and transfer ownership of the underlying port right to + /// the caller. + /// + /// Returns the Mach port name representing the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + /// + /// This function makes a syscall to remove the guard from + /// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract + /// the context value along with the port name. + __consuming func unguardAndRelinquish() -> mach_port_name_t { + let kr = mach_port_unguard(mach_task_self_, name, context); + assert(kr == KERN_SUCCESS) + return name + } + + /// Borrow access to the port name in a block that can perform + /// non-consuming operations. + /// + /// Take care when using this function; many operations consume rights. + /// + /// If the right is consumed, behavior is undefined. + /// + /// The body block may optionally return something, which will then be + /// returned to the caller of withBorrowedName. + func withBorrowedName(body:(mach_port_name_t, mach_port_context_t) -> ReturnType) -> ReturnType { + body(name, context) + } + + /// Create a send-once right for a given receive right. + /// + /// This does not affect the makeSendCount of the receive right. + /// + /// This function will abort if the right could not be created. + /// Callers may assert that a valid right is always returned. + func makeSendOnceRight() -> Mach.Port { + // send once rights do not coalesce + var kr:kern_return_t = KERN_FAILURE + 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 + kr = 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 + assert(kr == KERN_SUCCESS) + assert(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) + + return Mach.Port(name:newRight) + } + + /// Create a send right for a given receive right. + /// + /// This increments the makeSendCount of the receive right. + /// + /// This function will abort if the right could not be created. + /// Callers may assert that a valid right is always returned. + func makeSendRight() -> Mach.Port { + let how = MACH_MSG_TYPE_MAKE_SEND + + // send and recv rights are coalesced + let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(how)) + assert(kr == KERN_SUCCESS) + + return Mach.Port(name:name) + } + + /// Access the make-send count. + /// + /// Each get/set of this property makes a syscall. + 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) + withUnsafeMutablePointer(to: &size) { size in + withUnsafeMutablePointer(to: &status) { status in + let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1) + let kr = mach_port_get_attributes(mach_task_self_, name, MACH_PORT_RECEIVE_STATUS, info, size) + assert(kr == KERN_SUCCESS); + } + } + return status.mps_mscount + } + + set { + let kr = mach_port_set_mscount(mach_task_self_, name, newValue) + assert(kr == KERN_SUCCESS) + } + } +} + +extension Mach.Port where RightType == Mach.SendRight { + /// Transfer ownership of the underlying port right to the caller. + /// + /// Returns the Mach port name representing the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + __consuming func relinquish() -> mach_port_name_t { + return name + } + + /// Create another send right from a given send right. + /// + /// This does not affect the makeSendCount of the receive right. + /// + /// If the send right being copied has become a dead name, meaning the + /// receiving side has been deallocated, then copySendRight() will throw + /// a Mach.PortRightError.deadName error. + func copySendRight() throws -> Mach.Port { + let how = MACH_MSG_TYPE_COPY_SEND + + // 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 { + throw Mach.PortRightError.deadName + } + assert(kr == KERN_SUCCESS) + + return Mach.Port(name:name) + } +} + + +extension Mach.Port where RightType == Mach.SendOnceRight { + /// Transfer ownership of the underlying port right to the caller. + /// + /// Returns the Mach port name representing the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + __consuming func relinquish() -> mach_port_name_t { + return name + } +} + +#endif diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift new file mode 100644 index 0000000..0def85a --- /dev/null +++ b/Tests/SystemTests/MachPortTests.swift @@ -0,0 +1,140 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2022 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 $MoveOnly && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) + +import XCTest +import Darwin.Mach + +final class MachPortTests: XCTestCase { + func refCountForMachPortName(name:mach_port_name_t, kind:mach_port_right_t) -> mach_port_urefs_t { + var refCount:mach_port_urefs_t = 0 + withUnsafeMutablePointer(to: &refCount) { refCount in + let kr = mach_port_get_refs(mach_task_self_, name, kind, refCount) + assert(kr == KERN_SUCCESS) + } + return refCount + } + + func scopedReceiveRight(name:mach_port_name_t) -> mach_port_urefs_t { + _ = Mach.Port(name:name) // this should automatically deallocate when going out of scope + return refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_RECEIVE) + } + + func testRecieveRightDeallocation() throws { + var name:mach_port_name_t = 0 // Never read + withUnsafeMutablePointer(to:&name) { name in + let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, name) + assert(kr == KERN_SUCCESS) + } + + XCTAssert(name != 0xFFFFFFFF) + + let one = scopedReceiveRight(name:name) + let zero = refCountForMachPortName(name:name, kind: MACH_PORT_RIGHT_RECEIVE) + + XCTAssert(one == 1); + XCTAssert(zero == 0); + } + + func consumeSendRightAutomatically(name:mach_port_name_t) -> mach_port_urefs_t { + let send = Mach.Port(name:name) // this should automatically deallocate when going out of scope + return send.withBorrowedName { name in + // Get the ref count before automatic deallocation happens + return refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) + } + } + + func testSendRightDeallocation() throws { + 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) + let one = consumeSendRightAutomatically(name:name) + XCTAssert(one == 1); + let zero = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) + XCTAssert(zero == 0); + } + } + + func testSendRightRelinquishment() throws { + let recv = Mach.Port() + + let name = ({ + let send = recv.makeSendRight() + let one = send.withBorrowedName { name in + return self.refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) + } + XCTAssert(one == 1) + + return send.relinquish() + })() + + let stillOne = refCountForMachPortName(name:name, kind:MACH_PORT_RIGHT_SEND) + XCTAssert(stillOne == 1) + } + + func testMakeSendCountSettable() throws { + var recv = Mach.Port() + XCTAssert(recv.makeSendCount == 0) + recv.makeSendCount = 7 + XCTAssert(recv.makeSendCount == 7) + } + + func makeSendRight() throws -> Mach.Port { + let recv = Mach.Port() + let zero = recv.makeSendCount + XCTAssert(zero == 0) + let send = recv.makeSendRight() + let one = recv.makeSendCount + XCTAssert(one == 1) + return send + } + + func testMakeSendCountIncrement() throws { + _ = try makeSendRight() + } + + func testMakeSendOnceDoesntIncrementMakeSendCount() throws { + let recv = Mach.Port() + let zero = recv.makeSendCount + XCTAssert(zero == 0) + _ = recv.makeSendOnceRight() + let same = recv.makeSendCount + XCTAssert(same == zero) + } + + func testMakePair() throws { + let (recv, send) = Mach.allocatePortRightPair() + XCTAssert(recv.makeSendCount == 1) + recv.withBorrowedName { rName in + send.withBorrowedName { sName in + XCTAssert(rName != 0xFFFFFFFF) + XCTAssert(rName != MACH_PORT_NULL) + // send and recv port names coalesce + XCTAssert(rName == sName) + } + } + } + + func testCopySend() throws { + let recv = Mach.Port() + let zero = recv.makeSendCount + XCTAssert(zero == 0) + let send = recv.makeSendRight() + let one = recv.makeSendCount + XCTAssert(one == 1) + _ = try send.copySendRight() + let same = recv.makeSendCount + XCTAssert(same == one) + + } +} + +#endif From c2d940ecf39e011784ec462ab39755701e3b3449 Mon Sep 17 00:00:00 2001 From: loffgren <117697138+loffgren@users.noreply.github.com> Date: Mon, 19 Dec 2022 16:41:33 -0800 Subject: [PATCH 02/15] Remove parens around RightType condition in initializer Co-authored-by: Matt Wright --- 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 dcd9831..1301303 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -35,7 +35,7 @@ enum Mach { assert(name != mach_port_name_t(MACH_PORT_NULL)) self.name = name - if (RightType.self == ReceiveRight.self) { + if RightType.self == ReceiveRight.self { let secret = mach_port_context_t(arc4random()) let kr = mach_port_guard(mach_task_self_, name, secret, 0) assert(kr == KERN_SUCCESS) From bdc776bd3e1752358876d70b739a6c2791773ca2 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Mon, 19 Dec 2022 17:14:53 -0800 Subject: [PATCH 03/15] Correct parameter whitespace --- Sources/System/MachPort.swift | 36 +++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 1301303..2fe2168 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -15,9 +15,9 @@ protocol MachPortRight {} enum Mach { @_moveOnly - struct Port { - internal var name:mach_port_name_t - internal var context:mach_port_context_t + struct Port { + internal var name: mach_port_name_t + internal var context: mach_port_context_t /// Transfer ownership of an existing unmanaged Mach port right into a /// Mach.Port by name. @@ -31,7 +31,7 @@ enum Mach { /// end of the Mach.Port instance's lifetime. /// /// This initializer makes a syscall to guard the right. - init(name:mach_port_name_t) { + init(name: mach_port_name_t) { assert(name != mach_port_name_t(MACH_PORT_NULL)) self.name = name @@ -56,7 +56,7 @@ enum Mach { /// /// The body block may optionally return something, which will then be /// returned to the caller of withBorrowedName. - func withBorrowedName(body:(mach_port_name_t) -> ReturnType) -> ReturnType { + func withBorrowedName(body: (mach_port_name_t) -> ReturnType) -> ReturnType { return body(name) } @@ -129,7 +129,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// /// The underlying port right will be automatically deallocated when /// the Mach.Port object is destroyed. - init(name:mach_port_name_t, context:mach_port_context_t) { + init(name: mach_port_name_t, context: mach_port_context_t) { self.name = name self.context = context } @@ -140,14 +140,14 @@ 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. init() { - var storage:mach_port_name_t = 0 - withUnsafeMutablePointer(to:&storage) { storage in + var storage: mach_port_name_t = 0 + withUnsafeMutablePointer(to: &storage) { storage in let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage) assert(kr == KERN_SUCCESS) } // name-only init will guard ReceiveRights - self.init(name:storage) + self.init(name: storage) } @@ -194,7 +194,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. - func withBorrowedName(body:(mach_port_name_t, mach_port_context_t) -> ReturnType) -> ReturnType { + func withBorrowedName(body: (mach_port_name_t, mach_port_context_t) -> ReturnType) -> ReturnType { body(name, context) } @@ -206,9 +206,9 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// Callers may assert that a valid right is always returned. func makeSendOnceRight() -> Mach.Port { // send once rights do not coalesce - var kr:kern_return_t = KERN_FAILURE - var newRight:mach_port_name_t = mach_port_name_t(MACH_PORT_NULL) - var newRightType:mach_port_type_t = MACH_PORT_TYPE_NONE + var kr: kern_return_t = KERN_FAILURE + 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 @@ -221,7 +221,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { assert(kr == KERN_SUCCESS) assert(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) - return Mach.Port(name:newRight) + return Mach.Port(name: newRight) } /// Create a send right for a given receive right. @@ -237,7 +237,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(how)) assert(kr == KERN_SUCCESS) - return Mach.Port(name:name) + return Mach.Port(name: name) } /// Access the make-send count. @@ -245,8 +245,8 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// Each get/set of this property makes a syscall. 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) + var status: mach_port_status = mach_port_status() + var size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout.size) withUnsafeMutablePointer(to: &size) { size in withUnsafeMutablePointer(to: &status) { status in let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1) @@ -295,7 +295,7 @@ extension Mach.Port where RightType == Mach.SendRight { } assert(kr == KERN_SUCCESS) - return Mach.Port(name:name) + return Mach.Port(name: name) } } From 4536c4776325a4f41aa2a8fa3724cccffd432a77 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Tue, 20 Dec 2022 12:51:07 -0800 Subject: [PATCH 04/15] Use precondition instead of assert, adding a machPrecondition for the common KERN_SUCCESS check --- Sources/System/MachPort.swift | 61 ++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 2fe2168..bc89663 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -13,6 +13,16 @@ import Darwin.Mach protocol MachPortRight {} +private func machPrecondition( + file: StaticString = #file, + line: UInt = #line, + _ body: @autoclosure () -> kern_return_t +) { + let kr = body() + let expected = KERN_SUCCESS + precondition(kr == expected, file: file, line: line) +} + enum Mach { @_moveOnly struct Port { @@ -32,13 +42,12 @@ enum Mach { /// /// This initializer makes a syscall to guard the right. init(name: mach_port_name_t) { - assert(name != mach_port_name_t(MACH_PORT_NULL)) + precondition(name != mach_port_name_t(MACH_PORT_NULL)) self.name = name if RightType.self == ReceiveRight.self { let secret = mach_port_context_t(arc4random()) - let kr = mach_port_guard(mach_task_self_, name, secret, 0) - assert(kr == KERN_SUCCESS) + machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0)) self.context = secret } else { @@ -64,13 +73,10 @@ enum Mach { if name != 0xFFFFFFFF /* MACH_PORT_DEAD */ { if RightType.self == ReceiveRight.self { // recv rights must be mod ref'ed instead of deallocated - let kr = mach_port_unguard(mach_task_self_, name, context) - assert(kr == KERN_SUCCESS) - - let kr2 = mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_RECEIVE, -1) - assert(kr2 == KERN_SUCCESS) + machPrecondition(mach_port_unguard(mach_task_self_, name, context)) + machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_RECEIVE, -1)) } else { - mach_port_deallocate(mach_task_self_, name) + machPrecondition(mach_port_deallocate(mach_task_self_, name)) } } } @@ -110,8 +116,7 @@ enum Mach { var options = mach_port_options_t() options.flags = UInt32(MPO_INSERT_SEND_RIGHT); withUnsafeMutablePointer(to: &options) { options in - let kr = mach_port_construct(mach_task_self_, options, secret, name) - assert(kr == KERN_SUCCESS) + machPrecondition(mach_port_construct(mach_task_self_, options, secret, name)) } } return (Mach.Port(name: name, context: secret), Mach.Port(name: name)) @@ -142,8 +147,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { init() { var storage: mach_port_name_t = 0 withUnsafeMutablePointer(to: &storage) { storage in - let kr = mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage) - assert(kr == KERN_SUCCESS) + machPrecondition(mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, storage)) } // name-only init will guard ReceiveRights @@ -180,8 +184,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. __consuming func unguardAndRelinquish() -> mach_port_name_t { - let kr = mach_port_unguard(mach_task_self_, name, context); - assert(kr == KERN_SUCCESS) + machPrecondition(mach_port_unguard(mach_task_self_, name, context)) return name } @@ -206,20 +209,23 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// Callers may assert that a valid right is always returned. func makeSendOnceRight() -> Mach.Port { // send once rights do not coalesce - var kr: kern_return_t = KERN_FAILURE 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 - kr = 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 - assert(kr == KERN_SUCCESS) - assert(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) + precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) return Mach.Port(name: newRight) } @@ -233,9 +239,8 @@ extension Mach.Port where RightType == Mach.ReceiveRight { func makeSendRight() -> Mach.Port { let how = MACH_MSG_TYPE_MAKE_SEND - // send and recv rights are coalesced - let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(how)) - assert(kr == KERN_SUCCESS) + // 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))) return Mach.Port(name: name) } @@ -250,16 +255,14 @@ extension Mach.Port where RightType == Mach.ReceiveRight { withUnsafeMutablePointer(to: &size) { size in withUnsafeMutablePointer(to: &status) { status in let info = UnsafeMutableRawPointer(status).bindMemory(to: integer_t.self, capacity: 1) - let kr = mach_port_get_attributes(mach_task_self_, name, MACH_PORT_RECEIVE_STATUS, info, size) - assert(kr == KERN_SUCCESS); + machPrecondition(mach_port_get_attributes(mach_task_self_, name, MACH_PORT_RECEIVE_STATUS, info, size)) } } return status.mps_mscount } set { - let kr = mach_port_set_mscount(mach_task_self_, name, newValue) - assert(kr == KERN_SUCCESS) + machPrecondition(mach_port_set_mscount(mach_task_self_, name, newValue)) } } } @@ -288,12 +291,12 @@ extension Mach.Port where RightType == Mach.SendRight { func copySendRight() throws -> Mach.Port { let how = MACH_MSG_TYPE_COPY_SEND - // send rights are coalesced + // 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 { throw Mach.PortRightError.deadName } - assert(kr == KERN_SUCCESS) + machPrecondition(kr) return Mach.Port(name: name) } From bd036acda642174bc322eee9471d5f7a4d27ece7 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Tue, 20 Dec 2022 12:56:45 -0800 Subject: [PATCH 05/15] Storage should be initialized to MACH_PORT_NULL, rather than 0 --- 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 bc89663..be02c98 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -145,7 +145,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. init() { - var storage: mach_port_name_t = 0 + 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)) } From 213165ab72af039d38e3654432a864e456e54e8f Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Tue, 20 Dec 2022 13:02:18 -0800 Subject: [PATCH 06/15] size should be the number of natural_t's --- 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 be02c98..cf5ca1b 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -251,7 +251,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { 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) + 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) From 296374ecef32aa2fd27cd6fd57a4c62aaf733d07 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 21 Dec 2022 11:46:06 -0800 Subject: [PATCH 07/15] Label tuple contents for allocatePortPair() and relinquish() --- Sources/System/MachPort.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index cf5ca1b..a2cbe50 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -109,7 +109,7 @@ enum Mach { /// /// This function will abort if the rights could not be created. /// Callers may assert that valid rights are always returned. - static func allocatePortRightPair() -> (Mach.Port, Mach.Port) { + static func allocatePortRightPair() -> (receive: Mach.Port, send: Mach.Port) { var name = mach_port_name_t(MACH_PORT_NULL) let secret = mach_port_context_t(arc4random()) withUnsafeMutablePointer(to: &name) { name in @@ -165,8 +165,8 @@ extension Mach.Port where RightType == Mach.ReceiveRight { /// /// After this function completes, the Mach.Port is destroyed and no longer /// usable. - __consuming func relinquish() -> (mach_port_name_t, mach_port_context_t) { - return (name, context) + __consuming func relinquish() -> (name: mach_port_name_t, context: mach_port_context_t) { + return (name: name, context: context) } /// Remove guard and transfer ownership of the underlying port right to From 551d7b897f7dd2d76429ee8aad4a006ecd1e069d Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 21 Dec 2022 12:49:30 -0800 Subject: [PATCH 08/15] Use mach_port_destruct() to deinit receive rights eliminating the second syscall, and use mach_port_mod_refs() for all other right types to get a free type check at deinit time mach_port_mod_refs() requires the type of right being modified. So, MACH_PORT_DEAD must be identified as a separate type. As this is something that shouldn't be possible for receive rights, preconditions have also been added to protect against this particular error. --- Sources/System/MachPort.swift | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index a2cbe50..da7122c 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -32,7 +32,8 @@ enum Mach { /// Transfer ownership of an existing unmanaged Mach port right into a /// Mach.Port by name. /// - /// This initializer aborts if name is MACH_PORT_NULL. + /// This initializer aborts if name is MACH_PORT_NULL, or if name is + /// MACH_PORT_DEAD and the type T of Mach.Port is Mach.ReceiveRight. /// /// If the type of the right does not match the type T of Mach.Port /// being constructed, behavior is undefined. @@ -46,6 +47,8 @@ enum Mach { self.name = name if RightType.self == ReceiveRight.self { + 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)) self.context = secret @@ -70,13 +73,16 @@ enum Mach { } deinit { - if name != 0xFFFFFFFF /* MACH_PORT_DEAD */ { + 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)) + } else { if RightType.self == ReceiveRight.self { - // recv rights must be mod ref'ed instead of deallocated - machPrecondition(mach_port_unguard(mach_task_self_, name, context)) - machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_RECEIVE, -1)) - } else { - machPrecondition(mach_port_deallocate(mach_task_self_, name)) + machPrecondition(mach_port_destruct(mach_task_self_, name, -1, context)) + } else if RightType.self == SendRight.self { + machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_SEND, -1)) + } else if RightType.self == SendOnceRight.self { + machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_SEND_ONCE, -1)) } } } From 6dd57fe3a9f9238394683b5e25cb7632d645bf1c Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 21 Dec 2022 12:57:25 -0800 Subject: [PATCH 09/15] Add a friendly precondition message for the MACH_PORT_NULL check --- 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 da7122c..4ba16e9 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -43,7 +43,7 @@ enum Mach { /// /// This initializer makes a syscall to guard the right. init(name: mach_port_name_t) { - precondition(name != mach_port_name_t(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 { From 7f4560f02245027ec729fbabd1d7033baad206a8 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 21 Dec 2022 13:12:13 -0800 Subject: [PATCH 10/15] Remove unnecessary RightTypes for Mach.Ports being constructed inline with a return --- Sources/System/MachPort.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 4ba16e9..090067b 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -125,7 +125,7 @@ enum Mach { machPrecondition(mach_port_construct(mach_task_self_, options, secret, name)) } } - return (Mach.Port(name: name, context: secret), Mach.Port(name: name)) + return (Mach.Port(name: name, context: secret), Mach.Port(name: name)) } } @@ -233,7 +233,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { // The value of newRight is validated by the Mach.Port initializer precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) - return Mach.Port(name: newRight) + return Mach.Port(name: newRight) } /// Create a send right for a given receive right. @@ -248,7 +248,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { // 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))) - return Mach.Port(name: name) + return Mach.Port(name: name) } /// Access the make-send count. @@ -304,7 +304,7 @@ extension Mach.Port where RightType == Mach.SendRight { } machPrecondition(kr) - return Mach.Port(name: name) + return Mach.Port(name: name) } } From 6a9ebce25967fd856847af8f0c3c5a81034b1563 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 21 Dec 2022 13:20:38 -0800 Subject: [PATCH 11/15] Add public annotations where applicable --- Sources/System/MachPort.swift | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 090067b..bb32e14 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -11,7 +11,7 @@ import Darwin.Mach -protocol MachPortRight {} +public protocol MachPortRight {} private func machPrecondition( file: StaticString = #file, @@ -23,9 +23,9 @@ private func machPrecondition( precondition(kr == expected, file: file, line: line) } -enum Mach { +public enum Mach { @_moveOnly - struct Port { + public struct Port { internal var name: mach_port_name_t internal var context: mach_port_context_t @@ -42,7 +42,7 @@ enum Mach { /// end of the Mach.Port instance's lifetime. /// /// This initializer makes a syscall to guard the right. - init(name: mach_port_name_t) { + 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") self.name = name @@ -68,7 +68,7 @@ enum Mach { /// /// The body block may optionally return something, which will then be /// returned to the caller of withBorrowedName. - func withBorrowedName(body: (mach_port_name_t) -> ReturnType) -> ReturnType { + public func withBorrowedName(body: (mach_port_name_t) -> ReturnType) -> ReturnType { return body(name) } @@ -89,7 +89,7 @@ enum Mach { } /// Possible errors that can be thrown by Mach.Port operations. - enum PortRightError : Error { + public enum PortRightError : Error { /// Returned when an operation cannot be completed, because the Mach /// port right has become a dead name. This is caused by deallocation of the /// receive right on the other end. @@ -97,10 +97,10 @@ enum Mach { } /// The MachPortRight type used to manage a receive right. - struct ReceiveRight : MachPortRight {} + public struct ReceiveRight : MachPortRight {} /// The MachPortRight type used to manage a send right. - struct SendRight : MachPortRight {} + public struct SendRight : MachPortRight {} /// The MachPortRight type used to manage a send-once right. /// @@ -109,13 +109,13 @@ enum Mach { /// /// Upon destruction a send-once notification will be sent to the /// receiving end. - struct SendOnceRight : MachPortRight {} + public struct SendOnceRight : MachPortRight {} /// Create a connected pair of rights, one receive, and one send. /// /// This function will abort if the rights could not be created. /// Callers may assert that valid rights are always returned. - static func allocatePortRightPair() -> (receive: Mach.Port, send: Mach.Port) { + public static func allocatePortRightPair() -> (receive: Mach.Port, send: Mach.Port) { var name = mach_port_name_t(MACH_PORT_NULL) let secret = mach_port_context_t(arc4random()) withUnsafeMutablePointer(to: &name) { name in @@ -129,7 +129,7 @@ enum Mach { } } -extension Mach.Port where RightType == Mach.ReceiveRight { +public 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. /// @@ -273,7 +273,7 @@ extension Mach.Port where RightType == Mach.ReceiveRight { } } -extension Mach.Port where RightType == Mach.SendRight { +public extension Mach.Port where RightType == Mach.SendRight { /// Transfer ownership of the underlying port right to the caller. /// /// Returns the Mach port name representing the right. @@ -309,7 +309,7 @@ extension Mach.Port where RightType == Mach.SendRight { } -extension Mach.Port where RightType == Mach.SendOnceRight { +public extension Mach.Port where RightType == Mach.SendOnceRight { /// Transfer ownership of the underlying port right to the caller. /// /// Returns the Mach port name representing the right. From 47feb93a38cc69af60411392977ac30e53fe7cf7 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Wed, 21 Dec 2022 13:43:26 -0800 Subject: [PATCH 12/15] Add a test that ensures makeSendOnce is creating unique send-once rights --- Tests/SystemTests/MachPortTests.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Tests/SystemTests/MachPortTests.swift b/Tests/SystemTests/MachPortTests.swift index 0def85a..7faa976 100644 --- a/Tests/SystemTests/MachPortTests.swift +++ b/Tests/SystemTests/MachPortTests.swift @@ -110,6 +110,17 @@ final class MachPortTests: XCTestCase { XCTAssert(same == zero) } + func testMakeSendOnceIsUnique() throws { + let recv = Mach.Port() + let once = recv.makeSendOnceRight() + recv.withBorrowedName { rname in + once.withBorrowedName { oname in + print(oname, rname) + XCTAssert(oname != rname) + } + } + } + func testMakePair() throws { let (recv, send) = Mach.allocatePortRightPair() XCTAssert(recv.makeSendCount == 1) From ae6b1f24a99bfe07bc06c7c50a3aeadc3766be51 Mon Sep 17 00:00:00 2001 From: loffgren <117697138+loffgren@users.noreply.github.com> Date: Thu, 22 Dec 2022 14:52:36 -0800 Subject: [PATCH 13/15] Remove space before inheritance colon Co-authored-by: Michael Ilseman --- Sources/System/MachPort.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index bb32e14..0d8794d 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -97,10 +97,10 @@ public enum Mach { } /// The MachPortRight type used to manage a receive right. - public struct ReceiveRight : MachPortRight {} + public struct ReceiveRight: MachPortRight {} /// The MachPortRight type used to manage a send right. - public struct SendRight : MachPortRight {} + public struct SendRight: MachPortRight {} /// The MachPortRight type used to manage a send-once right. /// @@ -109,7 +109,7 @@ public enum Mach { /// /// Upon destruction a send-once notification will be sent to the /// receiving end. - public struct SendOnceRight : MachPortRight {} + public struct SendOnceRight: MachPortRight {} /// Create a connected pair of rights, one receive, and one send. /// From d129f62ce91766c5b1fe50ba391a27c5deb9a401 Mon Sep 17 00:00:00 2001 From: loffgren <117697138+loffgren@users.noreply.github.com> Date: Thu, 22 Dec 2022 17:12:26 -0800 Subject: [PATCH 14/15] Use Markdown code voice for initializer comment Co-authored-by: Karoy Lorentey --- Sources/System/MachPort.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 0d8794d..4d225a1 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -30,16 +30,16 @@ public enum Mach { internal var context: mach_port_context_t /// Transfer ownership of an existing unmanaged Mach port right into a - /// Mach.Port by name. + /// `Mach.Port` by name. /// - /// This initializer aborts if name is MACH_PORT_NULL, or if name is - /// MACH_PORT_DEAD and the type T of Mach.Port is Mach.ReceiveRight. + /// This initializer traps if `name` is `MACH_PORT_NULL`, or if `name` is + /// `MACH_PORT_DEAD` and the `RightType` is `Mach.ReceiveRight`. /// - /// If the type of the right does not match the type T of Mach.Port - /// being constructed, behavior is undefined. + /// If the type of the right does not match the `RightType` of the + /// `Mach.Port` being constructed, behavior is undefined. /// /// The underlying port right will be automatically deallocated at the - /// end of the Mach.Port instance's lifetime. + /// end of the `Mach.Port` instance's lifetime. /// /// This initializer makes a syscall to guard the right. public init(name: mach_port_name_t) { From 700b8f867e9fd1c4ffe07e318fd56ccf20560f21 Mon Sep 17 00:00:00 2001 From: Daniel Loffgren Date: Thu, 22 Dec 2022 18:01:40 -0800 Subject: [PATCH 15/15] Use two space indentation --- Sources/System/MachPort.swift | 534 +++++++++++++++++----------------- 1 file changed, 267 insertions(+), 267 deletions(-) diff --git a/Sources/System/MachPort.swift b/Sources/System/MachPort.swift index 4d225a1..8e7f8cf 100644 --- a/Sources/System/MachPort.swift +++ b/Sources/System/MachPort.swift @@ -14,314 +14,314 @@ import Darwin.Mach public protocol MachPortRight {} private func machPrecondition( - file: StaticString = #file, - line: UInt = #line, - _ body: @autoclosure () -> kern_return_t + file: StaticString = #file, + line: UInt = #line, + _ body: @autoclosure () -> kern_return_t ) { - let kr = body() - let expected = KERN_SUCCESS - precondition(kr == expected, file: file, line: line) + let kr = body() + let expected = KERN_SUCCESS + precondition(kr == expected, file: file, line: line) } public enum Mach { - @_moveOnly - public struct Port { - internal var name: mach_port_name_t - internal var context: mach_port_context_t + @_moveOnly + public struct Port { + internal var name: mach_port_name_t + internal var context: mach_port_context_t - /// Transfer ownership of an existing unmanaged Mach port right into a - /// `Mach.Port` by name. - /// - /// This initializer traps if `name` is `MACH_PORT_NULL`, or if `name` is - /// `MACH_PORT_DEAD` and the `RightType` is `Mach.ReceiveRight`. - /// - /// If the type of the right does not match the `RightType` of the - /// `Mach.Port` being constructed, behavior is undefined. - /// - /// The underlying port right will be automatically deallocated at the - /// end of the `Mach.Port` instance's lifetime. - /// - /// 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") - self.name = name - - if RightType.self == ReceiveRight.self { - 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)) - self.context = secret - } - else { - self.context = 0 - } - } - - /// Borrow access to the port name in a block that can perform - /// non-consuming operations. - /// - /// Take care when using this function; many operations consume rights, - /// and send-once rights are easily consumed. - /// - /// If the right is consumed, behavior is undefined. - /// - /// The body block may optionally return something, which will then be - /// returned to the caller of withBorrowedName. - public func withBorrowedName(body: (mach_port_name_t) -> ReturnType) -> ReturnType { - return body(name) - } - - 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)) - } else { - if RightType.self == ReceiveRight.self { - machPrecondition(mach_port_destruct(mach_task_self_, name, -1, context)) - } else if RightType.self == SendRight.self { - machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_SEND, -1)) - } else if RightType.self == SendOnceRight.self { - machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_SEND_ONCE, -1)) - } - } - } - } - - /// Possible errors that can be thrown by Mach.Port operations. - public enum PortRightError : Error { - /// Returned when an operation cannot be completed, because the Mach - /// port right has become a dead name. This is caused by deallocation of the - /// receive right on the other end. - case deadName - } - - /// The MachPortRight type used to manage a receive right. - public struct ReceiveRight: MachPortRight {} - - /// The MachPortRight type used to manage a send right. - public struct SendRight: MachPortRight {} - - /// The MachPortRight type used to manage a send-once right. + /// Transfer ownership of an existing unmanaged Mach port right into a + /// `Mach.Port` by name. /// - /// Send-once rights are the most restrictive type of Mach port rights. - /// They cannot create other rights, and are consumed upon use. + /// This initializer traps if `name` is `MACH_PORT_NULL`, or if `name` is + /// `MACH_PORT_DEAD` and the `RightType` is `Mach.ReceiveRight`. /// - /// Upon destruction a send-once notification will be sent to the - /// receiving end. - public struct SendOnceRight: MachPortRight {} + /// If the type of the right does not match the `RightType` of the + /// `Mach.Port` being constructed, behavior is undefined. + /// + /// The underlying port right will be automatically deallocated at the + /// end of the `Mach.Port` instance's lifetime. + /// + /// 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") + self.name = name + + if RightType.self == ReceiveRight.self { + precondition(name != 0xFFFFFFFF /* MACH_PORT_DEAD */, "Receive rights cannot be dead names") - /// Create a connected pair of rights, one receive, and one send. - /// - /// This function will abort if the rights could not be created. - /// Callers may assert that valid rights are always returned. - public static func allocatePortRightPair() -> (receive: Mach.Port, send: Mach.Port) { - var name = mach_port_name_t(MACH_PORT_NULL) let secret = mach_port_context_t(arc4random()) - withUnsafeMutablePointer(to: &name) { name in - var options = mach_port_options_t() - options.flags = UInt32(MPO_INSERT_SEND_RIGHT); - withUnsafeMutablePointer(to: &options) { options in - machPrecondition(mach_port_construct(mach_task_self_, options, secret, name)) - } - } - return (Mach.Port(name: name, context: secret), Mach.Port(name: name)) - } -} - -public 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. - /// - /// This initializer aborts if name is MACH_PORT_NULL. - /// - /// If the type of the right does not match the type T of Mach.Port - /// being constructed, the behavior is undefined. - /// - /// The underlying port right will be automatically deallocated when - /// the Mach.Port object is destroyed. - init(name: mach_port_name_t, context: mach_port_context_t) { - self.name = name - self.context = context - } - - /// Allocate a new Mach port with a receive right, creating a - /// Mach.Port to manage it. - /// - /// This initializer will abort if the right could not be created. - /// Callers may assert that a valid right is always returned. - 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)) - } - - // name-only init will guard ReceiveRights - self.init(name: storage) - } - - - /// Transfer ownership of the underlying port right to the caller. - /// - /// Returns a tuple containing the Mach port name representing the right, - /// and the context value used to guard the right. - /// - /// This operation liberates the right from management by the Mach.Port, - /// and the underlying right will no longer be automatically deallocated. - /// - /// After this function completes, the Mach.Port is destroyed and no longer - /// usable. - __consuming func relinquish() -> (name: mach_port_name_t, context: mach_port_context_t) { - return (name: name, context: context) - } - - /// Remove guard and transfer ownership of the underlying port right to - /// the caller. - /// - /// Returns the Mach port name representing the right. - /// - /// This operation liberates the right from management by the Mach.Port, - /// and the underlying right will no longer be automatically deallocated. - /// - /// After this function completes, the Mach.Port is destroyed and no longer - /// usable. - /// - /// This function makes a syscall to remove the guard from - /// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract - /// the context value along with the port name. - __consuming func unguardAndRelinquish() -> mach_port_name_t { - machPrecondition(mach_port_unguard(mach_task_self_, name, context)) - return name + machPrecondition(mach_port_guard(mach_task_self_, name, secret, 0)) + self.context = secret + } + else { + self.context = 0 + } } /// Borrow access to the port name in a block that can perform /// non-consuming operations. /// - /// Take care when using this function; many operations consume rights. + /// Take care when using this function; many operations consume rights, + /// and send-once rights are easily consumed. /// /// If the right is consumed, behavior is undefined. /// /// The body block may optionally return something, which will then be /// returned to the caller of withBorrowedName. - func withBorrowedName(body: (mach_port_name_t, mach_port_context_t) -> ReturnType) -> ReturnType { - body(name, context) + public func withBorrowedName(body: (mach_port_name_t) -> ReturnType) -> ReturnType { + return body(name) } - /// Create a send-once right for a given receive right. - /// - /// This does not affect the makeSendCount of the receive right. - /// - /// This function will abort if the right could not be created. - /// Callers may assert that a valid right is always returned. - func makeSendOnceRight() -> Mach.Port { - // send once rights do not coalesce - var newRight: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL) - var newRightType: mach_port_type_t = MACH_PORT_TYPE_NONE - - withUnsafeMutablePointer(to: &newRight) { newRight in - withUnsafeMutablePointer(to: &newRightType) { newRightType in - machPrecondition( - mach_port_extract_right(mach_task_self_, - name, - mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE), - newRight, - newRightType) - ) - } + 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)) + } else { + if RightType.self == ReceiveRight.self { + machPrecondition(mach_port_destruct(mach_task_self_, name, -1, context)) + } else if RightType.self == SendRight.self { + machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_SEND, -1)) + } else if RightType.self == SendOnceRight.self { + machPrecondition(mach_port_mod_refs(mach_task_self_, name, MACH_PORT_RIGHT_SEND_ONCE, -1)) } + } + } + } - // The value of newRight is validated by the Mach.Port initializer - precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) + /// Possible errors that can be thrown by Mach.Port operations. + public enum PortRightError : Error { + /// Returned when an operation cannot be completed, because the Mach + /// port right has become a dead name. This is caused by deallocation of the + /// receive right on the other end. + case deadName + } - return Mach.Port(name: newRight) + /// The MachPortRight type used to manage a receive right. + public struct ReceiveRight: MachPortRight {} + + /// The MachPortRight type used to manage a send right. + public struct SendRight: MachPortRight {} + + /// The MachPortRight type used to manage a send-once right. + /// + /// Send-once rights are the most restrictive type of Mach port rights. + /// They cannot create other rights, and are consumed upon use. + /// + /// Upon destruction a send-once notification will be sent to the + /// receiving end. + public struct SendOnceRight: MachPortRight {} + + /// Create a connected pair of rights, one receive, and one send. + /// + /// This function will abort if the rights could not be created. + /// Callers may assert that valid rights are always returned. + public static func allocatePortRightPair() -> (receive: Mach.Port, send: Mach.Port) { + var name = mach_port_name_t(MACH_PORT_NULL) + let secret = mach_port_context_t(arc4random()) + withUnsafeMutablePointer(to: &name) { name in + var options = mach_port_options_t() + options.flags = UInt32(MPO_INSERT_SEND_RIGHT); + withUnsafeMutablePointer(to: &options) { options in + machPrecondition(mach_port_construct(mach_task_self_, options, secret, name)) + } + } + return (Mach.Port(name: name, context: secret), Mach.Port(name: name)) + } +} + +public 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. + /// + /// This initializer aborts if name is MACH_PORT_NULL. + /// + /// If the type of the right does not match the type T of Mach.Port + /// being constructed, the behavior is undefined. + /// + /// The underlying port right will be automatically deallocated when + /// the Mach.Port object is destroyed. + init(name: mach_port_name_t, context: mach_port_context_t) { + self.name = name + self.context = context + } + + /// Allocate a new Mach port with a receive right, creating a + /// Mach.Port to manage it. + /// + /// This initializer will abort if the right could not be created. + /// Callers may assert that a valid right is always returned. + 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)) } - /// Create a send right for a given receive right. - /// - /// This increments the makeSendCount of the receive right. - /// - /// This function will abort if the right could not be created. - /// Callers may assert that a valid right is always returned. - func makeSendRight() -> Mach.Port { - let how = MACH_MSG_TYPE_MAKE_SEND + // name-only init will guard ReceiveRights + self.init(name: storage) + } - // 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))) - return Mach.Port(name: name) + /// Transfer ownership of the underlying port right to the caller. + /// + /// Returns a tuple containing the Mach port name representing the right, + /// and the context value used to guard the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + __consuming func relinquish() -> (name: mach_port_name_t, context: mach_port_context_t) { + return (name: name, context: context) + } + + /// Remove guard and transfer ownership of the underlying port right to + /// the caller. + /// + /// Returns the Mach port name representing the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + /// + /// This function makes a syscall to remove the guard from + /// Mach.ReceiveRights. Use relinquish() to avoid the syscall and extract + /// the context value along with the port name. + __consuming func unguardAndRelinquish() -> mach_port_name_t { + machPrecondition(mach_port_unguard(mach_task_self_, name, context)) + return name + } + + /// Borrow access to the port name in a block that can perform + /// non-consuming operations. + /// + /// Take care when using this function; many operations consume rights. + /// + /// If the right is consumed, behavior is undefined. + /// + /// The body block may optionally return something, which will then be + /// returned to the caller of withBorrowedName. + func withBorrowedName(body: (mach_port_name_t, mach_port_context_t) -> ReturnType) -> ReturnType { + body(name, context) + } + + /// Create a send-once right for a given receive right. + /// + /// This does not affect the makeSendCount of the receive right. + /// + /// This function will abort if the right could not be created. + /// Callers may assert that a valid right is always returned. + func makeSendOnceRight() -> Mach.Port { + // send once rights do not coalesce + var newRight: mach_port_name_t = mach_port_name_t(MACH_PORT_NULL) + var newRightType: mach_port_type_t = MACH_PORT_TYPE_NONE + + withUnsafeMutablePointer(to: &newRight) { newRight in + withUnsafeMutablePointer(to: &newRightType) { newRightType in + machPrecondition( + mach_port_extract_right(mach_task_self_, + name, + mach_msg_type_name_t(MACH_MSG_TYPE_MAKE_SEND_ONCE), + newRight, + newRightType) + ) + } } - /// Access the make-send count. - /// - /// Each get/set of this property makes a syscall. - 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)) - } - } - return status.mps_mscount - } - - set { - machPrecondition(mach_port_set_mscount(mach_task_self_, name, newValue)) + // The value of newRight is validated by the Mach.Port initializer + precondition(newRightType == MACH_MSG_TYPE_MOVE_SEND_ONCE) + + return Mach.Port(name: newRight) + } + + /// Create a send right for a given receive right. + /// + /// This increments the makeSendCount of the receive right. + /// + /// This function will abort if the right could not be created. + /// Callers may assert that a valid right is always returned. + func makeSendRight() -> Mach.Port { + let how = MACH_MSG_TYPE_MAKE_SEND + + // name is the same because send and recv rights are coalesced + machPrecondition(mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(how))) + + return Mach.Port(name: name) + } + + /// Access the make-send count. + /// + /// Each get/set of this property makes a syscall. + 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)) } + } + return status.mps_mscount } + + set { + machPrecondition(mach_port_set_mscount(mach_task_self_, name, newValue)) + } + } } public extension Mach.Port where RightType == Mach.SendRight { - /// Transfer ownership of the underlying port right to the caller. - /// - /// Returns the Mach port name representing the right. - /// - /// This operation liberates the right from management by the Mach.Port, - /// and the underlying right will no longer be automatically deallocated. - /// - /// After this function completes, the Mach.Port is destroyed and no longer - /// usable. - __consuming func relinquish() -> mach_port_name_t { - return name + /// Transfer ownership of the underlying port right to the caller. + /// + /// Returns the Mach port name representing the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + __consuming func relinquish() -> mach_port_name_t { + return name + } + + /// Create another send right from a given send right. + /// + /// This does not affect the makeSendCount of the receive right. + /// + /// If the send right being copied has become a dead name, meaning the + /// receiving side has been deallocated, then copySendRight() will throw + /// a Mach.PortRightError.deadName error. + func copySendRight() throws -> Mach.Port { + let how = MACH_MSG_TYPE_COPY_SEND + + // name is the same because send rights are coalesced + let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(how)) + if kr == KERN_INVALID_CAPABILITY { + throw Mach.PortRightError.deadName } + machPrecondition(kr) - /// Create another send right from a given send right. - /// - /// This does not affect the makeSendCount of the receive right. - /// - /// If the send right being copied has become a dead name, meaning the - /// receiving side has been deallocated, then copySendRight() will throw - /// a Mach.PortRightError.deadName error. - func copySendRight() throws -> Mach.Port { - let how = MACH_MSG_TYPE_COPY_SEND - - // name is the same because send rights are coalesced - let kr = mach_port_insert_right(mach_task_self_, name, name, mach_msg_type_name_t(how)) - if kr == KERN_INVALID_CAPABILITY { - throw Mach.PortRightError.deadName - } - machPrecondition(kr) - - return Mach.Port(name: name) - } + return Mach.Port(name: name) + } } public extension Mach.Port where RightType == Mach.SendOnceRight { - /// Transfer ownership of the underlying port right to the caller. - /// - /// Returns the Mach port name representing the right. - /// - /// This operation liberates the right from management by the Mach.Port, - /// and the underlying right will no longer be automatically deallocated. - /// - /// After this function completes, the Mach.Port is destroyed and no longer - /// usable. - __consuming func relinquish() -> mach_port_name_t { - return name - } + /// Transfer ownership of the underlying port right to the caller. + /// + /// Returns the Mach port name representing the right. + /// + /// This operation liberates the right from management by the Mach.Port, + /// and the underlying right will no longer be automatically deallocated. + /// + /// After this function completes, the Mach.Port is destroyed and no longer + /// usable. + __consuming func relinquish() -> mach_port_name_t { + return name + } } #endif