1 // Copyright 2012 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_MAC_SCOPED_MACH_PORT_H_ 6 #define BASE_MAC_SCOPED_MACH_PORT_H_ 7 8 #include <mach/mach.h> 9 10 #include "base/base_export.h" 11 #include "base/scoped_generic.h" 12 #include "third_party/abseil-cpp/absl/types/optional.h" 13 14 namespace base::mac { 15 16 namespace internal { 17 18 struct BASE_EXPORT SendRightTraits { InvalidValueSendRightTraits19 static mach_port_t InvalidValue() { 20 return MACH_PORT_NULL; 21 } 22 23 BASE_EXPORT static void Free(mach_port_t port); 24 }; 25 26 struct BASE_EXPORT ReceiveRightTraits { InvalidValueReceiveRightTraits27 static mach_port_t InvalidValue() { 28 return MACH_PORT_NULL; 29 } 30 31 BASE_EXPORT static void Free(mach_port_t port); 32 }; 33 34 struct PortSetTraits { InvalidValuePortSetTraits35 static mach_port_t InvalidValue() { 36 return MACH_PORT_NULL; 37 } 38 39 BASE_EXPORT static void Free(mach_port_t port); 40 }; 41 42 } // namespace internal 43 44 // A scoper for handling a Mach port that names a send right. Send rights are 45 // reference counted, and this takes ownership of the right on construction 46 // and then removes a reference to the right on destruction. If the reference 47 // is the last one on the right, the right is deallocated. 48 using ScopedMachSendRight = 49 ScopedGeneric<mach_port_t, internal::SendRightTraits>; 50 51 // A scoper for handling a Mach port's receive right. There is only one 52 // receive right per port. This takes ownership of the receive right on 53 // construction and then destroys the right on destruction, turning all 54 // outstanding send rights into dead names. 55 using ScopedMachReceiveRight = 56 ScopedGeneric<mach_port_t, internal::ReceiveRightTraits>; 57 58 // A scoper for handling a Mach port set. A port set can have only one 59 // reference. This takes ownership of that single reference on construction and 60 // destroys the port set on destruction. Destroying a port set does not destroy 61 // the receive rights that are members of the port set. 62 using ScopedMachPortSet = ScopedGeneric<mach_port_t, internal::PortSetTraits>; 63 64 // Constructs a Mach port receive right and places the result in |receive|. 65 // If |send| is non-null, a send right will be created as well and stored 66 // there. If |queue_limit| is specified, the receive right will be constructed 67 // with the specified mpo_qlmit. Returns true on success and false on failure. 68 BASE_EXPORT bool CreateMachPort( 69 ScopedMachReceiveRight* receive, 70 ScopedMachSendRight* send, 71 absl::optional<mach_port_msgcount_t> queue_limit = absl::nullopt); 72 73 // Increases the user reference count for MACH_PORT_RIGHT_SEND by 1 and returns 74 // a new scoper to manage the additional right. 75 BASE_EXPORT ScopedMachSendRight RetainMachSendRight(mach_port_t port); 76 77 } // namespace base::mac 78 79 #endif // BASE_MAC_SCOPED_MACH_PORT_H_ 80