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